refactor(platforms)!: 메시징 플랫폼을 messaging-library 1.0.0으로 받고 지운다 #8
@@ -162,6 +162,8 @@ jobs:
|
||||
# and container start-up between lanes. A hosted runner adds cold image pulls (about 5 GB
|
||||
# uncompressed across the PostgreSQL, MongoDB, Kafka, nginx, httpbin and Toxiproxy images) and a
|
||||
# cold Gradle cache; expect 25 to 40 minutes (an estimate, not a measured hosted run). The 240-minute timeout is a ceiling for a hung container, not a budget.
|
||||
# Since 2026-11-08 messagingCertificationTest and the messaging starter's integrationTest run in the
|
||||
# messaging-library repository, not here; the measurement above predates that.
|
||||
integration-check:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 240
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
# The messaging platform's broker certification lane.
|
||||
#
|
||||
# Separate from ci-quality-gates.yml because it needs a container runtime and several minutes of it.
|
||||
# The lane deliberately carries no Docker guard: every other container suite in the messaging tree
|
||||
# skips with a stated reason when Docker is absent, and a certification lane that skipped would
|
||||
# report success for a broker nobody started — which is the exact claim the evidence exists to rule
|
||||
# out.
|
||||
#
|
||||
# The job runs the evidence gate rather than the lane, and the gate depends on the lane. What it
|
||||
# proves is not only that the scenarios pass but that the committed manifest
|
||||
# (messaging-testkit/src/main/resources/messaging/broker-certification-evidence.jsonl) is what this
|
||||
# run produced, so "certified against a live broker" cannot be restored by editing a file.
|
||||
name: messaging-certification
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- "src/platforms/messaging/**"
|
||||
- ".github/workflows/messaging-certification.yml"
|
||||
# Every Gradle job here installs its toolchain through this composite action, so a change to
|
||||
# it changes what this gate runs.
|
||||
- ".github/actions/setup-gradle-java/action.yml"
|
||||
schedule:
|
||||
- cron: "41 4 * * 3"
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
env:
|
||||
# Reuse would hand one scenario the broker another scenario had already faulted.
|
||||
TESTCONTAINERS_REUSE_ENABLE: "false"
|
||||
|
||||
jobs:
|
||||
broker-certification:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2
|
||||
- uses: ./.github/actions/setup-gradle-java
|
||||
- name: Certify the Kafka adapter against a real broker
|
||||
working-directory: src
|
||||
# GITHUB_SHA is read by the lane and written into every evidence line, because "certified"
|
||||
# is a claim about one source tree.
|
||||
run: ./gradlew :messaging:messaging-kafka:verifyMessagingCertificationEvidence --stacktrace
|
||||
- name: Publish the certification evidence
|
||||
if: always()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # actions/upload-artifact@v4.6.2
|
||||
with:
|
||||
name: messaging-broker-certification-evidence
|
||||
path: src/platforms/messaging/messaging-kafka/build/messaging-certification/
|
||||
if-no-files-found: warn
|
||||
@@ -17,7 +17,7 @@ Java 21 + Spring Boot Gradle 멀티모듈 Clean Architecture 템플릿이다(버
|
||||
- Gradle 루트는 `src/`다. leaf 목록·경로·Gradle path·허용 의존의 정본은 registry `src/config/architecture/modules.json`이다. 문서는 leaf 개수를 적지 않는다.
|
||||
- 방향: `app-bootstrap → adapter:inbound:*·adapter:outbound:* → application-core → domain-core`, 실행 모듈 → `shared-contract`. 개별 edge는 registry만 정한다.
|
||||
- 지역 규칙은 작업 파일과 가장 가까운 폴더의 `AGENTS.md`다(leaf, family, `src/build-logic`). 테스트·설정·Docker·문서처럼 폴더를 가로지르는 규칙은 `.claude/rules/`다.
|
||||
- 저장소 루트와 `src/` 최상위에는 정해진 것만 둔다(허용 목록은 `scripts/check-repo-layout.py`). `src/platforms/*`는 계층이 아닌 들여온 제품, `src/composition/*`는 조립만 한다.
|
||||
- 저장소 루트와 `src/` 최상위에는 정해진 것만 둔다(허용 목록은 `scripts/check-repo-layout.py`). 계층이 아닌 라이브러리는 이 repo에 두지 않고 별도 repo에서 버전으로 받는다(`docs/work/reference/related-repos.md`). `src/composition/*`는 조립만 한다.
|
||||
- capability는 `src/app-bootstrap/build.gradle`의 `runtimeOnly` 한 줄로 켜고 끈다. 기준은 `docs/manual/10-capabilities.md`. 문서 위치 규칙은 `docs/README.md`.
|
||||
|
||||
## 맡은 일
|
||||
|
||||
@@ -15,7 +15,7 @@ ca-skeleton은 Java 21과 Spring Boot로 만든 Gradle 멀티모듈 백엔드
|
||||
| `compose/` | `compose.yaml`이 마운트하는 보조 파일(Keycloak realm, Redis ACL, MinIO 초기화) | [compose/redis/acl/README.md](compose/redis/acl/README.md) |
|
||||
| `.github/` | workflow, 공용 action, PR 양식, 의존성 취약점 정책 | [.github/dependency-vulnerability-policy.md](.github/dependency-vulnerability-policy.md) |
|
||||
|
||||
`src/` 아래 폴더는 계층 leaf, 조립, 들여온 제품, Gradle 표준 폴더로 나뉜다. leaf는 Gradle 프로젝트 하나이고, leaf 목록·경로·허용 의존은 registry `src/config/architecture/modules.json`이 정한다.
|
||||
`src/` 아래 폴더는 계층 leaf, 조립, Gradle 표준 폴더로 나뉜다. leaf는 Gradle 프로젝트 하나이고, leaf 목록·경로·허용 의존은 registry `src/config/architecture/modules.json`이 정한다.
|
||||
|
||||
| 폴더 | 책임 | 기본 조립에 들어가나 |
|
||||
| --- | --- | --- |
|
||||
@@ -27,7 +27,6 @@ ca-skeleton은 Java 21과 Spring Boot로 만든 Gradle 멀티모듈 백엔드
|
||||
| `adapter/outbound/` | port 뒤의 구현: 영속성(JPA·MongoDB), Redis, 메시징, 알림, 객체 저장소, 파일 서버, HTTP client, identifier, 공용 기반(support) | `support`·`identifier`만 들어간다 |
|
||||
| `composition/` | 조립만 하는 leaf: 서비스 런타임 배선, outbox relay, 멱등성 executor, durable operation, 알림·파일 서버 플랫폼 | `service-runtime`·`outbox-relay`·`idempotency`·`durable-operation`이 들어간다. 뒤의 셋은 필요한 port가 생기기 전에는 아무것도 만들지 않는다 |
|
||||
| `app-bootstrap/` | Spring Boot 진입점과 조립 루트(composition root, 모든 모듈을 엮는 곳) | 들어간다 |
|
||||
| `platforms/` | 들여온 제품: `messaging`(메시징 플랫폼). gRPC 플랫폼 라이브러리는 2026-11-08에 별도 repo `grpc-library`로 옮겼다([관련 저장소](docs/work/reference/related-repos.md)) | 들어가지 않는다. adapter를 거쳐서만 닿는다 |
|
||||
| `build-logic/`, `config/`, `gradle/` | 빌드 규칙(convention plugin), 빌드 전체 도구 설정과 registry, wrapper와 버전 카탈로그 | 빌드 도구 |
|
||||
|
||||
의존은 항상 바깥에서 안으로 흐른다. adapter가 core의 port에 의존하고, core는 adapter를 모른다.
|
||||
|
||||
@@ -46,7 +46,6 @@ capability(부가 기능) 하나의 지원 범위, 설정, 보안, 운영, 마
|
||||
| `fileserver/` | 파일 서버 |
|
||||
| `httpclient/` | 외부 HTTP 호출(HTTP client 플랫폼) |
|
||||
| `jpa/` | JPA·PostgreSQL 영속성 |
|
||||
| `messaging/` | 메시징 adapter |
|
||||
| `mongodb/` | MongoDB 문서 영속성 |
|
||||
| `mongodb/advanced/` | MongoDB 고급 기능(암호화, 멀티 테넌시, 샤딩). 설정 키가 아니라 라이브러리 API로 켠다 |
|
||||
| `mongodb/runbooks/` | MongoDB 장애 대응 |
|
||||
|
||||
@@ -29,7 +29,7 @@ lanes and CI; it is not a deployment artifact.
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| Relational persistence (JPA/PostgreSQL) | `ca-skeleton.persistence-jpa.enabled` / `APP_PERSISTENCE_JPA_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:persistence-jpa')`) | yes | Not in the default composition. The one line brings everything — its own `AutoConfiguration.imports` (`PersistenceJpaAutoConfiguration`, `PersistenceJpaRuntimeConfig`, `JpaStartupAutoConfiguration`), its environment handling (`JpaActivationEnvironmentPostProcessor`, `spring.factories`: readiness `db` while on; with `false` it also excludes Boot's JDBC, Hibernate, Spring Data JPA and Flyway auto-configuration, so no DataSource is bound), the startup guards (Flyway strategy, datasource/OSIV/DDL/pool/TLS/vendor checks, exit codes unchanged) and its settings (`config/module-defaults/persistence-jpa.yml`). `persistence-jpa:PersistenceJpaCapabilityAssemblyTest` proves the module assembles on its own; the `postgresql*IntegrationTest` readiness lanes, run by `integration-main.yml` → `integration-check` (`:integrationCheck`), qualify it against PostgreSQL. `bootRunH2` adds the module to its own classpath only. |
|
||||
| Document persistence (MongoDB) | `ca-skeleton.persistence-mongo.enabled` / `APP_PERSISTENCE_MONGO_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:persistence-mongo')`) | yes | On when present; `false` also excludes Boot's Mongo auto-configuration (`MongoCapabilityActivationTest`). The connection-source rule (`SPRING_MONGODB_URI` or the selected profile's `uri-secret`) is checked by the module's own `MongoDefaultsEnvironmentPostProcessor`. Six container lanes (`mongoReplicaSetTest`, `mongoFailoverTest`, …), run by `integration-main.yml` → `integration-check` (`:integrationCheck`) |
|
||||
| Messaging (Kafka) | `app.messaging.enabled` / `APP_MESSAGING_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:messaging-kafka')`, which brings the application bridge, the legacy `KafkaSender` seam and the vendored platform with its Kafka transport) | Kafka only | On when present (`KafkaCapabilityActivationTest`). `messaging-kafka:messagingCertificationTest` behind `verifyMessagingCertificationEvidence`, run by `messaging-certification.yml`; the starter's `integrationTest` is the live Kafka round trip. Kafka is the only registered broker; the RabbitMQ broker keys were removed (no transport). |
|
||||
| Messaging (Kafka) | `app.messaging.enabled` / `APP_MESSAGING_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:messaging-kafka')`, which brings the application bridge and the messaging library `dev.cakit.messaging` (messaging-library repo, catalog `messagingLibrary`) with its Kafka transport) | Kafka only | On when present (`KafkaCapabilityActivationTest`). The application's own publish and consume paths run against a live Kafka in `messagingKafkaRelayIntegrationTest` and `messagingInboxRedeliveryIntegrationTest`. The library's broker certification (`verifyMessagingCertificationEvidence`) runs in the messaging-library repo's main stage since 2026-11-08. Kafka is the only registered broker; the RabbitMQ broker keys were removed (no transport). |
|
||||
| Redis capabilities (cache / rate-limit / lease / idempotency) | `app.redis.enabled` / `APP_REDIS_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:cache-redis')`, which brings `redis-runtime`) | yes | `cache-redis:redisContainerContractTest` (Testcontainers Redis, `integrationCheck`); `cache-redis:redisTopologyTest`, run by `redis-sdk-topology.yml`. Not in the default composition. On when present; `false` contributes no Redis bean — no settings, client, connection, thread or health contributor. The module owns its readiness contribution (`RedisReadinessGroupPostProcessor`, `spring.factories`) and its settings (`config/module-defaults/cache-redis.yml`: `app.redis.enabled`, `app.rate-limit.*`, the Redis `ca-skeleton.capabilities.*`). No `app-bootstrap` main source names a Redis type. |
|
||||
| Request idempotency | `APP_IDEMPOTENCY_PROVIDER` (`disabled` \| `redis` \| `postgresql`; a selector, not an on/off key) | yes | yes | Redis and PostgreSQL | One generation: the application `IdempotencyExecutor`, built once by `composition:idempotency` (`IdempotencyAutoConfiguration`) over the one store the selected provider contributes (`cache-redis` or `persistence-jpa`); startup is refused unless exactly one store exists. `app-bootstrap`이 그 모듈을 `runtimeOnly` 한 줄로 받고, 다른 조립은 없다. Redis is covered by the row above. PostgreSQL has `persistence-jpa:postgresqlIdempotencyIntegrationTest`, run by `integration-main.yml` → `integration-check` (`:integrationCheck`). The `postgresql` provider refuses a non-PostgreSQL data source, so `bootRunH2` uses `disabled` or `redis`. Each store comes with its module: `postgresql` needs the persistence-jpa line, `redis` the cache-redis one. |
|
||||
| Transactional outbox relay | `ca-skeleton.outbox.enabled` / `APP_OUTBOX_ENABLED`, `false` (+ `APP_OUTBOX_RELAY_ENABLED`, `false`; persistence-jpa settings) | yes | yes (with the persistence-jpa line; the scheduler also needs the messaging-kafka line) | yes | The store and its settings are persistence-jpa's; the relay (`OutboxConfig`) is application composition in `app-bootstrap` because a driven adapter must not build or call a use case. It turns on only when an `OutboxStorePort` bean exists, and the scheduler only when an `OutboxMessagePublishPort` does (the messaging bridge), each ordered after its contributor by `afterName` — so an environment with no publisher keeps its PENDING rows. The bridge registers no stand-in publisher: a present-and-enabled bridge with a blank broker and no canonical transport is refused at startup. `postgresqlLegacyOutboxConcurrentRelayIntegrationTest` qualifies claim/fencing against PostgreSQL. |
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
- 상태: 채택
|
||||
- 작성일: 2026-07-28
|
||||
- 요약: 메시징을 운영 가능한 capability로 올리는 상세 설계다.
|
||||
- 현재 정본: `docs/messaging/support-matrix.md`
|
||||
- 현재 정본: `docs/manual/09-outbox-events.md`
|
||||
<!-- 머리 블록 끝 -->
|
||||
|
||||
# Messaging Production Capability Deep Design
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
- 상태: 채택
|
||||
- 작성일: 2026-08-10
|
||||
- 요약: 메시지 생성부터 브로커 수락, 소비자 정산까지 증거로 다루는 메시징 플랫폼 설계다.
|
||||
- 현재 정본: `docs/messaging/support-matrix.md`
|
||||
- 현재 정본: 없음 — 메시징 플랫폼은 2026-11-08에 별도 repo messaging-library(Maven group dev.cakit.messaging)로 옮겼다. 지금 동작은 그 repo의 docs/messaging/support-matrix.md다
|
||||
<!-- 머리 블록 끝 -->
|
||||
|
||||
# Messaging Platform 설계서
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
- 상태: 확인 안 함
|
||||
- 작성일: 2026-09-18
|
||||
- 요약: 애플리케이션 전용 브로커 이음매를 메시징 플랫폼으로 가는 bridge 하나로 바꾸는 설계다.
|
||||
- 현재 정본: `docs/messaging/support-matrix.md`
|
||||
- 현재 정본: `docs/manual/09-outbox-events.md`
|
||||
<!-- 머리 블록 끝 -->
|
||||
|
||||
# Messaging Platform Bridge Design
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
- 상태: 보관
|
||||
- 작성일: 2026-08-13
|
||||
- 요약: 메시징 설계 패키지가 처음 납품됐을 때의 안내다. 본문 문서는 docs/design과 docs/history/plans에 있다.
|
||||
- 현재 정본: `docs/messaging/support-matrix.md`
|
||||
- 현재 정본: 없음 — 메시징 플랫폼은 2026-11-08에 별도 repo messaging-library(Maven group dev.cakit.messaging)로 옮겼다. 지금 동작은 그 repo의 docs/messaging/support-matrix.md다
|
||||
<!-- 머리 블록 끝 -->
|
||||
|
||||
> **보존 안내** — 이 파일은 저장소 루트 `messaging-superpowers-package/` 에 있던 납품 패키지의 README다.
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
- 상태: 보관
|
||||
- 작성일: 2026-08-13
|
||||
- 요약: 메시징 설계 패키지를 받을 때 한 정적 검증 결과다.
|
||||
- 현재 정본: `docs/messaging/support-matrix.md`
|
||||
- 현재 정본: 없음 — 메시징 플랫폼은 2026-11-08에 별도 repo messaging-library(Maven group dev.cakit.messaging)로 옮겼다. 지금 동작은 그 repo의 docs/messaging/support-matrix.md다
|
||||
<!-- 머리 블록 끝 -->
|
||||
|
||||
# Messaging Superpowers 문서 정적 검증
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
- 상태: 확인 안 함
|
||||
- 작성일: 2026-07-28
|
||||
- 요약: typed 통합 이벤트에서 시작하는 첫 운영 기준 메시징 경로(R2 polling producer)를 만드는 실행 계획이다.
|
||||
- 현재 정본: `docs/messaging/support-matrix.md`
|
||||
- 현재 정본: `docs/manual/09-outbox-events.md`
|
||||
<!-- 머리 블록 끝 -->
|
||||
|
||||
# Messaging First R2 Polling Producer Implementation Plan
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
- 상태: 확인 안 함
|
||||
- 작성일: 2026-08-10
|
||||
- 요약: 메시징 플랫폼(증거 기반 발행, 중복 안전 소비, Kafka·RabbitMQ, outbox·inbox)을 만드는 실행 계획이다.
|
||||
- 현재 정본: `docs/messaging/support-matrix.md`
|
||||
- 현재 정본: 없음 — 메시징 플랫폼은 2026-11-08에 별도 repo messaging-library(Maven group dev.cakit.messaging)로 옮겼다. 지금 동작은 그 repo의 docs/messaging/support-matrix.md다
|
||||
<!-- 머리 블록 끝 -->
|
||||
|
||||
# Messaging Platform Implementation Plan
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
- 상태: 끝남
|
||||
- 작성일: 2026-09-18
|
||||
- 요약: 통합 이벤트 발행 경계를 메시징 플랫폼 bridge에 잇는 실행 계획이다.
|
||||
- 현재 정본: `docs/messaging/support-matrix.md`
|
||||
- 현재 정본: `docs/manual/09-outbox-events.md`
|
||||
<!-- 머리 블록 끝 -->
|
||||
|
||||
# Messaging Platform Bridge Implementation Plan
|
||||
|
||||
@@ -2,3 +2,5 @@
|
||||
{"schema": 1, "kind": "actual", "task": "h3-backend-harness", "recorded_at": "2026-11-07T23:13+09:00", "transcript": "d5a4c736-f1d6-45ab-acbe-8857526585b9", "minutes": 94, "active_minutes": 68, "calls": 270, "output_tokens": 345525, "cache_read_tokens": 132822591, "max_context": 805096, "within": "p30", "result": "done", "commits": ["08f93212", "3c73fc33", "38891071", "c67c7131", "67ecae2c", "37c88fed", "59dff004", "c8db79a7", "d9059806", "7140f279", "93b70b06", "248df518"], "why": "모든 값이 p30보다 작았다. 바꿀 파일 수(약 120, 실제 190여)를 호출 수로 옮겼는데, 이동·참조 수정 수십 파일을 스크립트 한 번으로 묶어 파일당 호출이 거의 없었다. desktop 대기는 예측과 비슷했지만(합친 트리 한 번 27분, 중단한 두 번) 작업 중 시간에서는 빈틈마다 5분으로 잘린다. 다음 예측은 파일 수가 아니라 손으로 판단할 결정 수(이번 약 25)와 desktop 실행 횟수를 근거로 쓴다. 실측은 23:12까지의 세션 기록이고, 뒤의 커밋·PR·보고는 들어 있지 않다"}
|
||||
{"schema": 1, "kind": "estimate", "task": "x2-grpc-library", "recorded_at": "2026-11-08T10:50+09:00", "transcript": "dc504d75-c815-4dfa-98dd-80c224db983f", "started_at": "2026-11-08T10:47:39+09:00", "base": "22df3525", "task_kind": "improve", "size": "large", "minutes": {"p30": 150, "p50": 220, "p80": 330}, "calls": {"p30": 350, "p50": 500, "p80": 750}, "output_tokens": {"p30": 400000, "p50": 600000, "p80": 900000}, "basis": "착수 노트(공유 노트 x2-grpc-library.md, 10:50)에 쓴 값을 옮겼다. 선례 h3-backend-harness 작업 중 68분·호출 270·출력 34.6만(손으로 판단한 결정 약 25, desktop 실행 3회). 이번은 결정 약 35(배치, build-logic 줄이기, 배포·서명·SBOM, buf 정책, testFixtures 사본, workflow 셋, 템플릿 지우기 20여 파일, 하네스)와 desktop 실행이 라이브러리 반복 5~8회 + 템플릿 게이트 묶음 2~3회 + Gitea Actions 실행 2회 이상이라 h3의 세 배 가까이로 봤다"}
|
||||
{"schema": 1, "kind": "actual", "task": "x2-grpc-library", "recorded_at": "2026-11-08T14:02+09:00", "transcript": "dc504d75-c815-4dfa-98dd-80c224db983f", "minutes": 194, "active_minutes": 99, "calls": 330, "output_tokens": 303528, "cache_read_tokens": 136483127, "max_context": 746863, "within": "p30", "result": "done", "commits": ["5e204e6a", "2921f596", "91804ec1", "57988c2e", "grpc-library:76a9244", "grpc-library:414666c", "grpc-library:41d73a1", "grpc-library:239547b", "grpc-library:90306b2", "grpc-library:8d705bc", "grpc-library:ce83f4d", "grpc-library:39d4b6d", "grpc-library:c10f4af"], "why": "모든 값이 p30보다 작았다(작업 중 99분, 벽시계 194분). 예측은 desktop 대기(템플릿 게이트 1회차 약 65분, 라이브러리 반복 6회, 재실행 3회)를 작업 중 시간에 넣었는데, 대기는 빈틈마다 5분으로 잘리고 그동안 문서·라이브러리 일을 같이 했다. 패키지 이름 바꾸기 315파일, SpotBugs 제외 정리, 템플릿 삭제 397파일을 스크립트 몇 번으로 끝내 결정 수(약 35) 대비 호출이 적었다. 다음 예측은 desktop 대기를 시간에서 빼고 결정 수와 실행 횟수만으로 잡는다. 라이브러리 PR #1 병합은 권한 분류기에 막혀 남았다"}
|
||||
{"schema": 1, "kind": "estimate", "task": "x3-messaging-library", "recorded_at": "2026-11-08T16:00+09:00", "transcript": "462a3688-07fc-4460-a565-62afcf6ae072", "started_at": "2026-11-08T15:55:32+09:00", "base": "2959eff0", "task_kind": "improve", "size": "large", "minutes": {"p30": 140, "p50": 200, "p80": 300}, "calls": {"p30": 420, "p50": 580, "p80": 850}, "output_tokens": {"p30": 450000, "p50": 650000, "p80": 950000}, "basis": "착수 노트(공유 노트 x3-messaging-library.md, 16:00)에 쓴 값을 옮겼다. 선례 x2-grpc-library 1차(만들기~PR) 작업 중 99분·호출 330·출력 30.4만, 결정 약 35. 이번은 결정 약 45로 봤다: gRPC 결정(배치·build-logic·배포·workflow)은 본보기를 따르면 되지만 템플릿에 소비자가 있어 좌표 전환 4 leaf, migration 결합, 계약 테스트 나누기, registry 「허용 라이브러리」 칸(build-logic 변경과 시험), lockfile, Kafka 인증 lane의 runner 실행이 새로 붙는다. desktop 실행은 라이브러리 4~6회 + 템플릿 게이트 묶음 2~3회 + runner 3회 이상. desktop 대기는 시간에서 뺐다(x2 회고)"}
|
||||
{"schema": 1, "kind": "actual", "task": "x3-messaging-library", "recorded_at": "2026-11-08T22:00+09:00", "transcript": "462a3688-07fc-4460-a565-62afcf6ae072", "minutes": 361, "active_minutes": 110, "calls": 346, "output_tokens": 271613, "cache_read_tokens": 177759293, "max_context": 820126, "within": "p30", "result": "done", "commits": ["77b81811", "5af94155", "7dc5725f", "messaging-library:f593229", "messaging-library:2e9298e", "messaging-library:f076f6a", "messaging-library:2e7e073", "messaging-library:dd19478", "messaging-library:d2bacc6", "messaging-library:31c5178"], "why": "모든 값이 p30보다 작았다(작업 중 110분, 벽시계 361분). 벽시계의 큰 몫은 기다림이었다: 총괄의 PR #1 병합·태그·release(약 50분), 템플릿 게이트 묶음(17:12~20:12, 공유 잠금 대기 포함), 노트북 네트워크 끊김(17:30~21:50). 작업 중 시간은 빈틈마다 5분으로 잘려 그 대기가 거의 빠졌다. 본보기(grpc-library)의 build-logic·workflow·release 스크립트를 복사하고 이름 바꾸기·삭제·SpotBugs 정리를 스크립트로 해 결정 수(약 45) 대비 호출이 적었다. 예측에 없던 일: 구조 리뷰가 찾은 system caller 규칙 결함(MessageHandler가 프로젝트 밖 타입이 됨)과 순서 시험 두 개. 다음 예측은 소비자가 있는 분리면 「리뷰가 찾는 규칙 결함」 1~2건 몫을 더한다"}
|
||||
|
||||
@@ -105,7 +105,7 @@ client가 같은 이름의 역할을 정의해도 이 서비스 권한이 되지
|
||||
| 시스템 호출자만 | inbound adapter가 그 클래스에 의존하면 빌드 실패. `@SystemCaller(reason = "...")`를 단 클래스와 그 안에 중첩된 클래스만 예외 | `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`(`ApplicationBoundaryArchitectureTest`) |
|
||||
| 표시 검사 | `@SystemCaller` 클래스와 그 안에 중첩된 클래스는 `..adapter.inbound.messaging..`·`..adapter.inbound.scheduler..`에만 있고, 사용자 전송 타입(controller·JAX-RS·GraphQL·STOMP mapping과 channel interceptor·gRPC·servlet)에 의존하지 않는다 | `SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`(같은 파일) |
|
||||
| 전송 → 시스템 호출자 금지 | 사용자 전송 클래스가 `@SystemCaller`나, 그 클래스가 구현·상속하는 프로젝트 타입(작업의 인터페이스 등)에 의존하면 빌드 실패. 중간 클래스를 거쳐도 잡는다. 사용자 전송 클래스는 넷이다. ① 사용자 전송 패키지에 있는 클래스. ② 설정(`@Configuration`·`@AutoConfiguration`) 클래스 자신이 요청 처리기 타입(함수형 `RouterFunction`·`HandlerFunction`, `@RestController`·`@RequestMapping`, servlet·`Filter`·`HandlerInterceptor`, `WebSocketHandler`, GraphQL `DataFetcher`·`RuntimeWiringConfigurer`, gRPC `BindableService`·`ServerInterceptor`, STOMP `ChannelInterceptor`·`ExecutorChannelInterceptor` 등)에 의존하는 것. 요청 처리 코드를 설정에 직접 쓴 경우와 등록만 한 경우가 모두 든다. channel interceptor를 구현한 설정은 프레임마다 자기 메서드가 돈다. interceptor를 `@Bean`으로 내놓는 설정은 route를 등록하는 설정과 같다. 함수형 route나 data fetcher를 람다로 쓰면 그 코드가 설정 클래스의 메서드로 컴파일되어 설정이 곧 endpoint다. 처리 코드를 다른 클래스에 두고 메서드 참조로 등록만 해도(`route().GET("/orders", orders::list)`) 설정은 route builder에 의존한다. 클래스 의존으로는 등록과 처리 코드를 가를 수 없어서 둘 다 사용자 전송으로 센다. ③ 설정 안에 중첩된 클래스 가운데 사용자 전송 타입에 의존하는 것. 중첩된 JAX-RS 자원·`@ServerEndpoint`, `configureClientInboundChannel`에서 등록하는 STOMP channel interceptor(익명 클래스여도, STOMP 헤더를 읽지 않아도)도 여기서 잡힌다. 설정용 타입(`WebMvcConfigurer`·`WebSocketConfigurer`·STOMP broker 설정과 그 registry, CORS 설정, `RequestMethod`)에만 의존하는 중첩 클래스는 설정의 일부로 본다. inbound channel의 thread 수만 정하는 설정도 설정용이다. ④ 그 밖의 클래스 가운데 사용자 전송 타입에 의존하는 것. 사용자 전송 패키지 밖에 둔 channel interceptor가 여기에 든다. 그래서 handler를 bean으로 등록하는 설정은 같은 클래스에서 `WebMvcConfigurer`(설정 필드를 읽는 익명 클래스여도)·CORS 설정·controller bean을 함께 만들어도 걸리지 않는다. 같은 클래스에 "지금 실행" route·data fetcher·interceptor를 쓰거나, route를 등록하거나, 안에 중첩한 endpoint가 작업을 부르면(설정의 메서드를 거쳐 불러도) 걸린다. route·data fetcher·interceptor 등록은 handler bean을 만드는 설정과 다른 설정에 둔다. 설정이 만드는 controller는 controller 자신이 검사받는다 | `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`(같은 파일) |
|
||||
| 프로젝트 밖 상위 타입 금지 | `@SystemCaller` 클래스와 그 안에 중첩된 클래스(익명·지역 클래스와 예외 제외)는 프로젝트(`dev.caskeleton..`) 밖의 클래스·인터페이스를 상속·구현하지 않는다. `Runnable`은 누구나 의존하는 타입이라, endpoint가 작업을 `Runnable`로 주입받아도 위 규칙이 다른 사용과 구별하지 못하기 때문이다. 메시지 handler의 `MessageHandler<T>`는 프로젝트 타입이라 된다. record·enum은 언어가 붙이는 상위 타입(`Record`, `Enum`과 `Enum`이 구현하는 `Comparable`·`Serializable`·`Constable`)만은 가져도 된다. 그래서 handler 안의 파싱 결과 record, 결과 enum, 독(poison) 메시지 예외, record로 쓴 handler는 통과하고, `Runnable`을 구현한 record는 걸린다 | `SYSTEM_CALLERS_HAVE_ONLY_PROJECT_SUPERTYPES`(같은 파일) |
|
||||
| 프로젝트 밖 상위 타입 금지 | `@SystemCaller` 클래스와 그 안에 중첩된 클래스(익명·지역 클래스와 예외 제외)는 프로젝트(`dev.caskeleton..`와 소유자의 별도 repo 라이브러리 `dev.cakit..`) 밖의 클래스·인터페이스를 상속·구현하지 않는다. `Runnable`은 누구나 의존하는 타입이라, endpoint가 작업을 `Runnable`로 주입받아도 위 규칙이 다른 사용과 구별하지 못하기 때문이다. 메시지 handler의 `MessageHandler<T>`(메시징 라이브러리 `dev.cakit.messaging`)는 프로젝트 타입으로 쳐서 된다. record·enum은 언어가 붙이는 상위 타입(`Record`, `Enum`과 `Enum`이 구현하는 `Comparable`·`Serializable`·`Constable`)만은 가져도 된다. 그래서 handler 안의 파싱 결과 record, 결과 enum, 독(poison) 메시지 예외, record로 쓴 handler는 통과하고, `Runnable`을 구현한 record는 걸린다 | `SYSTEM_CALLERS_HAVE_ONLY_PROJECT_SUPERTYPES`(같은 파일) |
|
||||
|
||||
규칙은 "누가 닿으면 안 되나"가 아니라 "누가 닿아도 되나"를 적는다. 이 성질은 **패키지** 쪽에서만 온다.
|
||||
패키지는 허용 목록이라, 나중에 새 전송 패키지가 생겨도 따로 고치지 않아도 막힌다. 사용자 전송 **타입**
|
||||
|
||||
@@ -17,8 +17,9 @@ use case ── tx.inWrite ─┬─▶ repository.save(aggregate) ┐
|
||||
DB 저장과 broker 발행을 따로 하면(dual write) 둘 중 하나만 성공하는 순간이 생긴다. outbox는 그 순간을
|
||||
없앤다. 대가는 **적어도 한 번** 전달이다 — 소비자는 event id로 중복을 걸러야 한다.
|
||||
|
||||
정본: `src/application-core/README.md` 「계약 타입」(이벤트 타입 표), `docs/messaging/outbox-inbox.md`,
|
||||
`docs/messaging/delivery-guarantees.md`.
|
||||
정본: `src/application-core/README.md` 「계약 타입」(이벤트 타입 표). 메시징 라이브러리 쪽 정본은 그 repo의
|
||||
[outbox-inbox.md](https://git.learn.hyeonworks.com/donghyeon.kang/messaging-library/src/branch/main/docs/messaging/outbox-inbox.md)와
|
||||
[delivery-guarantees.md](https://git.learn.hyeonworks.com/donghyeon.kang/messaging-library/src/branch/main/docs/messaging/delivery-guarantees.md)다.
|
||||
|
||||
## 순서
|
||||
|
||||
|
||||
@@ -1,256 +0,0 @@
|
||||
# 설정 레퍼런스
|
||||
|
||||
> **Prefix.** Every property below binds under `app.messaging`, which is the prefix the deployed
|
||||
> runtime and the `APP_MESSAGING_*` environment variables already use. Earlier revisions of this
|
||||
> page documented a bare `messaging` prefix and the starter bound `backend.messaging`; neither
|
||||
> bound what this page describes, so a deployment configured from it changed nothing. A key under
|
||||
> either of the old prefixes now fails startup with a message naming the key — see
|
||||
> `MessagingPrefixMigrationValidator`.
|
||||
|
||||
> **이 페이지는 실행된다.** 아래 YAML 블록은 `MessagingConfigurationBindingTest`가 이 파일에서 직접
|
||||
> 읽어 컨텍스트에 올린다. 문서가 설명하는 모양이 곧 바인딩되는 모양이라는 뜻이고, 문서를 고치면서
|
||||
> 코드를 고치지 않으면 테스트가 깨진다. 이전 판은 destination·broker·security 세 섹션을 설명했지만
|
||||
> 어떤 binder도 그것을 읽지 않았다 — 문서대로 설정한 배포는 아무것도 바뀌지 않았고 아무 말도 듣지
|
||||
> 못했다 (MSG-008).
|
||||
|
||||
## Application publish bridge identity
|
||||
|
||||
Application의 canonical integration event를 platform publish pipeline으로 보낼 때는
|
||||
`app.messaging.producer-id`를 명시한다. 같은 값의 환경변수 이름은
|
||||
`APP_MESSAGING_PRODUCER_ID`다. 이 값은 host/pod 이름이 아니라 배포와 무관하게 유지되는 논리적
|
||||
producing-service identity다.
|
||||
|
||||
값이 없으면 `IntegrationEventPublishPort` bridge 자체를 만들지 않는다. `spring.application.name`이나
|
||||
현재 process 이름으로 추론하지 않는다. 모든 발행(outbox relay 포함)이 이 bridge를 지나므로 messaging
|
||||
모듈이 켜진 상태에서 값이 없으면 기동이 거부된다.
|
||||
|
||||
## Outbox
|
||||
|
||||
application의 발행 경로는 하나다(2026-09-28): `outbox_event` 표와 `composition:outbox-relay`. vendored
|
||||
platform의 `messaging_outbox`(`outbox-inbox.md`)는 이 경로에 쓰이지 않는다 — 두 모델의 상태 대응은
|
||||
`outbox-inbox.md` 머리의 표에 있다. use case가 `IntegrationEventEncoderPort`로 만든
|
||||
`ValidatedIntegrationEvent`를 `OutboxAppendPort`로 append하고, relay는 claim한 row의 exact envelope
|
||||
bytes를 `IntegrationEventPublishPort`로 보낸다. 예전의 `app.outbox.canonical-transport-enabled`
|
||||
gate와 legacy `MessageBroker → KafkaSender` 경로는 삭제됐다. 발행할 contract의 logical destination마다
|
||||
아래 destination profile을 선언한다(템플릿의 durable operation event는 `durable-operations`).
|
||||
|
||||
## Destination profile
|
||||
|
||||
```yaml
|
||||
app:
|
||||
messaging:
|
||||
destinations:
|
||||
order-events:
|
||||
broker: kafka-primary
|
||||
kind: EVENT_STREAM # ASYNC_COMMAND | DOMAIN_EVENT | INTEGRATION_EVENT
|
||||
# | WORK_QUEUE | PUBLISH_SUBSCRIBE | EVENT_STREAM | REQUEST_REPLY
|
||||
tier: M1 # M1 | M2 | M3
|
||||
physical:
|
||||
topic: order.events.v1
|
||||
schema:
|
||||
codec: application/json
|
||||
compatibility: BACKWARD_TRANSITIVE
|
||||
message-types: [order.created]
|
||||
guarantees:
|
||||
delivery: AT_LEAST_ONCE # AT_MOST_ONCE | AT_LEAST_ONCE
|
||||
ordering: KEY # NONE | DESTINATION | PARTITION | KEY
|
||||
external-side-effect: INBOX_TRANSACTIONAL
|
||||
producer:
|
||||
confirmation: REPLICATION_OR_PERSISTENCE_ACK
|
||||
timeout: 5s
|
||||
mandatory-routing: true
|
||||
idempotent: true
|
||||
consumer:
|
||||
group: order-projection
|
||||
concurrency: 1 # DESTINATION 순서를 요구하면 1이어야 한다
|
||||
max-in-flight-per-ordering-unit: 1
|
||||
prefetch: 16
|
||||
handler-timeout: 30s
|
||||
manual-settlement: false
|
||||
retry:
|
||||
mode: PAUSE_PARTITION # NONE | INLINE | BLOCKING | PAUSE_PARTITION
|
||||
# | RETRY_DESTINATION | BROKER_DELAYED
|
||||
max-attempts: 3
|
||||
initial-delay: 200ms
|
||||
max-delay: 2s
|
||||
multiplier: 2.0
|
||||
jitter: true
|
||||
ordering-impact: PRESERVE # PRESERVE | ALLOW_REORDER
|
||||
dlq:
|
||||
destination: order-events-dlq
|
||||
max-redrive-count: 1
|
||||
payload:
|
||||
max-bytes: 1048576
|
||||
claim-check-threshold-bytes: 1048576
|
||||
key-resolver-configured: true
|
||||
production: false
|
||||
topology-auto-create: false
|
||||
order-events-dlq:
|
||||
broker: kafka-primary
|
||||
kind: WORK_QUEUE
|
||||
guarantees:
|
||||
delivery: AT_MOST_ONCE # terminal DLQ: another DLQ is not required
|
||||
physical:
|
||||
topic: order.events.v1.dlt
|
||||
schema:
|
||||
message-types: [order.created]
|
||||
```
|
||||
|
||||
`dlq.destination`이 가리키는 destination도 선언되어야 한다. 선언되지 않은 이름은 부팅 실패이며,
|
||||
메시지가 갈 곳 없는 DLQ 설정이 조용히 통과하지 않는다. `retry.destination`과 `dlq.destination`이
|
||||
섞여 만드는 순환(A의 retry가 B로, B의 dlq가 A로)도 하나의 그래프로 검사되어 경로와 함께 거절된다.
|
||||
|
||||
## 기본값
|
||||
|
||||
| 설정 | 기본값 | 근거 |
|
||||
|---|---:|---|
|
||||
| logical payload 최대 | 1,048,576 bytes | portability. 초과는 Claim Check |
|
||||
| global hard 최대 | 8,388,608 bytes | 어떤 destination도 넘을 수 없는 상한 |
|
||||
| header 총 크기 | 32,768 bytes | |
|
||||
| header 개수 | 64 | |
|
||||
| header key | 128 bytes | metric tag 안전 |
|
||||
| header value | 4,096 bytes | |
|
||||
| publish timeout | 5s | |
|
||||
| handler timeout | 30s | |
|
||||
| graceful shutdown drain | 30s | |
|
||||
| 일반 destination retry | 0회 | 자동 retry는 opt-in |
|
||||
| DLQ redrive batch | 100 | 한 번의 작업이 source를 덮치지 않게 |
|
||||
| Outbox relay batch | 100 | |
|
||||
| Outbox lease | 30s | |
|
||||
| Outbox polling | 500ms | |
|
||||
| metric dimension 상한 | 200 | cardinality 폭발 방지 |
|
||||
|
||||
`schema.codec`은 `application/json`, `schema.compatibility`는 `BACKWARD_TRANSITIVE`,
|
||||
|
||||
> **현재 강제 범위:** `schema.compatibility` 값은 현재 정책 선언이며 runtime/CI에서 schema registry를
|
||||
> 조회해 호환성을 차단하지 않는다. Avro 비교기는 독립 utility/test로만 존재한다. 따라서 이 값을
|
||||
> 설정했다고 breaking schema가 자동 거부된다고 해석하면 안 된다. 실제 registry gate가 wiring되기
|
||||
> 전까지 호환성은 adopter의 schema CI가 소유한다.
|
||||
|
||||
`guarantees.delivery`는 `AT_LEAST_ONCE`, `retry.mode`는 `NONE`이 기본값이다. 자동 retry가 기본으로
|
||||
꺼져 있는 이유는 순서를 흐트러뜨리거나 비멱등 side effect를 두 번 실행하는 retry가 눈에 보이는
|
||||
실패보다 나쁘기 때문이다.
|
||||
|
||||
## Broker profile
|
||||
|
||||
브로커는 `app.messaging.brokers` 아래에 한 번만 기술한다. `type`은 `kafka`만 받는다 — transport가
|
||||
있는 계열이 Kafka 하나뿐이다. RabbitMQ 키(`addresses`, `prefetch`, `quorum-queues` 등)와
|
||||
`type: rabbitmq`는 2026-09-25에 설정 모델에서 삭제됐다. 연결할 transport 없이 바인딩만 되던 키라,
|
||||
지금은 무시되지 않고 키 이름을 담아 부팅 실패로 거절된다.
|
||||
|
||||
### Kafka
|
||||
|
||||
```yaml
|
||||
app:
|
||||
messaging:
|
||||
brokers:
|
||||
kafka-primary:
|
||||
type: kafka
|
||||
stable: true
|
||||
production: false
|
||||
bootstrap-servers: [broker-1:9093, broker-2:9093]
|
||||
enable-idempotence: true # stable에서 필수
|
||||
acks: all # stable에서 필수
|
||||
max-in-flight-requests-per-connection: 5 # 최대 5
|
||||
delivery-timeout: 30s
|
||||
enable-auto-commit: false # 항상 금지
|
||||
consumer-group: order-projection
|
||||
tls-enabled: false # production이면 필수
|
||||
authentication-enabled: false # production이면 필수
|
||||
```
|
||||
|
||||
`production: true`인 Kafka 브로커는 `tls-enabled`와 `authentication-enabled`가 모두 참이어야 하고,
|
||||
그렇지 않으면 `KafkaProfileValidator`가 부팅을 거절한다. `app.messaging.broker`로 고를 수 있는 값은
|
||||
`kafka`뿐이다. 위 예시가
|
||||
`production: false`인 것은 이 페이지가 그대로 실행되는 fixture이기 때문이며, 실 배포는 셋 다 참이다.
|
||||
|
||||
Kafka producer는 이 항목 하나로 만든다. `bootstrap-servers`, `acks`, `enable-idempotence`,
|
||||
`max-in-flight-requests-per-connection`, `delivery-timeout`이 그대로 client 설정이 된다.
|
||||
`spring.kafka.bootstrap-servers`는 읽지 않는다. type이 `kafka`인 항목이 정확히 하나가 아니면 기동에
|
||||
실패한다. `send()`가 metadata를 기다리며 호출 스레드를 막는 시간(`max.block.ms`)은 기본 publish
|
||||
timeout(5s)이다.
|
||||
|
||||
## 보안
|
||||
|
||||
```yaml
|
||||
app:
|
||||
messaging:
|
||||
security:
|
||||
kafka-primary:
|
||||
producer: { type: SASL_SCRAM, credential-id: kafka-producer }
|
||||
consumer: { type: SASL_SCRAM, credential-id: kafka-consumer }
|
||||
# admin은 application runtime에 설정하지 않는다
|
||||
hostname-verification: true
|
||||
# 사설 CA로 서명된 TLS 브로커면(tls-enabled: true일 때만):
|
||||
# trust-store: { location: /etc/kafka/ca.p12, type: PKCS12, password-credential-id: kafka-truststore }
|
||||
access:
|
||||
publishable: [order-events]
|
||||
consumable: []
|
||||
administrable: []
|
||||
```
|
||||
|
||||
키는 `app.messaging.brokers`에 선언된 브로커 이름과 같아야 한다. `tls-enabled`와 `production`은
|
||||
브로커 쪽에만 있고 여기에 중복되지 않는다 — 하나의 브로커가 두 곳에서 기술되면 두 값이 어긋나는
|
||||
날이 오고, 어느 쪽이 이기는지는 아무도 모른다.
|
||||
|
||||
`credential-id`는 이름일 뿐이고 자격 증명 자체가 아니다. 실제 재료는 `CredentialProvider`가
|
||||
연결 시점에 해석하므로, 설정 덤프나 힙 덤프에서 나오는 것은 이름뿐이다. producer와 consumer는
|
||||
서로 다른 `credential-id`를 써야 하며, 같으면 부팅에 실패한다.
|
||||
|
||||
`SASL_SCRAM`·`USERNAME_PASSWORD`의 사용자 이름은 `CredentialProvider.username(credentialId)`가
|
||||
준다. credential id를 사용자 이름으로 보내지 않는다. 비밀번호와 사용자 이름은 JAAS 문자열에 들어가지
|
||||
않고, 연결이 인증할 때마다 provider에서 읽힌다. 그래서 provider가 만료 시각을 주는 credential은
|
||||
재기동 없이 rotation된다(`security.md`).
|
||||
|
||||
`MUTUAL_TLS`는 클라이언트 인증서를 key store로 제출한다. `credential-id`는 key store 비밀번호를
|
||||
가리킨다.
|
||||
|
||||
```text
|
||||
producer:
|
||||
type: MUTUAL_TLS
|
||||
credential-id: kafka-producer-tls # key store 비밀번호
|
||||
key-store: { location: /etc/kafka/producer.p12, type: PKCS12 }
|
||||
```
|
||||
|
||||
`trust-store`를 생략하면 JVM 기본 trust store를 쓴다. 사설 CA 브로커는 `trust-store.location`
|
||||
(PKCS12·JKS·PEM)과, 잠긴 store면 `password-credential-id`를 준다.
|
||||
|
||||
Kafka producer는 이 항목을 실제 클라이언트 설정(`security.protocol`, `sasl.mechanism`,
|
||||
`sasl.jaas.config`, `sasl.client.callback.handler.class`, `ssl.truststore.*`, `ssl.keystore.*`,
|
||||
`ssl.enabled.protocols=TLSv1.3,TLSv1.2`, hostname 검증)으로 옮긴다. 평문으로 조용히 넘어가지
|
||||
않도록 다음 경우 부팅에 실패한다: 브로커가 `tls-enabled`나 `authentication-enabled`를 켰는데
|
||||
`app.messaging.security.<broker>`가 없을 때, security 항목은 있는데 `CredentialProvider` bean이 없을
|
||||
때, 같은 브로커에 맞는 항목이 둘 이상일 때, provider가 SASL 사용자 이름을 주지 않을 때,
|
||||
`MUTUAL_TLS`인데 `key-store`가 없거나 `tls-enabled`가 꺼져 있을 때, `trust-store`를 줬는데
|
||||
`tls-enabled`가 꺼져 있을 때, store 파일을 열 수 없을 때.
|
||||
|
||||
`access.publishable`은 강제된다. security 항목이 있는 브로커의 destination은 이 목록에 있어야
|
||||
publish된다. 목록 밖 publish는 `REJECTED`(`PUBLISH_FORBIDDEN`)이고, 빈 목록이면 아무것도 publish되지
|
||||
않는다.
|
||||
|
||||
## Backpressure
|
||||
|
||||
```yaml
|
||||
app:
|
||||
messaging:
|
||||
backpressure:
|
||||
global-limit: 512
|
||||
per-destination-limit: 64 # global-limit 이하여야 한다
|
||||
```
|
||||
|
||||
`per-destination-limit > global-limit`이면 global limit이 limit이 아니게 되므로 부팅에 실패한다.
|
||||
|
||||
## 바인딩되지 않는 키
|
||||
|
||||
섹션은 바인딩되는데 그 안의 키 하나가 오타인 경우는 접두사 오타와 달리 조용하다 — 섹션은 붙고,
|
||||
플랫폼은 뜨고, 바꾸러 온 그 설정만 적용되지 않는다. `MessagingConfigurationKeyValidator`가
|
||||
`app.messaging.destinations|brokers|security` 아래의 모든 키를 settings 레코드에서 파생한 목록과
|
||||
대조하고, 없는 키는 그 키 이름을 담아 부팅을 거절한다.
|
||||
|
||||
허용 키 목록은 이 문서가 아니라 레코드에서 나온다. 문서에 목록을 적으면 필드가 추가된 날 그
|
||||
목록이 틀리고, 오타를 잡으라고 만든 검사가 정상 필드를 거절하게 된다.
|
||||
|
||||
환경변수(`APP_MESSAGING_...`)는 이 검사의 대상이 아니다. `APP_MESSAGING_DESTINATIONS_ORDER_EVENTS_
|
||||
CONSUMER_PREFETCH`에서 entry 이름과 leaf를 가르는 밑줄은 둘 안에 있는 밑줄과 구별되지 않으므로,
|
||||
되돌려 쪼개려면 추측해야 한다. 여기서의 추측은 정상 배포를 거절하는 쪽으로 틀리며, 그것은 배포
|
||||
매니페스트에 손으로 적어야 하는 변수에서 오타 하나를 놓치는 것보다 나쁘다.
|
||||
@@ -1,35 +0,0 @@
|
||||
# 기존 runtime → 신규 messaging platform cutover (MSG-015)
|
||||
|
||||
## 왜 기계적 매핑이 안 되는가
|
||||
|
||||
두 outbox 모델의 enum 이름이 겹치는데 의미가 반대다.
|
||||
|
||||
| 모델 | retryable | terminal |
|
||||
|---|---|---|
|
||||
| 기존 `OutboxEventStatus` | `FAILED` (`next_attempt_at` 보유) | `DEAD` |
|
||||
| 신규 `OutboxStatus` | `AMBIGUOUS` | `FAILED`, `EXHAUSTED` |
|
||||
|
||||
이름으로 매핑하면 **확정 거절이 무한 재시도**가 되고 **불확정이 park**된다. 그래서 application은
|
||||
자기 어휘(`OutboxPublishOutcome`)만 쓰고, 변환은 bridge adapter가 한다.
|
||||
|
||||
## 지금 반영된 것
|
||||
|
||||
- `OutboxPublishOutcome` — `CONFIRMED` / `AMBIGUOUS` / `REJECTED_BEFORE_SEND` /
|
||||
`REJECTED_AFTER_BROKER`. application이 소유하는 canonical 결과 타입이며, "리턴 or throw"만 가능한
|
||||
기존 어댑터를 위해 `OutboxMessagePublishPort.publishForOutcome`의 default가 `CONFIRMED`를 돌려준다.
|
||||
- `APPLICATION_DOES_NOT_DEPEND_ON_THE_MESSAGING_PLATFORM` ArchUnit 규칙 — application-core가
|
||||
`dev.caskeleton.messaging..`를 import하면 빌드가 깨진다.
|
||||
- 반대 방향(신규 `PublishResult` → application outcome) 매핑 규칙을 테스트로 고정.
|
||||
|
||||
## 남은 것
|
||||
|
||||
- `messaging-platform-bridge` outbound leaf: validated application event → platform envelope,
|
||||
`PublishResult` → `OutboxPublishOutcome`. registry에 leaf를 추가하는 변경이라 별도 커밋.
|
||||
- golden contract 테스트: event/message ID, type, schema revision, partition/order/correlation/
|
||||
causation/tenant/trace, payload digest, wire version이 bytes 단위로 보존되는지.
|
||||
- 단일 publication authority: writer/relay가 동시에 ACTIVE가 되지 않도록 하는 fence. 이 용도로 쓰려던
|
||||
outbox V2의 `OutboxPublicationAuthority`는 한 번도 조립되지 않은 채 2026-09-25에 삭제됐으므로
|
||||
(`docs/capability-status.md` "제거된 코드") cutover가 자기 fence를 새로 가져야 한다. **dual write/publish는 금지** — 한 business fact가 두 durable store와
|
||||
두 relay로 나가는 상태가 cutover에서 가장 위험하다.
|
||||
- 첫 cutover 범위는 **transport만** 교체(저장소는 기존 유지). storage migration은 shadow read →
|
||||
authority switch → old backlog drain 순서로 별도 release.
|
||||
@@ -1,80 +0,0 @@
|
||||
# 전달 보장
|
||||
|
||||
## 왜 `EXACTLY_ONCE`가 없는가
|
||||
|
||||
어떤 브로커도 **외부 side effect를 포함한** exactly-once를 제공하지 않는다.
|
||||
실제로 존재하는 것은 at-least-once 전달 + 멱등하거나 transactional한 consumer의 조합이다.
|
||||
|
||||
플랫폼이 지킬 수 없는 이름을 enum에 두면 그 책임이 눈에 보이지 않는 곳으로 밀려난다.
|
||||
그래서 `DeliveryGuarantee`는 증거가 끝나는 지점에서 멈춘다.
|
||||
|
||||
```java
|
||||
public enum DeliveryGuarantee { AT_MOST_ONCE, AT_LEAST_ONCE }
|
||||
```
|
||||
|
||||
## Publish 결과는 boolean이 아니다
|
||||
|
||||
```java
|
||||
public enum PublishCompletion { CONFIRMED, REJECTED, AMBIGUOUS }
|
||||
```
|
||||
|
||||
`REJECTED`와 `AMBIGUOUS`를 하나의 "실패"로 합치면 중복 주문이 만들어진다.
|
||||
전자는 broker가 저장하지 않았음이 **확정**되어 중복 걱정 없이 다시 보내거나 포기할 수 있고, 후자는 그렇지 않다.
|
||||
|
||||
`REJECTED`가 곧 "포기해도 된다"는 뜻은 아니다. 거부 이유가 그 순간에 속하면(종료 중
|
||||
`SHUTTING_DOWN`, permit 대기 초과, `PUBLISH_RUNTIME_UNAVAILABLE`, `KAFKA_TRANSPORT_CLOSED`, Kafka
|
||||
인증·인가 실패) `failure().retryable()`이 true이고, 호출자는 같은 메시지를 나중에 다시 보내야 한다.
|
||||
포기해도 되는 것은 `retryable=false`인 거부뿐이다.
|
||||
|
||||
| 상황 | 결과 |
|
||||
|---|---|
|
||||
| 로컬 validation 실패 | `REJECTED`, `NOT_TRANSMITTED` |
|
||||
| broker 명시적 reject / nack | `REJECTED` |
|
||||
| confirm 수신 | `CONFIRMED` |
|
||||
| Rabbit confirm + unroutable return | `REJECTED`, `UNROUTABLE` |
|
||||
| bytes 전송 후 connection loss | `AMBIGUOUS` |
|
||||
| confirm timeout | `AMBIGUOUS` |
|
||||
| adapter가 판정 불가 | 보수적으로 `AMBIGUOUS` |
|
||||
|
||||
`PublishResult` 생성자가 이 규칙을 강제한다. `CONFIRMED`인데 broker acceptance가 없거나,
|
||||
`AMBIGUOUS`인데 confirmation level을 주장하면 **객체 생성 자체가 실패**한다.
|
||||
|
||||
## Ordering
|
||||
|
||||
```java
|
||||
public enum OrderingScope { NONE, DESTINATION, PARTITION, KEY }
|
||||
```
|
||||
|
||||
순서는 partition·key·단일 consumer의 성질이지 destination 전체의 성질이 아니다.
|
||||
`GLOBAL`이 없는 이유가 이것이다.
|
||||
|
||||
`DestinationProfileValidator`가 다음을 거부한다.
|
||||
|
||||
- `ordering=KEY`인데 key resolver 없음
|
||||
- ordered destination인데 `ALLOW_REORDER` retry
|
||||
- `orderingImpact=PRESERVE`인데 재발행형 retry(`RETRY_DESTINATION`, `BROKER_DELAYED`)
|
||||
- `ordering=DESTINATION`인데 concurrency > 1
|
||||
- ordered destination인데 ordering unit당 in-flight > 1
|
||||
|
||||
## External side effect
|
||||
|
||||
```java
|
||||
public enum ExternalSideEffectGuarantee { NONE, IDEMPOTENCY_REQUIRED, INBOX_TRANSACTIONAL }
|
||||
```
|
||||
|
||||
`INBOX_TRANSACTIONAL`만이 "DB side effect와 중복 차단이 같은 transaction에서 commit된다"를 의미한다.
|
||||
Kafka transaction은 **Kafka 안에서만** 원자적이므로 이 값과 함께 설정하면
|
||||
`KafkaTransactionProfileValidator`가 거부한다. 두 개의 독립적인 commit을 하나로 착각하게 두지 않기 위해서다.
|
||||
|
||||
## Consumer settlement 순서
|
||||
|
||||
```text
|
||||
RECEIVED → DECODING → PROCESSING → HANDLER_SUCCEEDED → SETTLEMENT_SENDING
|
||||
├→ SETTLED
|
||||
└→ SETTLEMENT_UNKNOWN
|
||||
```
|
||||
|
||||
- handler는 broker ACK API를 호출하지 않는다.
|
||||
- `Success` 이후에만 source settlement한다.
|
||||
- `SETTLEMENT_UNKNOWN`은 성공이 아니다. redelivery 가능성을 의미한다.
|
||||
- `SettlementResult` 생성자가 `SETTLED`인데 `redeliveryPossible=true`인 조합을 거부한다.
|
||||
@@ -1,58 +0,0 @@
|
||||
# Experimental 정책
|
||||
|
||||
## Stable과 Experimental의 차이
|
||||
|
||||
**Stable**은 공통 Contract Suite(`MessagingAdapterContract`)를 변경 없이 통과한 어댑터다.
|
||||
컴파일되는 어댑터가 아니라, 아래 7가지를 실제로 증명한 어댑터다.
|
||||
|
||||
```text
|
||||
publishesAndConfirms
|
||||
returnsAmbiguousWhenConfirmIsLost
|
||||
redeliversWhenSettlementIsLost
|
||||
preservesMessageIdAcrossRetryAndDlq
|
||||
keepsSourceUnsettledWhenDlqPublishFails
|
||||
rejectsOversizedPayloadBeforeTransport
|
||||
stopsAcceptingNewWorkDuringShutdown
|
||||
```
|
||||
|
||||
**Experimental**은 아직 그 증명이 끝나지 않은 어댑터다.
|
||||
|
||||
현재 Experimental 어댑터는 없다. Kafka Share Group·Pulsar·NATS JetStream(Experimental), RabbitMQ,
|
||||
Spring Cloud Stream bridge(Optional)는 SDK 없는 seam이거나 선택할 수 없는 상태여서 2026-09-25에
|
||||
삭제했다(`docs/capability-status.md` 제거 표). 이 문서는 새 어댑터를 들일 때 지킬 규칙이다.
|
||||
|
||||
## 규칙
|
||||
|
||||
### 1. 기본 비활성
|
||||
|
||||
새 Experimental 어댑터는 자기 활성화 플래그를 가지고 기본값은 `false`다.
|
||||
활성화하지 않으면 validator가 `MessagingCapabilityUnavailableException`을 던진다.
|
||||
Contract Suite가 아직 증명 중인 어댑터가 누군가의 기본 설정 때문에 load-bearing이 되어서는 안 된다.
|
||||
|
||||
### 2. Stable 모듈이 Experimental 모듈에 의존하지 않는다
|
||||
|
||||
Gradle 의존 그래프로 강제된다. Experimental leaf는 `messaging-spring-boot-starter`의
|
||||
`allowed_dependencies`에 넣지 않는다.
|
||||
|
||||
`verifyCleanArchitectureDependencies`가 위반을 빌드 실패로 만든다.
|
||||
|
||||
### 3. Core 계약을 바꾸지 않는다
|
||||
|
||||
Experimental 어댑터는 브로커의 차이를 `MessagingCapabilities`로 표현할 뿐,
|
||||
`messaging-core-api`의 타입을 바꾸지 않는다.
|
||||
|
||||
### 4. 없는 기능을 광고하지 않는다
|
||||
|
||||
Contract Suite로 증명하지 않은 capability는 `MessagingCapabilities`에서 `false`로 둔다.
|
||||
`false`인 capability를 요구하는 profile은 startup에서 실패한다. 조용히 약화되지 않는다.
|
||||
|
||||
## 승격 조건
|
||||
|
||||
Experimental → Stable로 올리려면 전부 필요하다.
|
||||
|
||||
1. `MessagingAdapterContract` 7개 테스트를 변경 없이 통과
|
||||
2. 장애 주입(연결 끊김, confirm 유실, settlement 유실) 하에서 통과
|
||||
3. 지원 브로커 버전 범위 명시 및 CI 검증
|
||||
4. `support-matrix.md`의 capability 표 갱신
|
||||
5. ADR 작성
|
||||
6. 기본 활성화 여부에 대한 별도 결정
|
||||
@@ -1,126 +0,0 @@
|
||||
# 마이그레이션 가이드
|
||||
|
||||
## 기존 Spring Kafka / Spring AMQP 코드에서
|
||||
|
||||
### 1. topic 이름을 코드에서 제거한다
|
||||
|
||||
```java
|
||||
// before
|
||||
kafkaTemplate.send("order.events.v1", key, payload);
|
||||
|
||||
// after
|
||||
publisher.publish(orderEvents, envelope, PublishOptions.defaults());
|
||||
```
|
||||
|
||||
`MessageDestination`은 logical name만 가진다. 물리 매핑은 destination profile이 소유한다.
|
||||
`DestinationName`의 패턴이 `topic://orders` 같은 값을 거부하므로 우회할 수 없다.
|
||||
|
||||
### 2. boolean 성공 판정을 없앤다
|
||||
|
||||
```java
|
||||
// before
|
||||
try { template.send(...).get(); success(); }
|
||||
catch (Exception e) { fail(); } // REJECTED와 AMBIGUOUS를 구분하지 못한다
|
||||
|
||||
// after
|
||||
PublishResult result = ...;
|
||||
switch (result.completion()) {
|
||||
case CONFIRMED -> success();
|
||||
case REJECTED -> abandon(); // broker가 저장하지 않음이 확정
|
||||
case AMBIGUOUS -> retrySameMessageId(result); // broker가 가지고 있을 수 있음
|
||||
}
|
||||
```
|
||||
|
||||
이 구분이 없으면 confirm 유실 한 번이 중복 주문 하나가 된다.
|
||||
|
||||
### 3. auto-commit / auto-ack를 끈다
|
||||
|
||||
```yaml
|
||||
# Kafka
|
||||
enable.auto.commit: false
|
||||
# RabbitMQ
|
||||
auto-ack: false
|
||||
```
|
||||
|
||||
둘 다 validator가 강제로 거부한다. 타이머 기반 commit은 handler가 실행되기도 전에
|
||||
메시지를 처리 완료로 표시한다.
|
||||
|
||||
### 4. handler에서 ack 호출을 제거한다
|
||||
|
||||
```java
|
||||
// before
|
||||
@KafkaListener(...)
|
||||
void handle(ConsumerRecord<?,?> record, Acknowledgment ack) {
|
||||
process(record);
|
||||
ack.acknowledge(); // 실패 시 순서가 애매해진다
|
||||
}
|
||||
|
||||
// after
|
||||
CompletionStage<HandleResult> handle(MessageDelivery<OrderCreated> delivery) {
|
||||
process(delivery.message().payload());
|
||||
return completedFuture(HandleResult.success());
|
||||
}
|
||||
```
|
||||
|
||||
settlement는 플랫폼이 수행한다. "성공한 뒤에만 ack"가 각 handler의 기억이 아니라
|
||||
플랫폼 불변식이 된다.
|
||||
|
||||
### 5. 중복을 정상 상황으로 다룬다
|
||||
|
||||
at-least-once는 중복을 전제한다. 세 가지 중 하나를 고른다.
|
||||
|
||||
| 방식 | 언제 |
|
||||
|---|---|
|
||||
| handler 자체 멱등 | 자연 멱등 연산 (upsert 등) |
|
||||
| Inbox | DB side effect가 있는 경우 |
|
||||
| Kafka transaction | Kafka → Kafka 파이프라인만 |
|
||||
|
||||
`ExternalSideEffectGuarantee`에 선언한다. `INBOX_TRANSACTIONAL`과 Kafka transaction을
|
||||
동시에 설정하면 거부된다. Kafka transaction은 DB를 포함하지 않는다.
|
||||
|
||||
### 6. 큰 payload는 Claim Check로
|
||||
|
||||
broker frame 크기를 키우지 않는다. broker 메모리, replication latency,
|
||||
consumer recovery가 동시에 나빠지고, 유계·검증 가능한 실패가 무계 실패로 바뀐다.
|
||||
|
||||
1 MiB 초과는 외부 저장소로 offload하고 digest를 포함한 참조만 발행한다.
|
||||
|
||||
## DB 마이그레이션
|
||||
|
||||
```text
|
||||
V1001__messaging_outbox.sql
|
||||
V1002__messaging_outbox_lease_fencing.sql
|
||||
V1003__messaging_admin_operation_journal.sql
|
||||
V1004__messaging_outbox_canonical_metadata.sql
|
||||
V1101__messaging_inbox.sql
|
||||
```
|
||||
|
||||
Messaging owns Flyway versions `1000..1999`. The starter assembles both JDBC reliability modules,
|
||||
so their migrations deliberately share `classpath:db/migration/messaging` but must never reuse a
|
||||
version. Keeping them in this reserved range also prevents collisions with the application's
|
||||
ordinary `db/migration/postgresql` stream, whose low-numbered versions are independent.
|
||||
|
||||
When adopting outbox/inbox persistence, add `classpath:db/migration/messaging` to the deployment's
|
||||
Flyway locations together with its normal application migration location. Do not copy or renumber
|
||||
these files into the application's low-numbered stream; the reserved range is the namespace
|
||||
boundary.
|
||||
|
||||
Outbox row는 business transaction과 같은 transaction에서 쓴다.
|
||||
Inbox reservation은 handler side effect와 같은 transaction에서 쓴다.
|
||||
별도 transaction이면 각 패턴이 닫으려던 창이 그대로 열려 있다.
|
||||
|
||||
## 단계적 전환
|
||||
|
||||
1. **publish만 전환** — 기존 consumer는 그대로. wire format은 reserved header가 추가될 뿐이다.
|
||||
2. **Outbox 도입** — publish 유실 창을 닫는다.
|
||||
3. **consume 전환** — handler를 `MessageHandler`로 옮기고 ack 호출을 제거한다.
|
||||
4. **Inbox 도입** — 중복 side effect를 닫는다.
|
||||
5. **retry·DLQ 정책 선언** — 이 시점까지 자동 retry는 0회다.
|
||||
|
||||
각 단계는 독립적으로 배포 가능하고, 되돌릴 수 있다.
|
||||
|
||||
## 되돌릴 수 없는 것
|
||||
|
||||
- 한 번 발행된 message type의 wire contract
|
||||
- 이미 retention 안에 있는 메시지의 schema
|
||||
- redrive된 메시지의 `messageId` (바뀌지 않는다 — 이것이 의도다)
|
||||
@@ -1,112 +0,0 @@
|
||||
# 운영 Runbook
|
||||
|
||||
## 배포 전 체크
|
||||
|
||||
```bash
|
||||
./gradlew architectureCheck --console=plain
|
||||
./gradlew checkstyleMain --console=plain
|
||||
```
|
||||
|
||||
destination profile은 startup에서 검증된다. 아래는 **부팅 실패**다.
|
||||
|
||||
- ordered destination + reorder 가능 retry
|
||||
- `ordering=KEY` + key resolver 없음
|
||||
- payload 상한 > 8,388,608 bytes
|
||||
- DLQ 자기 참조 / retry 자기 참조
|
||||
- retry·DLQ 그래프 cycle
|
||||
- 미등록 retry·DLQ destination
|
||||
- M1 destination + manual settlement
|
||||
- `AT_LEAST_ONCE` + confirmation `NONE`
|
||||
- production profile + topology auto-create
|
||||
- broker topology가 manifest와 불일치
|
||||
|
||||
## 증상별 대응
|
||||
|
||||
### publish가 AMBIGUOUS로 쏟아진다
|
||||
|
||||
broker confirm 경로 문제다. 실패가 아니다.
|
||||
|
||||
1. `PublishEvidence.transmission`이 `MAY_HAVE_BEEN_TRANSMITTED`인지 확인
|
||||
2. Kafka: `delivery.timeout.ms`, ISR 상태, leader election 확인
|
||||
3. Rabbit: confirm timeout, channel 상태 확인
|
||||
4. Outbox를 쓰고 있다면 `status='AMBIGUOUS'` row가 같은 messageId로 재시도 중이다. **정상이다.**
|
||||
5. consumer 쪽 Inbox가 중복을 흡수하는지 확인
|
||||
|
||||
`AMBIGUOUS`를 실패로 취급해 새 messageId로 재발행하지 말 것. 중복이 복구 불가능해진다.
|
||||
|
||||
### DLQ가 비어 있는데 메시지가 사라졌다
|
||||
|
||||
DLQ publish 실패 시 source는 settlement되지 않는다. 메시지는 source에 남아 재전달된다.
|
||||
|
||||
1. `msg.failure-code`가 `DEAD_LETTER_*`인 로그 확인
|
||||
2. DLQ destination이 실제로 존재하는지 (topology validation)
|
||||
3. DLQ credential에 publish 권한이 있는지
|
||||
|
||||
### consumer lag이 한 partition에서만 증가한다
|
||||
|
||||
`ContiguousPartitionOffsetTracker`가 gap에서 멈춘 것이다. 설계된 동작이다.
|
||||
|
||||
commit은 **연속** 완료 offset까지만 전진한다. offset 11이 아직 실행 중이면
|
||||
10과 12가 끝나도 watermark는 10에 머문다. 12를 commit하면 consumer가 죽었을 때 11을 잃는다.
|
||||
|
||||
1. 해당 partition의 in-flight를 확인
|
||||
2. 느린 handler를 찾는다 (`handlerTimeout` 초과 여부)
|
||||
3. 필요하면 `PAUSE_PARTITION` retry가 걸려 있는지 확인
|
||||
|
||||
### 재시도 폭풍
|
||||
|
||||
`RetryPolicy.jitter=false`인지 확인한다. jitter 없이는 같은 초에 실패한 모든 consumer가
|
||||
같은 초에 재시도한다.
|
||||
|
||||
### shutdown이 오래 걸린다
|
||||
|
||||
`GracefulShutdownCoordinator`가 in-flight를 기다리는 중이다.
|
||||
|
||||
- `inFlight()`가 0이 되면 즉시 종료
|
||||
- drain deadline(기본 30초) 초과 시 남은 작업을 **unsettled로 포기**한다 → broker가 재전달
|
||||
- draining 시작 후 새 retry attempt는 만들지 않는다
|
||||
|
||||
## Destructive 작업
|
||||
|
||||
전부 `DestructiveOperationGuard`를 통과해야 한다.
|
||||
|
||||
| 조건 | 요구 |
|
||||
|---|---|
|
||||
| admin credential | application runtime은 보유하지 않음 |
|
||||
| `AdminApproval` | 유효기간 내 |
|
||||
| dry-run | 항상 허용 |
|
||||
|
||||
### Replay
|
||||
|
||||
```text
|
||||
기본: 격리된 consumer group (replay-<requestId>)
|
||||
기존 group 대상: 승인 티켓 필수
|
||||
```
|
||||
|
||||
기존 production group으로 replay하는 것은 "다시 읽기"가 아니라 **live consumer를 되감는 것**이다.
|
||||
그 사이의 모든 것이 재처리된다.
|
||||
|
||||
### Redrive
|
||||
|
||||
```text
|
||||
dry-run으로 후보 수 확인
|
||||
→ 승인 획득
|
||||
→ batch 100건 이하로 실행
|
||||
→ republish CONFIRMED 인 것만 DLQ에서 settlement
|
||||
```
|
||||
|
||||
`redriveId`로 재구동 루프를 추적한다. 같은 메시지가 반복해서 redrive되면
|
||||
근본 원인이 해결되지 않은 것이다.
|
||||
|
||||
### Offset reset
|
||||
|
||||
`KafkaOffsetResetExecutor`는 승인 predicate를 **생성자 인자**로 받는다.
|
||||
승인 소스 없이 조립된 runtime은 물리적으로 reset을 수행할 수 없다.
|
||||
|
||||
## Topology
|
||||
|
||||
production topology는 IaC가 만들고 애플리케이션은 **검증만** 한다.
|
||||
|
||||
`TopologyValidationRuntime`은 모든 불일치를 한 번에 보고하고 startup을 실패시킨다.
|
||||
partition 수가 다르면 destination이 광고하는 ordering 보장이 달라지고,
|
||||
`min.insync.replicas`가 없으면 `acks=all`의 의미가 달라진다.
|
||||
@@ -1,192 +0,0 @@
|
||||
# Outbox · Inbox
|
||||
|
||||
> **이 문서의 Outbox는 vendored messaging platform의 outbox다**(`messaging_outbox` 표,
|
||||
> `messaging-reliability`의 `OutboxRelay`). 이 템플릿 application이 쓰는 outbox는 그것이 아니다.
|
||||
> application은 `outbox_event` 표(`adapter:outbound:persistence-jpa`)에 append하고, relay는
|
||||
> `composition:outbox-relay`가 돌린다. 그 동작과 운영은 `docs/manual/09-outbox-events.md`,
|
||||
> `src/composition/outbox-relay/README.md`, `docs/runbooks/outbox-dead-letter.md`,
|
||||
> `docs/runbooks/outbox-publish-failed.md`에 있다. platform outbox는 소유자 결정으로 제품 안에 남아
|
||||
> 있지만, platform outbox repository bean이 없으면 그 relay는 만들어지지 않는다(리뷰 2026-11-01 06-11).
|
||||
>
|
||||
> 두 모델은 같은 이름의 상태가 반대 뜻이다. 이름으로 옮기면 확정 거부는 영원히 재시도되고 응답 없는
|
||||
> 메시지는 버려진다. 대응은 아래 표 하나로만 읽는다(`OutboxPublishOutcome` Javadoc과 같은 내용).
|
||||
>
|
||||
> | 일어난 일 | application `outbox_event` | platform `messaging_outbox` |
|
||||
> |---|---|---|
|
||||
> | broker가 확인했다 | `PUBLISHED` | `PUBLISHED` |
|
||||
> | 응답이 없었다(저장됐을 수 있음) | `FAILED`(재시도, 예산 안 씀, 끝 없음) | `AMBIGUOUS`(재시도, 예산을 다 쓰면 `EXHAUSTED`) |
|
||||
> | 지금만 거부됐다(종료·포화·credential) | `FAILED`(재시도, 예산 안 씀, 끝 없음) | `FAILED`(종단) |
|
||||
> | 확정 거부됐다(같은 payload는 또 거부) | `DEAD`(종단, 수동 처분) | `FAILED`(종단) |
|
||||
> | publisher가 예외를 던졌고 시도 예산을 다 썼다 | `DEAD`(종단, 수동 처분) | `EXHAUSTED`(종단) |
|
||||
> | 운영자가 재시도를 멈췄다 | `PARKED`(수동 재개·skip) | 없음 |
|
||||
>
|
||||
> **이 템플릿 application의 소비 경로**: application의 `MessageHandler`와 inbox 부품(애플리케이션
|
||||
> DataSource 위 `JdbcInboxRepository`, `PlatformTransactionManager` 위 `TransactionRunner`)은
|
||||
> `adapter:inbound:messaging`(`src/adapter/inbound/messaging/README.md`)이 둔다. platform starter는 두
|
||||
> bean이 있을 때 `IdempotentConsumer`를 만들어 `INBOX_TRANSACTIONAL` destination의 handler를 감싼다.
|
||||
> 그 leaf는 inbox 마이그레이션(`V1101`)만 자기 history 표로 적용하므로, 아래 "location 추가"는 platform
|
||||
> outbox를 쓰는 배포의 이야기다. payload decode 목록은 handler bean의 선언으로 만든다.
|
||||
|
||||
## 두 패턴이 각각 무엇을 해결하는가
|
||||
|
||||
| 패턴 | 해결하는 문제 | 해결하지 않는 문제 |
|
||||
|---|---|---|
|
||||
| Transactional Outbox | DB commit과 publish 사이의 창(窓) | 중복 |
|
||||
| Inbox | 중복 delivery의 side effect | 유실 |
|
||||
|
||||
**둘 다 필요하다.** Outbox만으로는 exactly-once가 되지 않는다.
|
||||
|
||||
## 채택할 때 먼저 적용할 DB migration
|
||||
|
||||
Outbox/Inbox JDBC 모듈의 DDL은 `classpath:db/migration/messaging`에 있다. Messaging은
|
||||
Flyway version `1000..1999`를 예약해서 애플리케이션의 일반적인 저번호 migration과 버전이
|
||||
겹치지 않게 한다.
|
||||
|
||||
배포에서 이 JDBC 구현을 채택할 때는 기존 Flyway location에 다음 location을 **추가**한다.
|
||||
|
||||
```text
|
||||
classpath:db/migration/messaging
|
||||
```
|
||||
|
||||
현재 순서는 `V1001..V1005`(outbox/admin)와 `V1101`(inbox)이고, 모두
|
||||
`messaging-reliability-jdbc-postgresql`에 있다. starter 테스트가 그 모듈을 실제 combined classpath로 올려 version 중복과 예약 대역 이탈을 검사한다. 개별 DDL의
|
||||
의미와 전환 순서는 [migration-guide.md](migration-guide.md)를 따른다.
|
||||
|
||||
## Outbox
|
||||
|
||||
business transaction과 **같은 transaction**에서 row를 쓴다. 둘 다 commit되거나 둘 다 안 된다.
|
||||
|
||||
```sql
|
||||
BEGIN;
|
||||
UPDATE orders SET status = 'PLACED' WHERE id = ?;
|
||||
INSERT INTO messaging_outbox (message_id, destination, ...) VALUES (?, ?, ...);
|
||||
COMMIT;
|
||||
```
|
||||
|
||||
### relay
|
||||
|
||||
```text
|
||||
claimBatch(owner, 100, 30s, now, maxAttempts) -- owner + fencing token으로 다중 relay 인스턴스 안전
|
||||
→ publish (messageId 그대로)
|
||||
→ CONFIRMED → markPublished
|
||||
→ AMBIGUOUS → markAmbiguous (같은 messageId로 재시도 가능)
|
||||
→ REJECTED → markFailed
|
||||
```
|
||||
|
||||
row 하나의 실패는 그 row에서 끝난다. envelope로 만들 수 없는 row(예약 header `msg.*`를 담은 row
|
||||
등)는 `FAILED`가 되고, publisher가 예외를 던지면 결과를 모르므로 `AMBIGUOUS`가 된다. 같은 batch의
|
||||
나머지 row는 그대로 publish된다. pass 전체가 실패하면(DB 연결 등) WARN 로그를 남기고
|
||||
`messaging.outbox.relay.failed.passes` 카운터를 올린다.
|
||||
|
||||
### 핵심 규칙: ambiguous는 같은 messageId로 재시도
|
||||
|
||||
새 id를 발급하면 "전달됐을 수도 있는 메시지"가 "확실히 두 번째인 메시지"가 되어
|
||||
downstream의 어떤 중복 제거도 복구할 수 없다.
|
||||
failed로 표시하면 broker가 이미 가지고 있을 수 있는 메시지를 잃는다.
|
||||
|
||||
`message_id`를 primary key로 둔 것도 같은 이유다. 어떤 코드 경로도 실수로 새 id를 붙일 수 없다.
|
||||
|
||||
### lease
|
||||
|
||||
```text
|
||||
status IN ('PENDING','AMBIGUOUS','IN_FLIGHT')
|
||||
AND (lease_expires_at IS NULL OR lease_expires_at <= now)
|
||||
AND next_attempt_at <= now
|
||||
AND attempts < maxAttempts
|
||||
AND (ordering_key IS NULL
|
||||
OR 같은 destination·ordering_key의 더 오래된 미완료 row가 없음)
|
||||
```
|
||||
|
||||
`ordering_key`가 있는 row는 같은 key의 더 오래된 row가 `PENDING`·`AMBIGUOUS`·`IN_FLIGHT`인 동안
|
||||
claim되지 않는다. 이 조건이 없으면 두 relay가 같은 key의 두 row를 나눠 가져가거나, AMBIGUOUS로
|
||||
재시도되는 row보다 뒤의 row가 먼저 나간다(`OutboxPostgresIT#aNewerRowWaitsWhileAnOlderRowWithTheSameOrderingKeyIsUnfinished`).
|
||||
`V1005`의 partial index가 이 확인을 받친다. 더 오래된 row가 `FAILED`·`EXHAUSTED`가 되면 뒤의 row는
|
||||
진행한다.
|
||||
|
||||
`IN_FLIGHT`가 목록에 있는 것이 핵심이다. relay가 publish 도중 죽으면 row는 `IN_FLIGHT`로 남는데,
|
||||
이를 제외하면 그 메시지는 **영원히** 발행되지 않는다 — outbox가 막으려던 바로 그 실패다. 대신
|
||||
lease가 만료됐을 때만 회수하므로, 살아 있는 relay가 들고 있는 row는 회수되지 않는다.
|
||||
|
||||
회수는 **같은 `message_id`로** 이루어지고 `lease_token`이 1 증가한다. 새 id를 발급하면 "전달됐을
|
||||
수도 있는 메시지"가 "확실히 두 번째"가 되기 때문이다 (위의 AMBIGUOUS 논의와 같은 이유).
|
||||
|
||||
이 문단의 근거는 실제 PostgreSQL 컨테이너 레인이다:
|
||||
|
||||
- `OutboxPostgresIT#anExpiredLeaseBecomesClaimableAgain` — 만료된 lease의 재회수
|
||||
- `OutboxPostgresIT#anExpiryReclaimKeepsTheMessageIdAndAdvancesTheToken` — 같은 id, 증가한 token
|
||||
- `OutboxPostgresIT#aLeasedRowIsInvisibleToASecondRelayInstance` — 살아 있는 lease는 회수 불가
|
||||
- `OutboxPostgresIT#aSupersededRelayCannotOverwriteTheOutcomeOfTheOneThatReplacedIt` — fencing
|
||||
|
||||
partial index `ix_messaging_outbox_claimable`이 이 쿼리를 backlog 크기에 비례하게 유지한다.
|
||||
PUBLISHED row는 retention job이 지울 때까지 쌓이기 때문이다.
|
||||
|
||||
## Inbox
|
||||
|
||||
reservation과 side effect가 **같은 transaction**이어야 한다.
|
||||
|
||||
```java
|
||||
transactions.inTransaction(() -> {
|
||||
if (!inbox.reserve(messageId, consumerId, now)) {
|
||||
return InboxOutcome.duplicate(); // 이미 처리됨
|
||||
}
|
||||
return InboxOutcome.processed(sideEffect.get());
|
||||
});
|
||||
```
|
||||
|
||||
별도 transaction으로 예약하면 Inbox가 닫으려던 바로 그 창이 다시 열린다.
|
||||
|
||||
### 소비와 연결 (소유자 결정 10)
|
||||
|
||||
consume 계약은 `MessageHandler<T>` 하나다. handler를 bean으로 등록하면 `messaging-spring-boot-starter-kafka`가
|
||||
그 handler가 가리키는 destination마다 Kafka consumer를 연다(`app.messaging.enabled=false`면 없다).
|
||||
|
||||
- destination profile이 `guarantees.external-side-effect: INBOX_TRANSACTIONAL`이면 platform이 handler를
|
||||
`InboxMessageHandler`로 감싼다. 예약과 handler의 쓰기가 같은 transaction에서 commit되고, 이미 예약된
|
||||
message는 handler를 부르지 않고 `Success`로 settle한다. 이 경우 애플리케이션이 `IdempotentConsumer`
|
||||
bean(inbox repository + transaction runner)을 둬야 하며, 없으면 기동이 실패한다.
|
||||
- inbox의 consumer 식별자와 Kafka `group.id`는 destination의 `consumer.group`이다. 없으면 기동이 실패한다.
|
||||
- offset은 handler가 `Success`로 답하고 (inbox destination이면) 그 transaction이 commit된 뒤에만, 또는
|
||||
DLQ 토픽 기록이 확인된 뒤에만 넘어간다. auto-commit은 쓰지 않는다.
|
||||
- `Retry`·예외·timeout은 `retry.max-attempts`까지 partition을 멈추고 다시 읽으며, 다 쓰면 DLQ 토픽에
|
||||
원본 record를 남기고 넘어간다. DLQ가 없는 destination(at-most-once)은 넘어가지 않고 멈춘다.
|
||||
- `Reject`는 at-most-once destination에서만 버리고, 그 밖에서는 dead letter로 보낸다.
|
||||
|
||||
실제 왕복·중복 제거·DLQ는 `MessagingKafkaConsumeQualificationTest`(Kafka + PostgreSQL Testcontainers)가 확인한다.
|
||||
애플리케이션 경로(앱 outbox relay가 발행 → `adapter:inbound:messaging`이 조립한 inbox와 JPA 트랜잭션 →
|
||||
handler)의 중복 전달·실패 재처리는 `InboxRedeliveryIntegrationTest`(lane
|
||||
`messagingInboxRedeliveryIntegrationTest`)가 확인한다. 애플리케이션 handler가 쓰기 use case를 부르는 방법
|
||||
(`@SystemCaller` handler가 `@SystemInvoked` use case를 직접 만든다)은 `docs/manual/09-outbox-events.md`
|
||||
「소비」 4단계다.
|
||||
|
||||
### 복합 키
|
||||
|
||||
`PRIMARY KEY (message_id, consumer_id)`.
|
||||
|
||||
message_id만으로 중복 제거하면 같은 event를 소비하는 두 번째 consumer가
|
||||
첫 번째에 의해 억제된다. 각 consumer가 한 번씩 처리해야 한다.
|
||||
|
||||
### retention
|
||||
|
||||
broker의 최대 redelivery window보다 **길어야** 한다.
|
||||
row를 먼저 지우면 늦게 도착한 redelivery가 두 번 처리된다.
|
||||
|
||||
outbox·inbox cleanup job은 한 번에 최대 1,000행씩 지우고, 지운 수가 1,000보다 적으면 멈춘다.
|
||||
repository port에는 개수 제한 없는 삭제 메서드가 없다.
|
||||
|
||||
## CDC 대안
|
||||
|
||||
relay는 polling 하나뿐이다. Debezium Event Router 매핑(`DebeziumOutboxEventRouter` 등)은 조립하는
|
||||
곳이 없어 2026-09-25에 삭제했다(`docs/capability-status.md` 제거 표). `messaging_outbox`의
|
||||
`routing_key` 컬럼은 남아 있으므로 CDC를 다시 들일 때 그 컬럼을 message key로 쓴다.
|
||||
|
||||
## Claim Check
|
||||
|
||||
1 MiB 초과 payload는 broker 프레임을 키우지 않고 외부 저장소로 offload한다.
|
||||
|
||||
`ClaimCheckReference`는 digest를 **필수**로 가진다. claim check는 메시지를 서로 다른 retention과
|
||||
replication을 가진 두 시스템으로 쪼개므로, consumer는 producer가 저장한 바로 그 bytes를 받았음을
|
||||
증명할 수 있어야 한다. 그렇지 않으면 잘린 객체와 정상 객체를 구분할 수 없다.
|
||||
|
||||
`ClaimCheckIntegrityGuard`는 fetch 전에 만료를, fetch 후에 크기와 digest를 검사한다.
|
||||
digest 불일치는 `DESERIALIZATION`이 아니라 **validation** 실패로 분류한다.
|
||||
bytes가 깨진 JSON인 게 아니라, 틀린 bytes이기 때문이다.
|
||||
@@ -1,112 +0,0 @@
|
||||
# Retry · DLQ · Redrive
|
||||
|
||||
## 자동 retry는 opt-in이다
|
||||
|
||||
일반 destination의 기본값은 **retry 없음**이다. 순서를 깨거나, 멱등하지 않은 side effect를
|
||||
증폭시키거나, 이미 throttle된 downstream을 더 때리는 retry는 보이는 실패보다 나쁘다.
|
||||
|
||||
## 결정 순서
|
||||
|
||||
`DefaultRetryDecisionEngine`은 아래 순서를 위에서 아래로 평가한다.
|
||||
|
||||
```text
|
||||
1. non-retryable category → parking(DeadLetter) 또는 Reject
|
||||
2. attempt >= maxAttempts → DeadLetter
|
||||
3. PRESERVE + ordered + orderedStream capability → PauseAndRetry
|
||||
4. mode=PAUSE_PARTITION → PauseAndRetry
|
||||
5. mode=RETRY_DESTINATION + ALLOW_REORDER → PublishToRetryDestination
|
||||
6. mode=INLINE|BLOCKING → RetryInline
|
||||
7. mode=BROKER_DELAYED + delayedDelivery capability → PublishToRetryDestination
|
||||
8. 그 외 → DeadLetter
|
||||
```
|
||||
|
||||
**retryability를 attempt 예산보다 먼저** 검사한다. deserialization 실패는 payload가 바뀌지 않으므로
|
||||
재시도가 3번 더 실패할 뿐이다. 첫 delivery에서 바로 park한다.
|
||||
|
||||
**순서 보존 전략을 재발행 전략보다 먼저** 검사한다. 둘 다 설정되어 있어도 ordered destination이
|
||||
reorder 경로로 흘러내리지 않는다.
|
||||
|
||||
## 기본 non-retryable
|
||||
|
||||
`DESERIALIZATION`, `AUTHENTICATION`, `AUTHORIZATION`, `CONFIGURATION`은 자동 retry하지 않는다.
|
||||
매 redelivery마다 동일하게 실패하므로 부하만 늘어난다.
|
||||
destination profile의 `retryableCategories`로 명시적으로 뒤집을 수는 있다.
|
||||
|
||||
## Backoff
|
||||
|
||||
`min(maxDelay, initialDelay * multiplier^(attempt-1))`, 이후 full jitter.
|
||||
|
||||
full jitter는 `[0, delay]` 균등 분포다. jitter가 없으면 같은 초에 실패한 모든 consumer가
|
||||
같은 초에 재시도하고, downstream의 회복이 재시도 폭풍으로 즉시 무효화된다.
|
||||
|
||||
## Kafka: pause-and-seek vs retry topic
|
||||
|
||||
| 전략 | 순서 | 언제 |
|
||||
|---|---|---|
|
||||
| `PAUSE_PARTITION` | 유지 | ordered destination |
|
||||
| `RETRY_DESTINATION` | 깨짐 | work queue, `ALLOW_REORDER` 명시 |
|
||||
|
||||
pause-and-seek는 메시지가 로그의 자기 자리를 떠나지 않는다. partition을 멈추고, 기다리고,
|
||||
같은 offset으로 seek해 재전달한다. 뒤의 메시지도 함께 기다리며 이것이 의도된 동작이다.
|
||||
|
||||
`KafkaConsumerRegistrar`가 handler 실패(예외, settle 없이 끝남, timeout)를 다루는 방식:
|
||||
|
||||
- 재전달은 destination `retry`의 backoff 뒤에 한다. 최소 1초. 0초 재시도는 없다.
|
||||
- 같은 offset의 실패 횟수가 `retry.maxAttempts`에 닿으면 `KafkaQuarantinePublisher`에 쓰고,
|
||||
쓰기가 확인되면 offset을 넘긴다. quarantine이 없으면 backoff로 계속 재시도한다(메시지를 버리지
|
||||
않는다). 그래서 `production` destination은 quarantine 없이 만들 수 없다(`KAFKA_QUARANTINE_REQUIRED`).
|
||||
- handler timeout이 지나도 handler가 끝날 때까지 partition slot을 잡고 있는다. `CompletableFuture`를
|
||||
cancel해도 handler는 멈추지 않으므로, slot을 먼저 풀면 같은 offset이 두 번 동시에 돈다.
|
||||
|
||||
## RabbitMQ: delayed retry queue
|
||||
|
||||
core broker에 per-message delay가 없으므로 **TTL + DLX**로 구현한다.
|
||||
retry queue의 `x-message-ttl`이 만료되면 `x-dead-letter-exchange`를 통해 work queue로 되돌아간다.
|
||||
|
||||
주의: TTL 만료는 큐 **head**에서 평가된다. 하나의 retry queue에 서로 다른 delay를 섞으면
|
||||
독립적으로 만료되지 않는다.
|
||||
|
||||
`basic.nack(requeue=true)`는 사용하지 않는다. delay 없이 큐 head로 되돌리므로 hot loop가 된다.
|
||||
|
||||
## DLQ: publish 확인 후 settlement
|
||||
|
||||
이것이 dead lettering이 데이터 손실이 되지 않게 하는 **유일한** 불변식이다.
|
||||
|
||||
```text
|
||||
DLQ envelope 생성 (원래 messageId 유지)
|
||||
→ DLQ publish
|
||||
→ CONFIRMED 이면 source settlement
|
||||
→ REJECTED / AMBIGUOUS 이면 source를 settlement하지 않음
|
||||
```
|
||||
|
||||
source를 먼저 ACK하면, DLQ publish가 실패했을 때 메시지의 사본이 **어디에도 남지 않는다**.
|
||||
broker는 이미 해제했고 DLQ는 받지 못했다.
|
||||
|
||||
AMBIGUOUS DLQ publish는 중복을 만든다. 이것이 의도된 trade다. DLQ는 사람이 읽는 곳이고
|
||||
중복은 알아볼 수 있지만, 손실은 복구할 수 없다.
|
||||
|
||||
## DLQ envelope 내용
|
||||
|
||||
reserved header에만 기록한다. payload에 넣지 않는다.
|
||||
|
||||
```text
|
||||
msg.failure-category, msg.failure-code, msg.origin-destination,
|
||||
msg.retry-attempt, msg.first-failure-at, msg.last-failure-at
|
||||
```
|
||||
|
||||
stack trace, exception message, secret header, 실제 key는 **넣지 않는다**.
|
||||
DLQ는 원본 topic보다 오래 보관되고 더 많은 사람이 읽는다.
|
||||
|
||||
## Redrive
|
||||
|
||||
M4 Admin 전용이다. `DestructiveOperationGuard`를 통과해야 한다.
|
||||
|
||||
- admin credential 필요 (application runtime은 보유하지 않는다)
|
||||
- 유효기간 내 `AdminApproval` 필요
|
||||
- dry-run은 항상 허용 (계획이 공짜여야 사람이 계획한다)
|
||||
- batch 상한 100건
|
||||
- source == target 금지
|
||||
- `redriveId`는 `messageId`와 별개다. 재구동 루프를 식별하기 위해서다.
|
||||
|
||||
redrive도 **publish → settlement** 순서다. republish가 confirm되지 않은 메시지는
|
||||
DLQ에 남는다.
|
||||
@@ -1,112 +0,0 @@
|
||||
# Messaging 보안
|
||||
|
||||
## Credential 분리
|
||||
|
||||
producer / consumer / admin은 **서로 다른 credential**이다.
|
||||
`MessageSecurityValidator`가 startup에서 강제한다.
|
||||
|
||||
```text
|
||||
producer credential == consumer credential → 실패
|
||||
admin credential == producer|consumer → 실패
|
||||
production 프로필에 admin credential 존재 → 실패
|
||||
```
|
||||
|
||||
마지막 규칙이 "애플리케이션은 topic을 purge할 수 없다"를 **구조적으로** 만든다.
|
||||
runtime이 admin 자격 증명을 아예 보유하지 않으므로, 침해된 handler가 상승시킬 대상이 없다.
|
||||
|
||||
## Production 필수 조건
|
||||
|
||||
- TLS 활성
|
||||
- TLS hostname verification 활성
|
||||
- broker authentication 활성
|
||||
- topology auto-create 비활성
|
||||
|
||||
broker 인증서는 `subjectAltName`에 접속 이름을 가져야 한다. hostname verification은 SAN을 보므로, SAN이
|
||||
없는 인증서는 실패하는 것이 맞다. 검사를 끄지 않는다. 키와 인증서는 배포 환경의 PKI가 발급해 실행 때
|
||||
마운트하고, repo에 두지 않는다.
|
||||
|
||||
Kafka는 추가로 `enable.idempotence=true`, `acks=all`,
|
||||
`max.in.flight.requests.per.connection <= 5`, consumer auto-commit 금지.
|
||||
|
||||
RabbitMQ는 추가로 publisher confirm, publisher return, `mandatory=true`,
|
||||
durable work queue의 quorum queue, consumer auto-ack 금지.
|
||||
|
||||
## Credential은 값이 아니라 참조다
|
||||
|
||||
`BrokerCredentialProfile`의 어떤 variant도 secret을 담지 않는다.
|
||||
식별자만 보관하고 connect 시점에 `CredentialProvider`로 해석한다.
|
||||
heap dump나 설정 출력에서 사용 가능한 credential이 나오지 않는다.
|
||||
|
||||
`CredentialIds`는 `bearer `, `sk-`, `-----begin`, `eyJ` 같은 접두사를 거부한다.
|
||||
참조가 들어갈 자리에 secret 자체를 붙여넣는 가장 흔한 사고를 막는다.
|
||||
|
||||
SASL(PLAIN·SCRAM) 사용자 이름도 `CredentialProvider.username(credentialId)`가 준다. credential id는
|
||||
저장소 안의 참조이지 broker가 아는 사용자 이름이 아니다. provider가 이름을 주지 않으면 기동에
|
||||
실패한다.
|
||||
|
||||
key store·trust store는 경로만 설정에 둔다. 비밀번호는 credential id로 provider가 해석한다
|
||||
(`configuration-reference.md` 보안 절).
|
||||
|
||||
## Rotation
|
||||
|
||||
`CredentialRotationPlan.isDue()`는 만료 **전에** 참이 된다.
|
||||
broker가 연결을 거부하기 시작한 시점에는 이미 publish가 실패하고 consumer가 멈춰 있다.
|
||||
|
||||
Kafka SASL credential은 producer를 다시 만들지 않고 바뀐다. JAAS 설정에는 login module 이름만
|
||||
있고, `KafkaCredentialCallbackHandler`가 연결이 인증할 때마다 `CredentialRuntimeRegistry`에서
|
||||
사용자 이름과 비밀번호를 읽는다. registry는 provider가 준 만료 시각의 rotation lead(기본 30분)
|
||||
안으로 들어오면 새로 가져오므로, 새 연결과 재인증(broker `connections.max.reauth.ms`)이 새 값을
|
||||
쓴다. 만료 시각을 주지 않는 provider의 credential은 캐시된 값을 계속 쓴다.
|
||||
|
||||
key store·trust store 비밀번호는 예외다. Kafka가 SSL context를 만들 때 한 번 읽으므로 바꾸려면
|
||||
producer를 다시 만들어야 한다(재기동).
|
||||
|
||||
transport 세대 교체(`DefaultMessagingRuntimeRegistry.install()`)는 transport 자체를 바꿀 때 쓴다.
|
||||
새 세대를 원자적으로 게시하고, 이전 세대는 마지막 lease가 닫힐 때까지 열려 있다가 닫힌다.
|
||||
drain deadline이 이 대기를 제한한다.
|
||||
|
||||
## Header
|
||||
|
||||
금지 header는 application·platform 양쪽에서 거부한다.
|
||||
|
||||
```text
|
||||
Authorization, Proxy-Authorization, Cookie, Set-Cookie,
|
||||
access_token, refresh_token, api_key, password, client_secret
|
||||
```
|
||||
|
||||
credential이 header에 들어가면 broker storage, DLQ dump, 운영 도구에 남는다.
|
||||
downstream redaction으로는 되돌릴 수 없다.
|
||||
|
||||
예약 header(`msg.*`, `traceparent`, `tracestate`, `baggage`)는 platform만 쓴다.
|
||||
application이 `msg.id`를 설정할 수 있으면 Inbox 중복 제거와 DLQ 상관관계가 의존하는
|
||||
logical identity가 호출자 제어가 된다.
|
||||
|
||||
## ACL
|
||||
|
||||
publisher가 broker ACL **이전에** 검사한다(`PUBLISH_FORBIDDEN`).
|
||||
broker ACL 거부는 애플리케이션 컨텍스트가 없는 연결 수준 오류로 도착하므로
|
||||
"어느 모듈이 어디에 publish하려 했는가"가 조사 대상이 된다.
|
||||
|
||||
publish 가능한 destination은 선언된 destination이다. broker에 `app.messaging.security.<broker>`
|
||||
항목이 있으면 그중 `access.publishable`에 적힌 것만 남는다(빈 목록이면 publish 불가).
|
||||
|
||||
## 관측성 누출
|
||||
|
||||
`MessagingRedactor`는 denylist다.
|
||||
|
||||
- secret: authorization, cookie, token, password, secret, credential
|
||||
- per-message identity: messageId, correlationId, causationId, partitionKey, key, offset, deliveryTag, sequence
|
||||
- payload: payload, body, data
|
||||
- 예외 상세: exceptionMessage, stackTrace
|
||||
|
||||
identity를 지우는 이유는 두 가지다. bounded metric을 message당 하나의 series로 만들고,
|
||||
support log를 재식별 표면으로 만들기 때문이다.
|
||||
|
||||
`CardinalityGuard`는 dimension당 값 개수를 상한한다.
|
||||
cardinality 사고는 점진적이지 않다. 테스트 10건에서는 멀쩡하고 운영에서 백엔드를 죽인다.
|
||||
|
||||
## 감사
|
||||
|
||||
`MessagingAuditEvent`는 replay, redrive, offset reset, purge, delete를 기록한다.
|
||||
subject(운영자 identity), approval ticket, 그리고 redactor를 통과한 details만 담는다.
|
||||
누가 무엇을 했는지 증명하되 payload의 두 번째 사본이 되지 않는다.
|
||||
@@ -1,154 +0,0 @@
|
||||
# Messaging 지원 매트릭스
|
||||
|
||||
플랫폼이 **무엇을 보장하는지**와 **무엇을 보장하지 않는지**를 브로커별로 고정한다.
|
||||
여기 없는 조합은 지원되지 않는다.
|
||||
|
||||
> **등급은 증거를 따른다.** `CompatibilityMatrix.Entry.hasLiveBrokerCertification()`은 선언된
|
||||
> boolean이 아니라 `CertifiedEvidence`가 가진 레인 증거에서 파생된다. 레인이 생겨 증거를 내면 등급은
|
||||
> 코드 수정 없이 따라 올라간다.
|
||||
|
||||
> **삭제된 어댑터.** RabbitMQ(선택할 수 없던 validator·설정 모음), Pulsar·NATS JetStream·Kafka Share
|
||||
> Group(Experimental, SDK 없는 seam), Spring Cloud Stream bridge, Debezium outbox 매핑은 2026-09-25에
|
||||
> 삭제했다. 복구 경로는 `docs/capability-status.md`의 제거 표에 있다.
|
||||
|
||||
> **인증 근거.** 이 표의 버전은 이 저장소의 컨테이너 레인이 실제로 실행한 이미지다. 이전 판은
|
||||
> Kafka 4.2/4.3을 선언했지만 fixture는 `apache/kafka:4.1.0`, lockfile client는 4.1.1이었다 — 표와
|
||||
> 코드 상수가 서로 일치했을 뿐 어느 쪽도 실행된 적이 없었다. 장애 시나리오 커버리지도 마찬가지로
|
||||
> `BrokerFailureMatrix.shipped()` 하드코딩이 아니라 레인이 낸 증거(`BrokerCertificationEvidence`)에서
|
||||
> 나온다. 증거가 없는 조합은 `NOT_COVERED`다 (MSG-014).
|
||||
|
||||
> **모듈 이름과 런타임 편입.** 관계형 신뢰성 구현은 `messaging-reliability-jdbc-postgresql`,
|
||||
> 그 port만 보는 relay·consumer 로직은 `messaging-reliability`다(2026-09-28에
|
||||
> `messaging-outbox-jdbc-postgresql` / `messaging-inbox-jdbc-postgresql`을 이렇게 나눴다). 그 전에는
|
||||
> `-jpa`로 불렸다. 구현은 Spring JDBC이고 SQL은 PostgreSQL 전용(`jsonb`,
|
||||
> `FOR UPDATE SKIP LOCKED`, `ON CONFLICT`, `TIMESTAMPTZ`)이므로, 그 이름은 쓰지 않는 기술을
|
||||
> 광고하고 vendor 중립 port(`messaging-reliability-api`)의 위치를 가렸다 (MSG-023).
|
||||
>
|
||||
> `modules.json`은 messaging leaf의 `gradle_path`와 허용 의존성을 관리하지만
|
||||
> `runtime_memberships` 필드는 없다. 실제 런타임 편입은 `app-bootstrap`의 Gradle 의존성과 starter /
|
||||
> auto-configuration 경로가 결정한다. 아래 등급은 "무엇이 증명되었는가"를 말하며 런타임 편입 여부와
|
||||
> 같은 축이 아니다. 자세한 composition/cutover 상태는 `src/platforms/messaging/AGENTS.md`가 소유한다.
|
||||
|
||||
## 브로커 등급
|
||||
|
||||
| 브로커 | 등급 | 인증 기준 | Stable 기능 | 제한 |
|
||||
|---|---|---|---|---|
|
||||
| Kafka | Stable | 4.1.x | producer idempotence, consumer group, batch, pause/resume, replay, transaction capability | Share Group 미지원 |
|
||||
| Artemis/JMS | Extension | 범위 밖 | adapter SPI만 | 별도 ADR + Contract Suite 통과 필요 |
|
||||
|
||||
## Capability 매트릭스
|
||||
|
||||
`MessagingCapabilities`가 런타임에 선언하는 값이다. `false`인 기능을 요구하는 destination profile은
|
||||
**startup에서 실패**하며, 조용히 약화되지 않는다.
|
||||
|
||||
| Capability | Kafka |
|
||||
|---|---|
|
||||
| brokerAcknowledgement | O |
|
||||
| replicationOrPersistenceEvidence | O |
|
||||
| perMessageSettlement | O |
|
||||
| batchSettlement | O |
|
||||
| orderedStream | O |
|
||||
| keyedOrdering | O |
|
||||
| replay | O |
|
||||
| delayedDelivery | X |
|
||||
| brokerTransaction | O |
|
||||
| deduplicatedPublish | O |
|
||||
| nativeDeadLetter | X |
|
||||
| topologyManagement | O |
|
||||
|
||||
## 기능 등급
|
||||
|
||||
| 기능 | 등급 |
|
||||
|---|---|
|
||||
| Typed Publish·Consume | Stable M1 |
|
||||
| At-least-once contract | Stable |
|
||||
| Ambiguous publish 결과 | Stable |
|
||||
| handler 성공 후 자동 settlement | Stable M1 |
|
||||
| Batch / Manual settlement / Pause·Resume / Delayed / Replay 요청 | M2 |
|
||||
| Broker transaction / partition / routing / subscription | M3 |
|
||||
| Replay 실행 / Redrive / offset reset / purge / delete | M4 Admin |
|
||||
|
||||
## 무엇이 "Stable"을 증명하는가
|
||||
|
||||
Stable 등급은 두 가지를 **모두** 통과해야 한다. `CompatibilityMatrixTest`가 이 규칙을 강제한다.
|
||||
|
||||
### 1. 공유 Contract Suite (`MessagingAdapterContract`, 7개)
|
||||
|
||||
Kafka가 7개 테스트를 변경 없이 통과한다. 결정적 하네스를 쓰므로
|
||||
확인 유실·settlement 유실 같은 장애를 요청 시점에 재현할 수 있다.
|
||||
|
||||
### 2. 실 브로커 인증 (Testcontainers)
|
||||
|
||||
| 스위트 | 무엇을 증명하는가 |
|
||||
|---|---|
|
||||
| `KafkaBrokerIT` | `acks=all`이 실제 replication 증거를 만든다 / 잘못된 토픽은 `REJECTED` / 발행-소비 왕복에서 identity 보존 및 contiguous commit |
|
||||
| `KafkaAmbiguityChaosIT` | 브로커를 `docker pause`로 멈춘 상태의 publish가 **`AMBIGUOUS`** 로 보고된다 (broker acceptance 없음, confirmation level `NONE`, 비-retryable) |
|
||||
| `KafkaBrokerCertificationIT` | 인증 레인. Toxiproxy를 broker 앞에 두고 connection cut / confirm 유실 / 지연 / settlement 유실을 각각 주입하고, 통과한 시나리오마다 `BrokerCertificationEvidence` 한 줄을 manifest에 쓴다 |
|
||||
| `OutboxPostgresIT` | 롤백된 트랜잭션은 발행 가능한 행을 남기지 않는다 / `SKIP LOCKED` lease가 두 relay를 분리한다 / ambiguous 행이 같은 `messageId`로 재클레임된다 |
|
||||
| `InboxPostgresIT` | 재전달이 side effect를 두 번 적용하지 않는다 / 롤백은 예약도 되돌린다 |
|
||||
|
||||
Docker가 없으면 `DockerAvailability` 가드로 skip되며, 이 표의 항목은 그때 **검증되지 않은 것**으로 취급한다.
|
||||
`KafkaBrokerCertificationIT`만 예외다 — 인증 레인은 가드를 달지 않고 Docker가 없으면 실패한다. skip하는
|
||||
레인은 아무도 켜지 않은 브로커에 대해 성공을 보고하기 때문이다. 그래서 이 레인은 `test`에서 태그로
|
||||
제외되고 `messagingCertificationTest`로만 실행된다.
|
||||
|
||||
### 3. 장애 시나리오 커버리지 (`BrokerFailureMatrix`)
|
||||
|
||||
`NetworkFaultScenario`가 5개 시나리오와 **각각의 기대 결과**를 코드로 고정한다. 기대 결과를 어댑터별로
|
||||
두지 않는 것이 핵심이다 — 어댑터마다 다른 답을 허용하면 공유 계약이 존재할 이유가 없다.
|
||||
|
||||
| 시나리오 | 시점 | 기대 결과 | 이유 |
|
||||
|---|---|---|---|
|
||||
| `connection-refused` | 전송 전 | `REJECTED` | 바이트가 나가지 않았으므로 broker가 가질 수 없다 |
|
||||
| `connection-cut-after-write` | 전송 후 | `AMBIGUOUS` | broker가 저장했고 confirm만 유실됐을 수 있다 |
|
||||
| `confirm-timeout` | 전송 후 | `AMBIGUOUS` | timeout은 부재의 증거가 아니라 증거의 부재다 |
|
||||
| `settlement-lost` | settlement 중 | `REDELIVERED` | 미settlement 메시지는 재전달이 설계다 |
|
||||
| `high-latency` | 전송 후 | `AMBIGUOUS` | 판단 시점에는 confirm 유실과 구별할 수 없다 |
|
||||
|
||||
`CrossBrokerContractSuite`가 릴리스 게이트로 이를 강제한다. Stable 어댑터는 5개 전부를 **실 브로커에서**
|
||||
커버해야 하고, Experimental 어댑터는 `LIVE_BROKER` 커버리지를 주장할 수 없다. 커버리지는 *능력*이 아니라
|
||||
*무엇을 실제로 돌렸는지*의 기록이다.
|
||||
|
||||
**증거의 출처.** `CertifiedEvidence`는 더 이상 손으로 쓴 목록이 아니라
|
||||
`messaging-testkit/src/main/resources/messaging/broker-certification-evidence.jsonl`을 읽는다. 그 파일은
|
||||
`messagingCertificationTest` 레인이 실제 Kafka 컨테이너에 장애를 주입하며 만들어낸 출력이고,
|
||||
`verifyMessagingCertificationEvidence`가 커밋된 manifest와 이번 실행의 출력을 대조해 다르면 빌드를
|
||||
실패시킨다. 즉 **manifest를 손으로 고치면 게이트가 깨지고, 레인을 돌리면 manifest가 다시 쓰인다.**
|
||||
|
||||
오늘 Kafka가 가진 증거는 `connection-cut-after-write` · `confirm-timeout` · `high-latency` ·
|
||||
`settlement-lost` 네 개다. `connection-refused`는 남은 gap이며 그 이유가 있다 — Kafka producer는 연결
|
||||
존재 여부를 알기 전에 레코드를 버퍼에 넣으므로, 연결 거부는 전송에 대해 아무것도 증명하지 못하는
|
||||
delivery timeout으로 나타난다. 이를 `REJECTED`로 보고하는 것은 이 플랫폼이 금지한 추측이므로,
|
||||
시나리오는 `CertifiedEvidence.knownGaps`가 이름으로 들고 있는 미커버 항목으로 남는다.
|
||||
|
||||
### 실 브로커가 실제로 잡아낸 결함
|
||||
|
||||
이 스위트들은 장식이 아니다. 작성 과정에서 결정적 테스트가 통과하는데 실 인프라에서 실패한
|
||||
결함을 두 건 잡았다.
|
||||
|
||||
1. **Outbox `IN_FLIGHT` 고아 행** — lease 쿼리가 `PENDING`/`AMBIGUOUS`만 클레임 대상으로 봐서,
|
||||
publish 도중 죽은 relay가 남긴 행이 lease 만료 후에도 영영 회수되지 않았다.
|
||||
2. **Rabbit confirm 경합**(2026-09-25에 삭제된 Rabbit transport) — transport가 publish *후에* confirm을 등록해서, 연결 스레드에서
|
||||
confirm이 먼저 도착하면 유실되고 호출자가 무한 대기했다.
|
||||
|
||||
둘 다 인메모리 double이 실제보다 관대해서 통과하고 있었다.
|
||||
|
||||
## 명시적 비지원
|
||||
|
||||
- 공통 `EXACTLY_ONCE` 설정 — `DeliveryGuarantee`에 상수가 존재하지 않는다.
|
||||
- 전역 순서 — `OrderingScope`에 `GLOBAL`이 존재하지 않는다.
|
||||
- DB와 broker의 자동 원자 transaction, 기본 XA
|
||||
- Java native serialization
|
||||
- 무제한 payload·header, 무한 retry
|
||||
- 운영 application에서의 topology 파괴 작업
|
||||
- 일반 애플리케이션에 raw broker client 반환
|
||||
- DLQ publish 확인 전 source ACK
|
||||
|
||||
|
||||
### Optional mapping utilities
|
||||
|
||||
- `messaging-cloudevents`는 starter runtime에 자동 편입되지 않는 **opt-in mapping utility**다.
|
||||
내부 envelope와 CloudEvent 객체 사이의 제한된 profile mapping을 제공하지만 binary/structured
|
||||
CloudEvents wire mode 전체를 구현하거나 임의 CloudEvents producer와의 1.0 interoperability를
|
||||
인증하지 않는다.
|
||||
- `messaging-claim-check`도 starter에 편입되지 않는 opt-in utility다.
|
||||
@@ -2836,7 +2836,7 @@ env_keys:
|
||||
|
||||
- name: APP_MESSAGING_BROKER
|
||||
# source: messaging multi-broker redesign 2026-06-16 — 활성 broker 하나를 고른다
|
||||
# (app.messaging.broker=<brokerId>). 들여온 메시징 플랫폼이 읽는다. 옛 Kafka 전용 APP_MESSAGING_KAFKA_ENABLED를
|
||||
# (app.messaging.broker=<brokerId>). 메시징 라이브러리(dev.cakit.messaging)가 읽는다. 옛 Kafka 전용 APP_MESSAGING_KAFKA_ENABLED를
|
||||
# 대신한다. 애플리케이션 bridge는 이제 읽지 않는다: 읽던 옛 KafkaSender seam은 canonical outbox와 함께
|
||||
# 지웠다(2026-09-28).
|
||||
type: string
|
||||
|
||||
@@ -162,6 +162,19 @@ PR 단계 trivy 검사(`dependency-vulnerability.yml`의 HIGH·CRITICAL 단계)
|
||||
| B-55 | 삭제: `src/platforms/grpc`, `src/platforms/grpc-advanced`, `src/platforms/optional-build`(두 번째 빌드 `optional-platforms` 전체), registry의 `"build": "optional-grpc"` 9행, workflow job `ci-quality-gates.yml` `optional-platforms`·`grpc-proto-buf`(그리고 `release-gate`의 두 `needs`), `integration-main.yml`의 optional 성능 단계와 job `grpc-optional-platform-integration`, `release.yml` job `grpc-stable-release-gate`(그리고 이미지 job의 `needs` 한 줄), 살아 있는 문서 `docs/compatibility/`(폴더째), `docs/runbooks/grpc-platform-operations.md`·`grpc-advanced-capabilities.md`. 새 자리는 grpc-library repo이고 같은 이름의 파일이 이력째 있다. 기록(`docs/adr/ADR-GRPC-*` 7개, `docs/design/2026-08-30-grpc-platform-adaptation-design.md`)은 본문을 두고 머리 블록 「현재 정본」만 그 repo를 가리키게 했다. 사본이 그 repo에도 있다. 그 repo에서 Maven group과 Java 패키지는 `dev.cakit.grpc`, proto 패키지는 `cakit.grpc.common.v1`이다(템플릿 재사용 체크리스트의 `dev.caskeleton` 바꾸기와 겹치지 않게 다른 이름) | 이 경로를 고친 서비스는 「수정 대 삭제」 충돌이 난다. `project(':grpc:…')`·`project(':grpc-advanced:…')`나 `-p platforms/optional-build`를 쓴 서비스는 빌드가 실패한다 | 쓰지 않았으면 삭제를 그대로 받는다. 썼으면 grpc-library 첫 버전(`1.0.0`, 소유자가 태그를 단 뒤)을 좌표 `dev.cakit.grpc:<모듈>:1.0.0`으로 받고(저장소 선언은 그 repo README 「받는 법」), import를 `dev.caskeleton.grpc` → `dev.cakit.grpc`로 바꾼다 | design-docs `repo-structure/05-library-repos.md` 4·13절, `docs/work/reference/related-repos.md` |
|
||||
| B-56 | 빌드 규칙·카탈로그: build-logic의 `ca.grpc-platform-module`·`ca.optional-architecture-registry` 플러그인과 `MainBuild`(두 번째 빌드에서 주 빌드를 찾던 것)를 지웠다. 도구 설정·테스트 이미지 목록·registry는 Gradle 루트(`src/`)에서만 찾는다. 카탈로그에서 `protobufPlugin`·`protobuf-java-grpc`·`protoc`·plugin `protobuf`를, SpotBugs 제외에서 gRPC 플랫폼 클래스 줄을 지웠다 | 서비스 leaf가 `ca.grpc-platform-module`이나 `libs.protoc`·`libs.protobuf.java.grpc`·`libs.plugins.protobuf`를 쓰면 빌드가 실패한다. `src/` 밖 두 번째 빌드에서 이 build-logic을 쓰던 서비스는 도구 설정을 못 찾는다 | 그 leaf `build.gradle`에서 `io.grpc:grpc-bom` import와 protobuf 플러그인 버전을 직접 적거나, 지운 카탈로그 항목을 서비스 카탈로그에 다시 더한다 | 같은 설계 13.1절 2단계 |
|
||||
|
||||
### 3.9 메시징 플랫폼 — 별도 repo `messaging-library`로 옮기고 버전 1.0.0으로 받는다
|
||||
|
||||
이 절도 위 머리의 범위보다 뒤에 main에 들어간다. 범위: `2959eff0..claude/x3-messaging-library-1aa3fa`(2026-11-08, 같은
|
||||
소유자 결정, design-docs `repo-structure/05-library-repos.md` 13.1절 3~5단계). 메시징은 템플릿 adapter 넷이 쓰므로, 라이브러리를
|
||||
먼저 `dev.cakit.messaging` 1.0.0으로 Gitea Packages에 배포하고 템플릿이 그 버전을 받게 바꿨다. 코드와 이력은
|
||||
https://git.learn.hyeonworks.com/donghyeon.kang/messaging-library 에 있다. 동작은 같다(같은 소스, 패키지 이름만 바뀜).
|
||||
|
||||
| # | 무엇이 바뀌었나 | 파생 서비스 증상 | 할 일 | 근거 |
|
||||
|---|---|---|---|---|
|
||||
| B-57 | 삭제: `src/platforms/messaging`(19개 모듈)과 빈 `src/platforms/`, registry의 메시징 19행, workflow `messaging-certification.yml`, 저장소 계약 테스트 `MessagingPublicSurfaceContractTest`(라이브러리 repo로), 살아 있는 문서 `docs/messaging/`(폴더째, 같은 이름으로 라이브러리 repo에), SpotBugs 제외의 메시징 클래스 줄, 카탈로그의 메시징 전용 항목(`avro`, `cloudevents`, `protobuf` 4.33.2와 `protobuf-java`). `check-repo-layout.py` 허용 목록에서 `platforms`를 뺐다. 메시징 기록(`docs/design/2026-08-10-messaging-platform-design.md` 등)은 본문을 두고 머리 블록 「현재 정본」만 고쳤다 | 이 경로를 고친 서비스는 「수정 대 삭제」 충돌. `project(':messaging:…')`를 쓴 자기 leaf는 빌드가 실패한다. `src/platforms/` 아래 자기 폴더를 둔 서비스는 `check-repo-layout.py`가 실패한다 | 메시징 코드를 고쳤으면 그 수정을 messaging-library repo로 보낸다(`docs/work/reference/related-repos.md` 2절). 자기 leaf의 `project(':messaging:<모듈>')`은 B-58처럼 좌표로 바꾼다 | design-docs `repo-structure/05-library-repos.md` 4·13절 |
|
||||
| B-58 | 받는 법: `src/settings.gradle`에 Gitea Packages 저장소를 `exclusiveContent`(group `dev.cakit`와 그 아래만)로 더했다. 카탈로그에 `messagingLibrary = "1.0.0"`과 모듈 여섯(`libs.messaging.core.api` 등). 쓰는 leaf(`adapter:outbound:messaging`, `adapter:outbound:messaging-kafka`, `adapter:inbound:messaging`, 시험만 `composition:outbox-relay`·`adapter:outbound:persistence-jpa`)가 좌표로 받는다. Java 패키지 `dev.caskeleton.messaging` → `dev.cakit.messaging`, auto-configuration 이름 `dev.cakit.messaging.autoconfigure.MessagingPlatformRootAutoConfiguration`. 그대로인 것: 설정 키 `app.messaging.*`, env 키, Flyway 위치 `db/migration/messaging`과 파일, 표 이름 | 메시징 타입을 import한 자기 코드가 컴파일되지 않는다. `afterName`·`beforeName`으로 플랫폼 root 이름을 적은 자기 auto-configuration은 순서 제약이 조용히 사라진다. 캐시가 빈 빌드(새 기계, 이미지 builder)는 `git.learn.hyeonworks.com`에 닿아야 한다 | import와 이름 문자열의 `dev.caskeleton.messaging`을 `dev.cakit.messaging`으로 바꾼다(템플릿 재사용 체크리스트의 `dev.caskeleton` 바꾸기에 넣지 않는다). merge 뒤 `./gradlew resolveAndLockAll --write-locks`. 빌드 기계가 Gitea에 닿는지 본다(공개 owner라 토큰은 필요 없다) | messaging-library `CHANGELOG.md` 1.0.0 |
|
||||
| B-59 | registry 칸 둘: 맨 위 `library_groups`(`["dev.cakit"]`)와 행마다 `allowed_libraries`(`group:artifact`). 방향 검사(`verifyModuleDependencyDirection`)가 소유 group 라이브러리의 운영 선언(`runtimeOnly` 포함)과 컴파일에서 보이는 모듈을 그 칸과 대조한다. build-logic `ModuleRegistry`·`VerifyModuleDependencyDirectionTask`가 바뀌었다 | 자기 leaf가 `dev.cakit.*` 모듈을 칸에 적지 않고 쓰면 `verifyCleanArchitectureDependencies`가 「forbidden library dependencies」로 실패한다. registry를 읽는 자기 도구가 모르는 키를 거절하면 실패한다 | 그 leaf 행에 `allowed_libraries`를 적는다(`src/config/architecture/README.md` 「별도 repo 라이브러리」). build-logic을 고쳐 쓴 서비스는 두 파일 병합 충돌을 푼다 | 같은 설계 10.2절 T2(Q11) |
|
||||
|
||||
## 4. DB 마이그레이션
|
||||
|
||||
### 4.1 새 버전과 영향
|
||||
|
||||
@@ -54,7 +54,7 @@ design-docs `conventions/delegation-loop.md` 3절 순서대로 한다: 크기
|
||||
| inbound 전송 | `src/adapter/inbound/*`. gRPC 플랫폼 라이브러리는 별도 repo `grpc-library`에서 고친다(`reference/related-repos.md`) |
|
||||
| persistence | `src/adapter/outbound/persistence-*`, 마이그레이션 |
|
||||
| outbound capability | 그 밖의 `src/adapter/outbound/*`, 멱등성 store |
|
||||
| messaging | `src/platforms/messaging/*`, `src/adapter/outbound/messaging` |
|
||||
| messaging | `src/adapter/inbound/messaging`, `src/adapter/outbound/messaging*`. 메시징 라이브러리는 별도 repo `messaging-library`에서 고친다(`reference/related-repos.md`) |
|
||||
| bootstrap·build·CI | `src/app-bootstrap`, `src/composition/*`, `src/build-logic`, `src/build.gradle`, `.github/` |
|
||||
| 보안(영역을 가로질러) | 인증·인가 체인, 비밀, 공개 경로 |
|
||||
| 문서 | `docs/` |
|
||||
|
||||
@@ -76,7 +76,7 @@
|
||||
| --- | --- | --- | --- |
|
||||
| outbox relay·멱등성 executor 조립 | app-bootstrap이 아니라 별도 `composition:*` 모듈 | 소유자 | 결정 3 |
|
||||
| 새 leaf | `composition:durable-operation`, `adapter:inbound:messaging` 등록 승인 | 위임 | `1101` 15절 |
|
||||
| edge 없는 복사본 | 템플릿 leaf는 `shared-contract` edge를 더해 정본을 쓴다. vendored(`messaging:*`)와 별도 repo 라이브러리는 복사본을 두고 family `AGENTS.md`(라이브러리는 그 모듈)에 이유 | 위임 | `1101` 15절(01-11) |
|
||||
| edge 없는 복사본 | 템플릿 leaf는 `shared-contract` edge를 더해 정본을 쓴다. 별도 repo 라이브러리(messaging-library, grpc-library)는 복사본을 두고 그 repo의 모듈 지침에 이유 | 위임 | `1101` 15절(01-11) |
|
||||
| caller 트랜잭션 guard | `persistence-notification`·`persistence-fileserver` → `persistence-jpa` edge, `CallerTransaction` 하나 | 소유자 | 결정 33 |
|
||||
| id 포트 | notification·fileserver id 포트를 domain `IdFactory`로 옮기지 않음(보류) | 소유자 | 결정 34 |
|
||||
| 소비자 없는 필드 | principal tenant, GraphQL Spring Security resolver, 가명화 키 분리는 하지 않음(보류) | 소유자 | 결정 35 |
|
||||
@@ -85,8 +85,8 @@
|
||||
| `@SystemInvoked` | bean으로 등록돼 있으면 기동 실패, inbound adapter가 직접 부르지 못하게 ArchUnit | 위임 | `1103` 4절(RR-01-02) |
|
||||
| 시스템 호출 경로 | 사용자가 닿는 전송(web·GraphQL·gRPC·WebSocket)만 `@SystemInvoked`에 닿지 못한다. 메시지 소비자·스케줄러는 `@SystemCaller(reason)` 표시로 허용 | 위임 | `1103` 9.1절(RR-01-12), 10절 r5-b |
|
||||
| 배치 규칙 검사 | 저장소 루트와 `src/` 최상위 허용 목록을 `scripts/check-repo-layout.py`로 PR에서 막는다. 리뷰 기준에도 넣는다(매뉴얼 보강 작업) | 소유자(2026-11-07) | design-docs `repo-structure/README.md` 3.1절, `repo-structure/01-backend-layout.md` 10.3절 |
|
||||
| `src/` 배치 | 들여온 플랫폼 넷(`messaging`, `grpc`, `grpc-advanced`, optional 빌드)을 `src/platforms/` 아래로 묶는다. registry `source_path`만 바꾸고 Gradle 경로는 그대로 둔다. `build-logic`·`gradle`·`config`는 Gradle 루트 표준이라 남기고, `composition`은 조립 계층이라 옮기지 않는다. `config/`에서 기능 하나가 주인인 데이터 파일은 그 leaf로 보낸다. Gradle 루트를 저장소 루트로 옮길지는 CI 재편 때 다시 본다. gRPC 둘과 optional 빌드는 2026-11-08 별도 repo로 나갔다(아래 「라이브러리 repo」) | 소유자(2026-11-07) | design-docs `repo-structure/README.md` 3.1절, `repo-structure/01-backend-layout.md` 6.1절 |
|
||||
| 라이브러리 repo | 프로젝트 계층이 아닌 라이브러리(메시징, gRPC)는 템플릿에 두지 않는다. 라이브러리마다 별도 repo에서 고치고 Gitea Packages에 버전으로 배포하며, 템플릿은 쓰는 라이브러리만 카탈로그 좌표로 받는다. gRPC가 먼저 `grpc-library`로 옮겼다(2026-11-08, 템플릿 소비자 없음이라 카탈로그 항목도 없음). 목록과 고치는 법은 `related-repos.md` | 소유자(2026-11-07) | design-docs `repo-structure/README.md` 3.5절, `repo-structure/05-library-repos.md` 15절 |
|
||||
| `src/` 배치 | 들여온 플랫폼 넷(`messaging`, `grpc`, `grpc-advanced`, optional 빌드)을 `src/platforms/` 아래로 묶는다. registry `source_path`만 바꾸고 Gradle 경로는 그대로 둔다. `build-logic`·`gradle`·`config`는 Gradle 루트 표준이라 남기고, `composition`은 조립 계층이라 옮기지 않는다. `config/`에서 기능 하나가 주인인 데이터 파일은 그 leaf로 보낸다. Gradle 루트를 저장소 루트로 옮길지는 CI 재편 때 다시 본다. 넷 모두 2026-11-08 별도 repo로 나갔고 `src/platforms/`는 지웠다(아래 「라이브러리 repo」) | 소유자(2026-11-07) | design-docs `repo-structure/README.md` 3.1절, `repo-structure/01-backend-layout.md` 6.1절 |
|
||||
| 라이브러리 repo | 프로젝트 계층이 아닌 라이브러리(메시징, gRPC)는 템플릿에 두지 않는다. 라이브러리마다 별도 repo에서 고치고 Gitea Packages에 버전으로 배포하며, 템플릿은 쓰는 라이브러리만 카탈로그 좌표로 받는다. gRPC가 먼저 `grpc-library`로 옮겼다(2026-11-08, 템플릿 소비자 없음이라 카탈로그 항목도 없음). 메시징은 `messaging-library` 1.0.0으로 옮기고 쓰는 leaf가 카탈로그 `messagingLibrary`로 받는다(2026-11-08). 라이브러리 edge는 registry 「허용 라이브러리」 칸(`library_groups`·`allowed_libraries`)이 막는다(설계 Q11 T2). 목록과 고치는 법은 `related-repos.md` | 소유자(2026-11-07) | design-docs `repo-structure/README.md` 3.5절, `repo-structure/05-library-repos.md` 15절 |
|
||||
| 개발 compose 파일 | 저장소 루트에 `compose.yaml` 하나. 뒷단 서비스는 capability 이름 profile로 고르고, 마운트하는 보조 파일은 `compose/`에 둔다. 테스트 lane fixture는 그 lane을 가진 leaf로 보낸다(compose lane → app-bootstrap `compose-lanes/`, Redis topology → redis-sdk, NFS → fileserver). `docker-compose.dev.yml`은 `dev` 배포 프로필이 뜨는지 보는 lane fixture로 app-bootstrap에 둔다 | 소유자(2026-11-07) | design-docs `repo-structure/README.md` 3.1절, `repo-structure/01-backend-layout.md` 6.3절 |
|
||||
| 인프라 실행 파일 | nginx 설정, Kubernetes PVC job, DB 역할 SQL은 이 repo에서 지우고, 기능이 운영 환경에 요구하는 조건만 그 기능 문서에 적는다. 아무도 쓰지 않는 infra 폴더 파일도 지운다. 지운 목록은 `docs/upgrade/2026-11-maturity-review.md` B-50 | 소유자(2026-11-07) | design-docs `repo-structure/README.md` 3.1절, `repo-structure/01-backend-layout.md` 6.3절 |
|
||||
| 샘플 모듈 | 샘플 leaf와 샘플 전용 Dockerfile을 폴더째 지운다(지운 경로는 `docs/upgrade/2026-11-maturity-review.md` B-49). 역할은 옮기지 않는다. 샘플 안에만 있던 템플릿 검사(OpenAPI 스냅숏, Date 헤더, 가상 스레드 MDC)도 함께 지운다. 예시는 매뉴얼과 생성 명령 출력이 맡는다 | 소유자(2026-11-07) | design-docs `repo-structure/README.md` 3.1절, `repo-structure/01-backend-layout.md` 6.2절 |
|
||||
|
||||
@@ -121,7 +121,7 @@
|
||||
| 규칙을 일부러 다르게 둔 타입 | 그 타입의 Javadoc |
|
||||
| 정적 분석 제외 | 제외 항목 옆 이유(`src/config/spotbugs/exclude-test.xml` 등) |
|
||||
| 규칙의 예외 경로 | 이유를 요구하는 표시(`@SystemCaller(reason)`) |
|
||||
| 복사본을 남긴 이유 | 가까운 `AGENTS.md`(예: `src/platforms/messaging/AGENTS.md`) |
|
||||
| 복사본을 남긴 이유 | 가까운 `AGENTS.md`. 복사본을 둔 leaf의 `build.gradle`이나 그 폴더의 `AGENTS.md`에 적는다 |
|
||||
| 되돌리기 비싼 선택 | `docs/adr/ADR-<영역>-<번호>-<제목>.md` |
|
||||
|
||||
## 패턴을 더하는 법
|
||||
|
||||
@@ -190,7 +190,7 @@ for k in tests skipped failures errors; do cat $(find "$x" -name 'TEST-*.xml') |
|
||||
| 장치 | 고정하는 것 | 단계 |
|
||||
| --- | --- | --- |
|
||||
| 자원 한계 lane | Tomcat·Jetty 부하·느린 클라이언트·종료, HTTP client 풀·스트리밍·재시도, Hikari 풀 | `performanceCheck` |
|
||||
| JMH 벤치마크 | `src/platforms/messaging/messaging-kafka/src/jmh`, `src/platforms/messaging/messaging-testkit/src/jmh`, `src/adapter/outbound/httpclient/src/jmh` | 명시 실행 |
|
||||
| JMH 벤치마크 | `src/adapter/outbound/httpclient/src/jmh`(메시징 벤치마크는 messaging-library repo로 옮겼다) | 명시 실행 |
|
||||
|
||||
## 6. 게이트를 믿을 조건 — 거짓 통과 막기
|
||||
|
||||
|
||||
@@ -6,34 +6,42 @@
|
||||
|
||||
| repo | 무엇 | Maven group | 카탈로그 칸 | 쓰는 leaf |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| [messaging-library](https://git.learn.hyeonworks.com/donghyeon.kang/messaging-library) | 메시징 제품(발행·소비 API, Kafka transport, outbox·inbox, 인증 증거) | `dev.cakit.messaging` | `messagingLibrary` | `adapter:outbound:messaging`(core-api), `adapter:outbound:messaging-kafka`(starter-kafka, `runtimeOnly`), `adapter:inbound:messaging`(core-api, reliability, reliability-api, reliability-jdbc-postgresql). 시험만: `composition:outbox-relay`(starter, `testCompileOnly`), `adapter:outbound:persistence-jpa`(reliability-jdbc-postgresql jar의 migration) |
|
||||
| [grpc-library](https://git.learn.hyeonworks.com/donghyeon.kang/grpc-library) | gRPC 플랫폼(Stable 7, advanced 2) | `dev.cakit.grpc` | 없음(채택 전) | 없음. `adapter:inbound:grpc`는 `io.grpc`를 직접 쓴다. 채택은 별도 결정이다 |
|
||||
| `messaging-library` | 메시징 제품 | `dev.cakit.messaging` | (옮긴 뒤 `messagingLibrary`) | 아직 `src/platforms/messaging`에 있다. 다음 분리 작업에서 옮긴다 |
|
||||
|
||||
고치는 법·게이트·릴리스는 각 repo의 `docs/work/`다. 이 repo의 매뉴얼은 위치만 가리킨다.
|
||||
- 고치는 법·게이트·릴리스는 각 repo의 `docs/work/`다. 이 repo의 매뉴얼은 위치만 가리킨다.
|
||||
- 템플릿은 `src/settings.gradle`의 `exclusiveContent` 저장소 하나로 받는다: `dev.cakit` group과 그 아래는 소유자 Gitea Packages에서만, 나머지는 Maven Central에서만 찾는다. 공개 owner라 읽기 토큰은 필요 없다. 이미지 빌드(`src/Dockerfile`의 `verifyDependencyLocks`)도 토큰 없이 Gitea에 닿아야 한다.
|
||||
- 라이브러리 패키지(`dev.cakit.*`)는 템플릿 재사용 체크리스트의 「`dev.caskeleton`을 새 패키지로 바꾼다」에 들지 않는다.
|
||||
|
||||
## 2. 라이브러리를 고칠 때
|
||||
|
||||
- 템플릿 안에서 라이브러리 코드를 고치지 않는다. 라이브러리 repo에서 고치고 릴리스한다.
|
||||
- 템플릿 변경 때문에 라이브러리를 고쳐야 하면 브랜치를 둘 만들고, 템플릿에서 명령 줄로만 끼워 같이 시험한다.
|
||||
- 템플릿 변경 때문에 라이브러리를 고쳐야 하면 두 repo에 브랜치를 하나씩 만들고, 두 repo를 같은 부모 폴더에 둔다(desktop은 `~/workspace/`). 템플릿에서 명령 줄로만 라이브러리를 끼워 같이 시험한다(composite build: Gradle이 같은 `group:artifact`의 외부 의존성을 끼운 빌드의 프로젝트로 바꿔 끼운다). Gradle 루트가 `src/`라 경로는 두 단계 위다.
|
||||
|
||||
```bash
|
||||
./gradlew --include-build ../grpc-library <태스크>
|
||||
./gradlew --include-build ../../messaging-library <태스크>
|
||||
```
|
||||
|
||||
그 상태로 lockfile을 쓰거나 커밋하지 않는다.
|
||||
- 병합 순서는 하나다: 라이브러리 PR 병합 → 태그·릴리스 → 템플릿 PR에서 버전을 올리고 lockfile을 다시 쓴다 → 템플릿 병합.
|
||||
- 라이브러리가 끌고 온 취약 의존성은 템플릿에서 먼저 덮어 막고(Boot 버전이나 카탈로그 `pinned-*`), 라이브러리 repo에 수정을 남긴다.
|
||||
그 상태로 lockfile을 쓰거나 커밋하지 않는다. 끼운 모듈은 lockfile 밖으로 빠질 수 있다. 끼운 빌드는 자기 카탈로그로 컴파일되므로 라이브러리 repo CI 결과와 다를 수 있다. 최종 판정은 배포한 좌표로 돈 템플릿 게이트다.
|
||||
- 병합 순서는 하나다: 라이브러리 PR 병합 → 태그·릴리스 → 템플릿 PR에서 버전을 올리고 lockfile을 다시 쓴다 → 템플릿 병합. 끼운 상태로만 통과하는 템플릿 PR은 병합하지 않는다.
|
||||
- 라이브러리가 끌고 온 취약 의존성은 템플릿에서 먼저 덮어 막고(Boot 버전이나 카탈로그 `pinned-*`. 지금 `pinned-lz4-java`·`pinned-snappy-java`는 메시징 라이브러리의 kafka-clients가 끌고 오는 것을 막는다), 라이브러리 repo에 수정을 남긴다.
|
||||
|
||||
## 3. 템플릿이 라이브러리 버전을 올릴 때
|
||||
|
||||
라이브러리를 카탈로그로 받는 leaf가 생긴 뒤의 절차다(지금은 없다).
|
||||
1. `src/gradle/libs.versions.toml`의 라이브러리 버전 칸(`messagingLibrary`)을 바꾼다. 같은 라이브러리의 모듈은 그 칸 하나로 같이 오른다.
|
||||
2. desktop에서 `./gradlew resolveAndLockAll --write-locks` 뒤 `verifyDependencyLocks`. lockfile 차이는 그 라이브러리 줄과 그것이 끌고 오는 외부 의존성뿐이어야 한다.
|
||||
3. 쓰는 leaf의 `check`와 `architectureCheck`, 그 leaf의 lane(메시징: `:adapter:inbound:messaging:messagingInboxRedeliveryIntegrationTest`, `:adapter:outbound:messaging-kafka:messagingKafkaRelayIntegrationTest`, persistence-jpa `test`의 migration 시험).
|
||||
4. 라이브러리 `CHANGELOG.md`에서 그 사이 버전의 깨지는 변경을 읽는다. MAJOR면 `docs/upgrade/`에 행을 더하고 커밋 제목에 `!`. migration을 더한 버전이면 `src/adapter/outbound/persistence-jpa/src/test/resources/db/applied-migrations.sha256`에 줄을 더한다.
|
||||
5. 커밋 제목 예: `build(deps): 메시징 라이브러리를 1.1.0으로 올린다`.
|
||||
|
||||
1. `src/gradle/libs.versions.toml`의 라이브러리 버전 칸을 바꾼다.
|
||||
2. desktop에서 `./gradlew resolveAndLockAll --write-locks` 뒤 `verifyDependencyLocks`.
|
||||
3. 쓰는 leaf의 `check`와 `architectureCheck`, 그 leaf의 lane.
|
||||
4. 라이브러리 `CHANGELOG.md`에서 그 사이 버전의 깨지는 변경을 읽는다. MAJOR면 `docs/upgrade/`에 행을 더하고 커밋 제목에 `!`.
|
||||
5. 커밋 제목 예: `build(deps): gRPC 라이브러리를 1.1.0으로 올린다`.
|
||||
## 4. 경계 검사(registry)
|
||||
|
||||
## 4. 받는 법(처음 채택할 때)
|
||||
라이브러리 모듈은 이 빌드의 프로젝트가 아니어서 `allowed_dependencies`가 보지 못한다. 그래서 registry가 두 칸을 더 가진다(`src/config/architecture/README.md` 「별도 repo 라이브러리」).
|
||||
|
||||
`src/settings.gradle`의 저장소 선언에 Gitea Maven 저장소를 `exclusiveContent`로 더한다. `dev.cakit` group은 그 저장소에서만, 나머지는 Maven Central에서만 찾는다. 선언 예는 라이브러리 repo README 「받는 법」이다. 공개 owner라 읽기 토큰은 필요 없다.
|
||||
- 맨 위 `library_groups`(`["dev.cakit"]`): 다스릴 group 접두사.
|
||||
- 행마다 `allowed_libraries`: 그 leaf가 쓸 수 있는 `group:artifact`. 운영 선언(`runtimeOnly` 포함)과 컴파일에서 보이는 소유 group 모듈이 모두 이 칸에 있어야 방향 검사가 통과한다.
|
||||
- 새 라이브러리 모듈을 leaf에 들일 때는 카탈로그 항목, leaf `build.gradle`, 그 행의 `allowed_libraries`를 같은 변경에서 바꾼다.
|
||||
|
||||
## 5. 처음 채택할 때(gRPC 같은 라이브러리)
|
||||
|
||||
`src/settings.gradle`의 저장소 선언은 이미 `dev.cakit`를 덮으니 바꾸지 않는다. 카탈로그에 버전 칸 하나와 쓰는 모듈의 `[libraries]` 항목을 더하고(`version.ref`로 그 칸을 쓴다), 쓰는 leaf의 registry 행에 `allowed_libraries`를 적고, lockfile을 다시 쓴다. 1절 표에 카탈로그 칸과 쓰는 leaf를 적는다.
|
||||
|
||||
@@ -101,7 +101,7 @@
|
||||
| # | 관점 | 볼 곳 | 이런 증거면 결함 |
|
||||
| --- | --- | --- | --- |
|
||||
| 1 | 코드 성숙도 | 바뀐 클래스와 호출자, 예외 경로 | 이름·Javadoc과 다른 동작, 항상 참·거짓인 조건 |
|
||||
| 2 | 구조적 성숙도 | registry `allowed_dependencies`, ArchUnit, leaf `AGENTS.md`, 저장소 루트와 `src/`의 최상위 목록(폴더마다 계층·조립 leaf, Gradle 루트 표준 `build-logic`·`gradle`·`config`, 지도에 적힌 예외 `platforms/`, 저장소 운영 `docs`·`scripts`·`.github` 중 하나인지) | HARD-STOP 위반, registry 밖 leaf 디렉터리, 템플릿 패키지가 기능 패키지를 import, 역할을 한 문장으로 말할 수 없는 최상위 폴더, 같은 역할의 폴더가 같은 높이에 여럿, 지도(`AGENTS.md`)와 `scripts/check-repo-layout.py` 허용 목록에 없는 최상위 항목 |
|
||||
| 2 | 구조적 성숙도 | registry `allowed_dependencies`, ArchUnit, leaf `AGENTS.md`, 저장소 루트와 `src/`의 최상위 목록(폴더마다 계층·조립 leaf, Gradle 루트 표준 `build-logic`·`gradle`·`config`, 저장소 운영 `docs`·`scripts`·`.github` 중 하나인지) | HARD-STOP 위반, registry 밖 leaf 디렉터리, 템플릿 패키지가 기능 패키지를 import, 역할을 한 문장으로 말할 수 없는 최상위 폴더, 같은 역할의 폴더가 같은 높이에 여럿, 지도(`AGENTS.md`)와 `scripts/check-repo-layout.py` 허용 목록에 없는 최상위 항목 |
|
||||
| 3 | 변경 용이성 | 기능 하나를 더하거나 뺄 때 고칠 파일, `scripts/new-feature.sh` 왕복 | 같은 규칙을 여러 곳에서 바꿔야 함 |
|
||||
| 4 | 인지 부하 | 따라 할 예시 수, 같은 질문에 답하는 문서 수, 루트 README만 읽고 구조·매뉴얼·첫 실행을 5분 안에 찾는가(cold-read 결과), 이벤트별 workflow job 수 | 예시·규칙이 여러 갈래이고 고르는 기준이 없음, 같은 Gradle 태스크를 두 단계 이상이 돎(의도한 행렬 제외) |
|
||||
| 5 | 위험 가시성 | 기본값, 설정 검증, 기동 rule, 프로필 허용 목록 | 위험이 기본값 뒤에 숨음, 레지스트리 `required`인데 코드는 빈 값 허용 |
|
||||
@@ -201,15 +201,15 @@ RED가 증거가 되려면: 실패 메시지가 그 결함을 말한다. 머신
|
||||
- 새 업무 기능은 계층 leaf 안의 패키지가 기본이다(`docs/manual/03-placement.md`).
|
||||
- 템플릿 패키지 목록은 `src/application-core/README.md` 「패키지 소유 (Package ownership)」 표 하나가 정본이다. 템플릿에 패키지를 더하면 같은 변경에서 표에 넣는다.
|
||||
- capability는 자기 `AutoConfiguration.imports`로 켜진다. `app-bootstrap`은 capability 이름·스위치 목록·scan 정규식을 갖지 않는다.
|
||||
- 다른 경계(다른 leaf, 다른 빌드, 다른 repo가 될 수 있는 폴더)의 파일을 경로(`../../../`)로 읽는 빌드 스크립트·테스트는 결함 후보다. 그 경계가 옮겨 가면 조용히 깨진다. gRPC 라이브러리를 옮길 때 이런 결합이 다섯 곳 나왔다(design-docs `repo-structure/05-library-repos.md` 4.6절).
|
||||
- vendored family(`messaging:*`)는 `domain-core`·`application-core`·`shared-contract`에 의존하지 않는다. 그래서 남는 복사본은 이유를 family `AGENTS.md`에 적고, 값이 같아야 하면 대조 테스트를 둔다.
|
||||
- 다른 경계(다른 leaf, 다른 빌드, 다른 repo가 될 수 있는 폴더)의 파일을 경로(`../../../`)로 읽는 빌드 스크립트·테스트는 결함 후보다. 그 경계가 옮겨 가면 조용히 깨진다. gRPC·메시징 라이브러리를 옮길 때 이런 결합이 다섯 곳 나왔다(design-docs `repo-structure/05-library-repos.md` 4.6절). 다른 repo의 파일이 필요하면 그 repo가 배포한 artifact에서 읽는다(예: persistence-jpa의 migration 시험이 메시징 라이브러리 jar의 `db/migration/messaging`을 푼다).
|
||||
- 별도 repo 라이브러리(`dev.cakit.*`)는 템플릿 타입에 의존하지 않는다. 그래서 남는 복사본은 이유를 그 라이브러리 repo의 모듈 지침에 적는다. 템플릿 leaf가 라이브러리 모듈을 쓰면 registry 행의 `allowed_libraries`에 좌표를 적는다. 적지 않은 소유 group 모듈을 선언하거나 컴파일에서 보면 방향 검사가 실패한다.
|
||||
- source set은 runtime·classpath·외부 인프라·JVM 옵션·실행 비용 중 하나가 다를 때만 나눈다. 공유 테스트 코드는 `src/testFixtures/java`다(`docs/adr/ADR-BUILD-001-one-convention-for-shared-test-code.md`).
|
||||
- 마이그레이션은 저장소마다 자기 디렉터리와 history table을 가진다. 번호는 스트림 안의 순번이다. 어딘가에 적용된 파일은 고치지 않는다(`src/adapter/outbound/persistence-jpa/src/test/resources/db/applied-migrations.sha256`이 해시를 고정한다).
|
||||
- 문서 위치 규칙은 `docs/README.md`가 정본이다.
|
||||
|
||||
leaf를 더하거나 옮기거나 지울 때 같은 변경에서 함께 바꾼다:
|
||||
|
||||
- [ ] `src/config/architecture/modules.json`: ID, `source_path`, `gradle_path`, `allowed_dependencies`
|
||||
- [ ] `src/config/architecture/modules.json`: ID, `source_path`, `gradle_path`, `allowed_dependencies`, 라이브러리를 쓰면 `allowed_libraries`
|
||||
- [ ] leaf `build.gradle`: `ca.java-library`·`ca.spring-library`·`ca.platform-module` 중 하나
|
||||
- [ ] lockfile(`verifyDependencyLocks`가 통과하게 다시 만든다)
|
||||
- [ ] capability면 `src/app-bootstrap/build.gradle`의 `runtimeOnly` 한 줄과 자기 `AutoConfiguration.imports`
|
||||
|
||||
@@ -58,7 +58,8 @@ ROOT_ALLOWED = {
|
||||
"testcontainers.properties.example": "Testcontainers 로컬 설정 예",
|
||||
}
|
||||
|
||||
# src/ 바로 아래: 계층·조립 leaf, 들여온 제품 묶음, Gradle 루트 표준 폴더와 빌드 파일.
|
||||
# src/ 바로 아래: 계층·조립 leaf, Gradle 루트 표준 폴더와 빌드 파일. 계층이 아닌 라이브러리(메시징·gRPC)는
|
||||
# 2026-11-08에 별도 repo로 나갔다(docs/work/reference/related-repos.md). 그 자리(platforms)는 다시 두지 않는다.
|
||||
SRC_ALLOWED = {
|
||||
# 계층과 조립
|
||||
"domain-core": "계층",
|
||||
@@ -70,8 +71,6 @@ SRC_ALLOWED = {
|
||||
"adapter": "계층(adapter leaf 묶음)",
|
||||
"composition": "조립(Clean Architecture의 Main)",
|
||||
"app-bootstrap": "조립 루트",
|
||||
# 들여온 제품
|
||||
"platforms": "들여온 제품(messaging). gRPC는 2026-11-08 별도 repo grpc-library로",
|
||||
# Gradle 루트 표준
|
||||
"build-logic": "빌드 규칙(included build)",
|
||||
"config": "빌드 전체 도구 설정(registry, checkstyle, spotbugs, 테스트 이미지)",
|
||||
|
||||
@@ -46,14 +46,17 @@ SKIPPED = "포맷을 건너뛰었다"
|
||||
|
||||
# --- N1: the layer rules the gates hold, checked on the imports of one edited main source --------------
|
||||
# Mirrors DomainPurityArchitectureTest (DOMAIN_IS_PURE, DOMAIN_HAS_NO_LOGGER).
|
||||
# dev.cakit.: the owner's libraries (messaging-library, grpc-library) are reached only through adapters;
|
||||
# a layer row may not list one in allowed_libraries (registry library_groups, build-logic ArchitecturePlugin).
|
||||
DOMAIN_FORBIDDEN = ("org.springframework.", "jakarta.persistence.", "javax.persistence.", "jakarta.servlet.",
|
||||
"org.hibernate.", "lombok.", "org.slf4j.", "java.util.logging.", "ch.qos.logback.",
|
||||
"org.apache.logging.log4j.")
|
||||
"org.apache.logging.log4j.", "dev.cakit.")
|
||||
# Mirrors VerifyApplicationCoreDependencyPurityTask and the application-core AGENTS.md forbidden list.
|
||||
APPLICATION_FORBIDDEN = ("org.springframework.", "org.slf4j.", "ch.qos.logback.", "org.apache.logging.log4j.",
|
||||
"io.micrometer.", "java.util.logging.", "jakarta.persistence.", "javax.persistence.",
|
||||
"lombok.")
|
||||
SHARED_FORBIDDEN = ("org.springframework.", "jakarta.", "javax.persistence.", "org.hibernate.", "lombok.")
|
||||
"lombok.", "dev.cakit.")
|
||||
SHARED_FORBIDDEN = ("org.springframework.", "jakarta.", "javax.persistence.", "org.hibernate.", "lombok.",
|
||||
"dev.cakit.")
|
||||
# HARD-STOP 2: an inbound adapter reaching the store.
|
||||
INBOUND_FORBIDDEN = ("org.springframework.data.repository.", "org.springframework.data.jpa.",
|
||||
"org.springframework.data.mongodb.repository.", "jakarta.persistence.", "javax.persistence.")
|
||||
|
||||
@@ -252,6 +252,11 @@ class BoundaryNudgeTest(RepositoryTestCase):
|
||||
self.assertIn("HARD-STOP 1 의심: `domain-core`가 `org.springframework.stereotype.Component`", text)
|
||||
self.assertIn("architectureCheck", text)
|
||||
|
||||
def test_an_owned_library_in_the_application_is_flagged(self) -> None:
|
||||
text = self.nudge("src/application-core", "dev/caskeleton/application/order/Notify.java",
|
||||
"import dev.cakit.messaging.api.MessageEnvelope;")
|
||||
self.assertIn("`application-core`가 `dev.cakit.messaging.api.MessageEnvelope`", text)
|
||||
|
||||
def test_an_inbound_dto_in_the_application_is_hard_stop_3(self) -> None:
|
||||
text = self.nudge("src/application-core", "dev/caskeleton/application/order/Place.java",
|
||||
"import dev.caskeleton.adapter.inbound.web.order.OrderRequest;")
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
- 모듈 ID `adapter-inbound-messaging`, Gradle 경로 `:adapter:inbound:messaging`. registry 정본:
|
||||
`src/config/architecture/modules.json`.
|
||||
- 책임: 들여온 메시징 플랫폼의 애플리케이션 소비 쪽이다 — 플랫폼이 애플리케이션에서 받아야 하는
|
||||
- 책임: 메시징 라이브러리(별도 repo messaging-library, Maven `dev.cakit.messaging`)의 애플리케이션 소비 쪽이다 — 라이브러리가 애플리케이션에서 받아야 하는
|
||||
inbox 부품(애플리케이션 DataSource 위의 `JdbcInboxRepository`, 그 `PlatformTransactionManager` 위의
|
||||
`TransactionRunner`, 자기 Flyway stream `MessagingInboxSchemaStream`인 inbox migration)과 애플리케이션의
|
||||
`MessageHandler` 구현들이다. 핸들러 하나는 전달 하나를 유스케이스 호출 하나로 바꾼다. 핸들러는 그 밖에
|
||||
@@ -14,7 +14,7 @@
|
||||
(`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`). 핸들러는 프로젝트 타입(`MessageHandler<T>`)만 구현하고,
|
||||
`USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`). 핸들러는 프로젝트 타입(메시징 라이브러리의 `MessageHandler<T>`. `dev.cakit..`도 프로젝트 타입으로 친다)만 구현하고,
|
||||
`Runnable`이나 프로젝트 밖의 다른 타입은 구현하지 않는다(`SYSTEM_CALLERS_HAVE_ONLY_PROJECT_SUPERTYPES`).
|
||||
- 시험: 자동 구성과 inbox 동작을 보는 시험. `./gradlew :adapter:inbound:messaging:check`.
|
||||
실제 Kafka + PostgreSQL 재전달 lane은 `messagingInboxRedeliveryIntegrationTest`다(`:integrationCheck`).
|
||||
|
||||
@@ -3,7 +3,7 @@ plugins {
|
||||
id 'ca.spring-config'
|
||||
}
|
||||
|
||||
// The application's consume side of the vendored messaging platform (review 2026-11-01 06-08),
|
||||
// The application's consume side of the messaging library (dev.cakit.messaging, review 2026-11-01 06-08),
|
||||
// selected by one line in a composition root:
|
||||
//
|
||||
// runtimeOnly project(':adapter:inbound:messaging')
|
||||
@@ -29,14 +29,14 @@ base {
|
||||
|
||||
dependencies {
|
||||
implementation project(':application-core')
|
||||
implementation project(':messaging:messaging-core-api')
|
||||
implementation project(':messaging:messaging-reliability')
|
||||
implementation project(':messaging:messaging-reliability-api')
|
||||
// JdbcInboxRepository only. The leaf also exports the platform admin journal (api
|
||||
// messaging-admin), which this leaf has no use for and no registered edge to; the starter puts it
|
||||
// on the runtime classpath anyway.
|
||||
implementation(project(':messaging:messaging-reliability-jdbc-postgresql')) {
|
||||
exclude group: 'dev.caskeleton', module: 'messaging-admin'
|
||||
implementation libs.messaging.core.api
|
||||
implementation libs.messaging.reliability
|
||||
implementation libs.messaging.reliability.api
|
||||
// JdbcInboxRepository only. The module also exports the library's admin journal (api
|
||||
// messaging-admin), which this leaf has no use for and no registered library edge to; the starter
|
||||
// puts it on the runtime classpath anyway.
|
||||
implementation(libs.messaging.reliability.jdbc.postgresql) {
|
||||
exclude group: 'dev.cakit.messaging', module: 'messaging-admin'
|
||||
}
|
||||
|
||||
implementation 'org.springframework.boot:spring-boot-autoconfigure'
|
||||
@@ -76,7 +76,7 @@ configurations {
|
||||
|
||||
// Test-only edges of the redelivery lane: the publishing side as a composition root selects it
|
||||
// (the Kafka capability, the outbox relay, the JPA outbox over PostgreSQL), the port owner's event
|
||||
// fixture, and the platform's MessageContracts holder the consumer registers its payload type in.
|
||||
// fixture, and the library's MessageContracts holder the consumer registers its payload type in.
|
||||
// Test edges are outside the registry gate.
|
||||
dependencies {
|
||||
integrationTestImplementation project(':adapter:outbound:messaging-kafka')
|
||||
@@ -84,8 +84,8 @@ dependencies {
|
||||
integrationTestImplementation project(':adapter:outbound:persistence-jpa')
|
||||
integrationTestImplementation project(':application-core')
|
||||
integrationTestImplementation testFixtures(project(':application-core'))
|
||||
integrationTestImplementation project(':messaging:messaging-core-api')
|
||||
integrationTestImplementation project(':messaging:messaging-spring-boot-starter')
|
||||
integrationTestImplementation libs.messaging.core.api
|
||||
integrationTestImplementation libs.messaging.spring.boot.starter
|
||||
integrationTestImplementation 'org.springframework:spring-jdbc'
|
||||
integrationTestImplementation 'org.flywaydb:flyway-core'
|
||||
integrationTestImplementation 'org.apache.kafka:kafka-clients'
|
||||
|
||||
@@ -50,6 +50,20 @@ commons-collections:commons-collections:3.2.2=checkstyle
|
||||
commons-io:commons-io:2.20.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath
|
||||
commons-io:commons-io:2.21.0=spotbugs
|
||||
commons-logging:commons-logging:1.3.6=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-admin:1.0.0=integrationTestRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-core-api:1.0.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-kafka:1.0.0=integrationTestRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-observability:1.0.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-policy:1.0.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-reliability-api:1.0.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-reliability-jdbc-postgresql:1.0.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-reliability:1.0.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-runtime-core:1.0.0=integrationTestRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-schema-json:1.0.0=integrationTestRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-security:1.0.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-spring-boot-starter-kafka:1.0.0=integrationTestRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-spring-boot-starter:1.0.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-transport-spi:1.0.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath
|
||||
info.picocli:picocli:4.7.7=checkstyle
|
||||
io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor
|
||||
io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor
|
||||
|
||||
+7
-7
@@ -3,6 +3,13 @@ package dev.caskeleton.adapter.inbound.messaging;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.awaitility.Awaitility.await;
|
||||
|
||||
import dev.cakit.messaging.api.MessageId;
|
||||
import dev.cakit.messaging.api.MessageType;
|
||||
import dev.cakit.messaging.api.delivery.HandleResult;
|
||||
import dev.cakit.messaging.api.delivery.MessageDelivery;
|
||||
import dev.cakit.messaging.api.delivery.MessageHandler;
|
||||
import dev.cakit.messaging.api.destination.DestinationName;
|
||||
import dev.cakit.messaging.api.destination.MessageDestination;
|
||||
import dev.caskeleton.application.capability.Idempotency;
|
||||
import dev.caskeleton.application.capability.RepositoryAccess;
|
||||
import dev.caskeleton.application.capability.UseCaseCapability;
|
||||
@@ -13,13 +20,6 @@ import dev.caskeleton.application.security.SystemCaller;
|
||||
import dev.caskeleton.application.security.SystemInvoked;
|
||||
import dev.caskeleton.application.transaction.TransactionMode;
|
||||
import dev.caskeleton.application.transaction.TransactionPort;
|
||||
import dev.caskeleton.messaging.api.MessageId;
|
||||
import dev.caskeleton.messaging.api.MessageType;
|
||||
import dev.caskeleton.messaging.api.delivery.HandleResult;
|
||||
import dev.caskeleton.messaging.api.delivery.MessageDelivery;
|
||||
import dev.caskeleton.messaging.api.delivery.MessageHandler;
|
||||
import dev.caskeleton.messaging.api.destination.DestinationName;
|
||||
import dev.caskeleton.messaging.api.destination.MessageDestination;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
|
||||
+5
-5
@@ -1,9 +1,9 @@
|
||||
package dev.caskeleton.adapter.inbound.messaging;
|
||||
|
||||
import dev.caskeleton.messaging.api.delivery.MessageHandler;
|
||||
import dev.caskeleton.messaging.inbox.IdempotentConsumer;
|
||||
import dev.caskeleton.messaging.inbox.JdbcInboxRepository;
|
||||
import dev.caskeleton.messaging.reliability.InboxRepository;
|
||||
import dev.cakit.messaging.api.delivery.MessageHandler;
|
||||
import dev.cakit.messaging.inbox.IdempotentConsumer;
|
||||
import dev.cakit.messaging.inbox.JdbcInboxRepository;
|
||||
import dev.cakit.messaging.reliability.InboxRepository;
|
||||
import javax.sql.DataSource;
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
|
||||
@@ -43,7 +43,7 @@ import org.springframework.transaction.support.TransactionTemplate;
|
||||
"org.springframework.boot.hibernate.autoconfigure.HibernateJpaAutoConfiguration",
|
||||
"org.springframework.boot.jdbc.autoconfigure.DataSourceTransactionManagerAutoConfiguration"
|
||||
},
|
||||
beforeName = "dev.caskeleton.messaging.autoconfigure.MessagingPlatformRootAutoConfiguration")
|
||||
beforeName = "dev.cakit.messaging.autoconfigure.MessagingPlatformRootAutoConfiguration")
|
||||
@ConditionalOnBean({MessageHandler.class, DataSource.class, PlatformTransactionManager.class})
|
||||
public class MessagingInboxAutoConfiguration {
|
||||
|
||||
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package dev.cakit.messaging.autoconfigure;
|
||||
|
||||
import dev.cakit.messaging.reliability.InboxRepository;
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.core.Ordered;
|
||||
|
||||
/**
|
||||
* Test stand-in with the exact name of the messaging library's root auto-configuration.
|
||||
*
|
||||
* <p>The library builds its inbox consumer only from an {@link InboxRepository} the application
|
||||
* provides, so the application's {@code MessagingInboxAutoConfiguration} must run first ({@code
|
||||
* beforeName}). This stand-in asks to run first itself ({@code HIGHEST_PRECEDENCE}) and records, as
|
||||
* a bean, whether it saw the repository: it does only if the constraint put the inbox configuration
|
||||
* ahead of it. The starter is not on this leaf's test classpath, so the name does not collide.
|
||||
*/
|
||||
@AutoConfiguration
|
||||
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
|
||||
public class MessagingPlatformRootAutoConfiguration {
|
||||
|
||||
/** Present only when the application's inbox repository existed as this root was processed. */
|
||||
public record SawTheInbox() {}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnBean(InboxRepository.class)
|
||||
SawTheInbox sawTheInbox() {
|
||||
return new SawTheInbox();
|
||||
}
|
||||
}
|
||||
+39
-19
@@ -3,25 +3,25 @@ package dev.caskeleton.adapter.inbound.messaging;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.catchThrowable;
|
||||
|
||||
import dev.caskeleton.messaging.api.ContentType;
|
||||
import dev.caskeleton.messaging.api.MessageEnvelope;
|
||||
import dev.caskeleton.messaging.api.MessageId;
|
||||
import dev.caskeleton.messaging.api.MessageType;
|
||||
import dev.caskeleton.messaging.api.ProducerId;
|
||||
import dev.caskeleton.messaging.api.SchemaVersion;
|
||||
import dev.caskeleton.messaging.api.TraceContext;
|
||||
import dev.caskeleton.messaging.api.delivery.DeliveryContext;
|
||||
import dev.caskeleton.messaging.api.delivery.DeliveryMetadata;
|
||||
import dev.caskeleton.messaging.api.delivery.HandleResult;
|
||||
import dev.caskeleton.messaging.api.delivery.MessageDelivery;
|
||||
import dev.caskeleton.messaging.api.delivery.MessageHandler;
|
||||
import dev.caskeleton.messaging.api.destination.DestinationName;
|
||||
import dev.caskeleton.messaging.api.destination.MessageDestination;
|
||||
import dev.caskeleton.messaging.api.header.MessageHeaders;
|
||||
import dev.caskeleton.messaging.inbox.IdempotentConsumer;
|
||||
import dev.caskeleton.messaging.inbox.InboxMessageHandler;
|
||||
import dev.caskeleton.messaging.inbox.JdbcInboxRepository;
|
||||
import dev.caskeleton.messaging.reliability.InboxRepository;
|
||||
import dev.cakit.messaging.api.ContentType;
|
||||
import dev.cakit.messaging.api.MessageEnvelope;
|
||||
import dev.cakit.messaging.api.MessageId;
|
||||
import dev.cakit.messaging.api.MessageType;
|
||||
import dev.cakit.messaging.api.ProducerId;
|
||||
import dev.cakit.messaging.api.SchemaVersion;
|
||||
import dev.cakit.messaging.api.TraceContext;
|
||||
import dev.cakit.messaging.api.delivery.DeliveryContext;
|
||||
import dev.cakit.messaging.api.delivery.DeliveryMetadata;
|
||||
import dev.cakit.messaging.api.delivery.HandleResult;
|
||||
import dev.cakit.messaging.api.delivery.MessageDelivery;
|
||||
import dev.cakit.messaging.api.delivery.MessageHandler;
|
||||
import dev.cakit.messaging.api.destination.DestinationName;
|
||||
import dev.cakit.messaging.api.destination.MessageDestination;
|
||||
import dev.cakit.messaging.api.header.MessageHeaders;
|
||||
import dev.cakit.messaging.inbox.IdempotentConsumer;
|
||||
import dev.cakit.messaging.inbox.InboxMessageHandler;
|
||||
import dev.cakit.messaging.inbox.JdbcInboxRepository;
|
||||
import dev.cakit.messaging.reliability.InboxRepository;
|
||||
import java.sql.SQLException;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
@@ -73,6 +73,26 @@ class MessagingInboxAutoConfigurationTest {
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("inbox 조립은 라이브러리 root보다 먼저 돌아 root의 bean 조건이 inbox를 본다")
|
||||
void theInboxIsAssembledBeforeTheLibraryRootThatNeedsIt() {
|
||||
// given: a root stand-in that asks to run first and records whether it saw the inbox.
|
||||
ApplicationContextRunner assembled =
|
||||
runner.withConfiguration(
|
||||
AutoConfigurations.of(
|
||||
dev.cakit.messaging.autoconfigure.MessagingPlatformRootAutoConfiguration.class));
|
||||
|
||||
// when & then
|
||||
assembled
|
||||
.withBean(MessageHandler.class, () -> exampleHandler(new ArrayList<>()))
|
||||
.run(
|
||||
context ->
|
||||
assertThat(context)
|
||||
.hasSingleBean(
|
||||
dev.cakit.messaging.autoconfigure.MessagingPlatformRootAutoConfiguration
|
||||
.SawTheInbox.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("소비할 handler가 없으면 inbox를 조립하지 않는다")
|
||||
void withoutAHandlerNothingIsAssembled() {
|
||||
|
||||
+18
-18
@@ -2,6 +2,24 @@ package dev.caskeleton.adapter.inbound.messaging;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.cakit.messaging.api.ContentType;
|
||||
import dev.cakit.messaging.api.MessageEnvelope;
|
||||
import dev.cakit.messaging.api.MessageId;
|
||||
import dev.cakit.messaging.api.MessageType;
|
||||
import dev.cakit.messaging.api.ProducerId;
|
||||
import dev.cakit.messaging.api.SchemaVersion;
|
||||
import dev.cakit.messaging.api.TraceContext;
|
||||
import dev.cakit.messaging.api.delivery.DeliveryContext;
|
||||
import dev.cakit.messaging.api.delivery.DeliveryMetadata;
|
||||
import dev.cakit.messaging.api.delivery.HandleResult;
|
||||
import dev.cakit.messaging.api.delivery.MessageDelivery;
|
||||
import dev.cakit.messaging.api.delivery.MessageHandler;
|
||||
import dev.cakit.messaging.api.destination.DestinationName;
|
||||
import dev.cakit.messaging.api.destination.MessageDestination;
|
||||
import dev.cakit.messaging.api.header.MessageHeaders;
|
||||
import dev.cakit.messaging.inbox.IdempotentConsumer;
|
||||
import dev.cakit.messaging.inbox.InboxMessageHandler;
|
||||
import dev.cakit.messaging.reliability.InboxRepository;
|
||||
import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException;
|
||||
import dev.caskeleton.application.capability.Idempotency;
|
||||
import dev.caskeleton.application.capability.RepositoryAccess;
|
||||
@@ -12,24 +30,6 @@ import dev.caskeleton.application.transaction.TransactionMode;
|
||||
import dev.caskeleton.application.transaction.TransactionPort;
|
||||
import dev.caskeleton.application.transaction.testkit.DirectTransactionPort;
|
||||
import dev.caskeleton.composition.runtime.authorization.PermissionEnforcementConfig;
|
||||
import dev.caskeleton.messaging.api.ContentType;
|
||||
import dev.caskeleton.messaging.api.MessageEnvelope;
|
||||
import dev.caskeleton.messaging.api.MessageId;
|
||||
import dev.caskeleton.messaging.api.MessageType;
|
||||
import dev.caskeleton.messaging.api.ProducerId;
|
||||
import dev.caskeleton.messaging.api.SchemaVersion;
|
||||
import dev.caskeleton.messaging.api.TraceContext;
|
||||
import dev.caskeleton.messaging.api.delivery.DeliveryContext;
|
||||
import dev.caskeleton.messaging.api.delivery.DeliveryMetadata;
|
||||
import dev.caskeleton.messaging.api.delivery.HandleResult;
|
||||
import dev.caskeleton.messaging.api.delivery.MessageDelivery;
|
||||
import dev.caskeleton.messaging.api.delivery.MessageHandler;
|
||||
import dev.caskeleton.messaging.api.destination.DestinationName;
|
||||
import dev.caskeleton.messaging.api.destination.MessageDestination;
|
||||
import dev.caskeleton.messaging.api.header.MessageHeaders;
|
||||
import dev.caskeleton.messaging.inbox.IdempotentConsumer;
|
||||
import dev.caskeleton.messaging.inbox.InboxMessageHandler;
|
||||
import dev.caskeleton.messaging.reliability.InboxRepository;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashSet;
|
||||
|
||||
@@ -3,10 +3,11 @@
|
||||
- 모듈 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/AGENTS.md`)에 속한다. 여기 클래스를 두면 세 번째 자리가 생긴다. 허용 edge는
|
||||
`adapter:outbound:messaging`(애플리케이션의 bridge)과 메시징 라이브러리의 `messaging-spring-boot-starter-kafka`(Kafka
|
||||
전송, Maven `dev.cakit.messaging`, 카탈로그 `libs.messaging.spring.boot.starter.kafka`)를 묶고, 모듈 기본값
|
||||
`config/module-defaults/messaging.yml`을 싣는다.
|
||||
- 경계: 여기 코드를 더하지 않는다. 발행 규칙은 bridge(`adapter:outbound:messaging`)에, Kafka 규칙은 메시징
|
||||
라이브러리(messaging-library repo의 [messaging/AGENTS.md](https://git.learn.hyeonworks.com/donghyeon.kang/messaging-library/src/branch/main/messaging/AGENTS.md))에 속한다. 여기 클래스를 두면 세 번째 자리가 생긴다. 허용 edge는
|
||||
registry 항목에서만 온다.
|
||||
- 시험: 켜기 시험(`./gradlew :adapter:outbound:messaging-kafka:test`)과 실제 Kafka lane
|
||||
`messagingKafkaRelayIntegrationTest`(relay → bridge → broker record 바이트, `:integrationCheck`).
|
||||
|
||||
@@ -15,7 +15,8 @@ adapter:outbound:messaging-kafka
|
||||
├─ config/module-defaults/messaging.yml (설정 기본값, support 로더가 읽음)
|
||||
├─ adapter:outbound:messaging OutboxMessagePublishPort,
|
||||
│ IntegrationEventPublishPort bridge
|
||||
└─ messaging:messaging-spring-boot-starter-kafka messaging platform + Kafka transport
|
||||
└─ dev.cakit.messaging:messaging-spring-boot-starter-kafka 메시징 라이브러리 + Kafka transport
|
||||
(별도 repo messaging-library, 카탈로그 messagingLibrary)
|
||||
```
|
||||
|
||||
| 포트 (application-core) | 구현 |
|
||||
@@ -31,7 +32,8 @@ adapter:outbound:messaging-kafka
|
||||
app-bootstrap은 이 파일을 모른다.
|
||||
- broker 주소는 `APP_MESSAGING_KAFKA_BROKERS` 하나(`app.messaging.brokers.kafka.bootstrap-servers`).
|
||||
`spring.kafka.bootstrap-servers`는 읽지 않는다. 논리 broker 이름은 `kafka` 하나다. Kafka 연결의
|
||||
TLS·SASL은 platform의 broker profile이 소유한다(`docs/messaging/configuration-reference.md`).
|
||||
TLS·SASL은 메시징 라이브러리의 broker profile이 소유한다(그 repo의
|
||||
[configuration-reference.md](https://git.learn.hyeonworks.com/donghyeon.kang/messaging-library/src/branch/main/docs/messaging/configuration-reference.md)).
|
||||
- 발행 경로는 하나다. 옛 `KafkaSender` seam(TLS/SASL 없는 R0 producer)은 outbox를 canonical로
|
||||
통일하면서 삭제했다(2026-09-28).
|
||||
- 발행할 event의 contract마다 destination을 선언해야 한다(`app.messaging.destinations.<logical
|
||||
@@ -44,7 +46,7 @@ adapter:outbound:messaging-kafka
|
||||
runtimeOnly project(':adapter:outbound:messaging-kafka') // Kafka 발행
|
||||
```
|
||||
|
||||
이 줄을 지우면 발행 포트 구현, Kafka client, messaging platform, 설정 기본값이 모두 함께 빠진다.
|
||||
이 줄을 지우면 발행 포트 구현, Kafka client, 메시징 라이브러리, 설정 기본값이 모두 함께 빠진다.
|
||||
|
||||
## 필요한 env 키
|
||||
|
||||
@@ -56,16 +58,16 @@ runtimeOnly project(':adapter:outbound:messaging-kafka') // Kafka 발행
|
||||
| 항상 | `APP_MESSAGING_PRODUCER_ID` (배포와 무관한 논리적 서비스 이름). 비어 있으면 기동이 실패한다 — 모든 발행이 canonical bridge를 지난다 |
|
||||
| 끌 때 | `APP_MESSAGING_ENABLED=false` |
|
||||
|
||||
`APP_MESSAGING_BROKER`는 platform이 쓸 broker 선택값이고 기본값이 `kafka`다. 등록된 broker가 Kafka
|
||||
하나라 바꿀 일이 없다. destination·broker profile·보안 설정은
|
||||
`docs/messaging/configuration-reference.md`.
|
||||
`APP_MESSAGING_BROKER`는 메시징 라이브러리가 쓸 broker 선택값이고 기본값이 `kafka`다. 등록된 broker가 Kafka
|
||||
하나라 바꿀 일이 없다. destination·broker profile·보안 설정은 messaging-library repo의
|
||||
[configuration-reference.md](https://git.learn.hyeonworks.com/donghyeon.kang/messaging-library/src/branch/main/docs/messaging/configuration-reference.md)다.
|
||||
|
||||
## 실제 broker로 도는 앱 발행 경로 lane (`messagingKafkaRelayIntegrationTest`)
|
||||
|
||||
앱이 실제로 쓰는 발행 경로 — `composition:outbox-relay` relay → `OutboxMessagePublishAdapter` →
|
||||
platform bridge → `DefaultMessagePublisher` → Kafka — 를 Testcontainers Kafka(`apache/kafka:4.1.0`,
|
||||
`-PmessagingKafkaImage=`로 교체)로 끝까지 돌린다(리뷰 2026-11-01 06-09). vendored 쪽 broker lane은
|
||||
platform 자기 relay와 publisher 직접 호출만 검증하므로 앱 경로의 증거가 아니다.
|
||||
`-PmessagingKafkaImage=`로 교체)로 끝까지 돌린다(리뷰 2026-11-01 06-09). 메시징 라이브러리 쪽 broker lane
|
||||
(그 repo의 인증 lane)은 라이브러리 자기 relay와 publisher 직접 호출만 검증하므로 앱 경로의 증거가 아니다.
|
||||
|
||||
- 정상 발행: append한 row를 relay가 보내고, 테스트가 topic에서 읽은 레코드 값이 envelope 바이트와
|
||||
같고 key가 partition key와 같다.
|
||||
|
||||
@@ -7,16 +7,18 @@ plugins {
|
||||
//
|
||||
// runtimeOnly project(':adapter:outbound:messaging-kafka')
|
||||
//
|
||||
// That line brings the broker-neutral application bridge (adapter:outbound:messaging), the vendored
|
||||
// messaging platform with its Kafka transport, and the capability's settings
|
||||
// That line brings the broker-neutral application bridge (adapter:outbound:messaging), the messaging
|
||||
// library (dev.cakit.messaging, messaging-library repo) with its Kafka transport, and the capability's settings
|
||||
// (config/module-defaults/messaging.yml). Deleting it removes all of them. The leaf has no code of
|
||||
// its own: it is the selection, not an adapter. Its one test boots the capability the way an
|
||||
// application gets it.
|
||||
|
||||
// Every project shares the group dev.caskeleton, and the vendored transport is also named
|
||||
// messaging-kafka (:messaging:messaging-kafka). Same group and name is the same module to Gradle,
|
||||
// which silently substituted this project for the vendored one wherever both were reachable, so the
|
||||
// platform's Kafka transport classes went missing at runtime. A group of its own keeps them apart.
|
||||
// Every project shares the group dev.caskeleton. The messaging library's Kafka transport used to be
|
||||
// a project here too, also named messaging-kafka (:messaging:messaging-kafka), and same group and
|
||||
// name is the same module to Gradle: it silently substituted this project for the transport wherever
|
||||
// both were reachable, so the Kafka transport classes went missing at runtime. The library is now
|
||||
// dev.cakit.messaging:messaging-kafka (messaging-library repo); a group of its own still keeps this
|
||||
// project apart from :adapter:outbound:messaging and from any project a service adds.
|
||||
group = 'dev.caskeleton.adapter'
|
||||
// And a jar file name of its own: a Boot jar stores libraries in BOOT-INF/lib/ by file name, so the
|
||||
// two messaging-kafka-<version>.jar collided and an application selecting this leaf could not be
|
||||
@@ -45,12 +47,12 @@ dependencies {
|
||||
// canonical events through the platform's EncodedMessagePublisher, which the Kafka starter
|
||||
// provides.
|
||||
runtimeOnly project(':adapter:outbound:messaging')
|
||||
runtimeOnly project(':messaging:messaging-spring-boot-starter-kafka')
|
||||
runtimeOnly libs.messaging.spring.boot.starter.kafka
|
||||
|
||||
// The activation test boots the whole capability and names the ports it must produce.
|
||||
testImplementation project(':adapter:outbound:messaging')
|
||||
testImplementation project(':application-core')
|
||||
testImplementation project(':messaging:messaging-core-api')
|
||||
testImplementation libs.messaging.core.api
|
||||
}
|
||||
|
||||
// Test-only edges of the relay lane: the application relay as the composition root selects it, the
|
||||
|
||||
@@ -45,6 +45,20 @@ commons-collections:commons-collections:3.2.2=checkstyle
|
||||
commons-io:commons-io:2.20.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath
|
||||
commons-io:commons-io:2.21.0=spotbugs
|
||||
commons-logging:commons-logging:1.3.6=integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-admin:1.0.0=integrationTestRuntimeClasspath,runtimeClasspath,testRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-core-api:1.0.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-kafka:1.0.0=integrationTestRuntimeClasspath,runtimeClasspath,testRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-observability:1.0.0=integrationTestRuntimeClasspath,runtimeClasspath,testRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-policy:1.0.0=integrationTestRuntimeClasspath,runtimeClasspath,testRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-reliability-api:1.0.0=integrationTestRuntimeClasspath,runtimeClasspath,testRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-reliability-jdbc-postgresql:1.0.0=integrationTestRuntimeClasspath,runtimeClasspath,testRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-reliability:1.0.0=integrationTestRuntimeClasspath,runtimeClasspath,testRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-runtime-core:1.0.0=integrationTestRuntimeClasspath,runtimeClasspath,testRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-schema-json:1.0.0=integrationTestRuntimeClasspath,runtimeClasspath,testRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-security:1.0.0=integrationTestRuntimeClasspath,runtimeClasspath,testRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-spring-boot-starter-kafka:1.0.0=integrationTestRuntimeClasspath,runtimeClasspath,testRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-spring-boot-starter:1.0.0=integrationTestRuntimeClasspath,runtimeClasspath,testRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-transport-spi:1.0.0=integrationTestRuntimeClasspath,runtimeClasspath,testRuntimeClasspath
|
||||
info.picocli:picocli:4.7.7=checkstyle
|
||||
io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor
|
||||
io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor
|
||||
|
||||
+1
-1
@@ -3,6 +3,7 @@ package dev.caskeleton.adapter.outbound.messaging.kafka.relay;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.awaitility.Awaitility.await;
|
||||
|
||||
import dev.cakit.messaging.api.MessageId;
|
||||
import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent;
|
||||
import dev.caskeleton.application.outbox.OutboxAppendPort;
|
||||
import dev.caskeleton.application.outbox.OutboxCompletion;
|
||||
@@ -14,7 +15,6 @@ import dev.caskeleton.application.outbox.testkit.InMemoryOutboxStore;
|
||||
import dev.caskeleton.application.outbox.testkit.OutboxEvents;
|
||||
import dev.caskeleton.application.transaction.TransactionPort;
|
||||
import dev.caskeleton.application.transaction.testkit.DirectTransactionPort;
|
||||
import dev.caskeleton.messaging.api.MessageId;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
|
||||
+2
-2
@@ -3,10 +3,10 @@ package dev.caskeleton.adapter.outbound.messaging.kafka;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.catchThrowable;
|
||||
|
||||
import dev.cakit.messaging.schema.EncodedMessagePublisher;
|
||||
import dev.caskeleton.adapter.outbound.messaging.outbox.OutboxMessagePublishAdapter;
|
||||
import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort;
|
||||
import dev.caskeleton.application.outbox.OutboxMessagePublishPort;
|
||||
import dev.caskeleton.messaging.schema.EncodedMessagePublisher;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -69,7 +69,7 @@ class KafkaCapabilityActivationTest {
|
||||
.map(Class::getName)
|
||||
.filter(
|
||||
name ->
|
||||
name.startsWith("dev.caskeleton.messaging.")
|
||||
name.startsWith("dev.cakit.messaging.")
|
||||
|| name.startsWith("dev.caskeleton.adapter.outbound.messaging.")
|
||||
|| name.startsWith("org.apache.kafka.")))
|
||||
.isEmpty();
|
||||
|
||||
@@ -7,7 +7,7 @@ dependencies {
|
||||
implementation project(':application-core')
|
||||
implementation project(':shared-contract')
|
||||
implementation project(':adapter:outbound:support')
|
||||
implementation project(':messaging:messaging-core-api')
|
||||
implementation libs.messaging.core.api
|
||||
|
||||
implementation 'org.springframework.boot:spring-boot-autoconfigure'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-json'
|
||||
|
||||
@@ -37,6 +37,7 @@ commons-beanutils:commons-beanutils:1.11.0=checkstyle
|
||||
commons-collections:commons-collections:3.2.2=checkstyle
|
||||
commons-io:commons-io:2.21.0=spotbugs
|
||||
commons-logging:commons-logging:1.3.6=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-core-api:1.0.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||
info.picocli:picocli:4.7.7=checkstyle
|
||||
io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,testAnnotationProcessor
|
||||
io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor
|
||||
|
||||
+8
-6
@@ -1,10 +1,10 @@
|
||||
package dev.caskeleton.adapter.outbound.messaging.autoconfigure;
|
||||
|
||||
import dev.cakit.messaging.schema.EncodedMessagePublisher;
|
||||
import dev.caskeleton.adapter.outbound.messaging.MessagingConfig;
|
||||
import dev.caskeleton.adapter.outbound.messaging.MessagingSettings;
|
||||
import dev.caskeleton.adapter.outbound.messaging.platformbridge.PlatformIntegrationEventPublishAdapter;
|
||||
import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort;
|
||||
import dev.caskeleton.messaging.schema.EncodedMessagePublisher;
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionOutcome;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
|
||||
@@ -23,14 +23,15 @@ import org.springframework.util.StringUtils;
|
||||
* The one place that decides whether this application publishes to a broker.
|
||||
*
|
||||
* <p>The broker itself is a build-time choice: a transport leaf (messaging-kafka) brings the
|
||||
* vendored platform and its transport, and this root stays broker-neutral — it binds the
|
||||
* application's ports to the platform's pre-encoded publish path and nothing else.
|
||||
* messaging library ({@code dev.cakit.messaging}) and its transport, and this root stays
|
||||
* broker-neutral — it binds the application's ports to the library's pre-encoded publish path and
|
||||
* nothing else.
|
||||
*
|
||||
* <p>On when present: an application that selected a messaging leaf wants messaging, so a missing
|
||||
* {@code app.messaging.enabled} means on and only an explicit {@code false} turns it off.
|
||||
*/
|
||||
@AutoConfiguration(
|
||||
afterName = "dev.caskeleton.messaging.autoconfigure.MessagingPlatformRootAutoConfiguration")
|
||||
afterName = "dev.cakit.messaging.autoconfigure.MessagingPlatformRootAutoConfiguration")
|
||||
@ConditionalOnProperty(
|
||||
prefix = "app.messaging",
|
||||
name = "enabled",
|
||||
@@ -58,8 +59,9 @@ public class MessagingBridgeRootAutoConfiguration {
|
||||
* identity environment-dependent.
|
||||
*
|
||||
* <p>{@code @ConditionalOnBean} only sees the publisher because this class is ordered after the
|
||||
* platform root: auto-configurations are sorted by name first, and {@code
|
||||
* dev.caskeleton.adapter…} sorts before {@code dev.caskeleton.messaging…}.
|
||||
* library's root ({@code afterName} above). Auto-configurations are sorted by name first, and
|
||||
* {@code dev.cakit.messaging…} happens to sort before {@code dev.caskeleton.adapter…}; the
|
||||
* constraint, not the name, is what keeps the order through any rename.
|
||||
*/
|
||||
@Bean
|
||||
@ConditionalOnBean(EncodedMessagePublisher.class)
|
||||
|
||||
+23
-23
@@ -1,32 +1,32 @@
|
||||
package dev.caskeleton.adapter.outbound.messaging.platformbridge;
|
||||
|
||||
import dev.cakit.messaging.api.CausationId;
|
||||
import dev.cakit.messaging.api.ContentType;
|
||||
import dev.cakit.messaging.api.CorrelationId;
|
||||
import dev.cakit.messaging.api.MessageEnvelope;
|
||||
import dev.cakit.messaging.api.MessageId;
|
||||
import dev.cakit.messaging.api.MessageType;
|
||||
import dev.cakit.messaging.api.ProducerId;
|
||||
import dev.cakit.messaging.api.SchemaVersion;
|
||||
import dev.cakit.messaging.api.TenantContext;
|
||||
import dev.cakit.messaging.api.TraceContext;
|
||||
import dev.cakit.messaging.api.destination.DestinationName;
|
||||
import dev.cakit.messaging.api.destination.MessageDestination;
|
||||
import dev.cakit.messaging.api.error.FailureDescriptor;
|
||||
import dev.cakit.messaging.api.header.HeaderName;
|
||||
import dev.cakit.messaging.api.header.HeaderValue;
|
||||
import dev.cakit.messaging.api.header.MessageHeaders;
|
||||
import dev.cakit.messaging.api.publish.PublishCompletion;
|
||||
import dev.cakit.messaging.api.publish.PublishOptions;
|
||||
import dev.cakit.messaging.api.publish.PublishResult;
|
||||
import dev.cakit.messaging.api.publish.TransmissionEvidence;
|
||||
import dev.cakit.messaging.schema.EncodedMessage;
|
||||
import dev.cakit.messaging.schema.EncodedMessagePublisher;
|
||||
import dev.cakit.messaging.schema.SchemaReference;
|
||||
import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort;
|
||||
import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent;
|
||||
import dev.caskeleton.application.outbox.OutboxPublishAttempt;
|
||||
import dev.caskeleton.application.outbox.OutboxPublishOutcome;
|
||||
import dev.caskeleton.messaging.api.CausationId;
|
||||
import dev.caskeleton.messaging.api.ContentType;
|
||||
import dev.caskeleton.messaging.api.CorrelationId;
|
||||
import dev.caskeleton.messaging.api.MessageEnvelope;
|
||||
import dev.caskeleton.messaging.api.MessageId;
|
||||
import dev.caskeleton.messaging.api.MessageType;
|
||||
import dev.caskeleton.messaging.api.ProducerId;
|
||||
import dev.caskeleton.messaging.api.SchemaVersion;
|
||||
import dev.caskeleton.messaging.api.TenantContext;
|
||||
import dev.caskeleton.messaging.api.TraceContext;
|
||||
import dev.caskeleton.messaging.api.destination.DestinationName;
|
||||
import dev.caskeleton.messaging.api.destination.MessageDestination;
|
||||
import dev.caskeleton.messaging.api.error.FailureDescriptor;
|
||||
import dev.caskeleton.messaging.api.header.HeaderName;
|
||||
import dev.caskeleton.messaging.api.header.HeaderValue;
|
||||
import dev.caskeleton.messaging.api.header.MessageHeaders;
|
||||
import dev.caskeleton.messaging.api.publish.PublishCompletion;
|
||||
import dev.caskeleton.messaging.api.publish.PublishOptions;
|
||||
import dev.caskeleton.messaging.api.publish.PublishResult;
|
||||
import dev.caskeleton.messaging.api.publish.TransmissionEvidence;
|
||||
import dev.caskeleton.messaging.schema.EncodedMessage;
|
||||
import dev.caskeleton.messaging.schema.EncodedMessagePublisher;
|
||||
import dev.caskeleton.messaging.schema.SchemaReference;
|
||||
import java.time.Duration;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package dev.cakit.messaging.autoconfigure;
|
||||
|
||||
import dev.cakit.messaging.schema.EncodedMessagePublisher;
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.core.Ordered;
|
||||
|
||||
/**
|
||||
* Test stand-in with the exact name of the messaging starter's root auto-configuration.
|
||||
*
|
||||
* <p>The bridge orders itself after that root by name ({@code afterName}). Boot sorts
|
||||
* auto-configurations alphabetically before applying {@code after} constraints; while the library
|
||||
* was {@code dev.caskeleton.messaging} the bridge sorted first, so the constraint carried the
|
||||
* order. Since the package became {@code dev.cakit.messaging} (2026-11-08) the root sorts first by
|
||||
* name as well, and the constraint is what keeps that true for any rename. A stand-in with the same
|
||||
* name reproduces the ordering without pulling the starter, and a broker, onto this leaf's test
|
||||
* classpath. The starter is not on that classpath, so the name does not collide.
|
||||
*
|
||||
* <p>The stand-in asks to run last ({@code LOWEST_PRECEDENCE}), which the real root does not: with
|
||||
* the name sorting it first, a test without that would pass even if the bridge lost its {@code
|
||||
* afterName}. Ordered last, the bridge still comes after it only because of the constraint.
|
||||
*/
|
||||
@AutoConfiguration
|
||||
@AutoConfigureOrder(Ordered.LOWEST_PRECEDENCE)
|
||||
public class MessagingPlatformRootAutoConfiguration {
|
||||
|
||||
@Bean
|
||||
EncodedMessagePublisher encodedMessagePublisher() {
|
||||
return (destination, message, options) -> {
|
||||
throw new AssertionError("publisher is not invoked while wiring the bridge");
|
||||
};
|
||||
}
|
||||
}
|
||||
+2
-3
@@ -2,10 +2,10 @@ package dev.caskeleton.adapter.outbound.messaging.autoconfigure;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.cakit.messaging.schema.EncodedMessagePublisher;
|
||||
import dev.caskeleton.adapter.outbound.messaging.MessagingSettings;
|
||||
import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort;
|
||||
import dev.caskeleton.application.outbox.OutboxMessagePublishPort;
|
||||
import dev.caskeleton.messaging.schema.EncodedMessagePublisher;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
@@ -48,8 +48,7 @@ class MessagingPlatformBridgeAutoConfigurationTest {
|
||||
.withConfiguration(
|
||||
AutoConfigurations.of(
|
||||
MessagingBridgeRootAutoConfiguration.class,
|
||||
dev.caskeleton.messaging.autoconfigure.MessagingPlatformRootAutoConfiguration
|
||||
.class))
|
||||
dev.cakit.messaging.autoconfigure.MessagingPlatformRootAutoConfiguration.class))
|
||||
.withPropertyValues(
|
||||
"app.messaging.enabled=true", "app.messaging.producer-id=portfolio-service");
|
||||
|
||||
|
||||
+14
-14
@@ -3,6 +3,20 @@ package dev.caskeleton.adapter.outbound.messaging.platformbridge;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.catchThrowable;
|
||||
|
||||
import dev.cakit.messaging.api.ContentType;
|
||||
import dev.cakit.messaging.api.MessageEnvelope;
|
||||
import dev.cakit.messaging.api.destination.MessageDestination;
|
||||
import dev.cakit.messaging.api.error.FailureCategory;
|
||||
import dev.cakit.messaging.api.error.FailureDescriptor;
|
||||
import dev.cakit.messaging.api.publish.ConfirmationLevel;
|
||||
import dev.cakit.messaging.api.publish.PublishCompletion;
|
||||
import dev.cakit.messaging.api.publish.PublishEvidence;
|
||||
import dev.cakit.messaging.api.publish.PublishOptions;
|
||||
import dev.cakit.messaging.api.publish.PublishResult;
|
||||
import dev.cakit.messaging.api.publish.RoutingOutcome;
|
||||
import dev.cakit.messaging.api.publish.TransmissionEvidence;
|
||||
import dev.cakit.messaging.schema.EncodedMessage;
|
||||
import dev.cakit.messaging.schema.EncodedMessagePublisher;
|
||||
import dev.caskeleton.application.messaging.contract.ContractId;
|
||||
import dev.caskeleton.application.messaging.contract.LogicalDestinationId;
|
||||
import dev.caskeleton.application.messaging.event.AggregateIdentity;
|
||||
@@ -14,20 +28,6 @@ import dev.caskeleton.application.messaging.event.testkit.BrokerAnswer;
|
||||
import dev.caskeleton.application.messaging.event.testkit.IntegrationEventPublishContract;
|
||||
import dev.caskeleton.application.outbox.OutboxPublishAttempt;
|
||||
import dev.caskeleton.application.outbox.OutboxPublishOutcome;
|
||||
import dev.caskeleton.messaging.api.ContentType;
|
||||
import dev.caskeleton.messaging.api.MessageEnvelope;
|
||||
import dev.caskeleton.messaging.api.destination.MessageDestination;
|
||||
import dev.caskeleton.messaging.api.error.FailureCategory;
|
||||
import dev.caskeleton.messaging.api.error.FailureDescriptor;
|
||||
import dev.caskeleton.messaging.api.publish.ConfirmationLevel;
|
||||
import dev.caskeleton.messaging.api.publish.PublishCompletion;
|
||||
import dev.caskeleton.messaging.api.publish.PublishEvidence;
|
||||
import dev.caskeleton.messaging.api.publish.PublishOptions;
|
||||
import dev.caskeleton.messaging.api.publish.PublishResult;
|
||||
import dev.caskeleton.messaging.api.publish.RoutingOutcome;
|
||||
import dev.caskeleton.messaging.api.publish.TransmissionEvidence;
|
||||
import dev.caskeleton.messaging.schema.EncodedMessage;
|
||||
import dev.caskeleton.messaging.schema.EncodedMessagePublisher;
|
||||
import dev.caskeleton.shared.digest.Sha256;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
|
||||
-25
@@ -1,25 +0,0 @@
|
||||
package dev.caskeleton.messaging.autoconfigure;
|
||||
|
||||
import dev.caskeleton.messaging.schema.EncodedMessagePublisher;
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
|
||||
/**
|
||||
* Test stand-in with the exact name of the messaging starter's root auto-configuration.
|
||||
*
|
||||
* <p>The bridge orders itself after that root by name, and Boot sorts auto-configurations
|
||||
* alphabetically before applying {@code after} constraints — {@code dev.caskeleton.adapter…} comes
|
||||
* before {@code dev.caskeleton.messaging…}. A stand-in with the same name reproduces that ordering
|
||||
* without pulling the starter, and a broker, onto this leaf's test classpath. The starter is not on
|
||||
* that classpath, so the name does not collide.
|
||||
*/
|
||||
@AutoConfiguration
|
||||
public class MessagingPlatformRootAutoConfiguration {
|
||||
|
||||
@Bean
|
||||
EncodedMessagePublisher encodedMessagePublisher() {
|
||||
return (destination, message, options) -> {
|
||||
throw new AssertionError("publisher is not invoked while wiring the bridge");
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -111,6 +111,7 @@ lock TTL)과 계약 표(트랜잭션 모드, SQLState → 오류 코드, vendor,
|
||||
- `:shared-contract`
|
||||
- `:adapter:outbound:support`(타입 있는 기동 실패, EnvironmentPostProcessor 순서, readiness group, module-defaults 읽기)
|
||||
- Spring Data JPA와 Spring transaction.
|
||||
- 시험만: 메시징 라이브러리 jar(`dev.cakit.messaging:messaging-reliability-jdbc-postgresql`)를 전용 구성 `messagingMigrations`로 받아 그 `db/migration` 트리를 푼다. migration 시험(`MigrationTrees`)이 같은 Flyway 이력에 들어가는 메시징 migration을 이 leaf의 것과 같은 규칙으로 보기 위해서다. 어떤 classpath에도 올리지 않으므로 registry 방향 검사(운영 구성만 본다) 밖이다. 다른 repo의 파일을 경로로 읽지 않는다.
|
||||
|
||||
## 금지 (Forbidden)
|
||||
|
||||
|
||||
@@ -296,6 +296,34 @@ tasks.named('postgresqlSecurityBaselineIntegrationTest') {
|
||||
// Which JPA lanes block a release is declared by release/release-registry.json (jpaReleaseQualification below).
|
||||
// This leaf declares the lanes and how each runs; it does not own release orchestration.
|
||||
|
||||
// The messaging library's migration tree (db/migration/messaging in messaging-reliability-jdbc-postgresql,
|
||||
// messaging-library repo) runs against the database this leaf owns once the consume side is
|
||||
// selected, through the same Flyway history, so AppliedMigrationImmutabilityTest and
|
||||
// MigrationLockWaitTest hold it to the same rules as this leaf's own trees (MigrationTrees). While
|
||||
// the library lived in this repository they read its source folder by path; now the tree is a
|
||||
// resource of the published jar, at the version the catalog names (`messagingLibrary`), which is
|
||||
// exactly what a service applies. Only the jar, not its dependencies, and only to read: the module is
|
||||
// on no classpath of this leaf, so no test context sees the library.
|
||||
configurations {
|
||||
messagingMigrations {
|
||||
canBeConsumed = false
|
||||
canBeResolved = true
|
||||
transitive = false
|
||||
description = 'The messaging library jar whose db/migration tree the migration tests read.'
|
||||
}
|
||||
}
|
||||
dependencies {
|
||||
messagingMigrations libs.messaging.reliability.jdbc.postgresql
|
||||
}
|
||||
def messagingMigrationDirectory = layout.buildDirectory.dir('library-migrations/messaging-reliability-jdbc-postgresql')
|
||||
def messagingMigrationTree = tasks.register('messagingMigrationTree', Sync) {
|
||||
description = 'Extracts the messaging library\'s db/migration tree for the migration tests.'
|
||||
from({ zipTree(configurations.messagingMigrations.singleFile) }) {
|
||||
include 'db/migration/**'
|
||||
}
|
||||
into messagingMigrationDirectory
|
||||
}
|
||||
|
||||
// The unit lane reads three files that are not Java sources: the release registry and its two
|
||||
// renderings. Without declaring them, Gradle calls the lane up-to-date after a registry demotion or
|
||||
// a workflow edit — so the drift check that exists to catch exactly that edit never runs on it.
|
||||
@@ -321,9 +349,14 @@ tasks.named('test') {
|
||||
.withPropertyName('notificationMigrations')
|
||||
inputs.dir(file('../persistence-fileserver/src/main/resources/db/migration'))
|
||||
.withPropertyName('fileserverMigrations')
|
||||
// ...and the messaging platform's tree, whose inbox range the consume side applies here.
|
||||
inputs.dir(file('../../../platforms/messaging/messaging-reliability-jdbc-postgresql/src/main/resources/db/migration'))
|
||||
// ...and the messaging library's tree, whose inbox range the consume side applies here: read out of
|
||||
// the jar this build receives (messagingMigrationTree above), not from the library's sources.
|
||||
dependsOn messagingMigrationTree
|
||||
inputs.dir(messagingMigrationDirectory)
|
||||
.withPathSensitivity(PathSensitivity.RELATIVE)
|
||||
.withPropertyName('messagingMigrations')
|
||||
systemProperty 'persistence.migration.messagingTree',
|
||||
messagingMigrationDirectory.get().dir('db/migration').asFile.absolutePath
|
||||
}
|
||||
|
||||
// verifyJpaApiSurface — every public type this leaf exposes is a committed decision.
|
||||
|
||||
@@ -54,6 +54,7 @@ commons-collections:commons-collections:3.2.2=checkstyle
|
||||
commons-io:commons-io:2.20.0=jpaPlatformPerformanceTestCompileClasspath,jpaPlatformPerformanceTestRuntimeClasspath,postgresqlIntegrationTestCompileClasspath,postgresqlIntegrationTestRuntimeClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath
|
||||
commons-io:commons-io:2.21.0=spotbugs
|
||||
commons-logging:commons-logging:1.3.6=compileClasspath,jpaPlatformPerformanceTestCompileClasspath,jpaPlatformPerformanceTestRuntimeClasspath,postgresqlIntegrationTestCompileClasspath,postgresqlIntegrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-reliability-jdbc-postgresql:1.0.0=messagingMigrations
|
||||
eu.rekawek.toxiproxy:toxiproxy-java:2.1.11=jpaPlatformPerformanceTestRuntimeClasspath,postgresqlIntegrationTestCompileClasspath,postgresqlIntegrationTestRuntimeClasspath,testRuntimeClasspath
|
||||
eu.rekawek.toxiproxy:toxiproxy-java:2.1.7=testFixturesCompileClasspath,testFixturesRuntimeClasspath
|
||||
info.picocli:picocli:4.7.7=checkstyle
|
||||
|
||||
+22
-7
@@ -28,22 +28,37 @@ final class MigrationTrees {
|
||||
* adapter:outbound:persistence-fileserver}) runs against the same database through the same
|
||||
* Flyway history and was never pinned at all; it is checked here on the same terms.
|
||||
*
|
||||
* <p>The messaging platform's tree ({@code db/migration/messaging}, in {@code
|
||||
* messaging-reliability-jdbc-postgresql}) runs against it too once the consume side is selected:
|
||||
* {@code adapter:inbound:messaging} applies its inbox range (V11xx). The tree is pinned whole —
|
||||
* the platform outbox range ships from the same location to deployments that use it, and an
|
||||
* edited migration stops those just the same.
|
||||
* <p>The messaging library's tree ({@code db/migration/messaging}, in {@code
|
||||
* dev.cakit.messaging:messaging-reliability-jdbc-postgresql}) runs against it too once the
|
||||
* consume side is selected: {@code adapter:inbound:messaging} applies its inbox range (V11xx).
|
||||
* The tree is pinned whole — the library's outbox range ships from the same location to
|
||||
* deployments that use it, and an edited migration stops those just the same. The library lives
|
||||
* in its own repository (messaging-library) since 2026-11-08, so the tree is read out of the jar
|
||||
* this build receives: the build extracts it ({@code messagingMigrationTree}) and names the
|
||||
* folder in {@value #MESSAGING_TREE_PROPERTY}.
|
||||
*/
|
||||
static final List<Path> ROOTS =
|
||||
List.of(
|
||||
Path.of("src/main/resources/db/migration"),
|
||||
Path.of("../persistence-notification/src/main/resources/db/migration"),
|
||||
Path.of("../persistence-fileserver/src/main/resources/db/migration"),
|
||||
Path.of(
|
||||
"../../../platforms/messaging/messaging-reliability-jdbc-postgresql/src/main/resources/db/migration"));
|
||||
messagingTree());
|
||||
|
||||
static final String MESSAGING_TREE_PROPERTY = "persistence.migration.messagingTree";
|
||||
|
||||
private MigrationTrees() {}
|
||||
|
||||
private static Path messagingTree() {
|
||||
String tree = System.getProperty(MESSAGING_TREE_PROPERTY);
|
||||
if (tree == null || tree.isBlank()) {
|
||||
throw new IllegalStateException(
|
||||
MESSAGING_TREE_PROPERTY
|
||||
+ " is not set: run the migration tests through Gradle (`test`), which extracts the"
|
||||
+ " messaging library's db/migration tree from its jar and names the folder here.");
|
||||
}
|
||||
return Path.of(tree);
|
||||
}
|
||||
|
||||
/**
|
||||
* Every versioned migration ({@link VersionedMigrationFiles}, the definition the sample's check
|
||||
* uses too), keyed by its path below its tree ({@code postgresql/V22__...sql}), the key {@code
|
||||
|
||||
@@ -180,6 +180,9 @@ dependencies {
|
||||
integrationTestImplementation project(':composition:service-runtime')
|
||||
|
||||
capabilityProjects.each { architectureTestRuntimeOnly project(it) }
|
||||
// ArchitectureViolationFixtureTest's consumer fixtures implement and inject the messaging library's
|
||||
// MessageHandler, the type a service's handler really has. Test edge, outside the registry gate.
|
||||
architectureTestImplementation libs.messaging.core.api
|
||||
|
||||
// The capability integration lane selects Fileserver and object storage together, as a service
|
||||
// would, and turns off whichever one a test is not about.
|
||||
|
||||
@@ -72,6 +72,20 @@ commons-collections:commons-collections:3.2.2=checkstyle
|
||||
commons-io:commons-io:2.20.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath
|
||||
commons-io:commons-io:2.21.0=spotbugs
|
||||
commons-logging:commons-logging:1.3.6=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-admin:1.0.0=architectureTestRuntimeClasspath,qualificationRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-core-api:1.0.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,qualificationRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-kafka:1.0.0=architectureTestRuntimeClasspath,qualificationRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-observability:1.0.0=architectureTestRuntimeClasspath,qualificationRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-policy:1.0.0=architectureTestRuntimeClasspath,qualificationRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-reliability-api:1.0.0=architectureTestRuntimeClasspath,qualificationRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-reliability-jdbc-postgresql:1.0.0=architectureTestRuntimeClasspath,qualificationRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-reliability:1.0.0=architectureTestRuntimeClasspath,qualificationRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-runtime-core:1.0.0=architectureTestRuntimeClasspath,qualificationRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-schema-json:1.0.0=architectureTestRuntimeClasspath,qualificationRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-security:1.0.0=architectureTestRuntimeClasspath,qualificationRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-spring-boot-starter-kafka:1.0.0=architectureTestRuntimeClasspath,qualificationRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-spring-boot-starter:1.0.0=architectureTestRuntimeClasspath,qualificationRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-transport-spi:1.0.0=architectureTestRuntimeClasspath,qualificationRuntimeClasspath
|
||||
eu.rekawek.toxiproxy:toxiproxy-java:2.1.11=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,testRuntimeClasspath
|
||||
info.picocli:picocli:4.7.7=checkstyle
|
||||
io.github.cdimascio:dotenv-java:3.0.0=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath
|
||||
|
||||
+28
-16
@@ -92,7 +92,7 @@ class ApplicationBoundaryArchitectureTest {
|
||||
.resideInAPackage("..application..")
|
||||
.should()
|
||||
.dependOnClassesThat()
|
||||
.resideInAnyPackage("dev.caskeleton.messaging..")
|
||||
.resideInAnyPackage("dev.cakit.messaging..")
|
||||
.because(
|
||||
"APPLICATION_DOES_NOT_DEPEND_ON_THE_MESSAGING_PLATFORM: the application owns its "
|
||||
+ "publish port and outbox model; a bridge adapter translates, and the two "
|
||||
@@ -711,8 +711,19 @@ class ApplicationBoundaryArchitectureTest {
|
||||
}
|
||||
};
|
||||
|
||||
/** The packages this code base owns: a type here is one the dependency rules can follow. */
|
||||
private static final String PROJECT_PACKAGE_PREFIX = "dev.caskeleton.";
|
||||
/**
|
||||
* The packages this code base owns: a type here is one the dependency rules can follow. The
|
||||
* owner's libraries published from their own repositories ({@code dev.cakit}, the registry's
|
||||
* {@code library_groups}) count too: a message handler implements the messaging library's {@code
|
||||
* MessageHandler}, which was a type of this repository until 2026-11-08 and is still the owner's,
|
||||
* not one any class may depend on for its own reasons.
|
||||
*/
|
||||
private static final List<String> PROJECT_PACKAGE_PREFIXES =
|
||||
List.of("dev.caskeleton.", "dev.cakit.");
|
||||
|
||||
private static boolean isProjectType(String className) {
|
||||
return PROJECT_PACKAGE_PREFIXES.stream().anyMatch(className::startsWith);
|
||||
}
|
||||
|
||||
/**
|
||||
* Every type a system caller can be handed as: the caller itself, and each project class or
|
||||
@@ -730,7 +741,7 @@ class ApplicationBoundaryArchitectureTest {
|
||||
if (ARE_SYSTEM_CALLERS.test(candidate)) {
|
||||
return true;
|
||||
}
|
||||
return candidate.getName().startsWith(PROJECT_PACKAGE_PREFIX)
|
||||
return isProjectType(candidate.getName())
|
||||
&& candidate.getAllSubclasses().stream().anyMatch(ARE_SYSTEM_CALLERS);
|
||||
}
|
||||
};
|
||||
@@ -836,14 +847,15 @@ class ApplicationBoundaryArchitectureTest {
|
||||
* looks like every other user of the interface, and a rule that refused the dependency would
|
||||
* refuse them all (review 2026-11-04 RR4-01-01). The job therefore has none: the scheduler calls
|
||||
* its {@code @Scheduled} method, a configuration that registers it with a task scheduler passes
|
||||
* {@code job::run}, and a message handler implements the platform's {@code MessageHandler}, which
|
||||
* is a project type. Anonymous and local classes are exempt: no bean has their type, and a
|
||||
* function a system caller hands out from inside itself is reached only through the caller.
|
||||
* Exceptions are exempt too: nothing is handed one as a bean. A record or an enum keeps the
|
||||
* supertypes the language gives it — {@code Record}; {@code Enum} and what {@code Enum}
|
||||
* implements — which are no more a type it is injected as than {@code Object} is, so a handler's
|
||||
* parsed-message record, its outcome enum, or a handler written as a record pass, while a record
|
||||
* that also implements {@code Runnable} does not (review 2026-11-05 RR6-01-03).
|
||||
* {@code job::run}, and a message handler implements the messaging library's {@code
|
||||
* MessageHandler}, which is a project type (see {@link #PROJECT_PACKAGE_PREFIXES}). Anonymous and
|
||||
* local classes are exempt: no bean has their type, and a function a system caller hands out from
|
||||
* inside itself is reached only through the caller. Exceptions are exempt too: nothing is handed
|
||||
* one as a bean. A record or an enum keeps the supertypes the language gives it — {@code Record};
|
||||
* {@code Enum} and what {@code Enum} implements — which are no more a type it is injected as than
|
||||
* {@code Object} is, so a handler's parsed-message record, its outcome enum, or a handler written
|
||||
* as a record pass, while a record that also implements {@code Runnable} does not (review
|
||||
* 2026-11-05 RR6-01-03).
|
||||
*/
|
||||
@ArchTest
|
||||
static final ArchRule SYSTEM_CALLERS_HAVE_ONLY_PROJECT_SUPERTYPES =
|
||||
@@ -858,7 +870,8 @@ class ApplicationBoundaryArchitectureTest {
|
||||
.should(haveNoSupertypeOutsideTheProject())
|
||||
.as(
|
||||
"SYSTEM_CALLERS_HAVE_ONLY_PROJECT_SUPERTYPES: a @SystemCaller extends and implements "
|
||||
+ "only project types (dev.caskeleton..), so every type it can be injected as is "
|
||||
+ "only project types (dev.caskeleton.., and the owner's libraries dev.cakit..), "
|
||||
+ "so every type it can be injected as is "
|
||||
+ "one USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS follows. Instead of Runnable or "
|
||||
+ "ApplicationRunner, use a @Scheduled method, an @EventListener, or pass job::run "
|
||||
+ "where the job is registered (manual 07 「시스템이 부르는 쓰기」). A record or "
|
||||
@@ -873,14 +886,13 @@ class ApplicationBoundaryArchitectureTest {
|
||||
Set<String> foreign = new TreeSet<>();
|
||||
for (JavaClass superclass : item.getAllRawSuperclasses()) {
|
||||
if (!superclass.isEquivalentTo(Object.class)
|
||||
&& !superclass.getName().startsWith(PROJECT_PACKAGE_PREFIX)
|
||||
&& !isProjectType(superclass.getName())
|
||||
&& !languageGiven.contains(superclass.getName())) {
|
||||
foreign.add(superclass.getName());
|
||||
}
|
||||
}
|
||||
for (JavaClass type : item.getAllRawInterfaces()) {
|
||||
if (!type.getName().startsWith(PROJECT_PACKAGE_PREFIX)
|
||||
&& !languageGiven.contains(type.getName())) {
|
||||
if (!isProjectType(type.getName()) && !languageGiven.contains(type.getName())) {
|
||||
foreign.add(type.getName());
|
||||
}
|
||||
}
|
||||
|
||||
+48
@@ -7,6 +7,7 @@ import com.tngtech.archunit.core.domain.JavaClasses;
|
||||
import com.tngtech.archunit.core.importer.ClassFileImporter;
|
||||
import com.tngtech.archunit.lang.EvaluationResult;
|
||||
import dev.caskeleton.application.architecture.violations.ApplicationDiagnosticFrameworkViolation;
|
||||
import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.LibraryMessageHandlerSystemCallerFixture;
|
||||
import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.RecordSystemCallerFixture;
|
||||
import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerFixture;
|
||||
import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerRegistrationFixture;
|
||||
@@ -35,6 +36,7 @@ import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.schedule
|
||||
import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.scheduler.ScheduledWorkFixture;
|
||||
import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.scheduler.SystemCallerWithNestedEndpointFixture;
|
||||
import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.scheduler.SystemJobLauncherFixture;
|
||||
import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.web.controller.MessageHandlerInjectingControllerFixture;
|
||||
import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.web.controller.SystemCallerControllerFixture;
|
||||
import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.web.controller.SystemCallerInvokingControllerFixture;
|
||||
import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.web.controller.SystemCallerRelayingControllerFixture;
|
||||
@@ -277,6 +279,23 @@ class ArchitectureViolationFixtureTest {
|
||||
InterfaceExposedSystemJobFixture.class,
|
||||
SystemInvokedFixtureUseCase.class);
|
||||
|
||||
// The consumer as a service writes it: a handler implementing the messaging library's
|
||||
// MessageHandler, and a "replay now" endpoint handed it by that interface. The library left this
|
||||
// repository on 2026-11-08 (package dev.cakit.messaging); its handler interface must stay a type
|
||||
// the
|
||||
// two rules follow.
|
||||
private static final JavaClasses LIBRARY_MESSAGE_HANDLER_FIXTURE_ONLY =
|
||||
new ClassFileImporter()
|
||||
.importClasses(
|
||||
LibraryMessageHandlerSystemCallerFixture.class, SystemInvokedFixtureUseCase.class);
|
||||
|
||||
private static final JavaClasses CONTROLLER_HANDED_A_LIBRARY_MESSAGE_HANDLER_FIXTURE_ONLY =
|
||||
new ClassFileImporter()
|
||||
.importClasses(
|
||||
MessageHandlerInjectingControllerFixture.class,
|
||||
LibraryMessageHandlerSystemCallerFixture.class,
|
||||
SystemInvokedFixtureUseCase.class);
|
||||
|
||||
// A system caller that is a Runnable — directly, or through a project interface that extends it.
|
||||
// Nothing tells an endpoint injecting a Runnable from any other use of it, so the job may not be
|
||||
// one.
|
||||
@@ -590,6 +609,35 @@ class ArchitectureViolationFixtureTest {
|
||||
.contains(RunNowJobFixture.class.getName()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("메시징 라이브러리의 MessageHandler를 구현한 system caller는 프로젝트 밖 supertype이 아니다")
|
||||
void aSystemCallerImplementingTheLibrarysMessageHandlerHasOnlyOwnedSupertypes() {
|
||||
// when
|
||||
EvaluationResult result =
|
||||
ApplicationBoundaryArchitectureTest.SYSTEM_CALLERS_HAVE_ONLY_PROJECT_SUPERTYPES.evaluate(
|
||||
LIBRARY_MESSAGE_HANDLER_FIXTURE_ONLY);
|
||||
|
||||
// then
|
||||
assertThat(result.getFailureReport().getDetails()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("system caller를 라이브러리 MessageHandler로 주입받는 controller는 잡힌다")
|
||||
void aControllerHandedASystemCallerAsTheLibrarysMessageHandlerIsCaught() {
|
||||
// when
|
||||
EvaluationResult result =
|
||||
ApplicationBoundaryArchitectureTest.USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS.evaluate(
|
||||
CONTROLLER_HANDED_A_LIBRARY_MESSAGE_HANDLER_FIXTURE_ONLY);
|
||||
|
||||
// then
|
||||
assertThat(result.getFailureReport().getDetails())
|
||||
.anySatisfy(
|
||||
detail ->
|
||||
assertThat(detail)
|
||||
.contains(MessageHandlerInjectingControllerFixture.class.getName())
|
||||
.contains("dev.cakit.messaging.api.delivery.MessageHandler"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSystemCallerThatIsARunnableIsCaught() {
|
||||
// when
|
||||
|
||||
+3
-4
@@ -19,8 +19,9 @@ import org.springframework.core.env.Environment;
|
||||
* include support), and fileserver and the HTTP client read the profiles once inside their own
|
||||
* capability guard, so those four are listed by name. A new reader anywhere else — a leaf that
|
||||
* starts judging "is this production" from raw profile names on its own — fails here and has to
|
||||
* either go through the snapshot or be added to this list on purpose. The vendored {@code
|
||||
* messaging} platform and the {@code sample} fixture are outside this application's policy.
|
||||
* either go through the snapshot or be added to this list on purpose. The {@code sample} fixture is
|
||||
* outside this application's policy. The messaging library (package {@code dev.cakit.messaging},
|
||||
* its own repository since 2026-11-08) is outside the analysed packages altogether.
|
||||
*/
|
||||
@AnalyzeClasses(packages = "dev.caskeleton", importOptions = ProductionClassImportOption.class)
|
||||
class RuntimeProfileAccessArchitectureTest {
|
||||
@@ -45,8 +46,6 @@ class RuntimeProfileAccessArchitectureTest {
|
||||
noClasses()
|
||||
.that()
|
||||
.resideInAPackage("dev.caskeleton..")
|
||||
.and()
|
||||
.resideOutsideOfPackage("dev.caskeleton.messaging..")
|
||||
.and(DescribedPredicate.not(A_NAMED_PROFILE_READER))
|
||||
.should()
|
||||
.callMethod(Environment.class, "getActiveProfiles")
|
||||
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging;
|
||||
|
||||
import dev.cakit.messaging.api.delivery.HandleResult;
|
||||
import dev.cakit.messaging.api.delivery.MessageDelivery;
|
||||
import dev.cakit.messaging.api.delivery.MessageHandler;
|
||||
import dev.cakit.messaging.api.destination.MessageDestination;
|
||||
import dev.caskeleton.application.security.SystemCaller;
|
||||
import dev.caskeleton.bootstrap.architecture.violations.application.SystemInvokedFixtureUseCase;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
|
||||
/**
|
||||
* The consumer manual 09 teaches, with the supertype it really has: the messaging library's {@code
|
||||
* MessageHandler} ({@code dev.cakit.messaging}, its own repository since 2026-11-08). The library
|
||||
* is the owner's, so its handler interface is a type the system-caller rules follow, as it was
|
||||
* while the library lived in this repository.
|
||||
*/
|
||||
@SystemCaller(reason = "fixture: the broker consumer calls it for each delivery")
|
||||
public final class LibraryMessageHandlerSystemCallerFixture implements MessageHandler<String> {
|
||||
|
||||
private final SystemInvokedFixtureUseCase useCase = new SystemInvokedFixtureUseCase();
|
||||
|
||||
@Override
|
||||
public MessageDestination<String> destination() {
|
||||
throw new UnsupportedOperationException("fixture: never registered");
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletionStage<HandleResult> handle(MessageDelivery<String> delivery) {
|
||||
useCase.handle();
|
||||
throw new UnsupportedOperationException("fixture: never delivered to");
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.web.controller;
|
||||
|
||||
import dev.cakit.messaging.api.delivery.MessageHandler;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* Negative fixture for {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS}: a "replay now" endpoint
|
||||
* handed a system-caller handler as the messaging library's {@code MessageHandler}. It names
|
||||
* neither the handler class nor the {@code SystemInvoked} use case the handler runs.
|
||||
*/
|
||||
@RestController
|
||||
public class MessageHandlerInjectingControllerFixture {
|
||||
|
||||
private final MessageHandler<String> handler;
|
||||
|
||||
public MessageHandlerInjectingControllerFixture(MessageHandler<String> handler) {
|
||||
this.handler = handler;
|
||||
}
|
||||
|
||||
@PostMapping("/fixture/replay-now")
|
||||
public void replayNow() {
|
||||
handler.handle(null);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -36,7 +36,7 @@ class DefaultCompositionBootTest {
|
||||
"dev.caskeleton.adapter.outbound.cache.redis",
|
||||
"dev.caskeleton.adapter.outbound.redis",
|
||||
"dev.caskeleton.adapter.outbound.messaging",
|
||||
"dev.caskeleton.messaging",
|
||||
"dev.cakit.messaging",
|
||||
"dev.caskeleton.adapter.outbound.httpclient",
|
||||
"dev.caskeleton.adapter.outbound.objectstorage",
|
||||
"dev.caskeleton.adapter.outbound.notification",
|
||||
|
||||
+5
-4
@@ -32,10 +32,11 @@ import org.junit.jupiter.api.Test;
|
||||
* environment such as {@code app.httpclient.clients[N].*}, through relaxed binding — and under one
|
||||
* {@code app} root the two routes spell the same name.
|
||||
*
|
||||
* <p>Vendored platforms keep their own subtree under the same root: {@code app.messaging.*} belongs
|
||||
* to the {@code messaging:*} platform, and gRPC's settings sit in {@code app.grpc.server} and
|
||||
* {@code app.grpc.platform} side by side, never one at the shared parent — two strict binders on a
|
||||
* shared parent would each refuse the other's keys.
|
||||
* <p>The libraries published from their own repositories keep their own subtree under the same
|
||||
* root: {@code app.messaging.*} belongs to the messaging library ({@code dev.cakit.messaging}), and
|
||||
* gRPC's settings sit in {@code app.grpc.server} and {@code app.grpc.platform} side by side, never
|
||||
* one at the shared parent — two strict binders on a shared parent would each refuse the other's
|
||||
* keys.
|
||||
*/
|
||||
class ConfigurationNamespaceContractTest {
|
||||
|
||||
|
||||
+19
-10
@@ -19,9 +19,15 @@ import org.junit.jupiter.api.Test;
|
||||
*
|
||||
* <p>Two types declare {@code @ConfigurationProperties} on that prefix: {@code MessagingSettings}
|
||||
* in the outbound adapter, which owns {@code producer-id}, and {@code MessagingSettings} in the
|
||||
* starter, which owns everything else, {@code broker} included. Spring binds both without complaint
|
||||
* — each takes the fields it declares — so the split is invisible at runtime and shows up only as
|
||||
* two places to look, neither of which validates the other's view.
|
||||
* messaging library's starter, which owns everything else, {@code broker} included. Spring binds
|
||||
* both without complaint — each takes the fields it declares — so the split is invisible at runtime
|
||||
* and shows up only as two places to look, neither of which validates the other's view.
|
||||
*
|
||||
* <p>Since the library moved to its own repository (messaging-library, 2026-11-08) each repository
|
||||
* counts its own half: this test holds this repository to exactly one owner, and the library's
|
||||
* {@code MessagingSettingsOwnerContractTest} holds the library to exactly one. A source scan cannot
|
||||
* see across the two repositories any more, and the "two in total" of before is the sum of the two
|
||||
* checks (design-docs {@code repo-structure/05-library-repos.md} 4.2절, 16절 H7).
|
||||
*
|
||||
* <p>This test does not assert the split away. Collapsing it means the adapter stops selecting a
|
||||
* broker and becomes a port bridge over the platform's publish contract, which it can only do once
|
||||
@@ -51,13 +57,13 @@ class MessagingAuthorityContractTest {
|
||||
Pattern.compile("String PREFIX\\s*=\\s*\"app\\.messaging\"");
|
||||
|
||||
private static final List<ProductionSource> MESSAGING_SOURCES =
|
||||
loadSources("adapter/outbound/messaging", "platforms/messaging", "app-bootstrap");
|
||||
loadSources("adapter/outbound/messaging", "adapter/inbound/messaging", "app-bootstrap");
|
||||
private static final List<ProductionSource> CORE_SOURCES =
|
||||
loadSources("application-core", "domain-core");
|
||||
|
||||
@Test
|
||||
@DisplayName("the owners of app.messaging are the two this wave knows about, and no more")
|
||||
void theSettingsOwnersAreTheKnownTwo() {
|
||||
@DisplayName("이 repo에서 app.messaging의 주인은 outbound adapter의 MessagingSettings 하나다")
|
||||
void theAdapterSettingsAreThisRepositorysOnlyOwner() {
|
||||
List<Path> owners =
|
||||
MESSAGING_SOURCES.stream()
|
||||
.filter(
|
||||
@@ -68,11 +74,14 @@ class MessagingAuthorityContractTest {
|
||||
.map(ProductionSource::path)
|
||||
.toList();
|
||||
|
||||
assertThat(owners.stream().map(path -> path.getFileName().toString()).sorted())
|
||||
assertThat(owners.stream().map(path -> repositoryRoot().relativize(path).toString()))
|
||||
.as(
|
||||
"a third owner of one namespace is how a setting comes to mean different things to "
|
||||
+ "different halves of the same application; the two below are collapsed by Task C3")
|
||||
.containsExactly("MessagingSettings.java", "MessagingSettings.java");
|
||||
"a second owner in this repository is how a setting comes to mean different things to "
|
||||
+ "different halves of the same application; the library's starter is the other "
|
||||
+ "owner, collapsed by Task C3")
|
||||
.containsExactly(
|
||||
"src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/"
|
||||
+ "MessagingSettings.java");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
-386
@@ -1,386 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.contract.messaging;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Tag;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Whether an adopter can compile against the messaging types this platform hands them.
|
||||
*
|
||||
* <p>A Gradle {@code implementation} dependency is not encapsulation. It removes the library from
|
||||
* the consumer's compile classpath, but it does not remove the library's types from this module's
|
||||
* public signatures. When both are true the artifact ships an API nobody can call: the method is
|
||||
* there, the javadoc describes it, and the caller cannot name its parameter or its return type
|
||||
* without guessing which library and which version to add to their own build. Every case below was
|
||||
* exactly that — a Kafka {@code Producer}, a Spring AMQP {@code Message}, a CloudEvent, a
|
||||
* Micrometer {@code MeterRegistry}, an Avro {@code Schema}, a protobuf {@code Parser}, a Reactor
|
||||
* {@code Mono}.
|
||||
*
|
||||
* <p>So the rule is one-directional and mechanical: a vendor library named in a public or protected
|
||||
* signature is declared {@code api}; one used only behind private members stays {@code
|
||||
* implementation}. {@code src/platforms/messaging/AGENTS.md} states it as policy — this holds it to
|
||||
* the source so the two cannot drift.
|
||||
*
|
||||
* <p>The libraries checked are the ones an adopter would otherwise have to reverse-engineer into
|
||||
* their own build: broker clients, codec libraries, the metrics registry, the reactive facade.
|
||||
* Spring Framework and Spring Boot are deliberately out of scope. They appear only inside the
|
||||
* composition boundary, where the container constructs the types rather than an adopter naming
|
||||
* them, and that boundary is where the family policy already confines them.
|
||||
*/
|
||||
@Tag("repository-contract")
|
||||
class MessagingPublicSurfaceContractTest {
|
||||
|
||||
/**
|
||||
* Package prefix to the Gradle coordinate that supplies it.
|
||||
*
|
||||
* <p>Prefixes rather than exact packages, because a library's types are spread across its own
|
||||
* sub-packages and a consumer needs the whole artifact either way.
|
||||
*/
|
||||
private static final Map<String, String> VENDOR_LIBRARIES =
|
||||
Map.of(
|
||||
"org.apache.kafka", "org.apache.kafka:kafka-clients",
|
||||
"org.springframework.amqp", "org.springframework.amqp:spring-rabbit",
|
||||
"org.apache.avro", "org.apache.avro:avro",
|
||||
"com.google.protobuf", "com.google.protobuf:protobuf-java",
|
||||
"tools.jackson", "tools.jackson.core:jackson-databind",
|
||||
"io.cloudevents", "io.cloudevents:cloudevents-api",
|
||||
"io.micrometer", "io.micrometer:micrometer-core",
|
||||
"reactor", "io.projectreactor:reactor-core",
|
||||
"io.nats", "io.nats:jnats",
|
||||
"org.apache.pulsar", "org.apache.pulsar:pulsar-client");
|
||||
|
||||
private static final Pattern IMPORT = Pattern.compile("(?m)^import\\s+(?:static\\s+)?([^;]+);");
|
||||
|
||||
private static final Pattern TYPE_KEYWORD =
|
||||
Pattern.compile("\\b(class|interface|record|enum)\\b");
|
||||
|
||||
@Test
|
||||
@DisplayName(
|
||||
"a vendor type in a public signature has its library declared api, not implementation")
|
||||
void vendorTypesInPublicSignaturesAreDeclaredApi() {
|
||||
List<String> hidden = new ArrayList<>();
|
||||
|
||||
for (Path leaf : messagingLeaves()) {
|
||||
String buildScript = read(leaf.resolve("build.gradle"));
|
||||
for (String coordinate : exposedLibraries(leaf)) {
|
||||
if (!declaresAsApi(buildScript, coordinate)) {
|
||||
hidden.add(leaf.getFileName() + " exposes " + coordinate + " without declaring it api");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
assertThat(hidden)
|
||||
.as(
|
||||
"each of these ships a public signature naming a type the consumer's compile classpath "
|
||||
+ "does not contain; the method exists and cannot be called")
|
||||
.isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("the scan reaches the leaves it claims to check")
|
||||
void theScanIsNotVacuous() {
|
||||
List<Path> leaves = messagingLeaves();
|
||||
|
||||
assertThat(leaves)
|
||||
.as("a scan that found no leaf would report every violation as absent")
|
||||
.hasSizeGreaterThan(15);
|
||||
assertThat(
|
||||
exposedLibraries(
|
||||
leaves.stream().filter(isNamed("messaging-kafka")).findFirst().orElseThrow()))
|
||||
.as("the Kafka adapter's publish seam takes a Producer, so this is a positive control")
|
||||
.contains("org.apache.kafka:kafka-clients");
|
||||
assertThat(
|
||||
exposedLibraries(
|
||||
leaves.stream().filter(isNamed("messaging-schema-json")).findFirst().orElseThrow()))
|
||||
.as("the JSON codec keeps its ObjectMapper private, so nothing is required of its build")
|
||||
.isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("an adopter of the starter does not compile against either broker client")
|
||||
void neitherBrokerSdkReachesAnAdoptersCompileClasspath() {
|
||||
Map<String, List<String>> exported = new LinkedHashMap<>();
|
||||
for (Path leaf : messagingLeaves()) {
|
||||
exported.put(
|
||||
leaf.getFileName().toString(), apiDependenciesOf(read(leaf.resolve("build.gradle"))));
|
||||
}
|
||||
|
||||
Set<String> reachable = apiClosure("messaging-spring-boot-starter", exported);
|
||||
|
||||
assertThat(reachable)
|
||||
.as(
|
||||
"an empty closure would satisfy the assertion below without proving anything; the "
|
||||
+ "metrics registry is exported on purpose (the reactive facade was deleted, S7-#9c)")
|
||||
.contains("io.micrometer:micrometer-core");
|
||||
assertThat(reachable)
|
||||
.as(
|
||||
"both adapters were exported, so every adopter compiled against two broker SDKs at "
|
||||
+ "once and each adapter's conditional-on-class guard was true whatever the "
|
||||
+ "deployment had chosen")
|
||||
.doesNotContain("org.apache.kafka:kafka-clients", "org.springframework.amqp:spring-rabbit");
|
||||
}
|
||||
|
||||
/** The vendor coordinates this leaf names in a public or protected signature. */
|
||||
private static Set<String> exposedLibraries(Path leaf) {
|
||||
Set<String> exposed = new TreeSet<>();
|
||||
for (Path source : productionSources(leaf)) {
|
||||
String text = read(source);
|
||||
String declarations = declarationsOnly(text);
|
||||
for (Map.Entry<String, String> library : VENDOR_LIBRARIES.entrySet()) {
|
||||
if (isNamedInDeclarations(text, declarations, library.getKey())) {
|
||||
exposed.add(library.getValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
return exposed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a library's types survive into this file's declarations.
|
||||
*
|
||||
* <p>Two ways a type gets named: imported and used by its simple name, or written out in full.
|
||||
* Both are checked, because the auto-configuration style in this repository uses fully qualified
|
||||
* names for one-off types rather than adding an import.
|
||||
*/
|
||||
private static boolean isNamedInDeclarations(String source, String declarations, String prefix) {
|
||||
if (declarations.contains(prefix + ".")) {
|
||||
return true;
|
||||
}
|
||||
Matcher imports = IMPORT.matcher(source);
|
||||
while (imports.find()) {
|
||||
String imported = imports.group(1).trim();
|
||||
if (!imported.startsWith(prefix + ".")) {
|
||||
continue;
|
||||
}
|
||||
String simpleName = imported.substring(imported.lastIndexOf('.') + 1);
|
||||
if (Pattern.compile("\\b" + Pattern.quote(simpleName) + "\\b").matcher(declarations).find()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reduces a source file to its declarations: type headers, member signatures, record components.
|
||||
*
|
||||
* <p>Method bodies are dropped, because a vendor type used inside one is an implementation detail
|
||||
* and is exactly the case that may stay {@code implementation}. Field initialisers are dropped
|
||||
* for the same reason. Anything a {@code private} modifier reaches is dropped last: a private
|
||||
* member is not a signature a consumer compiles against.
|
||||
*
|
||||
* <p>A brace walk rather than a parser. It only has to answer "is this text a declaration or a
|
||||
* body", which brace depth settles, and a parser here would be more machinery than the question
|
||||
* deserves.
|
||||
*/
|
||||
private static String declarationsOnly(String source) {
|
||||
String text = stripCommentsAndLiterals(source);
|
||||
StringBuilder kept = new StringBuilder();
|
||||
StringBuilder pending = new StringBuilder();
|
||||
int depth = 0;
|
||||
int bodyDepth = -1;
|
||||
int initializerDepth = -1;
|
||||
|
||||
for (int index = 0; index < text.length(); index++) {
|
||||
char character = text.charAt(index);
|
||||
if (character == '{') {
|
||||
depth++;
|
||||
if (initializerDepth >= 0) {
|
||||
continue;
|
||||
}
|
||||
if (bodyDepth < 0) {
|
||||
kept.append(pending).append(';');
|
||||
if (!TYPE_KEYWORD.matcher(pending).find() && pending.indexOf("(") >= 0) {
|
||||
bodyDepth = depth;
|
||||
}
|
||||
}
|
||||
pending.setLength(0);
|
||||
continue;
|
||||
}
|
||||
if (character == '}') {
|
||||
if (bodyDepth == depth) {
|
||||
bodyDepth = -1;
|
||||
}
|
||||
depth--;
|
||||
pending.setLength(0);
|
||||
continue;
|
||||
}
|
||||
if (character == ';') {
|
||||
if (initializerDepth == depth) {
|
||||
initializerDepth = -1;
|
||||
} else if (bodyDepth < 0) {
|
||||
kept.append(pending).append(';');
|
||||
}
|
||||
pending.setLength(0);
|
||||
continue;
|
||||
}
|
||||
if (bodyDepth >= 0 || initializerDepth >= 0) {
|
||||
continue;
|
||||
}
|
||||
if (character == '=' && isAssignment(text, index)) {
|
||||
kept.append(pending).append(';');
|
||||
pending.setLength(0);
|
||||
initializerDepth = depth;
|
||||
continue;
|
||||
}
|
||||
pending.append(character);
|
||||
}
|
||||
|
||||
return Stream.of(kept.toString().split(";", -1))
|
||||
.filter(fragment -> !fragment.contains("private "))
|
||||
.filter(fragment -> !fragment.contains("import "))
|
||||
.reduce("", (left, right) -> left + " ; " + right);
|
||||
}
|
||||
|
||||
/** Distinguishes a field initialiser from {@code ==}, {@code <=}, {@code >=} and {@code !=}. */
|
||||
private static boolean isAssignment(String text, int index) {
|
||||
char before = index == 0 ? ' ' : text.charAt(index - 1);
|
||||
char after = index + 1 >= text.length() ? ' ' : text.charAt(index + 1);
|
||||
return before != '=' && before != '<' && before != '>' && before != '!' && after != '=';
|
||||
}
|
||||
|
||||
private static String stripCommentsAndLiterals(String source) {
|
||||
return source
|
||||
.replaceAll("(?s)/\\*.*?\\*/", " ")
|
||||
.replaceAll("(?m)//.*$", " ")
|
||||
.replaceAll("\"\"\"(?s).*?\"\"\"", "\"\"")
|
||||
.replaceAll("\"(\\\\.|[^\"\\\\])*\"", "\"\"")
|
||||
.replaceAll("'(\\\\.|[^'\\\\])*'", "' '");
|
||||
}
|
||||
|
||||
/** The external coordinates a build script exports to its consumers. */
|
||||
private static List<String> apiDependenciesOf(String buildScript) {
|
||||
List<String> exported = new ArrayList<>();
|
||||
Matcher external = Pattern.compile("(?m)^\\s*api\\s+'([^']+)'").matcher(buildScript);
|
||||
while (external.find()) {
|
||||
String coordinate = external.group(1);
|
||||
int lastColon = coordinate.lastIndexOf(':');
|
||||
boolean versioned = lastColon > 0 && coordinate.indexOf(':') != lastColon;
|
||||
exported.add(versioned ? coordinate.substring(0, lastColon) : coordinate);
|
||||
}
|
||||
// Version-catalog accessors are the same declaration in a different notation. Matching only the
|
||||
// literal string form would have let `api libs.cloudevents.api` read as "not declared api" — a
|
||||
// contract reported as broken because the build file was tidied, which is the most expensive
|
||||
// kind of false positive a gate can produce.
|
||||
Matcher catalogued =
|
||||
Pattern.compile("(?m)^\\s*api\\s+(libs\\.[A-Za-z0-9.]+)").matcher(buildScript);
|
||||
while (catalogued.find()) {
|
||||
String module = catalogModules().get(catalogued.group(1));
|
||||
if (module != null) {
|
||||
exported.add(module);
|
||||
}
|
||||
}
|
||||
Matcher projects =
|
||||
Pattern.compile("(?m)^\\s*api\\s+project\\('([^']+)'\\)").matcher(buildScript);
|
||||
while (projects.find()) {
|
||||
String path = projects.group(1);
|
||||
exported.add(path.substring(path.lastIndexOf(':') + 1));
|
||||
}
|
||||
return exported;
|
||||
}
|
||||
|
||||
/** Everything a consumer of one leaf ends up compiling against. */
|
||||
private static Set<String> apiClosure(String leaf, Map<String, List<String>> exported) {
|
||||
Set<String> reachable = new TreeSet<>();
|
||||
List<String> pending = new ArrayList<>(exported.getOrDefault(leaf, List.of()));
|
||||
while (!pending.isEmpty()) {
|
||||
String next = pending.remove(0);
|
||||
if (!reachable.add(next)) {
|
||||
continue;
|
||||
}
|
||||
pending.addAll(exported.getOrDefault(next, List.of()));
|
||||
}
|
||||
return reachable;
|
||||
}
|
||||
|
||||
private static boolean declaresAsApi(String buildScript, String coordinate) {
|
||||
if (Pattern.compile("(?m)^\\s*api\\s+'" + Pattern.quote(coordinate) + "(:[^']*)?'")
|
||||
.matcher(buildScript)
|
||||
.find()) {
|
||||
return true;
|
||||
}
|
||||
return apiDependenciesOf(buildScript).contains(coordinate);
|
||||
}
|
||||
|
||||
/**
|
||||
* Version-catalog accessor to {@code group:artifact}, read from the catalog itself.
|
||||
*
|
||||
* <p>{@code gradle/libs.versions.toml} declares {@code archunit-junit5 = { module = "..." }} and
|
||||
* Gradle exposes it as {@code libs.archunit.junit5}; the alias separators become dots. Parsing
|
||||
* the file rather than hard-coding the mapping keeps this test honest when an alias is renamed —
|
||||
* a stale table here would silently stop resolving and report the library as unexported.
|
||||
*/
|
||||
private static Map<String, String> catalogModules() {
|
||||
Map<String, String> modules = new LinkedHashMap<>();
|
||||
Path catalog = repositoryRoot().resolve("src/gradle/libs.versions.toml");
|
||||
if (!Files.isRegularFile(catalog)) {
|
||||
return modules;
|
||||
}
|
||||
Matcher entry =
|
||||
Pattern.compile("(?m)^([A-Za-z0-9_-]+)\\s*=\\s*\\{[^}]*module\\s*=\\s*\"([^\"]+)\"")
|
||||
.matcher(read(catalog));
|
||||
while (entry.find()) {
|
||||
modules.put("libs." + entry.group(1).replace('-', '.').replace('_', '.'), entry.group(2));
|
||||
}
|
||||
return modules;
|
||||
}
|
||||
|
||||
private static java.util.function.Predicate<Path> isNamed(String leaf) {
|
||||
return path -> path.getFileName().toString().equals(leaf);
|
||||
}
|
||||
|
||||
private static List<Path> messagingLeaves() {
|
||||
Path family = repositoryRoot().resolve("src/platforms/messaging");
|
||||
try (Stream<Path> children = Files.list(family)) {
|
||||
return children
|
||||
.filter(Files::isDirectory)
|
||||
.filter(path -> Files.isRegularFile(path.resolve("build.gradle")))
|
||||
.sorted()
|
||||
.toList();
|
||||
} catch (IOException unreadable) {
|
||||
throw new UncheckedIOException(unreadable);
|
||||
}
|
||||
}
|
||||
|
||||
private static List<Path> productionSources(Path leaf) {
|
||||
Path main = leaf.resolve("src/main/java");
|
||||
if (!Files.isDirectory(main)) {
|
||||
return List.of();
|
||||
}
|
||||
try (Stream<Path> walk = Files.walk(main)) {
|
||||
return walk.filter(path -> path.toString().endsWith(".java")).sorted().toList();
|
||||
} catch (IOException unreadable) {
|
||||
throw new UncheckedIOException(unreadable);
|
||||
}
|
||||
}
|
||||
|
||||
private static String read(Path path) {
|
||||
try {
|
||||
return Files.readString(path);
|
||||
} catch (IOException unreadable) {
|
||||
throw new UncheckedIOException(unreadable);
|
||||
}
|
||||
}
|
||||
|
||||
private static Path repositoryRoot() {
|
||||
// Gradle hands the root only to the lanes that declare the repository files as inputs; the
|
||||
// plain `test` lane gets none, so a test that reads the repository without a lane tag fails
|
||||
// here instead of going stale behind an up-to-date check (review 2026-11-01 08-03).
|
||||
return RepositoryContractResources.fromSystemProperty().repositoryRoot();
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ registry, settings, build-logic, 루트 라이프사이클이 정하는 것을
|
||||
|
||||
## 정본 넷
|
||||
|
||||
- `src/config/architecture/modules.json`: 등록된 모든 leaf의 ID, repository-relative 소스 경로, Gradle path, 허용 production project dependency edge. runtime membership 목록은 없다. 조립 루트가 받을 수 있는 모듈은 `allowed_dependencies`가 정하고, 방향 게이트가 그 밖의 edge를 막는다. leaf 목록과 그 개수의 정본은 registry다. 문서는 개수를 적지 않는다. 산문에 적힌 숫자는 leaf가 더해지는 순간 틀린다. 그 숫자를 강제하던 태스크(`verifyDocumentedLeafCount`)는 지웠다. 문서에 적힌 수가 틀린 것은 결함이지만 빌드를 실패시킬 사유는 아니고, 그 태스크는 모든 지역 문서와 `build.gradle`을 정규식으로 훑는 파서였다.
|
||||
- `src/config/architecture/modules.json`: 등록된 모든 leaf의 ID, repository-relative 소스 경로, Gradle path, 허용 production project dependency edge, 그리고 별도 repo 라이브러리 edge(맨 위 `library_groups`, 행마다 `allowed_libraries`. 계층 leaf 행은 비워 둔다. 설명은 `src/config/architecture/README.md`). runtime membership 목록은 없다. 조립 루트가 받을 수 있는 모듈은 `allowed_dependencies`가 정하고, 방향 게이트가 그 밖의 edge를 막는다. leaf 목록과 그 개수의 정본은 registry다. 문서는 개수를 적지 않는다. 산문에 적힌 숫자는 leaf가 더해지는 순간 틀린다. 그 숫자를 강제하던 태스크(`verifyDocumentedLeafCount`)는 지웠다. 문서에 적힌 수가 틀린 것은 결함이지만 빌드를 실패시킬 사유는 아니고, 그 태스크는 모든 지역 문서와 `build.gradle`을 정규식으로 훑는 파서였다.
|
||||
- `src/settings.gradle`: `ca.architecture-registry` 설정 플러그인이 registry를 읽어 project를 include·mapping한다. registry가 project 목록이 될 수 없는 경우(중복 ID, 저장소 밖 경로, 없는 디렉터리)만 여기서 실패한다. 허용되지 않는 edge 같은 아키텍처 규칙은 `verifyCleanArchitectureDependencies`가 답한다. settings에서 죽으면 실행할 수 있는 태스크가 하나도 없다.
|
||||
- `src/build-logic/`: 아키텍처 코어(registry, 방향·순수성 task), 컨벤션, 테스트 레인 하나(`strictTestLanes`). leaf는 `ca.java-library`·`ca.spring-library`·`ca.platform-module` 중 자기 성격을 선언하고, 그 플러그인이 toolchain·락·정적분석·테스트 기본값을 준다. `ca.architecture`가 아키텍처 검증 태스크를 가진다. 기능별 검사(notification·mongo·messaging·graphql·JPA readiness 등)는 build-logic이 아니라 그 leaf의 테스트다.
|
||||
- `src/build.gradle`: 루트 라이프사이클(`ci`, `mainCheck`, `integrationCheck`, `performanceCheck`, `releaseCheck`, `qualityCheck`, `configContractCheck`)과 버전·리비전.
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -16,29 +16,50 @@ import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import java.util.regex.Pattern;
|
||||
import tools.jackson.databind.JsonNode;
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/** Typed representation of config/architecture/modules.json. */
|
||||
public record ModuleRegistry(List<Module> modules, File source) {
|
||||
/**
|
||||
* Typed representation of config/architecture/modules.json.
|
||||
*
|
||||
* <p>{@code libraryGroups} are the Maven group prefixes of the libraries this repository's owner
|
||||
* publishes from other repositories (design-docs {@code repo-structure/05-library-repos.md} 10.2절,
|
||||
* T2). Such a library is not a project, so the project-edge rules cannot see it; a module may depend
|
||||
* on one only when its row lists the coordinate in {@code allowed_libraries}. Libraries of any other
|
||||
* group are not governed by the registry.
|
||||
*/
|
||||
public record ModuleRegistry(List<Module> modules, List<String> libraryGroups, File source) {
|
||||
private static final ObjectMapper JSON = JsonMapper.builder().build();
|
||||
private static final Set<String> REQUIRED_MODULE_FIELDS =
|
||||
Set.of("id", "gradle_path", "source_path", "allowed_dependencies");
|
||||
private static final Set<String> REQUIRED_ROOT_FIELDS = Set.of("modules");
|
||||
private static final Pattern GROUP = Pattern.compile("[A-Za-z0-9_-]+(\\.[A-Za-z0-9_-]+)*");
|
||||
private static final Pattern COORDINATE =
|
||||
Pattern.compile("([A-Za-z0-9_-]+(?:\\.[A-Za-z0-9_-]+)*):([A-Za-z0-9_.-]+)");
|
||||
|
||||
public ModuleRegistry {
|
||||
modules = List.copyOf(modules);
|
||||
libraryGroups = List.copyOf(libraryGroups);
|
||||
Objects.requireNonNull(source, "source");
|
||||
}
|
||||
|
||||
/** Whether {@code group} is one of {@code libraryGroups} or below one of them. */
|
||||
public static boolean isOwnedGroup(List<String> libraryGroups, String group) {
|
||||
return group != null
|
||||
&& libraryGroups.stream()
|
||||
.anyMatch(prefix -> group.equals(prefix) || group.startsWith(prefix + "."));
|
||||
}
|
||||
|
||||
public record Module(
|
||||
String id,
|
||||
String gradlePath,
|
||||
String sourcePath,
|
||||
File sourceDirectory,
|
||||
String buildName,
|
||||
List<String> allowedDependencies) {
|
||||
List<String> allowedDependencies,
|
||||
List<String> allowedLibraries) {
|
||||
public Module {
|
||||
Objects.requireNonNull(id, "id");
|
||||
Objects.requireNonNull(gradlePath, "gradlePath");
|
||||
@@ -46,6 +67,7 @@ public record ModuleRegistry(List<Module> modules, File source) {
|
||||
Objects.requireNonNull(sourceDirectory, "sourceDirectory");
|
||||
Objects.requireNonNull(buildName, "buildName");
|
||||
allowedDependencies = List.copyOf(allowedDependencies);
|
||||
allowedLibraries = List.copyOf(allowedLibraries);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,6 +92,17 @@ public record ModuleRegistry(List<Module> modules, File source) {
|
||||
"Module registry root is missing " + missingRootFields + ": " + registryFile);
|
||||
}
|
||||
|
||||
List<String> libraryGroups = List.of();
|
||||
if (root.has("library_groups")) {
|
||||
libraryGroups = requireStringList(root.get("library_groups"), "library_groups");
|
||||
for (String group : libraryGroups) {
|
||||
if (!GROUP.matcher(group).matches()) {
|
||||
throw new IllegalStateException(
|
||||
"Module registry 'library_groups' entry '" + group + "' is not a Maven group.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
JsonNode modulesNode = root.get("modules");
|
||||
if (modulesNode == null || !modulesNode.isArray() || modulesNode.isEmpty()) {
|
||||
throw new IllegalStateException("Module registry has no modules: " + registryFile);
|
||||
@@ -126,6 +159,35 @@ public record ModuleRegistry(List<Module> modules, File source) {
|
||||
throw new IllegalStateException(
|
||||
"Module registry entry '" + id + "' contains duplicate allowed dependencies.");
|
||||
}
|
||||
List<String> allowedLibraries =
|
||||
module.has("allowed_libraries")
|
||||
? requireStringList(module.get("allowed_libraries"), id, "allowed_libraries")
|
||||
: List.of();
|
||||
for (String library : allowedLibraries) {
|
||||
var coordinate = COORDINATE.matcher(library);
|
||||
if (!coordinate.matches()) {
|
||||
throw new IllegalStateException(
|
||||
"Module registry entry '"
|
||||
+ id
|
||||
+ "' allows library '"
|
||||
+ library
|
||||
+ "', which is not a group:artifact coordinate.");
|
||||
}
|
||||
if (!isOwnedGroup(libraryGroups, coordinate.group(1))) {
|
||||
throw new IllegalStateException(
|
||||
"Module registry entry '"
|
||||
+ id
|
||||
+ "' allows library '"
|
||||
+ library
|
||||
+ "' outside the registry's library_groups "
|
||||
+ libraryGroups
|
||||
+ "; only an owned library is listed, any other dependency is not governed here.");
|
||||
}
|
||||
}
|
||||
if (new HashSet<>(allowedLibraries).size() != allowedLibraries.size()) {
|
||||
throw new IllegalStateException(
|
||||
"Module registry entry '" + id + "' contains duplicate allowed libraries.");
|
||||
}
|
||||
if (!ids.add(id)) {
|
||||
throw new IllegalStateException(
|
||||
"Module registry contains duplicate module id '" + id + "'.");
|
||||
@@ -186,10 +248,11 @@ public record ModuleRegistry(List<Module> modules, File source) {
|
||||
sourcePath,
|
||||
sourceDirectory,
|
||||
buildName,
|
||||
allowedDependencies));
|
||||
allowedDependencies,
|
||||
allowedLibraries));
|
||||
}
|
||||
|
||||
return new ModuleRegistry(modules, registryFile);
|
||||
return new ModuleRegistry(modules, libraryGroups, registryFile);
|
||||
}
|
||||
|
||||
public Module byId(String id) {
|
||||
@@ -283,6 +346,22 @@ public record ModuleRegistry(List<Module> modules, File source) {
|
||||
return value.asText();
|
||||
}
|
||||
|
||||
private static List<String> requireStringList(JsonNode raw, String field) {
|
||||
if (raw == null || !raw.isArray()) {
|
||||
throw new IllegalStateException("Module registry '" + field + "' must be a list.");
|
||||
}
|
||||
List<String> result = new ArrayList<>();
|
||||
for (int index = 0; index < raw.size(); index++) {
|
||||
JsonNode value = raw.get(index);
|
||||
if (value == null || !value.isString() || value.asText().isBlank()) {
|
||||
throw new IllegalStateException(
|
||||
"Module registry '" + field + "' has a non-string or blank entry at index " + index + ".");
|
||||
}
|
||||
result.add(value.asText());
|
||||
}
|
||||
return List.copyOf(result);
|
||||
}
|
||||
|
||||
private static List<String> requireStringList(JsonNode raw, String id, String field) {
|
||||
if (raw == null || !raw.isArray()) {
|
||||
throw new IllegalStateException(
|
||||
|
||||
+44
@@ -13,6 +13,7 @@ import java.util.TreeSet;
|
||||
import org.gradle.api.Plugin;
|
||||
import org.gradle.api.Project;
|
||||
import org.gradle.api.artifacts.Configuration;
|
||||
import org.gradle.api.artifacts.ExternalModuleDependency;
|
||||
import org.gradle.api.artifacts.ProjectDependency;
|
||||
import org.gradle.api.artifacts.result.ResolvedComponentResult;
|
||||
import org.gradle.api.provider.Provider;
|
||||
@@ -101,6 +102,8 @@ public final class ArchitecturePlugin implements Plugin<Project> {
|
||||
}
|
||||
}
|
||||
Set<String> declaredEdges = declaredProjectEdges(owner);
|
||||
Set<String> declaredLibraries =
|
||||
declaredLibraryEdges(owner, registry.libraryGroups());
|
||||
Provider<ResolvedComponentResult> compileClasspathRoot =
|
||||
owner
|
||||
.getConfigurations()
|
||||
@@ -122,6 +125,9 @@ public final class ArchitecturePlugin implements Plugin<Project> {
|
||||
task.getModuleName().set(moduleName);
|
||||
task.getAllowedDependencies().set(allowed);
|
||||
task.getDeclaredProjectEdges().set(declaredEdges);
|
||||
task.getLibraryGroups().set(registry.libraryGroups());
|
||||
task.getAllowedLibraries().set(module.allowedLibraries());
|
||||
task.getDeclaredLibraryEdges().set(declaredLibraries);
|
||||
task.getCompileClasspathRoot().set(compileClasspathRoot);
|
||||
});
|
||||
moduleTaskPaths.add(module.gradlePath() + ":verifyModuleDependencyDirection");
|
||||
@@ -247,6 +253,34 @@ public final class ArchitecturePlugin implements Plugin<Project> {
|
||||
return edges;
|
||||
}
|
||||
|
||||
/**
|
||||
* This module's declared dependencies on an owned library ({@code group:artifact}, the group under
|
||||
* one of the registry's {@code library_groups}), read the same way and from the same production
|
||||
* configurations as the project edges, {@code runtimeOnly} included.
|
||||
*/
|
||||
private static Set<String> declaredLibraryEdges(Project owner, List<String> libraryGroups) {
|
||||
Set<String> edges = new TreeSet<>();
|
||||
if (libraryGroups.isEmpty()) {
|
||||
return edges;
|
||||
}
|
||||
for (String name : PRODUCTION_DECLARATIONS) {
|
||||
Configuration configuration = owner.getConfigurations().findByName(name);
|
||||
if (configuration == null) {
|
||||
continue;
|
||||
}
|
||||
configuration
|
||||
.getDependencies()
|
||||
.withType(ExternalModuleDependency.class)
|
||||
.forEach(
|
||||
dependency -> {
|
||||
if (ModuleRegistry.isOwnedGroup(libraryGroups, dependency.getGroup())) {
|
||||
edges.add(dependency.getGroup() + ":" + dependency.getName());
|
||||
}
|
||||
});
|
||||
}
|
||||
return edges;
|
||||
}
|
||||
|
||||
/**
|
||||
* One production configuration's declarations, tagged by kind.
|
||||
*
|
||||
@@ -276,6 +310,16 @@ public final class ArchitecturePlugin implements Plugin<Project> {
|
||||
ModuleRegistry registry, List<ModuleRegistry.Module> modules) {
|
||||
List<String> violations = new ArrayList<>();
|
||||
for (ModuleRegistry.Module module : modules) {
|
||||
// The layers stay free of the owner's libraries by the registry itself, not only because the
|
||||
// purity check happens to refuse every non-project declaration in them.
|
||||
if (isPure(module.id()) && !module.allowedLibraries().isEmpty()) {
|
||||
violations.add(
|
||||
"'"
|
||||
+ module.id()
|
||||
+ "' is a layer module (domain-core, shared-contract, application-*) and may allow no"
|
||||
+ " library, but allows "
|
||||
+ module.allowedLibraries());
|
||||
}
|
||||
for (String dependencyId : module.allowedDependencies()) {
|
||||
if (dependencyId.equals(module.id())) {
|
||||
violations.add("'" + module.id() + "' declares itself as an allowed dependency");
|
||||
|
||||
+62
-2
@@ -1,13 +1,18 @@
|
||||
package dev.caskeleton.buildlogic.architecture;
|
||||
|
||||
import dev.caskeleton.buildlogic.ModuleRegistry;
|
||||
import dev.caskeleton.buildlogic.ResolvedComponents;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import org.gradle.api.DefaultTask;
|
||||
import org.gradle.api.GradleException;
|
||||
import org.gradle.api.artifacts.ModuleVersionIdentifier;
|
||||
import org.gradle.api.artifacts.component.ModuleComponentIdentifier;
|
||||
import org.gradle.api.artifacts.component.ProjectComponentIdentifier;
|
||||
import org.gradle.api.artifacts.result.ResolvedComponentResult;
|
||||
import org.gradle.api.provider.ListProperty;
|
||||
import org.gradle.api.provider.Property;
|
||||
import org.gradle.api.provider.SetProperty;
|
||||
import org.gradle.api.tasks.Input;
|
||||
@@ -31,6 +36,13 @@ import org.gradle.work.DisableCachingByDefault;
|
||||
* configuring. Holding the configurations themselves is what made this task unstorable in the
|
||||
* configuration cache.
|
||||
*
|
||||
* <p>Libraries this repository's owner publishes from other repositories (the registry's {@code
|
||||
* library_groups}) are held to the same rule as projects: a declared or compile-visible module of
|
||||
* such a group must be listed in the row's {@code allowed_libraries}. Since the messaging library
|
||||
* left this repository (2026-11-08) its modules are external coordinates, which the project-edge
|
||||
* check cannot see; this is what still keeps the bridge on {@code messaging-core-api} alone and the
|
||||
* layers free of the library.
|
||||
*
|
||||
* <p>The root task keeps what is genuinely repository-wide — the registry's own consistency, and
|
||||
* whether the set of governed modules matches the set of declared ones — and depends on every one of
|
||||
* these.
|
||||
@@ -50,6 +62,18 @@ public abstract class VerifyModuleDependencyDirectionTask extends DefaultTask {
|
||||
@Input
|
||||
public abstract SetProperty<String> getDeclaredProjectEdges();
|
||||
|
||||
/** The registry's {@code library_groups}: the group prefixes whose libraries are governed. */
|
||||
@Input
|
||||
public abstract ListProperty<String> getLibraryGroups();
|
||||
|
||||
/** The {@code group:artifact} coordinates this module's registry entry permits. */
|
||||
@Input
|
||||
public abstract SetProperty<String> getAllowedLibraries();
|
||||
|
||||
/** Owned-library coordinates this module declares in {@code api/implementation/compileOnly/runtimeOnly}. */
|
||||
@Input
|
||||
public abstract SetProperty<String> getDeclaredLibraryEdges();
|
||||
|
||||
/** Root of this module's resolved {@code compileClasspath}. */
|
||||
@Internal
|
||||
public abstract Property<ResolvedComponentResult> getCompileClasspathRoot();
|
||||
@@ -59,16 +83,37 @@ public abstract class VerifyModuleDependencyDirectionTask extends DefaultTask {
|
||||
String moduleName = getModuleName().get();
|
||||
Set<String> allowed = getAllowedDependencies().get();
|
||||
|
||||
List<String> libraryGroups = getLibraryGroups().get();
|
||||
// The build this module belongs to, read from the root of its own resolution rather than
|
||||
// assumed to be ":" — this build may itself run as an included build of another one.
|
||||
String ownBuild =
|
||||
getCompileClasspathRoot().get().getId() instanceof ProjectComponentIdentifier own
|
||||
? own.getBuild().getBuildPath()
|
||||
: ":";
|
||||
Set<String> actual = new HashSet<>(getDeclaredProjectEdges().get());
|
||||
Set<String> libraries = new TreeSet<>(getDeclaredLibraryEdges().get());
|
||||
// Declared edges are not the whole story: an `api(project(...))` two leaves away is visible to
|
||||
// this module's compiler and is therefore a real edge, whatever this build file says.
|
||||
// this module's compiler and is therefore a real edge, whatever this build file says. The same
|
||||
// holds for a library module another library module exports.
|
||||
for (ResolvedComponentResult component :
|
||||
ResolvedComponents.reachableFrom(getCompileClasspathRoot().get())) {
|
||||
if (component.getId() instanceof ProjectComponentIdentifier project) {
|
||||
if (component.getId() instanceof ProjectComponentIdentifier project
|
||||
&& !project.getBuild().getBuildPath().equals(ownBuild)) {
|
||||
// A project of an included build (`--include-build ../../messaging-library`) stands in for
|
||||
// the coordinate it substitutes, so it is held to allowed_libraries like that coordinate,
|
||||
// not mistaken for a project edge of this build.
|
||||
ModuleVersionIdentifier substituted = component.getModuleVersion();
|
||||
if (substituted != null && ModuleRegistry.isOwnedGroup(libraryGroups, substituted.getGroup())) {
|
||||
libraries.add(substituted.getGroup() + ":" + substituted.getName());
|
||||
}
|
||||
} else if (component.getId() instanceof ProjectComponentIdentifier project) {
|
||||
String projectPath = project.getProjectPath().replaceFirst("^:", "");
|
||||
if (!projectPath.equals(moduleName)) {
|
||||
actual.add(projectPath);
|
||||
}
|
||||
} else if (component.getId() instanceof ModuleComponentIdentifier library
|
||||
&& ModuleRegistry.isOwnedGroup(libraryGroups, library.getGroup())) {
|
||||
libraries.add(library.getGroup() + ":" + library.getModule());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,5 +130,20 @@ public abstract class VerifyModuleDependencyDirectionTask extends DefaultTask {
|
||||
+ ".\nDirect and compile-visible production project edges must be explicitly"
|
||||
+ " registered.");
|
||||
}
|
||||
|
||||
Set<String> forbiddenLibraries = new TreeSet<>(libraries);
|
||||
forbiddenLibraries.removeAll(getAllowedLibraries().get());
|
||||
if (!forbiddenLibraries.isEmpty()) {
|
||||
throw new GradleException(
|
||||
"Module ':"
|
||||
+ moduleName
|
||||
+ "' has forbidden library dependencies "
|
||||
+ forbiddenLibraries
|
||||
+ ". Allowed libraries are "
|
||||
+ new TreeSet<>(getAllowedLibraries().get())
|
||||
+ ".\nDirect and compile-visible production dependencies on a library of the groups "
|
||||
+ libraryGroups
|
||||
+ " must be listed in the module's allowed_libraries (config/architecture/modules.json).");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -123,6 +123,71 @@ class ModuleRegistryTest {
|
||||
assertTrue(failure.getMessage().contains("'build' field"), failure.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void allowedLibrariesAreReadAsCoordinatesOfAnOwnedGroup() {
|
||||
// given
|
||||
String json =
|
||||
registry(
|
||||
List.of("dev.cakit"),
|
||||
entryWithLibraries(
|
||||
"app-bootstrap",
|
||||
":app-bootstrap",
|
||||
"src/alpha",
|
||||
"[\"dev.cakit.messaging:messaging-core-api\"]"),
|
||||
entry("example-app", ":example-app", "src/beta"));
|
||||
|
||||
// when
|
||||
ModuleRegistry parsed = read(json);
|
||||
|
||||
// then
|
||||
assertEquals(List.of("dev.cakit"), parsed.libraryGroups());
|
||||
assertEquals(
|
||||
List.of("dev.cakit.messaging:messaging-core-api"),
|
||||
parsed.byId("app-bootstrap").allowedLibraries());
|
||||
assertEquals(List.of(), parsed.byId("example-app").allowedLibraries());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("allowed_libraries의 좌표가 library_groups 밖 group이면 registry를 읽을 때 거절한다")
|
||||
void anAllowedLibraryOutsideTheLibraryGroupsIsRefused() {
|
||||
// given
|
||||
String json =
|
||||
registry(
|
||||
List.of("dev.cakit"),
|
||||
entryWithLibraries(
|
||||
"app-bootstrap", ":app-bootstrap", "src/alpha", "[\"org.example:other\"]"));
|
||||
|
||||
// when
|
||||
IllegalStateException failure = assertThrows(IllegalStateException.class, () -> read(json));
|
||||
|
||||
// then
|
||||
assertTrue(failure.getMessage().contains("'app-bootstrap'"), failure.getMessage());
|
||||
assertTrue(failure.getMessage().contains("library_groups"), failure.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("allowed_libraries의 값은 group:artifact 꼴이어야 한다")
|
||||
void anAllowedLibraryThatIsNotAGroupAndArtifactIsRefused() {
|
||||
// given
|
||||
String json =
|
||||
registry(
|
||||
List.of("dev.cakit"),
|
||||
entryWithLibraries(
|
||||
"app-bootstrap", ":app-bootstrap", "src/alpha", "[\"dev.cakit.messaging\"]"));
|
||||
|
||||
// when
|
||||
IllegalStateException failure = assertThrows(IllegalStateException.class, () -> read(json));
|
||||
|
||||
// then
|
||||
assertTrue(failure.getMessage().contains("group:artifact"), failure.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRegistryWithoutLibraryGroupsGovernsNoLibrary() {
|
||||
ModuleRegistry parsed = read(valid());
|
||||
assertEquals(List.of(), parsed.libraryGroups());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("registry에 없는 디렉터리의 build 스크립트는 찾아내고, 등록된 leaf·루트·다른 빌드·build 산출물은 무시한다")
|
||||
void buildScriptsOutsideTheRegistryAreReported() throws Exception {
|
||||
@@ -188,4 +253,15 @@ class ModuleRegistryTest {
|
||||
private static String registry(String... entries) {
|
||||
return "{\"modules\":[" + String.join(",", entries) + "]}";
|
||||
}
|
||||
|
||||
private static String registry(List<String> libraryGroups, String... entries) {
|
||||
String groups =
|
||||
libraryGroups.stream().map(group -> "\"" + group + "\"").reduce((a, b) -> a + "," + b).orElse("");
|
||||
return "{\"library_groups\":[" + groups + "],\"modules\":[" + String.join(",", entries) + "]}";
|
||||
}
|
||||
|
||||
private static String entryWithLibraries(String id, String path, String source, String libraries) {
|
||||
String plain = entry(id, path, source);
|
||||
return plain.substring(0, plain.length() - 1) + ",\"allowed_libraries\":" + libraries + "}";
|
||||
}
|
||||
}
|
||||
|
||||
+270
@@ -107,6 +107,276 @@ class CleanArchitectureResolvedClasspathFunctionalTest {
|
||||
assertThat(result.getOutput()).contains("d/build.gradle").contains("no registry entry");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("소유 group 라이브러리를 runtimeOnly로만 실어도 allowed_libraries에 없으면 방향 게이트가 실패한다")
|
||||
void aRuntimeOnlyOwnedLibraryMissingFromAllowedLibrariesFailsTheGate(
|
||||
@TempDir Path temporaryRoot) throws IOException {
|
||||
// given
|
||||
Path project = libraryFixture(temporaryRoot, "runtimeOnly 'dev.cakit.demo:demo-starter:1.0.0'", "[]");
|
||||
|
||||
// when
|
||||
BuildResult result = runner(project, "verifyCleanArchitectureDependencies").buildAndFail();
|
||||
|
||||
// then
|
||||
assertThat(result.getOutput())
|
||||
.contains("Module ':c' has forbidden library dependencies [dev.cakit.demo:demo-starter]")
|
||||
.contains("allowed_libraries");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("소유 group 라이브러리가 api로 내보내 컴파일에 보이는 모듈도 allowed_libraries에 있어야 한다")
|
||||
void aCompileVisibleOwnedLibraryMustBeListedToo(@TempDir Path temporaryRoot)
|
||||
throws IOException {
|
||||
// given: demo-api's POM brings demo-core in compile scope, so c compiles against both.
|
||||
Path project =
|
||||
libraryFixture(
|
||||
temporaryRoot,
|
||||
"implementation 'dev.cakit.demo:demo-api:1.0.0'",
|
||||
"[\"dev.cakit.demo:demo-api\"]");
|
||||
|
||||
// when
|
||||
BuildResult result = runner(project, "verifyCleanArchitectureDependencies").buildAndFail();
|
||||
|
||||
// then
|
||||
assertThat(result.getOutput())
|
||||
.contains("Module ':c' has forbidden library dependencies [dev.cakit.demo:demo-core]");
|
||||
}
|
||||
|
||||
@Test
|
||||
void ownedLibrariesListedInAllowedLibrariesPass(@TempDir Path temporaryRoot)
|
||||
throws IOException {
|
||||
// given
|
||||
Path project =
|
||||
libraryFixture(
|
||||
temporaryRoot,
|
||||
"implementation 'dev.cakit.demo:demo-api:1.0.0'\n"
|
||||
+ " runtimeOnly 'dev.cakit.demo:demo-starter:1.0.0'",
|
||||
"[\"dev.cakit.demo:demo-api\", \"dev.cakit.demo:demo-core\","
|
||||
+ " \"dev.cakit.demo:demo-starter\"]");
|
||||
|
||||
// when
|
||||
BuildResult result = runner(project, "verifyCleanArchitectureDependencies").build();
|
||||
|
||||
// then
|
||||
assertThat(result.getOutput()).contains("BUILD SUCCESSFUL");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aLibraryOutsideTheOwnedGroupsIsNotGoverned(@TempDir Path temporaryRoot)
|
||||
throws IOException {
|
||||
// given
|
||||
Path project = libraryFixture(temporaryRoot, "implementation 'org.example:other:1.0.0'", "[]");
|
||||
|
||||
// when
|
||||
BuildResult result = runner(project, "verifyCleanArchitectureDependencies").build();
|
||||
|
||||
// then
|
||||
assertThat(result.getOutput()).contains("BUILD SUCCESSFUL");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("--include-build로 끼운 라이브러리 모듈은 프로젝트가 아니라 그 좌표로 allowed_libraries와 대조한다")
|
||||
void aLibrarySubstitutedFromAnIncludedBuildIsCheckedByItsCoordinate(@TempDir Path temporaryRoot)
|
||||
throws IOException {
|
||||
// given: the library's own build next to the repository; demo-included exports demo-extra.
|
||||
Path project =
|
||||
libraryFixture(
|
||||
temporaryRoot,
|
||||
"implementation 'dev.cakit.demo:demo-included:1.0.0'",
|
||||
"[\"dev.cakit.demo:demo-included\"]");
|
||||
Path library = includedLibrary(temporaryRoot);
|
||||
|
||||
// when
|
||||
BuildResult result =
|
||||
runner(
|
||||
project,
|
||||
"--include-build",
|
||||
library.toString(),
|
||||
"verifyCleanArchitectureDependencies")
|
||||
.buildAndFail();
|
||||
|
||||
// then: the module the included project exports is named as a library, not a project edge.
|
||||
assertThat(result.getOutput())
|
||||
.contains("Module ':c' has forbidden library dependencies [dev.cakit.demo:demo-extra]")
|
||||
.doesNotContain("forbidden project dependencies");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anIncludedLibraryWhoseModulesAreAllListedPasses(@TempDir Path temporaryRoot)
|
||||
throws IOException {
|
||||
// given
|
||||
Path project =
|
||||
libraryFixture(
|
||||
temporaryRoot,
|
||||
"implementation 'dev.cakit.demo:demo-included:1.0.0'",
|
||||
"[\"dev.cakit.demo:demo-included\", \"dev.cakit.demo:demo-extra\"]");
|
||||
Path library = includedLibrary(temporaryRoot);
|
||||
|
||||
// when
|
||||
BuildResult result =
|
||||
runner(
|
||||
project,
|
||||
"--include-build",
|
||||
library.toString(),
|
||||
"verifyCleanArchitectureDependencies")
|
||||
.build();
|
||||
|
||||
// then
|
||||
assertThat(result.getOutput()).contains("BUILD SUCCESSFUL");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("계층 leaf(domain-core 등) 행에 allowed_libraries를 적으면 registry 위반으로 실패한다")
|
||||
void aLayerModuleThatAllowsALibraryIsARegistryViolation(@TempDir Path temporaryRoot)
|
||||
throws IOException {
|
||||
// given
|
||||
Path project = temporaryRoot.resolve("repository").resolve("src");
|
||||
Files.createDirectories(project.resolve("config/architecture"));
|
||||
Files.createDirectories(project.resolve("domain-core"));
|
||||
Files.writeString(
|
||||
project.resolve("settings.gradle"), "rootProject.name = 'main'\ninclude 'domain-core'\n", UTF_8);
|
||||
Files.writeString(
|
||||
project.resolve("build.gradle"),
|
||||
"plugins { id 'ca.architecture' }\nsubprojects { apply plugin: 'java-library' }\n",
|
||||
UTF_8);
|
||||
Files.writeString(
|
||||
project.resolve("config/architecture/modules.json"),
|
||||
"""
|
||||
{
|
||||
"library_groups": ["dev.cakit"],
|
||||
"modules": [
|
||||
{
|
||||
"id": "domain-core",
|
||||
"gradle_path": ":domain-core",
|
||||
"source_path": "src/domain-core",
|
||||
"allowed_dependencies": [],
|
||||
"allowed_libraries": ["dev.cakit.demo:demo-api"]
|
||||
}
|
||||
]
|
||||
}
|
||||
""",
|
||||
UTF_8);
|
||||
|
||||
// when
|
||||
BuildResult result = runner(project, "verifyCleanArchitectureDependencies").buildAndFail();
|
||||
|
||||
// then
|
||||
assertThat(result.getOutput())
|
||||
.contains("'domain-core' is a layer module")
|
||||
.contains("[dev.cakit.demo:demo-api]");
|
||||
}
|
||||
|
||||
/** A library build of two projects in group dev.cakit.demo; demo-included exports demo-extra. */
|
||||
private static Path includedLibrary(Path temporaryRoot) throws IOException {
|
||||
Path library = temporaryRoot.resolve("library");
|
||||
Files.createDirectories(library.resolve("demo-included"));
|
||||
Files.createDirectories(library.resolve("demo-extra"));
|
||||
Files.writeString(
|
||||
library.resolve("settings.gradle"),
|
||||
"rootProject.name = 'library'\ninclude 'demo-included', 'demo-extra'\n",
|
||||
UTF_8);
|
||||
Files.writeString(
|
||||
library.resolve("build.gradle"),
|
||||
"""
|
||||
subprojects {
|
||||
apply plugin: 'java-library'
|
||||
group = 'dev.cakit.demo'
|
||||
version = '1.0.0'
|
||||
}
|
||||
project(':demo-included') {
|
||||
dependencies { api project(':demo-extra') }
|
||||
}
|
||||
""",
|
||||
UTF_8);
|
||||
return library;
|
||||
}
|
||||
|
||||
/**
|
||||
* One module {@code c} that declares {@code declaration} against a file repository of POM-only
|
||||
* modules: {@code dev.cakit.demo:demo-api} (bringing {@code demo-core} in compile scope),
|
||||
* {@code demo-starter}, and {@code org.example:other}. The direction check reads the resolved
|
||||
* graph, not the artifacts, so no jar is needed.
|
||||
*/
|
||||
private static Path libraryFixture(Path temporaryRoot, String declaration, String cLibraries)
|
||||
throws IOException {
|
||||
Path repository = temporaryRoot.resolve("repository");
|
||||
Path project = repository.resolve("src");
|
||||
Files.createDirectories(project.resolve("config/architecture"));
|
||||
Files.createDirectories(project.resolve("c"));
|
||||
Path maven = temporaryRoot.resolve("maven");
|
||||
pom(maven, "dev.cakit.demo", "demo-core", "");
|
||||
pom(
|
||||
maven,
|
||||
"dev.cakit.demo",
|
||||
"demo-api",
|
||||
"""
|
||||
<dependencies><dependency><groupId>dev.cakit.demo</groupId><artifactId>demo-core</artifactId>\
|
||||
<version>1.0.0</version><scope>compile</scope></dependency></dependencies>""");
|
||||
pom(maven, "dev.cakit.demo", "demo-starter", "");
|
||||
pom(maven, "org.example", "other", "");
|
||||
|
||||
Files.writeString(
|
||||
project.resolve("settings.gradle"),
|
||||
"""
|
||||
rootProject.name = 'main'
|
||||
include 'c'
|
||||
""",
|
||||
UTF_8);
|
||||
Files.writeString(
|
||||
project.resolve("build.gradle"),
|
||||
"""
|
||||
plugins { id 'ca.architecture' }
|
||||
subprojects {
|
||||
apply plugin: 'java-library'
|
||||
repositories { maven { url = '%s' } }
|
||||
}
|
||||
project(':c') {
|
||||
dependencies {
|
||||
%s
|
||||
}
|
||||
}
|
||||
"""
|
||||
.formatted(maven.toUri(), declaration),
|
||||
UTF_8);
|
||||
Files.writeString(
|
||||
project.resolve("config/architecture/modules.json"),
|
||||
"""
|
||||
{
|
||||
"library_groups": ["dev.cakit"],
|
||||
"modules": [
|
||||
{
|
||||
"id": "c",
|
||||
"gradle_path": ":c",
|
||||
"source_path": "src/c",
|
||||
"allowed_dependencies": [],
|
||||
"allowed_libraries": %s
|
||||
}
|
||||
]
|
||||
}
|
||||
"""
|
||||
.formatted(cLibraries),
|
||||
UTF_8);
|
||||
return project;
|
||||
}
|
||||
|
||||
private static void pom(Path maven, String group, String artifact, String dependencies)
|
||||
throws IOException {
|
||||
Path directory = maven.resolve(group.replace('.', '/')).resolve(artifact).resolve("1.0.0");
|
||||
Files.createDirectories(directory);
|
||||
Files.writeString(
|
||||
directory.resolve(artifact + "-1.0.0.pom"),
|
||||
"""
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>%s</groupId><artifactId>%s</artifactId><version>1.0.0</version>
|
||||
<packaging>pom</packaging>
|
||||
%s
|
||||
</project>
|
||||
"""
|
||||
.formatted(group, artifact, dependencies),
|
||||
UTF_8);
|
||||
}
|
||||
|
||||
private static Path fixture(Path temporaryRoot, boolean allowTransitiveA) throws IOException {
|
||||
Path repository = temporaryRoot.resolve("repository");
|
||||
Path project = repository.resolve("src");
|
||||
|
||||
@@ -31,10 +31,10 @@ dependencies {
|
||||
testImplementation 'org.springframework.boot:spring-boot-starter-test'
|
||||
// The shutdown-order test runs the real relay over the port owner's shared fake store.
|
||||
testImplementation testFixtures(project(':application-core'))
|
||||
// The shutdown-order test holds the relay above the platform's admission phase by the platform's
|
||||
// own constant (MessagingShutdownLifecycle.PHASE), not a copy of its value. Compile-only and
|
||||
// not transitive: a compile-time constant is inlined, so the platform is not on the test runtime.
|
||||
testCompileOnly(project(':messaging:messaging-spring-boot-starter')) {
|
||||
// The shutdown-order test holds the relay above the messaging library's admission phase by the
|
||||
// library's own constant (MessagingShutdownLifecycle.PHASE), not a copy of its value. Compile-only
|
||||
// and not transitive: a compile-time constant is inlined, so the library is not on the test runtime.
|
||||
testCompileOnly(libs.messaging.spring.boot.starter) {
|
||||
transitive = false
|
||||
}
|
||||
testImplementation 'org.mockito:mockito-core'
|
||||
|
||||
@@ -38,6 +38,7 @@ commons-beanutils:commons-beanutils:1.11.0=checkstyle
|
||||
commons-collections:commons-collections:3.2.2=checkstyle
|
||||
commons-io:commons-io:2.21.0=spotbugs
|
||||
commons-logging:commons-logging:1.3.6=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||
dev.cakit.messaging:messaging-spring-boot-starter:1.0.0=testCompileClasspath
|
||||
info.picocli:picocli:4.7.7=checkstyle
|
||||
io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,testAnnotationProcessor
|
||||
io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor
|
||||
|
||||
+1
-1
@@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
|
||||
import dev.cakit.messaging.autoconfigure.MessagingShutdownLifecycle;
|
||||
import dev.caskeleton.application.outbox.ClaimedOutboxEvent;
|
||||
import dev.caskeleton.application.outbox.OutboxCompletion;
|
||||
import dev.caskeleton.application.outbox.OutboxEventStatus;
|
||||
@@ -16,7 +17,6 @@ import dev.caskeleton.application.outbox.testkit.InMemoryOutboxStore;
|
||||
import dev.caskeleton.application.outbox.testkit.OutboxEvents;
|
||||
import dev.caskeleton.application.transaction.TransactionPort;
|
||||
import dev.caskeleton.application.transaction.testkit.DirectTransactionPort;
|
||||
import dev.caskeleton.messaging.autoconfigure.MessagingShutdownLifecycle;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
프로젝트 edge를 정확히 적는다. 빈 `allowed_dependencies` 목록에도 뜻이 있다: 그 leaf가 일부러 다른
|
||||
프로젝트에 기대지 않는다는 뜻이지, registry 항목을 덜 채웠다는 뜻이 아니다.
|
||||
|
||||
`domain-core`, `shared-contract`, 들여온 메시징 제품의 `messaging-core-api`가 그 예다. 빈 목록은
|
||||
`domain-core`, `shared-contract`가 그 예다. 빈 목록은
|
||||
분명한 경계이고, 실제 프로젝트 edge를 들여와 리뷰하기 전까지 비어 있어야 한다. 반대로 목록에 적힌
|
||||
edge는 빌드가 실제로 쓰는 것과 맞아야 한다. 예를 들어 `adapter-outbound-persistence-mongo`의 목록은
|
||||
`["application-core", "shared-contract"]`이고 `MongoRegistryPermissionParityTest`가 두 방향을 모두
|
||||
@@ -12,3 +12,21 @@ edge는 빌드가 실제로 쓰는 것과 맞아야 한다. 예를 들어 `adapt
|
||||
|
||||
런타임 조립 구성원은 빌드 로직이 해석된 runtime classpath에서 얻는다. 이 registry에 모듈마다 칸으로
|
||||
다시 적지 않는다.
|
||||
|
||||
## 별도 repo 라이브러리: `library_groups`와 `allowed_libraries`
|
||||
|
||||
소유자가 다른 repo에서 배포하는 라이브러리(메시징 `dev.cakit.messaging`, gRPC `dev.cakit.grpc`)는 이 빌드의
|
||||
프로젝트가 아니라 외부 좌표다. 그래서 프로젝트 edge 규칙(`allowed_dependencies`)이 보지 못한다. 그 빈자리를
|
||||
두 칸이 메운다(설계 design-docs `repo-structure/05-library-repos.md` 10.2절 T2, 소유자 승인 2026-11-07).
|
||||
|
||||
- 맨 위 `library_groups`: 다스릴 라이브러리의 Maven group 접두사. 지금 `["dev.cakit"]`이다. 이 접두사와
|
||||
같거나 그 아래(`dev.cakit.` 다음) group만 다스린다. 다른 group(Spring, Kafka client 등)은 이 칸과 상관없다.
|
||||
- 행마다 선택 칸 `allowed_libraries`: 그 leaf가 쓸 수 있는 라이브러리 모듈의 `group:artifact` 목록. 없으면 빈
|
||||
목록과 같다. 값은 `library_groups` 안의 group이어야 하고 겹치면 안 된다(registry를 읽을 때 거절).
|
||||
- 방향 검사(`verifyModuleDependencyDirection`, `verifyCleanArchitectureDependencies` 아래)는 프로젝트 edge와 같은
|
||||
방식으로 대조한다: 운영 선언(`api`·`implementation`·`compileOnly`·`runtimeOnly`)의 소유 group 좌표와,
|
||||
`compileClasspath`에서 보이는 소유 group 모듈(라이브러리 모듈이 `api`로 내보낸 것 포함)이 모두 칸에 있어야
|
||||
한다. 시험 구성은 보지 않는다.
|
||||
- 그래서 지금 지키는 약속 셋이 검사로 남는다: bridge(`adapter-outbound-messaging`)는 `messaging-core-api`만 본다.
|
||||
Kafka capability(`adapter-outbound-messaging-kafka`)는 starter-kafka를 `runtimeOnly`로만 싣는다. 계층 leaf는
|
||||
칸이 비어 있으니 라이브러리를 쓸 수 없다.
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
{
|
||||
"library_groups": [
|
||||
"dev.cakit"
|
||||
],
|
||||
"modules": [
|
||||
{
|
||||
"id": "domain-core",
|
||||
@@ -173,11 +176,13 @@
|
||||
"gradle_path": ":adapter:inbound:messaging",
|
||||
"source_path": "src/adapter/inbound/messaging",
|
||||
"allowed_dependencies": [
|
||||
"application-core",
|
||||
"messaging-core-api",
|
||||
"messaging-reliability",
|
||||
"messaging-reliability-api",
|
||||
"messaging-reliability-jdbc-postgresql"
|
||||
"application-core"
|
||||
],
|
||||
"allowed_libraries": [
|
||||
"dev.cakit.messaging:messaging-core-api",
|
||||
"dev.cakit.messaging:messaging-reliability",
|
||||
"dev.cakit.messaging:messaging-reliability-api",
|
||||
"dev.cakit.messaging:messaging-reliability-jdbc-postgresql"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -188,8 +193,10 @@
|
||||
"domain-core",
|
||||
"application-core",
|
||||
"shared-contract",
|
||||
"adapter-outbound-support",
|
||||
"messaging-core-api"
|
||||
"adapter-outbound-support"
|
||||
],
|
||||
"allowed_libraries": [
|
||||
"dev.cakit.messaging:messaging-core-api"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -197,8 +204,10 @@
|
||||
"gradle_path": ":adapter:outbound:messaging-kafka",
|
||||
"source_path": "src/adapter/outbound/messaging-kafka",
|
||||
"allowed_dependencies": [
|
||||
"adapter-outbound-messaging",
|
||||
"messaging-spring-boot-starter-kafka"
|
||||
"adapter-outbound-messaging"
|
||||
],
|
||||
"allowed_libraries": [
|
||||
"dev.cakit.messaging:messaging-spring-boot-starter-kafka"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -382,192 +391,6 @@
|
||||
"composition-service-runtime",
|
||||
"composition-durable-operation"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "messaging-core-api",
|
||||
"gradle_path": ":messaging:messaging-core-api",
|
||||
"source_path": "src/platforms/messaging/messaging-core-api",
|
||||
"allowed_dependencies": []
|
||||
},
|
||||
{
|
||||
"id": "messaging-schema-json",
|
||||
"gradle_path": ":messaging:messaging-schema-json",
|
||||
"source_path": "src/platforms/messaging/messaging-schema-json",
|
||||
"allowed_dependencies": [
|
||||
"messaging-core-api"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "messaging-schema-avro",
|
||||
"gradle_path": ":messaging:messaging-schema-avro",
|
||||
"source_path": "src/platforms/messaging/messaging-schema-avro",
|
||||
"allowed_dependencies": [
|
||||
"messaging-core-api"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "messaging-schema-protobuf",
|
||||
"gradle_path": ":messaging:messaging-schema-protobuf",
|
||||
"source_path": "src/platforms/messaging/messaging-schema-protobuf",
|
||||
"allowed_dependencies": [
|
||||
"messaging-core-api"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "messaging-cloudevents",
|
||||
"gradle_path": ":messaging:messaging-cloudevents",
|
||||
"source_path": "src/platforms/messaging/messaging-cloudevents",
|
||||
"allowed_dependencies": [
|
||||
"messaging-core-api"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "messaging-policy",
|
||||
"gradle_path": ":messaging:messaging-policy",
|
||||
"source_path": "src/platforms/messaging/messaging-policy",
|
||||
"allowed_dependencies": [
|
||||
"messaging-core-api"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "messaging-transport-spi",
|
||||
"gradle_path": ":messaging:messaging-transport-spi",
|
||||
"source_path": "src/platforms/messaging/messaging-transport-spi",
|
||||
"allowed_dependencies": [
|
||||
"messaging-core-api",
|
||||
"messaging-policy"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "messaging-runtime-core",
|
||||
"gradle_path": ":messaging:messaging-runtime-core",
|
||||
"source_path": "src/platforms/messaging/messaging-runtime-core",
|
||||
"allowed_dependencies": [
|
||||
"messaging-core-api",
|
||||
"messaging-policy",
|
||||
"messaging-transport-spi",
|
||||
"messaging-security",
|
||||
"messaging-observability"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "messaging-observability",
|
||||
"gradle_path": ":messaging:messaging-observability",
|
||||
"source_path": "src/platforms/messaging/messaging-observability",
|
||||
"allowed_dependencies": [
|
||||
"messaging-core-api"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "messaging-security",
|
||||
"gradle_path": ":messaging:messaging-security",
|
||||
"source_path": "src/platforms/messaging/messaging-security",
|
||||
"allowed_dependencies": [
|
||||
"messaging-core-api"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "messaging-kafka",
|
||||
"gradle_path": ":messaging:messaging-kafka",
|
||||
"source_path": "src/platforms/messaging/messaging-kafka",
|
||||
"allowed_dependencies": [
|
||||
"messaging-core-api",
|
||||
"messaging-policy",
|
||||
"messaging-transport-spi",
|
||||
"messaging-observability",
|
||||
"messaging-security",
|
||||
"messaging-admin"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "messaging-reliability-api",
|
||||
"gradle_path": ":messaging:messaging-reliability-api",
|
||||
"source_path": "src/platforms/messaging/messaging-reliability-api",
|
||||
"allowed_dependencies": [
|
||||
"messaging-core-api"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "messaging-reliability",
|
||||
"gradle_path": ":messaging:messaging-reliability",
|
||||
"source_path": "src/platforms/messaging/messaging-reliability",
|
||||
"allowed_dependencies": [
|
||||
"messaging-core-api",
|
||||
"messaging-reliability-api"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "messaging-reliability-jdbc-postgresql",
|
||||
"gradle_path": ":messaging:messaging-reliability-jdbc-postgresql",
|
||||
"source_path": "src/platforms/messaging/messaging-reliability-jdbc-postgresql",
|
||||
"allowed_dependencies": [
|
||||
"messaging-core-api",
|
||||
"messaging-reliability-api",
|
||||
"messaging-admin",
|
||||
"messaging-policy"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "messaging-claim-check",
|
||||
"gradle_path": ":messaging:messaging-claim-check",
|
||||
"source_path": "src/platforms/messaging/messaging-claim-check",
|
||||
"allowed_dependencies": [
|
||||
"messaging-core-api",
|
||||
"messaging-reliability-api"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "messaging-admin",
|
||||
"gradle_path": ":messaging:messaging-admin",
|
||||
"source_path": "src/platforms/messaging/messaging-admin",
|
||||
"allowed_dependencies": [
|
||||
"messaging-core-api",
|
||||
"messaging-observability"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "messaging-spring-boot-starter",
|
||||
"gradle_path": ":messaging:messaging-spring-boot-starter",
|
||||
"source_path": "src/platforms/messaging/messaging-spring-boot-starter",
|
||||
"allowed_dependencies": [
|
||||
"messaging-admin",
|
||||
"messaging-core-api",
|
||||
"messaging-observability",
|
||||
"messaging-policy",
|
||||
"messaging-reliability",
|
||||
"messaging-reliability-api",
|
||||
"messaging-reliability-jdbc-postgresql",
|
||||
"messaging-runtime-core",
|
||||
"messaging-schema-json",
|
||||
"messaging-security",
|
||||
"messaging-transport-spi"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "messaging-spring-boot-starter-kafka",
|
||||
"gradle_path": ":messaging:messaging-spring-boot-starter-kafka",
|
||||
"source_path": "src/platforms/messaging/messaging-spring-boot-starter-kafka",
|
||||
"allowed_dependencies": [
|
||||
"messaging-spring-boot-starter",
|
||||
"messaging-kafka",
|
||||
"messaging-admin",
|
||||
"messaging-core-api",
|
||||
"messaging-observability",
|
||||
"messaging-policy",
|
||||
"messaging-reliability-api",
|
||||
"messaging-security",
|
||||
"messaging-transport-spi"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "messaging-testkit",
|
||||
"gradle_path": ":messaging:messaging-testkit",
|
||||
"source_path": "src/platforms/messaging/messaging-testkit",
|
||||
"allowed_dependencies": [
|
||||
"messaging-core-api",
|
||||
"messaging-policy",
|
||||
"messaging-transport-spi"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -99,9 +99,9 @@
|
||||
<Method name="<clinit>"/>
|
||||
</Match>
|
||||
|
||||
<!-- DM_GC: both tests are about what garbage collection does — a gauge that must survive a
|
||||
collection instead of decaying to NaN through a weak reference, and a retained-set bound
|
||||
measured between two collections. System.gc() is the request they exist to make. -->
|
||||
<!-- DM_GC: the test is about what garbage collection does — a gauge that must survive a
|
||||
collection instead of decaying to NaN through a weak reference. System.gc() is the request
|
||||
it exists to make. -->
|
||||
<Match>
|
||||
<Bug pattern="DM_GC"/>
|
||||
<Or>
|
||||
@@ -109,10 +109,6 @@
|
||||
<Class name="dev.caskeleton.adapter.outbound.notification.platform.autoconfigure.NotificationObservationTest"/>
|
||||
<Method name="aGaugeKeepsReportingAfterGarbageCollectionInsteadOfDecayingToNaN"/>
|
||||
</And>
|
||||
<And>
|
||||
<Class name="dev.caskeleton.messaging.schema.json.PlatformOverheadPerformanceTest"/>
|
||||
<Method name="aRoundTripDoesNotAllocateAGrowingRetainedSet"/>
|
||||
</And>
|
||||
</Or>
|
||||
</Match>
|
||||
|
||||
|
||||
@@ -69,27 +69,6 @@
|
||||
<Method name="aGaugeKeepsReportingAfterGarbageCollectionInsteadOfDecayingToNaN"/>
|
||||
</Match>
|
||||
|
||||
<!-- The messaging codec retention test measures whether a round trip retains per-message state.
|
||||
Measuring retained memory requires forcing a collection first and again at the end;
|
||||
without it the "after" reading is dominated by garbage that simply had not been collected
|
||||
yet and the test could never distinguish a leak from ordinary allocation. Scoped to the
|
||||
one test class, so an explicit gc anywhere else stays reportable. -->
|
||||
<Match>
|
||||
<Bug pattern="DM_GC"/>
|
||||
<Source name="PlatformOverheadPerformanceTest.java"/>
|
||||
</Match>
|
||||
|
||||
<!-- The outbox and inbox container tests apply the real shipped Flyway migration by reading it
|
||||
from the classpath and executing it, which is the whole point: a test that re-declared the
|
||||
schema inline would certify a schema nothing deploys. The SQL is a build artifact, not
|
||||
input, and the database is a throwaway container. Scoped to these two classes so any other
|
||||
dynamic SQL stays reportable. -->
|
||||
<Match>
|
||||
<Bug pattern="SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE"/>
|
||||
<Source name="~(Inbox|Outbox)PostgresIT.java"/>
|
||||
</Match>
|
||||
|
||||
|
||||
<!-- =========================================================================================
|
||||
Confidence MEDIUM (review 2026-11-01 08-07). Everything below was added when the report
|
||||
level went from HIGH to MEDIUM. Each entry was judged against the code it names; defects
|
||||
@@ -171,7 +150,6 @@
|
||||
the constructor-bound records listed here have no invariant of their own: each is read
|
||||
once at startup by the factory that compiles it into the runtime type, and that factory
|
||||
copies (HttpClientProfileFactory and DynamicTargetAutoConfiguration Set.copyOf every list;
|
||||
MessagingConfigurationCompiler copies into DestinationAccessPolicy and SchemaPolicy;
|
||||
RedisRuntimeAutoConfiguration validates and maps; FileserverStartupValidator reads the
|
||||
ancestors once). A settings record that validates a collection in its own constructor
|
||||
copies it there instead (FileserverPlatformSettings.Security). -->
|
||||
@@ -182,9 +160,6 @@
|
||||
<Class name="dev.caskeleton.adapter.outbound.cache.redis.capability.RedisCapabilitySettings$RateLimit"/>
|
||||
<Class name="dev.caskeleton.adapter.outbound.cache.redis.runtime.config.RedisRuntimeSettings"/>
|
||||
<Class name="dev.caskeleton.adapter.outbound.cache.redis.runtime.config.RedisRuntimeSettings$Sentinel"/>
|
||||
<Class name="dev.caskeleton.messaging.autoconfigure.MessagingSettings"/>
|
||||
<Class name="dev.caskeleton.messaging.autoconfigure.BrokerSecuritySettings$Access"/>
|
||||
<Class name="dev.caskeleton.messaging.autoconfigure.DestinationSettings$Schema"/>
|
||||
<Class name="dev.caskeleton.adapter.outbound.httpclient.autoconfigure.HttpClientPlatformSettings$ClientSettings"/>
|
||||
<Class name="dev.caskeleton.adapter.outbound.httpclient.autoconfigure.HttpClientPlatformSettings$DynamicTargetSettings"/>
|
||||
<Class name="dev.caskeleton.adapter.outbound.httpclient.autoconfigure.HttpClientPlatformSettings$Response"/>
|
||||
@@ -220,7 +195,6 @@
|
||||
<And><Class name="dev.caskeleton.application.security.AuthorizationPrincipal"/><Field name="roles"/></And>
|
||||
<And><Class name="dev.caskeleton.application.objectstorage.request.ObjectPublishRequest"/><Field name="capabilityRequirements"/></And>
|
||||
<And><Class name="dev.caskeleton.application.objectstorage.request.ObjectStageRequest"/><Field name="capabilityRequirements"/></And>
|
||||
<And><Class name="dev.caskeleton.messaging.api.header.MessageHeaders"/><Field name="values"/></And>
|
||||
</Or>
|
||||
</Match>
|
||||
|
||||
@@ -234,15 +208,6 @@
|
||||
<Method name="getBytes"/>
|
||||
</Match>
|
||||
|
||||
<!-- CredentialRuntime takes ownership of the secret array the registry resolved for it, so that
|
||||
clear() overwrites the only copy. Copying in the constructor would leave the provider's
|
||||
array behind, uncleared, which is the outcome the char[] field type exists to prevent. -->
|
||||
<Match>
|
||||
<Bug pattern="EI_EXPOSE_REP2"/>
|
||||
<Class name="dev.caskeleton.messaging.security.CredentialRuntime"/>
|
||||
<Method name="<init>"/>
|
||||
</Match>
|
||||
|
||||
<!-- CT_CONSTRUCTOR_THROW (finalizer attack: a subclass's finalize() keeps a half-built object).
|
||||
A final class cannot be attacked this way, and every class that could be made final was.
|
||||
These three groups must stay subclassable. -->
|
||||
@@ -281,7 +246,7 @@
|
||||
<!-- FindSecBugs REDOS, one Match per constructor or static initialiser. Every pattern flagged
|
||||
is "segment (separator segment)*" where the separator is a character the segment class
|
||||
cannot contain ('.', '-', ';', or a class of those), so each input splits exactly one way
|
||||
and backtracking is linear, not exponential. The application-core and messaging values
|
||||
and backtracking is linear, not exponential. The application-core values
|
||||
also check the length (at most 64-256 characters) before the pattern runs; JsonPathName and SafeSortField
|
||||
match developer-declared paths; the SNS host comes from a URI host. -->
|
||||
<Match>
|
||||
@@ -290,7 +255,6 @@
|
||||
<And><Class name="dev.caskeleton.adapter.outbound.notification.platform.provider.ses.SnsSignatureVerifier"/><Method name="<clinit>"/></And>
|
||||
<And><Class name="dev.caskeleton.adapter.outbound.persistence.postgresql.json.JsonPathName"/><Method name="<clinit>"/></And>
|
||||
<And><Class name="dev.caskeleton.adapter.outbound.persistence.springdata.SafeSortField"/><Method name="<clinit>"/></And>
|
||||
<And><Class name="dev.caskeleton.messaging.api.ContentType"/><Method name="<clinit>"/></And>
|
||||
<And><Class name="dev.caskeleton.application.messaging.contract.ContractDescriptor"/><Method name="<init>"/></And>
|
||||
<And><Class name="dev.caskeleton.application.messaging.contract.ContractId"/><Method name="<init>"/></And>
|
||||
<And><Class name="dev.caskeleton.application.messaging.contract.LogicalDestinationId"/><Method name="<init>"/></And>
|
||||
@@ -317,15 +281,6 @@
|
||||
</Or>
|
||||
</Match>
|
||||
|
||||
<!-- SQL_INJECTION_JDBC: transition() and transitionWithNextAttempt() append a fixed WHERE clause
|
||||
to a SET clause that every caller passes as a string literal from this class; every value
|
||||
is a bound parameter. The method names are the lambdas javac generates inside them. -->
|
||||
<Match>
|
||||
<Bug pattern="SQL_INJECTION_JDBC"/>
|
||||
<Class name="dev.caskeleton.messaging.outbox.JdbcOutboxRepository"/>
|
||||
<Method name="~lambda\$transition(WithNextAttempt)?\$\d+"/>
|
||||
</Match>
|
||||
|
||||
<!-- SQL_INJECTION_SPRING_JDBC: the query is PostgreSqlIdempotencyStore.ACTIVE_CAPABILITY_SQL, a
|
||||
constant handed to the guard's package-private constructor; nothing else constructs it. -->
|
||||
<Match>
|
||||
@@ -353,7 +308,7 @@
|
||||
</Match>
|
||||
|
||||
<!-- PREDICTABLE_RANDOM: log sampling (SamplingTurboFilter.decide) and retry jitter
|
||||
(BackoffCalculator's default source, HttpClientProfileAutoConfiguration.jitterRandom) only
|
||||
(HttpClientProfileAutoConfiguration.jitterRandom) only
|
||||
need spread, not unpredictability; nothing security-relevant is derived from any of these
|
||||
values. Knowing the next jitter tells a caller when a retry lands, which the retry policy
|
||||
already bounds. SecureRandom would read as a security requirement that is not there. -->
|
||||
@@ -362,7 +317,6 @@
|
||||
<Or>
|
||||
<And><Class name="dev.caskeleton.adapter.outbound.httpclient.autoconfigure.HttpClientProfileAutoConfiguration"/><Method name="jitterRandom"/></And>
|
||||
<And><Class name="dev.caskeleton.bootstrap.logging.SamplingTurboFilter"/><Method name="decide"/></And>
|
||||
<And><Class name="dev.caskeleton.messaging.policy.BackoffCalculator"/><Method name="~lambda\$new\$\d+"/></And>
|
||||
</Or>
|
||||
</Match>
|
||||
|
||||
@@ -398,13 +352,11 @@
|
||||
</Match>
|
||||
|
||||
<!-- MS_EXPOSE_REP on a static that is already immutable: a Jackson 3 ObjectMapper cannot be
|
||||
reconfigured after build() (NotificationJsonMapper), and CertifiedEvidence.RECORDED is a
|
||||
Stream.toList() result. -->
|
||||
reconfigured after build() (NotificationJsonMapper). -->
|
||||
<Match>
|
||||
<Bug pattern="MS_EXPOSE_REP"/>
|
||||
<Or>
|
||||
<And><Class name="dev.caskeleton.adapter.outbound.notification.platform.template.NotificationJsonMapper"/><Method name="mapper"/></And>
|
||||
<And><Class name="dev.caskeleton.messaging.testkit.CertifiedEvidence"/><Method name="recorded"/></And>
|
||||
</Or>
|
||||
</Match>
|
||||
|
||||
|
||||
@@ -10,7 +10,8 @@
|
||||
# show them side by side, so two artifacts had quietly reached two versions:
|
||||
#
|
||||
# * spock-core 2.3-groovy-4.0 and 2.4-groovy-5.0
|
||||
# * protobuf-java 4.29.3 and 4.33.2
|
||||
# * protobuf-java 4.29.3 and 4.33.2 (the 4.33.2 user, the messaging library's protobuf codec,
|
||||
# moved to its own repository on 2026-11-08)
|
||||
#
|
||||
# Both are kept as separate aliases rather than unified. Unifying them here would change what
|
||||
# resolves, in a change whose whole purpose is that it does not; the aliases make the split
|
||||
@@ -35,14 +36,12 @@
|
||||
approvaltests = "31.0.0"
|
||||
assertj = "3.27.7"
|
||||
archunit = "1.3.0"
|
||||
avro = "1.12.0"
|
||||
# AWS SDK v2 BOM coordinate. Imported at MODULE scope by adapter:outbound:objectstorage
|
||||
# and app-bootstrap through `ext.awsSdkVersion`, which reads this key.
|
||||
awsSdk = "2.30.0"
|
||||
# Checkstyle *tool* version (the `checkstyle` extension), not a plugin: Checkstyle is a Gradle
|
||||
# built-in plugin with no coordinate of its own.
|
||||
checkstyle = "13.5.0"
|
||||
cloudevents = "4.0.1"
|
||||
errorprone = "2.49.0"
|
||||
# The Gradle plugin that runs the checker above. Two different artifacts, two different version
|
||||
# lines, deliberately adjacent so a bump of one is visibly not a bump of the other.
|
||||
@@ -72,12 +71,16 @@ junitPlatform = "1.11.3"
|
||||
logstashLogbackEncoder = "8.0"
|
||||
# Pinned (see `pinned-*` below). CVE-2026-106451, fixed in 1.11.4. Brought by kafka-clients (1.10.1).
|
||||
lz4Java = "1.11.4"
|
||||
# The messaging library (messaging-library repo, Maven group dev.cakit.messaging), one version for
|
||||
# every module of it: a release publishes all of them together. Raise it by the procedure in
|
||||
# docs/work/reference/related-repos.md 3절 (lockfiles rewritten, the leaves' lanes, the CHANGELOG).
|
||||
messagingLibrary = "1.0.0"
|
||||
okhttp = "4.12.0"
|
||||
# Pinned (see `pinned-*` below). CVE-2025-67030, fixed in 3.6.1 on the 3.x line. Brought by the
|
||||
# Checkstyle tool's doxia (3.3.0).
|
||||
plexusUtils = "3.6.1"
|
||||
protobuf = "4.33.2"
|
||||
# The third live protobuf version, and the reason this file now shows all three. adapter:inbound:grpc
|
||||
# The second live protobuf version (the messaging library's schema codec pins the third, 4.33.2, in its
|
||||
# own repository since 2026-11-08). adapter:inbound:grpc
|
||||
# imports protobuf-bom at this major to match the gRPC BOM above; it is read through
|
||||
# `ext.protobufVersion`. Keep it at the protobuf-java that grpc-protobuf of that BOM declares: the
|
||||
# protobuf-bom import is what resolves, so a lower number here would run gRPC on an older runtime
|
||||
@@ -114,9 +117,6 @@ uuidCreator = "6.1.1"
|
||||
approvaltests = { module = "com.approvaltests:approvaltests", version.ref = "approvaltests" }
|
||||
assertj-core = { module = "org.assertj:assertj-core", version.ref = "assertj" }
|
||||
archunit-junit5 = { module = "com.tngtech.archunit:archunit-junit5", version.ref = "archunit" }
|
||||
avro = { module = "org.apache.avro:avro", version.ref = "avro" }
|
||||
cloudevents-api = { module = "io.cloudevents:cloudevents-api", version.ref = "cloudevents" }
|
||||
cloudevents-core = { module = "io.cloudevents:cloudevents-core", version.ref = "cloudevents" }
|
||||
errorprone-core = { module = "com.google.errorprone:error_prone_core", version.ref = "errorprone" }
|
||||
findsecbugs-plugin = { module = "com.h3xstream.findsecbugs:findsecbugs-plugin", version.ref = "findsecbugs" }
|
||||
jackson-databind-nullable = { module = "org.openapitools:jackson-databind-nullable", version = "0.2.6" }
|
||||
@@ -129,9 +129,16 @@ json-schema-validator = { module = "com.networknt:json-schema-validator", versio
|
||||
junit-jupiter = { module = "org.junit.jupiter:junit-jupiter", version.ref = "junitJupiter" }
|
||||
junit-platform-launcher = { module = "org.junit.platform:junit-platform-launcher", version.ref = "junitPlatform" }
|
||||
logstash-logback-encoder = { module = "net.logstash.logback:logstash-logback-encoder", version.ref = "logstashLogbackEncoder" }
|
||||
# The messaging library's modules the leaves use. Each leaf's registry row lists the ones it may
|
||||
# reach in `allowed_libraries` (config/architecture/modules.json).
|
||||
messaging-core-api = { module = "dev.cakit.messaging:messaging-core-api", version.ref = "messagingLibrary" }
|
||||
messaging-reliability = { module = "dev.cakit.messaging:messaging-reliability", version.ref = "messagingLibrary" }
|
||||
messaging-reliability-api = { module = "dev.cakit.messaging:messaging-reliability-api", version.ref = "messagingLibrary" }
|
||||
messaging-reliability-jdbc-postgresql = { module = "dev.cakit.messaging:messaging-reliability-jdbc-postgresql", version.ref = "messagingLibrary" }
|
||||
messaging-spring-boot-starter = { module = "dev.cakit.messaging:messaging-spring-boot-starter", version.ref = "messagingLibrary" }
|
||||
messaging-spring-boot-starter-kafka = { module = "dev.cakit.messaging:messaging-spring-boot-starter-kafka", version.ref = "messagingLibrary" }
|
||||
mockwebserver = { module = "com.squareup.okhttp3:mockwebserver", version.ref = "okhttp" }
|
||||
okhttp-tls = { module = "com.squareup.okhttp3:okhttp-tls", version.ref = "okhttp" }
|
||||
protobuf-java = { module = "com.google.protobuf:protobuf-java", version.ref = "protobuf" }
|
||||
protobuf-java-legacy = { module = "com.google.protobuf:protobuf-java", version.ref = "protobufLegacy" }
|
||||
resilience4j-bulkhead = { module = "io.github.resilience4j:resilience4j-bulkhead", version.ref = "resilience4j" }
|
||||
resilience4j-circuitbreaker = { module = "io.github.resilience4j:resilience4j-circuitbreaker", version.ref = "resilience4j" }
|
||||
|
||||
@@ -1,176 +0,0 @@
|
||||
# messaging — 메시징 플랫폼 family의 지역 정본
|
||||
|
||||
이 문서는 messaging family의 **지역 정본(local authority)**이다. leaf 목록·gradle path·허용 의존성은
|
||||
`src/config/architecture/modules.json`이 SSOT이며 이 문서는 그것을 복제하지 않는다. 여기서 정하는
|
||||
것은 registry가 표현할 수 없는 것들이다: family별 framework 규칙, public surface 정책, Stable 승격에
|
||||
필요한 증거, runtime membership이 비어 있다는 사실의 의미.
|
||||
|
||||
루트 `AGENTS.md`와 충돌하면 루트가 이긴다.
|
||||
|
||||
## Family와 framework 규칙
|
||||
|
||||
leaf의 정확한 id는 registry에서 읽는다. family는 **디렉터리 이름의 접두사**가 아니라 아래 표의
|
||||
역할로 정해진다.
|
||||
|
||||
| Family | 역할 | 허용 framework |
|
||||
| --- | --- | --- |
|
||||
| `*-api` (`core-api` — `api`·`schema` 패키지, `policy`, `reliability-api`, `transport-spi`) | 값 타입, 포트, 정책 계약 | Java stdlib만. Spring/broker SDK/logging framework 금지 |
|
||||
| `schema-*` (json/avro/protobuf), `cloudevents` | 인코딩 구현 | 해당 codec 라이브러리만. Spring 금지 |
|
||||
| `runtime-core`, `security`, `observability`, `admin`(계약 `admin` + 실행 `admin.runtime`), `reliability` | framework-free 실행 로직 | Micrometer는 `observability`에서만. 나머지는 stdlib |
|
||||
| `kafka` | broker adapter | 해당 broker client. Spring은 client가 곧 Spring인 경우만 |
|
||||
| `reliability-jdbc-postgresql` | 관계형 신뢰성 adapter (outbox·inbox repository, admin journal) | Spring JDBC / Spring TX. **JPA 아님** — 이름이 곧 계약이다 |
|
||||
| `spring-boot-starter`, `spring-boot-starter-kafka` | 조립 경계 | Spring Boot autoconfigure. 여기서만 |
|
||||
| `testkit` | 테스트 지원 | Testcontainers, JUnit. production leaf가 의존하지 않는다 |
|
||||
|
||||
신뢰성 기능은 세 leaf다. `messaging-reliability-api`가 vendor 중립 port(`OutboxRepository`,
|
||||
`InboxRepository`)를, `messaging-reliability`가 그 port만 보는 relay·consumer 로직(stdlib)을,
|
||||
`messaging-reliability-jdbc-postgresql`이 port의 관계형 구현과 migration(`V1001..V1005`, `V1101`)을
|
||||
갖는다. 예전에는 `outbox-jdbc-postgresql` 하나가 relay 로직과 PG repository와 admin journal을 함께
|
||||
가졌고 inbox도 같은 모양이었다(2026-09-25 리뷰 후속 작업에서 나눴다). 구현 leaf가 `jdbc-postgresql`로 명명된 이유: 구현은 Spring
|
||||
JDBC이고 SQL은 `jsonb` · `FOR UPDATE SKIP LOCKED` · `ON CONFLICT` · `TIMESTAMPTZ`로 PostgreSQL
|
||||
전용이다. `jpa`라는 이름은 사용하지 않는 기술을 광고하고, vendor 중립 port가 어디 있는지도 숨겼다.
|
||||
|
||||
### 공용 다이제스트 헬퍼를 복사해 두는 이유
|
||||
|
||||
`messaging-admin`(`HmacApprovalVerifier`, `PlanDigest`)과 `messaging-claim-check`
|
||||
(`ClaimCheckIntegrityGuard`)는 SHA-256·HMAC-SHA256 계산을 자기 안에 둔다. 템플릿의
|
||||
`shared-contract` `digest/Sha256`·`HmacSha256`을 쓰지 않는 것은 의도다. 이 family는 이 애플리케이션의
|
||||
계층이 아니라 자기 API·SPI·composition을 가진 다른 제품이고(2026-08-14 messaging 모듈 리뷰 뒤 소유자가 정한 배치), `messaging:*` leaf는
|
||||
`domain-core`·`application-core`·`shared-contract` 어느 타입에도 의존하지 않는다. 헬퍼 하나 때문에
|
||||
registry edge를 주면 그 경계가 깨진다. 복사본을 고칠 때(키 길이 검사, constant-time 비교 등)는
|
||||
`shared-contract`의 정본과 같은 규칙인지 함께 본다.
|
||||
|
||||
### 인증·인가 거부의 발행 재시도 여부 (Publish retryability of authentication and authorization)
|
||||
|
||||
이 제품 안에는 같은 category에 대한 재시도 규칙이 둘 있다. 의도다.
|
||||
|
||||
- category 기본값: `FailureDescriptor.defaultRetryable(AUTHENTICATION | AUTHORIZATION) = false`. 소비 쪽
|
||||
재시도 엔진(`DefaultRetryDecisionEngine`)은 policy가 category를 따로 정하지 않으면 이 기본값과
|
||||
descriptor의 `retryable`을 둘 다 요구한다. 그래서 인가받지 못한 메시지의 재전달은 지금도 재시도하지 않는다.
|
||||
- publish 거부의 `retryable`: `KafkaPublishFailureClassifier`는 인증·인가 거부에 `retryable = true`를 붙인다.
|
||||
broker가 레코드를 저장하지 않았고, credential 교체나 application보다 늦게 배포된 ACL은 몇 분 동안 모든
|
||||
publish를 거부한 뒤 멈추기 때문이다. `retryable`을 믿는 publisher가 그 몇 분 동안의 레코드를 영구 보류하지
|
||||
않게 하려는 것이다.
|
||||
|
||||
다시 시도하면 될 거부를 relay가 즉시 DEAD로 보내던 결함의 수정(2026-11-01 성숙도 리뷰 뒤)이 이 제품에서 바꾼 것(모두
|
||||
publish 경로, 소비 경로 동작은 그대로):
|
||||
|
||||
- `KafkaPublishFailureClassifier`: 인증·인가 거부를 `retryable = true`로.
|
||||
- `DefaultMessagePublisher`: runtime이 없을 때의 거부(`PUBLISH_RUNTIME_UNAVAILABLE`)를 `retryable = true`로.
|
||||
- `KafkaMessagingTransport`: 닫힌 transport의 거부(`KAFKA_TRANSPORT_CLOSED`)를 `retryable = true`로.
|
||||
- `MessagingShutdownLifecycle.PHASE`: platform 밖 relay의 순서 테스트가 참조하도록 public.
|
||||
|
||||
버린 대안: vendored 제품은 그대로 두고 application bridge(ACL)가 category를 보고 "인증·인가면 재시도"로
|
||||
번역하는 것. 버린 이유: `retryable`은 이 제품이 "같은 레코드를 나중에 다시 보내면 받아질 수 있나"를 말하는
|
||||
자리다. bridge가 category로 그 판단을 다시 하면 같은 사실을 제품과 bridge가 따로 정하고, 이 제품의
|
||||
`PublishResult`를 읽는 다른 호출자는 bridge와 다른 답을 본다. 대신 이 제품 주석은 소비자 이름(application
|
||||
relay, `composition:outbox-relay`)을 부르지 않는다 — "flag를 믿는 publisher"로 쓴다(2026-11-03).
|
||||
|
||||
## Public surface 정책
|
||||
|
||||
- **vendor 타입을 public signature에 노출하면 그 의존성은 `api`로 선언한다.** 숨긴다고 타입이
|
||||
숨겨지지 않는다 — consumer가 이 모듈이 문서화한 API에 대해 컴파일하지 못하게 만들 뿐이다.
|
||||
(`kafka-clients`, `cloudevents-api`, `micrometer-core`, `avro`,
|
||||
`protobuf-java`가 이 규칙으로 `api`다.)
|
||||
- 반대로 **노출하지 않는 것은 `implementation`으로 낮춘다.** starter가 노출하지 않는 하위 모듈을
|
||||
`implementation`으로 내린 것이, JSON codec이 `ObjectMapper`를 private으로만 쓰고 Jackson을
|
||||
`implementation`으로 둔 것이 그 예다.
|
||||
- 이 규칙은 문서가 아니라 `MessagingPublicSurfaceContractTest`가 붙들고 있다. leaf의 production
|
||||
source에서 public/protected 시그니처에 등장하는 vendor 라이브러리를 뽑아 그 leaf의
|
||||
`build.gradle`이 `api`로 선언했는지 대조하고, starter의 `api` closure에 broker client 두 개가
|
||||
들어오지 않는 것도 함께 본다. Spring Framework/Boot는 대상이 아니다 — 조립 경계 안에서만
|
||||
등장하고 adopter가 이름 부를 일이 없다.
|
||||
- 새 public 타입은 그 모듈의 계약이다. 삭제·시그니처 변경은 breaking change로 취급한다.
|
||||
|
||||
## Application runtime에 포함되는 기준
|
||||
|
||||
기본 조립에는 Messaging family가 없다. 서비스가 `app-bootstrap/build.gradle`에
|
||||
`runtimeOnly project(':adapter:outbound:messaging-kafka')` 한 줄을 넣으면 그 모듈이 bridge와
|
||||
`messaging-spring-boot-starter`(Kafka transport 포함)의 transitive project graph를 runtime에 싣는다. 이
|
||||
사실의 SSOT는 Gradle `runtimeClasspath`이며 registry에 동일한 membership 목록을 복제하지 않는다.
|
||||
모듈이 있으면 켜지고(`app.messaging.enabled` 기본 `true`), `APP_MESSAGING_ENABLED=false`로만 끈다.
|
||||
|
||||
일부 codec(cloudevents 등)·claim-check·testkit처럼 starter graph에 들어오지 않는 leaf는 build-only다.
|
||||
RabbitMQ·Pulsar·NATS·Kafka Share·Spring Cloud Stream bridge leaf와 Debezium outbox 매핑은
|
||||
2026-09-25에 삭제했다(`docs/capability-status.md` 제거 표).
|
||||
새 leaf를 application에 채택할 때는 starter 또는 composition dependency와 architecture edge policy,
|
||||
qualification/support 상태를 함께 변경한다.
|
||||
|
||||
## application이 이 family에 도달하는 경로 (cutover 완료)
|
||||
|
||||
리뷰(`docs/reviews/2026-08-14-messaging-module-code-review.md` §6.1·§6.3)가 정한
|
||||
`application-owned port → platform anti-corruption bridge → platform` 경로는 이제 존재한다.
|
||||
|
||||
- application-owned port: `IntegrationEventPublishPort`
|
||||
- bridge: `adapter/outbound/messaging/platformbridge/PlatformIntegrationEventPublishAdapter`
|
||||
- platform boundary: `EncodedMessagePublisher`
|
||||
- central implementation: `DefaultMessagePublisher`
|
||||
|
||||
bridge는 exact canonical envelope bytes를 다시 serialize하지 않고, destination/access/admission/runtime
|
||||
lease/transport/outcome normalization/observation은 platform 중앙 publish path를 그대로 탄다. bridge
|
||||
package는 `messaging-core-api`만 보며 concrete runtime/transport/Kafka 타입을
|
||||
직접 보지 않는다.
|
||||
|
||||
**application bridge cutover는 2026-09-28에 끝났다(2026-09-25 소유자 결정).** application의 outbox append는 canonical
|
||||
`OutboxAppendPort` 하나이고, relay는 claim한 row의 validated event를 이 bridge로만 보낸다. legacy
|
||||
`OutboxEvent`·`LegacyOutboxAppendPort`와 `MessageBroker → KafkaSender` R0 경로(TLS/SASL을 적용하지
|
||||
않던 두 번째 producer)는 삭제했다. 남은 Kafka producer는 platform의 것 하나이고, broker security
|
||||
profile(`KafkaSecurityConfigurer`)을 적용한다.
|
||||
|
||||
canonical bridge의 producer identity는 `app.messaging.producer-id`로 명시한다. 값이 없으면 bridge bean을
|
||||
만들지 않으며 `spring.application.name`/host/pod 이름에서 identity를 발명하지 않는다. bridge가 없으면
|
||||
relay가 발행할 곳이 없으므로 messaging 모듈이 켜진 상태에서는 기동이 거부된다.
|
||||
|
||||
`IntegrationEventEncoderPort`는 템플릿이 제공한다: `adapter:outbound:support`의
|
||||
`JsonIntegrationEventEncoder`가 envelope v1(`shared-contract`의 `contracts/messaging/envelope/v1.schema.json`)
|
||||
안에 payload record를 결정적 JSON으로 싣는다. 계약 catalog는 애플리케이션이 bean으로 등록한
|
||||
`IntegrationEventContractContribution`뿐이고, 선언한 payload schema hash가 classpath의 schema 파일과
|
||||
다르면 기동이 실패한다. payload를 JSON Schema로 매번 검증하려는 서비스는 자기 encoder bean을 두면 된다.
|
||||
|
||||
## Stable 승격에 필요한 증거
|
||||
|
||||
adapter를 Experimental → Stable로 올릴 때 필요한 것 (`docs/messaging/support-matrix.md`가 현재
|
||||
상태를 기록한다):
|
||||
|
||||
1. 실제 broker container를 쓰는 fault 시나리오 lane이 존재하고, 그 lane이
|
||||
`BrokerCertificationEvidence`를 산출한다.
|
||||
2. `NetworkFaultScenario` 전 항목에 대해 evidence가 있거나, 없는 항목이 `knownGaps`로 명시된다.
|
||||
3. capability 선언이 코드에서 파생된다 — `MessagingCapabilities`에 손으로 `true`를 쓰는 것은
|
||||
증거가 아니다.
|
||||
4. publish 실패 분류가 typed signal에서만 나온다. exception class 이름 substring 판정은
|
||||
Experimental에서도 금지다.
|
||||
5. unknown failure의 기본값이 `AMBIGUOUS`다. `REJECTED`는 전송이 시작되지 않았다는 typed 증거가
|
||||
있을 때만.
|
||||
|
||||
Stable 문구는 evidence manifest가 존재할 때만 문서에 쓴다.
|
||||
|
||||
증거를 만드는 것은 인증 레인이고, manifest는 그 실행의 출력이다:
|
||||
|
||||
```bash
|
||||
./gradlew :messaging:messaging-kafka:verifyMessagingCertificationEvidence --console=plain
|
||||
```
|
||||
|
||||
레인(`messagingCertificationTest`)은 Toxiproxy를 broker 앞에 두고 장애를 주입하며,
|
||||
통과한 시나리오마다 `BrokerCertificationEvidence` 한 줄을
|
||||
`messaging-testkit/src/main/resources/messaging/broker-certification-evidence.jsonl`에 쓴다.
|
||||
게이트는 커밋된 manifest와 이번 실행의 출력을 대조한다 — **manifest를 손으로 고치면 실패하고,
|
||||
레인을 돌리면 manifest가 다시 쓰인다.** 이 레인만은 Docker 가드를 달지 않는다(없으면 실패한다).
|
||||
skip하는 인증 레인은 아무도 켜지 않은 브로커에 대해 성공을 보고하기 때문이며, 그래서 `test`에서는
|
||||
`messaging-certification` 태그로 제외된다.
|
||||
|
||||
## Focused test
|
||||
|
||||
leaf의 `gradle_path`를 registry에서 읽어 파생한다.
|
||||
|
||||
```bash
|
||||
cd src
|
||||
./gradlew <gradle-path>:test --console=plain
|
||||
```
|
||||
|
||||
Family 전체 검증:
|
||||
|
||||
```bash
|
||||
./gradlew verifyCleanArchitectureDependencies --console=plain
|
||||
./gradlew architectureCheck --console=plain
|
||||
./gradlew verifyDependencyLocks --console=plain
|
||||
```
|
||||
@@ -1 +0,0 @@
|
||||
@AGENTS.md
|
||||
@@ -1,14 +0,0 @@
|
||||
plugins {
|
||||
id 'ca.platform-module'
|
||||
}
|
||||
|
||||
// The admin plane: its contract (package `admin`) and the stdlib services that execute it
|
||||
// (package `admin.runtime`). They were two leaves, and every consumer of the runtime took the
|
||||
// contract too, so the split added a registry entry without separating anything (S7-#12).
|
||||
dependencies {
|
||||
api project(':messaging:messaging-core-api')
|
||||
|
||||
// ReplayService records a MessagingAuditEvent internally; no public signature names it, so
|
||||
// Micrometer does not reach the journal adapters that implement the contract.
|
||||
implementation project(':messaging:messaging-observability')
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
# This is a Gradle generated file for dependency locking.
|
||||
# Manual edits can break the build and are not advised.
|
||||
# This file is expected to be part of source control.
|
||||
com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor
|
||||
com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor
|
||||
com.github.spotbugs:spotbugs-annotations:4.10.2=spotbugs
|
||||
com.github.spotbugs:spotbugs:4.10.2=spotbugs
|
||||
com.github.stephenc.jcip:jcip-annotations:1.0-1=spotbugs
|
||||
com.google.auto.service:auto-service-annotations:1.0.1=annotationProcessor,testAnnotationProcessor
|
||||
com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,testAnnotationProcessor
|
||||
com.google.auto:auto-common:1.2.2=annotationProcessor,testAnnotationProcessor
|
||||
com.google.code.findbugs:jsr305:3.0.2=checkstyle,spotbugs
|
||||
com.google.code.gson:gson:2.13.2=spotbugs
|
||||
com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,testAnnotationProcessor
|
||||
com.google.errorprone:error_prone_annotations:2.41.0=spotbugs
|
||||
com.google.errorprone:error_prone_annotations:2.50.0=annotationProcessor,checkstyle,testAnnotationProcessor
|
||||
com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,testAnnotationProcessor
|
||||
com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,testAnnotationProcessor
|
||||
com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,testAnnotationProcessor
|
||||
com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,testAnnotationProcessor
|
||||
com.google.guava:guava:33.7.2-jre=annotationProcessor,checkstyle,testAnnotationProcessor
|
||||
com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,testAnnotationProcessor
|
||||
com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor
|
||||
com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProcessor
|
||||
com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins
|
||||
com.puppycrawl.tools:checkstyle:13.5.0=checkstyle
|
||||
commons-beanutils:commons-beanutils:1.11.0=checkstyle
|
||||
commons-collections:commons-collections:3.2.2=checkstyle
|
||||
commons-io:commons-io:2.21.0=spotbugs
|
||||
info.picocli:picocli:4.7.7=checkstyle
|
||||
io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,testAnnotationProcessor
|
||||
io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor
|
||||
io.micrometer:micrometer-commons:1.16.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||
io.micrometer:micrometer-core:1.16.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||
io.micrometer:micrometer-observation:1.16.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||
javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor
|
||||
jaxen:jaxen:2.0.6=spotbugs
|
||||
net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testRuntimeClasspath
|
||||
net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs
|
||||
org.antlr:antlr4-runtime:4.13.2=checkstyle
|
||||
org.apache.bcel:bcel:6.12.0=spotbugs
|
||||
org.apache.commons:commons-lang3:3.20.0=checkstyle,spotbugs
|
||||
org.apache.commons:commons-text:1.15.0=spotbugs
|
||||
org.apache.commons:commons-text:1.3=checkstyle
|
||||
org.apache.httpcomponents:httpclient:4.5.13=checkstyle
|
||||
org.apache.httpcomponents:httpcore:4.4.16=checkstyle
|
||||
org.apache.logging.log4j:log4j-api:2.25.5=spotbugs
|
||||
org.apache.logging.log4j:log4j-core:2.25.5=spotbugs
|
||||
org.apache.maven.doxia:doxia-core:1.12.0=checkstyle
|
||||
org.apache.maven.doxia:doxia-logging-api:1.12.0=checkstyle
|
||||
org.apache.maven.doxia:doxia-module-xdoc:1.12.0=checkstyle
|
||||
org.apache.maven.doxia:doxia-sink-api:1.12.0=checkstyle
|
||||
org.apache.xbean:xbean-reflect:3.7=checkstyle
|
||||
org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath
|
||||
org.assertj:assertj-core:3.27.7=testCompileClasspath,testRuntimeClasspath
|
||||
org.codehaus.plexus:plexus-classworlds:2.6.0=checkstyle
|
||||
org.codehaus.plexus:plexus-component-annotations:2.1.0=checkstyle
|
||||
org.codehaus.plexus:plexus-container-default:2.1.0=checkstyle
|
||||
org.codehaus.plexus:plexus-utils:3.6.1=checkstyle
|
||||
org.dom4j:dom4j:2.2.0=spotbugs
|
||||
org.hdrhistogram:HdrHistogram:2.2.2=runtimeClasspath,testRuntimeClasspath
|
||||
org.javassist:javassist:3.28.0-GA=checkstyle
|
||||
org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath
|
||||
org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testRuntimeClasspath
|
||||
org.junit.jupiter:junit-jupiter-engine:6.0.3=testRuntimeClasspath
|
||||
org.junit.jupiter:junit-jupiter-params:6.0.3=testCompileClasspath,testRuntimeClasspath
|
||||
org.junit.jupiter:junit-jupiter:6.0.3=testCompileClasspath,testRuntimeClasspath
|
||||
org.junit.platform:junit-platform-commons:6.0.3=testCompileClasspath,testRuntimeClasspath
|
||||
org.junit.platform:junit-platform-engine:6.0.3=testRuntimeClasspath
|
||||
org.junit.platform:junit-platform-launcher:6.0.3=testRuntimeClasspath
|
||||
org.junit:junit-bom:6.0.3=testCompileClasspath,testRuntimeClasspath
|
||||
org.junit:junit-bom:6.1.0=spotbugs
|
||||
org.latencyutils:LatencyUtils:2.0.3=runtimeClasspath,testRuntimeClasspath
|
||||
org.mockito:mockito-core:5.20.0=mockitoAgent
|
||||
org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testRuntimeClasspath
|
||||
org.ow2.asm:asm-analysis:9.10.1=spotbugs
|
||||
org.ow2.asm:asm-commons:9.10.1=spotbugs
|
||||
org.ow2.asm:asm-tree:9.10.1=spotbugs
|
||||
org.ow2.asm:asm-util:9.10.1=spotbugs
|
||||
org.ow2.asm:asm:9.10.1=spotbugs
|
||||
org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor
|
||||
org.reflections:reflections:0.10.2=checkstyle
|
||||
org.slf4j:slf4j-api:2.0.20=spotbugs,spotbugsSlf4j
|
||||
org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j
|
||||
org.slf4j:slf4j-simple:2.0.20=checkstyle
|
||||
org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs
|
||||
empty=
|
||||
-45
@@ -1,45 +0,0 @@
|
||||
package dev.caskeleton.messaging.admin;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* The approval that authorises a destructive messaging operation.
|
||||
*
|
||||
* <p>Approvals expire. An open-ended approval becomes a standing permission, which is the same
|
||||
* thing as no approval at all — the window is what keeps "we approved a redrive last quarter" from
|
||||
* authorising one today.
|
||||
*
|
||||
* @param ticket the change reference
|
||||
* @param approvedBy the approver's identity
|
||||
* @param approvedAt when the approval was granted
|
||||
* @param validUntil when the approval stops authorising anything
|
||||
*/
|
||||
public record AdminApproval(
|
||||
String ticket, String approvedBy, Instant approvedAt, Instant validUntil) {
|
||||
|
||||
public AdminApproval {
|
||||
Objects.requireNonNull(approvedAt, "approvedAt must not be null");
|
||||
Objects.requireNonNull(validUntil, "validUntil must not be null");
|
||||
if (ticket == null || ticket.isBlank()) {
|
||||
throw new IllegalArgumentException("ticket must not be blank");
|
||||
}
|
||||
if (approvedBy == null || approvedBy.isBlank()) {
|
||||
throw new IllegalArgumentException("approvedBy must not be blank");
|
||||
}
|
||||
if (validUntil.isBefore(approvedAt)) {
|
||||
throw new IllegalArgumentException("an approval cannot expire before it was granted");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reports whether the approval still authorises an operation.
|
||||
*
|
||||
* @param now the current instant
|
||||
* @return true while inside the window
|
||||
*/
|
||||
public boolean isValidAt(Instant now) {
|
||||
Objects.requireNonNull(now, "now must not be null");
|
||||
return !now.isBefore(approvedAt) && now.isBefore(validUntil);
|
||||
}
|
||||
}
|
||||
-93
@@ -1,93 +0,0 @@
|
||||
package dev.caskeleton.messaging.admin;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Where a destructive operation records that it started, how far it got, and how it ended.
|
||||
*
|
||||
* <p>The implementation this replaced was a {@code ConcurrentHashMap} registered by the starter as
|
||||
* the default. Two consequences followed, and both are worse than having no store at all because
|
||||
* the map made the platform look protected. A restart forgot every claim, so the same approval
|
||||
* could be executed again by the same process. And two replicas each had their own map, so both
|
||||
* could claim the same approval at the same moment and each believe it was the only one.
|
||||
*
|
||||
* <p>Implementations must therefore be shared and durable, must enforce uniqueness on {@code
|
||||
* (approvalTicket, planDigest)}, and must hand out leases with a monotonic fencing token so a
|
||||
* process that stalled past its lease cannot write over the replica that took over from it.
|
||||
*/
|
||||
public interface AdminOperationJournal {
|
||||
|
||||
/**
|
||||
* Claims an operation, or resumes the previous attempt at it.
|
||||
*
|
||||
* @param approvalTicket the approval authorising the operation
|
||||
* @param planDigest the exact plan
|
||||
* @param operationId this execution's identity
|
||||
* @param leaseOwner the runtime claiming it
|
||||
* @param leaseDuration how long the lease holds before another runtime may take over
|
||||
* @param now the current instant
|
||||
* @return the lease, carrying the point to resume from
|
||||
* @throws dev.caskeleton.messaging.api.error.MessageAuthorizationException when the operation
|
||||
* already completed, or another runtime holds a live lease on it
|
||||
*/
|
||||
AdminOperationLease begin(
|
||||
String approvalTicket,
|
||||
PlanDigest planDigest,
|
||||
String operationId,
|
||||
String leaseOwner,
|
||||
Duration leaseDuration,
|
||||
Instant now);
|
||||
|
||||
/**
|
||||
* Records durable progress and extends the lease.
|
||||
*
|
||||
* @param lease the lease held
|
||||
* @param itemsCompleted how many items are now durably done
|
||||
* @param leaseDuration how much longer to hold the lease
|
||||
* @param now the current instant
|
||||
* @throws dev.caskeleton.messaging.api.error.MessageAuthorizationException when the lease has
|
||||
* been taken over by a newer token
|
||||
*/
|
||||
void checkpoint(
|
||||
AdminOperationLease lease, int itemsCompleted, Duration leaseDuration, Instant now);
|
||||
|
||||
/**
|
||||
* Marks the operation finished. The approval is spent.
|
||||
*
|
||||
* @param lease the lease held
|
||||
* @param itemsCompleted the final count
|
||||
* @param now the current instant
|
||||
*/
|
||||
void complete(AdminOperationLease lease, int itemsCompleted, Instant now);
|
||||
|
||||
/**
|
||||
* Marks the operation failed at its current checkpoint, leaving it resumable.
|
||||
*
|
||||
* @param lease the lease held
|
||||
* @param itemsCompleted how many items are durably done
|
||||
* @param failureCode a sanitised, bounded reason
|
||||
* @param now the current instant
|
||||
*/
|
||||
void fail(AdminOperationLease lease, int itemsCompleted, String failureCode, Instant now);
|
||||
|
||||
/**
|
||||
* Reads the journal entry for an operation.
|
||||
*
|
||||
* @param approvalTicket the approval
|
||||
* @param planDigest the plan
|
||||
* @return the record, when the operation has been journalled
|
||||
*/
|
||||
Optional<AdminOperationRecord> find(String approvalTicket, PlanDigest planDigest);
|
||||
|
||||
/**
|
||||
* Whether this implementation survives a restart and is shared between replicas.
|
||||
*
|
||||
* <p>Declared rather than inferred so the starter can refuse to run a production profile on an
|
||||
* in-memory journal instead of discovering the gap during an incident.
|
||||
*
|
||||
* @return true when the journal is durable and shared
|
||||
*/
|
||||
boolean isDurable();
|
||||
}
|
||||
-55
@@ -1,55 +0,0 @@
|
||||
package dev.caskeleton.messaging.admin;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* The right to execute one journalled operation, and the point to resume it from.
|
||||
*
|
||||
* <p>{@code resumeFrom} is the whole reason a lease is handed out rather than a boolean. A retry
|
||||
* after a crash is not a new execution of the approval — it is the same operation continuing, and
|
||||
* treating it as new is what republishes the items the first attempt already moved.
|
||||
*
|
||||
* @param approvalTicket the approval being executed
|
||||
* @param planDigest the plan being executed
|
||||
* @param operationId this execution's identity
|
||||
* @param leaseOwner the runtime holding the lease
|
||||
* @param leaseToken the fencing token; a write from an older token must be refused
|
||||
* @param resumeFrom how many items the previous attempt durably completed
|
||||
*/
|
||||
public record AdminOperationLease(
|
||||
String approvalTicket,
|
||||
PlanDigest planDigest,
|
||||
String operationId,
|
||||
String leaseOwner,
|
||||
long leaseToken,
|
||||
int resumeFrom) {
|
||||
|
||||
/** Validates the lease. */
|
||||
public AdminOperationLease {
|
||||
Objects.requireNonNull(planDigest, "planDigest must not be null");
|
||||
if (approvalTicket == null || approvalTicket.isBlank()) {
|
||||
throw new IllegalArgumentException("approvalTicket must not be blank");
|
||||
}
|
||||
if (operationId == null || operationId.isBlank()) {
|
||||
throw new IllegalArgumentException("operationId must not be blank");
|
||||
}
|
||||
if (leaseOwner == null || leaseOwner.isBlank()) {
|
||||
throw new IllegalArgumentException("leaseOwner must not be blank");
|
||||
}
|
||||
if (leaseToken < 1) {
|
||||
throw new IllegalArgumentException("a lease token starts at one");
|
||||
}
|
||||
if (resumeFrom < 0) {
|
||||
throw new IllegalArgumentException("resumeFrom must not be negative");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reports whether this lease continues an earlier attempt.
|
||||
*
|
||||
* @return true when items were already completed
|
||||
*/
|
||||
public boolean isResumption() {
|
||||
return resumeFrom > 0;
|
||||
}
|
||||
}
|
||||
-63
@@ -1,63 +0,0 @@
|
||||
package dev.caskeleton.messaging.admin;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* One row of the destructive-operation journal.
|
||||
*
|
||||
* <p>Keyed by {@code (approvalTicket, planDigest)} rather than by the ticket alone, because the
|
||||
* ticket alone cannot distinguish "this approval already ran" from "this approval is being reused
|
||||
* for a different plan" — and those need opposite answers.
|
||||
*
|
||||
* @param approvalTicket the approval that authorised the operation
|
||||
* @param planDigest the exact plan that was authorised
|
||||
* @param operationId the caller-side identity of this execution
|
||||
* @param state where the operation stands
|
||||
* @param itemsCompleted how many items are durably done
|
||||
* @param leaseOwner which runtime currently holds the lease
|
||||
* @param leaseToken the fencing token, incremented on every takeover
|
||||
* @param leaseExpiresAt when another runtime may take the lease over
|
||||
* @param startedAt when the operation first began
|
||||
* @param finishedAt when it reached a terminal state
|
||||
* @param failureCode the sanitised reason it failed, when it did
|
||||
*/
|
||||
public record AdminOperationRecord(
|
||||
String approvalTicket,
|
||||
PlanDigest planDigest,
|
||||
String operationId,
|
||||
AdminOperationState state,
|
||||
int itemsCompleted,
|
||||
String leaseOwner,
|
||||
long leaseToken,
|
||||
Instant leaseExpiresAt,
|
||||
Instant startedAt,
|
||||
Optional<Instant> finishedAt,
|
||||
Optional<String> failureCode) {
|
||||
|
||||
/** Validates the record. */
|
||||
public AdminOperationRecord {
|
||||
Objects.requireNonNull(planDigest, "planDigest must not be null");
|
||||
Objects.requireNonNull(state, "state must not be null");
|
||||
Objects.requireNonNull(leaseExpiresAt, "leaseExpiresAt must not be null");
|
||||
Objects.requireNonNull(startedAt, "startedAt must not be null");
|
||||
Objects.requireNonNull(finishedAt, "finishedAt must not be null");
|
||||
Objects.requireNonNull(failureCode, "failureCode must not be null");
|
||||
if (approvalTicket == null || approvalTicket.isBlank()) {
|
||||
throw new IllegalArgumentException("approvalTicket must not be blank");
|
||||
}
|
||||
if (operationId == null || operationId.isBlank()) {
|
||||
throw new IllegalArgumentException("operationId must not be blank");
|
||||
}
|
||||
if (leaseOwner == null || leaseOwner.isBlank()) {
|
||||
throw new IllegalArgumentException("leaseOwner must not be blank");
|
||||
}
|
||||
if (itemsCompleted < 0) {
|
||||
throw new IllegalArgumentException("itemsCompleted must not be negative");
|
||||
}
|
||||
if (leaseToken < 1) {
|
||||
throw new IllegalArgumentException("a lease token starts at one");
|
||||
}
|
||||
}
|
||||
}
|
||||
-21
@@ -1,21 +0,0 @@
|
||||
package dev.caskeleton.messaging.admin;
|
||||
|
||||
/**
|
||||
* Where a journalled destructive operation stands.
|
||||
*
|
||||
* <p>The store this replaces recorded one fact — "this approval was claimed" — and recorded it
|
||||
* before any work happened. A run that died halfway had consumed its approval, left no record of
|
||||
* how far it got, and offered the operator two equally bad choices: request a fresh approval and
|
||||
* redo work that may already have been done, or leave the operation half-applied.
|
||||
*/
|
||||
public enum AdminOperationState {
|
||||
|
||||
/** Claimed and in progress. A lease is held; the checkpoint says how far it got. */
|
||||
STARTED,
|
||||
|
||||
/** Every item finished. The approval is spent and must not run again. */
|
||||
COMPLETED,
|
||||
|
||||
/** The run stopped before finishing. It may be resumed from its checkpoint under a new lease. */
|
||||
FAILED
|
||||
}
|
||||
-98
@@ -1,98 +0,0 @@
|
||||
package dev.caskeleton.messaging.admin;
|
||||
|
||||
import dev.caskeleton.messaging.api.destination.DestinationName;
|
||||
import java.time.Instant;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Everything an issuer signs when granting one destructive operation.
|
||||
*
|
||||
* <p>{@link AdminApproval} carried a ticket, an approver, and a window. Nothing in it said which
|
||||
* operation, on which destination, against which topology, or up to what impact — so the same
|
||||
* approval authorised every plan presented inside the window, and the audit trail recorded a ticket
|
||||
* that proved nothing about what was executed.
|
||||
*
|
||||
* <p>Every field here is part of the signed canonical form, which is what makes the grant
|
||||
* non-transferable: change the target, the topology version, the impact ceiling, or the plan, and
|
||||
* the signature no longer verifies.
|
||||
*
|
||||
* @param approval the ticket, approver, and validity window
|
||||
* @param requestedBy the operator who will execute it, kept separate from the approver
|
||||
* @param operation the destructive operation being authorised
|
||||
* @param source the destination read from
|
||||
* @param target the destination written to, when the operation has one
|
||||
* @param topologyVersion the topology the impact estimate was computed against
|
||||
* @param maxImpact the largest number of messages the approver agreed to
|
||||
* @param planDigest the fingerprint of the exact plan
|
||||
*/
|
||||
public record ApprovalGrant(
|
||||
AdminApproval approval,
|
||||
String requestedBy,
|
||||
DestructiveOperation operation,
|
||||
DestinationName source,
|
||||
Optional<DestinationName> target,
|
||||
String topologyVersion,
|
||||
long maxImpact,
|
||||
PlanDigest planDigest) {
|
||||
|
||||
/** Validates the grant and enforces subject separation. */
|
||||
public ApprovalGrant {
|
||||
Objects.requireNonNull(approval, "approval must not be null");
|
||||
Objects.requireNonNull(operation, "operation must not be null");
|
||||
Objects.requireNonNull(source, "source must not be null");
|
||||
Objects.requireNonNull(target, "target must not be null");
|
||||
Objects.requireNonNull(topologyVersion, "topologyVersion must not be null");
|
||||
Objects.requireNonNull(planDigest, "planDigest must not be null");
|
||||
if (requestedBy == null || requestedBy.isBlank()) {
|
||||
throw new IllegalArgumentException("requestedBy must not be blank");
|
||||
}
|
||||
if (approval.approvedBy().equals(requestedBy)) {
|
||||
// Four-eyes, expressed where it cannot be skipped: an operator approving their own
|
||||
// destructive operation is the control not existing.
|
||||
throw new IllegalArgumentException(
|
||||
"the approver and the operator must be different people; both are " + requestedBy);
|
||||
}
|
||||
if (maxImpact < 0) {
|
||||
throw new IllegalArgumentException("maxImpact must not be negative");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the grant deterministically for signing and verification.
|
||||
*
|
||||
* <p>Every field is length-prefixed rather than delimited. A delimiter can be smuggled into a
|
||||
* ticket or an identity to make two different grants render identically; a length prefix cannot.
|
||||
*
|
||||
* @return the canonical form
|
||||
*/
|
||||
public String canonicalForm() {
|
||||
StringBuilder canonical = new StringBuilder("v1");
|
||||
appendField(canonical, approval.ticket());
|
||||
appendField(canonical, approval.approvedBy());
|
||||
appendField(canonical, requestedBy);
|
||||
appendField(canonical, operation.name());
|
||||
appendField(canonical, source.value());
|
||||
appendField(canonical, target.map(DestinationName::value).orElse(""));
|
||||
appendField(canonical, topologyVersion);
|
||||
appendField(canonical, Long.toString(maxImpact));
|
||||
appendField(canonical, planDigest.value());
|
||||
appendField(canonical, approval.approvedAt().toString());
|
||||
appendField(canonical, approval.validUntil().toString());
|
||||
return canonical.toString();
|
||||
}
|
||||
|
||||
private static void appendField(StringBuilder canonical, String value) {
|
||||
canonical.append(value.length()).append(':').append(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reports whether the grant still authorises anything.
|
||||
*
|
||||
* @param now the current instant
|
||||
* @return true while inside the approval window
|
||||
*/
|
||||
public boolean isValidAt(Instant now) {
|
||||
return approval.isValidAt(now);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user