feat!: 남은 리뷰 발견을 고치고 개발 매뉴얼과 기능 생성 명령을 더한다

문제: High·P1을 고친 뒤에도 P2·P3 약 90건이 남았다. 연결·구독·메시지
크기 상한이 없는 전송(WebSocket·gRPC·GraphQL deadline), 낙관적 충돌의
500, upsert 경쟁, Mongo 무제한 timeout, 샘플 목록 N+1, 갈라진 복사본
(TenantId 3벌, 이벤트 ID 문법 5곳, SQLState 표 2벌), 문서를 읽는 PR
테스트와 캐시를 막는 lane 설정 등이다. 새 기능을 어디에 어떤 순서로
만드는지 알려 주는 문서와 도구가 없었다. MinIO 공식 이미지가 사라져
객체 저장소 lane이 돌지 않았다.

방법: 영역별 묶음으로 실패 테스트를 먼저 쓰고 고쳤다. 고치는 중에 찾은
결함도 함께 고쳤다(durable operation id가 UUIDv4라 이벤트가 전부 DEAD,
S3 어댑터 생성·작은 chunk 읽기 실패, Redis 조건부 기록의 EVALSHA 권한).
MinIO는 pgsty/minio를 digest로 고정했다(Chainguard는 태그·실행 사용자·
mc 이미지 문제로 버림). docs/manual/에 작업 순서와 판단 지점을 쓰고,
scripts/new-feature.sh가 5개 leaf에 뼈대를 만든다. 생성→빌드→통과
왕복을 verifyFeatureScaffold가 mainCheck에서 본다. 묶음별 결과와
결정은 리뷰 README 14절에 있다.

위험·한계: 파생 서비스 동작이 바뀐다. JDBC batch 50 기본, 운영 jar에서
H2 제거, 트랜잭션 30초 제한, 격리 수준을 Hikari에서 고정, gRPC·
WebSocket·GraphQL 새 한도, correlation ID 규칙 밖이면 서버가 교체,
샘플 키 오류 코드 IDEMPOTENCY_KEY_INVALID. 새 leaf 두 개
(composition:durable-operation, adapter:inbound:messaging)와 새
마이그레이션(postgresql V20·V21, notification V11·V12, sample V8_1,
grpc-ledger V002)이 생긴다. V21 유일 인덱스는 기존 중복이 있으면
실패한다(runbook에 확인 쿼리).

검증: ci, mainCheck(생성 명령 왕복 포함), integrationCheck(MinIO 포함
전 컨테이너 lane), -p optional-platforms ci integrationCheck 통과.

Refs: docs/reviews/2026-11-01-maturity-review/README.md 14절
BREAKING CHANGE: JDBC batch 기본 켜짐, H2 운영 의존 제거, 트랜잭션
기본 제한 30초, gRPC·WebSocket·GraphQL 서버 한도 기본값 추가,
샘플 Idempotency-Key 오류 코드 변경.
This commit is contained in:
DongHyeonka
2026-11-03 19:52:06 +09:00
parent 34565130e0
commit 1400dc1506
768 changed files with 26982 additions and 3348 deletions
@@ -0,0 +1,26 @@
# composition:durable-operation — durable operation 조립
- Module ID: `composition-durable-operation`
- Gradle path: `:composition:durable-operation`
- Package: `dev.caskeleton.composition.operation`
- 테스트: `./gradlew :composition:durable-operation:test --console=plain`
## 제공하는 것
`/operations` 엔드포인트와 그 뒤의 유스케이스 셋(제출·조회·취소)을 포트로부터 조립한다.
```
composition:durable-operation
└─ DurableOperationAutoConfiguration servlet 웹 앱 + DurableOperationStorePort·OutboxAppendPort·
│ TransactionPort 가 모두 있을 때만
├─ Submit/Get/CancelDurableOperationUseCase bean 이라 @RequiresPermission 이 프록시로 검사된다
├─ DurableOperationSubmittedContract 제출 이벤트 계약(encoder 가 읽는다)
└─ DurableOperationController web leaf 의 HTTP 경계
config/module-defaults/durable-operation.yml operation-submit 역할 → operation:submit, operation:cancel
```
- 켜지는 조건: 세 포트를 주는 모듈(지금은 persistence-jpa, outbox는 `app.outbox.enabled`)이 있어야 한다.
없으면 아무 bean도 만들지 않는다. 그래서 기본 조합(app-bootstrap)에 한 줄로 들어 있어도 비용이 없다.
- app-bootstrap 안이 아니라 여기 있는 이유(07-08): 조립 루트가 capability 이름(조립 클래스, 권한 매핑)을
알면 기능을 지워도 흔적이 남는다. outbox relay·멱등성 executor를 `composition:*`로 옮긴 소유자 결정 3과 같다.
- persistence-jpa 안이 아닌 이유: driven adapter는 use case를 만들지 않는다.
@@ -0,0 +1,22 @@
plugins {
id 'ca.spring-library'
id 'ca.spring-config'
}
// Durable operations: the three use cases and their HTTP endpoints, assembled from ports when the
// selected modules provide an operation store, an outbox and a transaction port (persistence-jpa
// does). Moved out of app-bootstrap (07-08) so the composition root names no capability.
dependencies {
implementation project(':application-core')
implementation project(':adapter:inbound:web')
// The module-defaults loader that reads config/module-defaults/durable-operation.yml.
implementation project(':adapter:outbound:support')
// The UUIDv7 operation id generator (UuidV7DurableOperationIdFactory).
implementation project(':adapter:outbound:identifier')
implementation 'org.springframework.boot:spring-boot-autoconfigure'
implementation 'org.springframework:spring-context'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testRuntimeOnly 'org.yaml:snakeyaml'
}
@@ -0,0 +1,182 @@
# 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.
biz.aQute.bnd:biz.aQute.bnd.annotation:7.1.0=testCompileClasspath
ch.qos.logback:logback-classic:1.5.38=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
ch.qos.logback:logback-core:1.5.38=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.fasterxml.jackson.core:jackson-annotations:2.21=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.fasterxml.jackson.core:jackson-core:2.21.5=runtimeClasspath,testRuntimeClasspath
com.fasterxml.jackson.core:jackson-databind:2.21.5=runtimeClasspath,testRuntimeClasspath
com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.21.5=runtimeClasspath,testRuntimeClasspath
com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.21.5=runtimeClasspath,testRuntimeClasspath
com.fasterxml.jackson:jackson-bom:2.21.5=runtimeClasspath,testRuntimeClasspath
com.fasterxml:classmate:1.7.3=runtimeClasspath,testRuntimeClasspath
com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor
com.github.f4b6a3:uuid-creator:6.1.1=runtimeClasspath,testRuntimeClasspath
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.38.0=testCompileClasspath
com.google.errorprone:error_prone_annotations:2.41.0=spotbugs
com.google.errorprone:error_prone_annotations:2.47.0=checkstyle
com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,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.5.0-jre=annotationProcessor,testAnnotationProcessor
com.google.guava:guava:33.6.0-jre=checkstyle
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.jayway.jsonpath:json-path:2.10.0=testCompileClasspath,testRuntimeClasspath
com.nimbusds:nimbus-jose-jwt:10.4=runtimeClasspath,testRuntimeClasspath
com.puppycrawl.tools:checkstyle:13.5.0=checkstyle
com.vaadin.external.google:android-json:0.0.20131108.vaadin1=testCompileClasspath,testRuntimeClasspath
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
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.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.micrometer:micrometer-observation:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.swagger.core.v3:swagger-annotations-jakarta:2.2.38=runtimeClasspath,testRuntimeClasspath
io.swagger.core.v3:swagger-core-jakarta:2.2.38=runtimeClasspath,testRuntimeClasspath
io.swagger.core.v3:swagger-models-jakarta:2.2.38=runtimeClasspath,testRuntimeClasspath
jakarta.activation:jakarta.activation-api:2.1.4=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
jakarta.annotation:jakarta.annotation-api:3.0.0=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
jakarta.validation:jakarta.validation-api:3.1.1=runtimeClasspath,testRuntimeClasspath
jakarta.xml.bind:jakarta.xml.bind-api:4.0.5=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor
jaxen:jaxen:2.0.6=spotbugs
net.bytebuddy:byte-buddy-agent:1.17.8=testCompileClasspath,testRuntimeClasspath
net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testRuntimeClasspath
net.minidev:accessors-smart:2.6.0=testCompileClasspath,testRuntimeClasspath
net.minidev:json-smart:2.6.0=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,runtimeClasspath,spotbugs,testRuntimeClasspath
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=runtimeClasspath,spotbugs,testCompileClasspath,testRuntimeClasspath
org.apache.logging.log4j:log4j-core:2.25.5=spotbugs
org.apache.logging.log4j:log4j-to-slf4j:2.25.5=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
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.tomcat.embed:tomcat-embed-core:11.0.24=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.apache.tomcat.embed:tomcat-embed-el:11.0.24=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.apache.tomcat.embed:tomcat-embed-websocket:11.0.24=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
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.awaitility:awaitility:4.3.0=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.3.0=checkstyle
org.dom4j:dom4j:2.2.0=spotbugs
org.hamcrest:hamcrest:3.0=testCompileClasspath,testRuntimeClasspath
org.hibernate.validator:hibernate-validator:9.0.1.Final=runtimeClasspath,testRuntimeClasspath
org.javassist:javassist:3.28.0-GA=checkstyle
org.jboss.logging:jboss-logging:3.6.3.Final=runtimeClasspath,testRuntimeClasspath
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.mockito:mockito-core:5.20.0=mockitoAgent,testCompileClasspath,testRuntimeClasspath
org.mockito:mockito-junit-jupiter:5.20.0=testCompileClasspath,testRuntimeClasspath
org.objenesis:objenesis:3.3=testRuntimeClasspath
org.openapitools:jackson-databind-nullable:0.2.6=runtimeClasspath,testRuntimeClasspath
org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testRuntimeClasspath
org.osgi:org.osgi.annotation.bundle:2.0.0=testCompileClasspath
org.osgi:org.osgi.annotation.versioning:1.1.2=testCompileClasspath
org.osgi:org.osgi.resource:1.0.0=testCompileClasspath
org.osgi:org.osgi.service.serviceloader:1.0.0=testCompileClasspath
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.ow2.asm:asm:9.7.1=testCompileClasspath,testRuntimeClasspath
org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor
org.reflections:reflections:0.10.2=checkstyle
org.skyscreamer:jsonassert:1.5.3=testCompileClasspath,testRuntimeClasspath
org.slf4j:jul-to-slf4j:2.0.18=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.slf4j:slf4j-api:2.0.18=runtimeClasspath,spotbugs,spotbugsSlf4j,testCompileClasspath,testRuntimeClasspath
org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j
org.slf4j:slf4j-simple:2.0.18=checkstyle
org.springdoc:springdoc-openapi-starter-common:3.0.0=runtimeClasspath,testRuntimeClasspath
org.springdoc:springdoc-openapi-starter-webmvc-api:3.0.0=runtimeClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-autoconfigure:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-configuration-processor:4.0.8=annotationProcessor
org.springframework.boot:spring-boot-http-converter:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-jackson:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-resttestclient:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-security-oauth2-resource-server:4.0.8=runtimeClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-security:4.0.8=runtimeClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-servlet:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-jackson-test:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-jackson:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-logging:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-oauth2-resource-server:4.0.8=runtimeClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-security:4.0.8=runtimeClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-test:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-tomcat-runtime:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-tomcat:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-validation:4.0.8=runtimeClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-web:4.0.8=runtimeClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-webmvc-test:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-webmvc:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-test-autoconfigure:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-test:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-tomcat:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-validation:4.0.8=runtimeClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-web-server:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-webmvc-test:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-webmvc:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.security:spring-security-config:7.0.7=runtimeClasspath,testRuntimeClasspath
org.springframework.security:spring-security-core:7.0.7=runtimeClasspath,testRuntimeClasspath
org.springframework.security:spring-security-crypto:7.0.7=runtimeClasspath,testRuntimeClasspath
org.springframework.security:spring-security-oauth2-core:7.0.7=runtimeClasspath,testRuntimeClasspath
org.springframework.security:spring-security-oauth2-jose:7.0.7=runtimeClasspath,testRuntimeClasspath
org.springframework.security:spring-security-oauth2-resource-server:7.0.7=runtimeClasspath,testRuntimeClasspath
org.springframework.security:spring-security-web:7.0.7=runtimeClasspath,testRuntimeClasspath
org.springframework.session:spring-session-core:4.0.5=runtimeClasspath,testRuntimeClasspath
org.springframework:spring-aop:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-beans:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-context:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-core:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-expression:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-test:7.0.9=testCompileClasspath,testRuntimeClasspath
org.springframework:spring-web:7.0.9=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-webmvc:7.0.9=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs
org.xmlunit:xmlunit-core:2.10.4=testCompileClasspath,testRuntimeClasspath
org.yaml:snakeyaml:2.5=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
tools.jackson.core:jackson-core:3.1.5=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
tools.jackson.core:jackson-databind:3.1.5=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
tools.jackson:jackson-bom:3.1.5=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
empty=
@@ -0,0 +1,91 @@
package dev.caskeleton.composition.operation;
import dev.caskeleton.adapter.inbound.web.operation.DurableOperationController;
import dev.caskeleton.adapter.outbound.identifier.UuidV7DurableOperationIdFactory;
import dev.caskeleton.application.messaging.event.IntegrationEventEncoderPort;
import dev.caskeleton.application.operation.CancelDurableOperationUseCase;
import dev.caskeleton.application.operation.DurableOperationIdFactory;
import dev.caskeleton.application.operation.DurableOperationStorePort;
import dev.caskeleton.application.operation.DurableOperationSubmittedContract;
import dev.caskeleton.application.operation.GetDurableOperationUseCase;
import dev.caskeleton.application.operation.SubmitDurableOperationUseCase;
import dev.caskeleton.application.outbox.OutboxAppendPort;
import dev.caskeleton.application.transaction.TransactionPort;
import java.time.Clock;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
/**
* Durable operations: the three use cases and their HTTP endpoints.
*
* <p>Application composition, like the outbox relay: it builds use cases from ports, which a driven
* adapter must not do. Its own module since 07-08 — it used to sit in the composition root, which
* then knew a capability by name and held its permission mapping; the sample could not reuse it
* either. The {@code operation-submit} role mapping ships beside it in {@code
* config/module-defaults/durable-operation.yml}. It names no module type, only ports, and turns
* itself on from what the selected modules provide — an operation store and an outbox to announce
* submissions through, both of which the JPA module contributes (the outbox with {@code
* app.outbox.enabled}). Removing that module's build line removes the endpoints with it.
*
* <p>The use cases are beans rather than objects built inside the controller so that the method
* security advisor proxies them: {@code @RequiresPermission} on submit and cancel is enforced by
* that proxy, and a use case constructed by hand would carry the annotation and skip the check.
*
* <p>The submission event's contract is registered here as a bean, which is how the application's
* {@link IntegrationEventEncoderPort} learns it: the encoder is built over every contract
* contribution the context holds.
*/
@AutoConfiguration(
afterName =
"dev.caskeleton.adapter.outbound.persistence.autoconfigure.PersistenceJpaAutoConfiguration")
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@ConditionalOnBean({DurableOperationStorePort.class, OutboxAppendPort.class, TransactionPort.class})
@Import(DurableOperationController.class)
public class DurableOperationAutoConfiguration {
/** The {@code durable-operation.submitted} contract, so the encoder can validate the event. */
@Bean
public DurableOperationSubmittedContract durableOperationSubmittedContract() {
return new DurableOperationSubmittedContract();
}
/**
* Mints operation ids as UUIDv7. The id is also the submission event's id, and the messaging
* platform accepts only a UUIDv7 message id; the controller's former {@code UUID.randomUUID()}
* (v4) made every submission event a DEAD outbox row.
*/
@Bean
@ConditionalOnMissingBean
public DurableOperationIdFactory durableOperationIdFactory() {
return new UuidV7DurableOperationIdFactory();
}
/** Accepts work: the operation row and its outbox event in one transaction. */
@Bean
public SubmitDurableOperationUseCase submitDurableOperationUseCase(
DurableOperationStorePort operations,
OutboxAppendPort outbox,
IntegrationEventEncoderPort encoder,
TransactionPort transactions,
Clock clock) {
return new SubmitDurableOperationUseCase(operations, outbox, encoder, transactions, clock);
}
/** Reads one operation for the caller that submitted it. */
@Bean
public GetDurableOperationUseCase getDurableOperationUseCase(
DurableOperationStorePort operations, TransactionPort transactions, Clock clock) {
return new GetDurableOperationUseCase(operations, transactions, clock);
}
/** Cancels one operation for the caller that submitted it. */
@Bean
public CancelDurableOperationUseCase cancelDurableOperationUseCase(
DurableOperationStorePort operations, TransactionPort transactions, Clock clock) {
return new CancelDurableOperationUseCase(operations, transactions, clock);
}
}
@@ -0,0 +1 @@
dev.caskeleton.composition.operation.DurableOperationAutoConfiguration
@@ -0,0 +1,10 @@
# Durable operations (/operations). composition:durable-operation 모듈이 싣고 support 의
# ModuleDefaultsEnvironmentPostProcessor 가 읽는다. 모듈 한 줄을 빼면 이 설정도 함께 사라진다(07-08).
# 우선순위가 가장 낮다: application.yml, application-{profile}.yml, 환경 변수가 이긴다.
app:
authz:
role-permissions:
# One role for both: a caller that may start an operation may cancel its own, and reading one
# needs no permission beyond being the one who submitted it. Map entries from every source
# merge, so a deployment's own role-permissions add roles beside this one.
operation-submit: operation:submit,operation:cancel
@@ -0,0 +1,58 @@
package dev.caskeleton.composition.operation;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.context.annotation.ImportCandidates;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.boot.test.context.runner.WebApplicationContextRunner;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.ClassPathResource;
class DurableOperationModuleTest {
@Test
@DisplayName("모듈이 classpath에 있으면 Boot가 durable operation 조립을 자동 설정으로 찾는다")
void bootDiscoversTheCompositionFromThisModule() {
// when
List<String> candidates =
ImportCandidates.load(AutoConfiguration.class, getClass().getClassLoader()).getCandidates();
// then
assertThat(candidates).contains(DurableOperationAutoConfiguration.class.getName());
}
@Test
@DisplayName("operation store·outbox·트랜잭션 포트가 없으면 유스케이스도 엔드포인트도 만들지 않는다")
void withoutItsPortsTheModuleBuildsNothing() {
// when
new WebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(DurableOperationAutoConfiguration.class))
.run(
context -> {
// then
assertThat(context).hasNotFailed();
assertThat(context).doesNotHaveBean(DurableOperationAutoConfiguration.class);
});
}
@Test
@DisplayName("operation-submit 역할의 권한 매핑은 이 모듈의 기본 설정에 있다")
void theRolePermissionMappingShipsWithTheModule() throws Exception {
// given
ClassPathResource defaults =
new ClassPathResource("config/module-defaults/durable-operation.yml");
// when
List<PropertySource<?>> loaded = new YamlPropertySourceLoader().load("defaults", defaults);
// then
assertThat(loaded).hasSize(1);
assertThat(loaded.getFirst().getProperty("app.authz.role-permissions.operation-submit"))
.hasToString("operation:submit,operation:cancel");
}
}
@@ -5,9 +5,11 @@ plugins {
// The Fileserver capability's cross-adapter assembly.
//
// It exists because one capability spans four leaves that must not see each other: the HTTP surface
// in `adapter:inbound:web`, the storage and platform policy in `adapter:outbound:fileserver`, the
// quota/recovery tables in `adapter:outbound:persistence-jpa`, and identifier generation. An
// It exists because one capability spans leaves that must not see each other: the HTTP surface in
// `adapter:inbound:web-fileserver`/`web`, the storage and platform policy in
// `adapter:outbound:fileserver`, and the metadata tables in `persistence-fileserver` on the
// `persistence-jpa` platform. (It used to list identifier generation too; nothing here uses
// `adapter:outbound:identifier`, and the registry edge was removed — review 05-21.) An
// outbound adapter reaching an inbound one is the direction the architecture exists to forbid, so
// something has to hold the assembly — and until now that something was the composition root, which
// is why every application shipped Fileserver whether or not it wanted it.
@@ -35,7 +35,6 @@ com.google.guava:guava:33.6.0-jre=checkstyle
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.h2database:h2:2.4.240=runtimeClasspath,testRuntimeClasspath
com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins
com.jayway.jsonpath:json-path:2.10.0=testCompileClasspath,testRuntimeClasspath
com.nimbusds:nimbus-jose-jwt:10.4=runtimeClasspath,testRuntimeClasspath
@@ -12,6 +12,19 @@ spring:
max-file-size: ${APP_FILESERVER_PLATFORM_UPLOAD_MAX_FILE_SIZE:100MB}
max-request-size: ${APP_FILESERVER_PLATFORM_UPLOAD_MAX_REQUEST_SIZE:110MB}
app:
# Fileserver permissions (/v1/files, /v1/uploads, /internal/fileserver). Keyed by the fileserver's
# own default tier roles (app.fileserver-platform.security.*-roles), so one role grants both halves
# of a fileserver write: the permission here, checked on the use case, and the tier
# FileAccessPolicyPort checks inside it along with ownership. The brackets keep the underscores,
# which unbracketed map keys lose in binding. A deployment that renames those roles maps its own
# names too. The tiers do not inherit, and neither do these: a writer that also reads holds both
# roles. Here rather than in app-bootstrap's security.yml (07-08): the mapping goes when this
# module's line is removed; entries from every source merge.
authz:
role-permissions:
"[ROLE_FILE_READ]": file:read
"[ROLE_FILE_WRITE]": file:upload,file:delete,file:copy,file:move
"[ROLE_FILE_ADMIN]": file:admin
# HTTP Fileserver platform: upload/download/lifecycle routes over HTTP.
#
# While enabled=false none of the detail below is bound: FileserverPlatformAutoConfiguration
@@ -33,7 +33,6 @@ com.google.guava:guava:33.6.0-jre=checkstyle
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.h2database:h2:2.4.240=testRuntimeClasspath
com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins
com.jayway.jsonpath:json-path:2.10.0=testCompileClasspath,testRuntimeClasspath
com.puppycrawl.tools:checkstyle:13.5.0=checkstyle
@@ -37,7 +37,6 @@ com.google.guava:guava:33.6.0-jre=checkstyle
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.h2database:h2:2.4.240=runtimeClasspath,testRuntimeClasspath
com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins
com.jayway.jsonpath:json-path:2.10.0=testCompileClasspath,testRuntimeClasspath
com.networknt:json-schema-validator:3.0.2=runtimeClasspath,testRuntimeClasspath
@@ -21,6 +21,16 @@ info:
enabled: ${app.notification.platform.enabled:true}
app:
# The notification platform's own two permissions, granted to two roles rather than one.
# Publishing a template changes what every future submission renders, so a service that may send
# notifications is not thereby a service that may rewrite them; a deployment that wants both
# grants both roles. Here rather than in app-bootstrap's security.yml (07-08): the mapping goes
# when this module's line is removed. Map entries from every source merge, so a deployment's own
# app.authz.role-permissions adds roles beside these and can override either key.
authz:
role-permissions:
notification-submit: notification:submit
notification-template-publish: notification-template:publish
notification:
platform:
# The capability switch. False binds nothing at all.
+40 -20
View File
@@ -16,8 +16,11 @@ composition:outbox-relay
├─ OutboxSettings app.outbox.* strict 바인딩(오타는 기동 실패)
├─ OutboxRelayScheduler relay-enabled=true + OutboxMessagePublishPort 가 있을 때만,
│ PublishPendingOutboxEventsUseCase 를 fixed-delay 로 구동,
│ 종료 때 platform보다 먼저 멈춤(SmartLifecycle)
├─ OutboxMetrics outbox.pending.size / outbox.publisher.lag / published.total
│ 발행이 이어지는 동안 한 tick 안에서 바로 다시 claim(최대 50회차),
│ 종료 때 platform보다 먼저 멈추고 남은 claim을 놓음(SmartLifecycle)
├─ OutboxMetrics outbox.pending.size / outbox.publisher.lag(relay와 무관하게
│ poll 주기마다 갱신) / published.total(relay 회차 결과)
├─ OutboxRelayOffWarning 발행 포트가 있는데 relay가 꺼져 있으면 기동 시 WARN 한 줄
└─ OutboxLeaderElectionToken SKIP LOCKED 가 리더 선출이라는 표시(로직 없음)
```
@@ -68,11 +71,9 @@ poll 주기·batch 크기·in-flight timeout·보존 기간은 env 키 없이 `a
- **이 모듈은 failure reporter를 구현하지 않고 주입만 한다.** messaging bridge의 `MessagingConfig`가
정확히 하나의 `OutboxRelayFailureReportPort` 구현을 만들고, `OutboxRelayAutoConfiguration`은 이를
relay 생성자에 전달한다.
- **릴레이 use case 를 독립 컨텍스트 빈으로 등록하지 않는다.** 만약 빈으로 올리면 `adapter-web`의
`MethodSecurityConfig` 메서드 보안 pointcut(`@RequiresPermission`)이 이 타입을 CGLIB 프록시로
감싼다. 그런데 use case 가 `final` 클래스라 프록시 생성 자체가 실패하고, 설령 된다 해도 스케줄러
스레드에는 `Authentication`이 없어 매 릴레이 틱이 fail-closed 로 거부된다. 그래서 빈으로 올리지
않고, `outbox:relay` 권한 확인은 스케줄러 컨텍스트에서 관례로 둔다.
- **릴레이 use case 를 독립 컨텍스트 빈으로 등록하지 않는다.** relay는 스케줄러만 부르는
`@SystemInvoked` 유스케이스라 권한 선언이 없다. 빈으로 올리면 전송 계층이 권한 검사 없이 닿을
수 있다. 스케줄러 스레드에는 `Authentication`이 없으므로 권한 게이트를 달아도 매 틱 거부될 뿐이다.
- **`outboxRelayScheduler` 빈은 `app.outbox.relay-enabled=true`일 때만 만든다(기본
false).** 키가 없으면 꺼진 것으로 본다. 모듈 기본값(`persistence-jpa.yml`의
`${APP_OUTBOX_RELAY_ENABLED:false}`), `@ConditionalOnProperty`, `OutboxSettings`의 null 기본값이
@@ -119,7 +120,7 @@ poll 주기·batch 크기·in-flight timeout·보존 기간은 env 키 없이 `a
- **합성 루트가 직접 등록하고 컴포넌트 스캔하지 않는다.** 이 스케줄러가 구동하는 릴레이 use case 가
(위 OutboxRelayAutoConfiguration 사유로) 일부러 빈이 아니기 때문에, 그 use case 를 조립하는 `OutboxRelayAutoConfiguration`가
스케줄러 등록까지 같이 소유한다.
- **릴레이 사이클에서 발생하는 예상치 못한 예외를 잡아 ERROR 로 로깅만 하고 삼킨다.** 스케줄러
- **릴레이 사이클에서 발생하는 예상치 못한 예외를 잡아 ERROR 로 로깅만 하고 삼킨다(그 tick의 남은 회차도 건너뛴다).** 스케줄러
스레드가 죽으면 릴레이가 조용히 멈추므로, 다음 틱을 위해 스레드를 살려둔다. 단, 개별 발행 실패
(FAILED/DEAD 전이)는 relay가 persisted transition 성공 뒤 typed reporter로 canonical ERROR를
요청하고 결과에 반영하므로 이 catch 블록까지 오지 않는다 — 여기서 삼키는 것은 어디까지나
@@ -127,20 +128,39 @@ poll 주기·batch 크기·in-flight timeout·보존 기간은 env 키 없이 `a
- **스케줄링은 `OutboxRelayAutoConfiguration`가 직접 켜고(`@EnableScheduling`) fixed-delay 를 쓴다.** 예전에는 JDBC
idempotency 설정만 스케줄링을 켰기 때문에 다른 provider 를 고르면 릴레이가 조립만 되고 돌지
않았다. fixed-delay 는 릴레이 실행 시간과 무관하게 사이클이 겹치지 않도록(non-overlapping) 보장한다.
- **종료 때는 platform보다 먼저 멈추고 진행 중 회차를 끝낸다(SmartLifecycle, phase
`Integer.MAX_VALUE`).** relay 회차는 messaging platform을 거쳐 발행한다. platform은 자기 종료
phase(`MessagingShutdownLifecycle`, `Integer.MAX_VALUE - 1024`)에서 발행 admission을 닫고, 그 뒤
- **종료 때는 platform보다 먼저 멈추고, 진행 중 발행 하나만 끝낸 뒤 남은 claim을 놓는다(SmartLifecycle,
phase `Integer.MAX_VALUE`).** relay 회차는 messaging platform을 거쳐 발행한다. platform은 자기 종료
phase(`MessagingShutdownLifecycle.PHASE` = `Integer.MAX_VALUE - 1024`)에서 발행 admission을 닫고, 그 뒤
발행은 `SHUTTING_DOWN`으로 거부된다. `@Scheduled`만으로는 이 순서에 들어가지 못한다(Spring은
`ContextClosedEvent`에서 다음 tick만 취소하고 실행 중 회차는 그대로 둔다). 그래서 스케줄러가
SmartLifecycle로 platform 위 phase(platform 자체 relay `MessagingOutboxRelayLifecycle`와 같은 값)에
서고, `stop`에서 새 회차를 막고 실행 중 회차가 결과를 기록할 때까지 종료를 붙잡는다. 기다리는 한도는
Spring의 `spring.lifecycle.timeout-per-shutdown-phase`다. 한도를 넘긴 회차의 남은 row는 거부되지만
재시도 대상(FAILED)이고, 프로세스가 강제 종료되면 IN_FLIGHT row는 lease 만료(`in-flight-timeout`)
뒤 다시 claim된다. 이 leaf는 messaging 타입을 이름으로 부를 수 없어 phase를 값으로 맞췄고,
`OutboxRelayShutdownOrderTest`가 같은 phase의 대역으로 순서를 고정한다.
- 버린 대안: scheduler executor phase 올리기(전역 설정이라 다른 `@Scheduled` 작업까지 바뀐다),
relay 루프를 전용 스레드로 직접 소유하기(`@Scheduled`·fixed-delay 정책과 `@EnableScheduling`
결정까지 다시 열어야 해서 이번 범위보다 크다).
SmartLifecycle로 platform 위 phase에 선다. `stop`은 새 회차를 막고 실행 중 회차에 멈춤을 알린다
(`PublishPendingOutboxEventsCommand.stopRequested`). 회차는 지금 하는 발행 하나를 끝내고, claim했지만
손대지 않은 row를 `OutboxStorePort.releaseLease`로 놓는다: PENDING, 곧바로 claim 가능, 시도 횟수에서
그 claim을 뺀다. 결과는 `RELEASED`로 센다. 그래서 종료 대기는 발행 하나(최대 약 10초)로 묶이고
`spring.lifecycle.timeout-per-shutdown-phase`(기본 30초) 안에 끝난다. 놓은 row는 다른 인스턴스가 다음
poll에서, 아니면 재시작한 이 인스턴스가 가져간다. 프로세스가 강제 종료되면 IN_FLIGHT row는 lease
만료(`in-flight-timeout`) 뒤 다시 claim된다. `OutboxRelayShutdownOrderTest`가 platform 상수
(`MessagingShutdownLifecycle.PHASE`, test compile-only 참조)로 순서를, 남은 claim 해제를 고정한다.
- 고른 방법: 멈춤 요청 즉시 남은 claim 해제. 버린 대안: 종료 한도까지 계속 발행하다 한도 직전에
해제 — 한도 값과 발행 하나의 최악 시간을 이 leaf가 알아야 하고, 그 추정이 틀리면 admission이 닫힌
뒤 발행해 retry 지연(30초 이상)과 FAILED 경고를 남긴다. scheduler executor phase 올리기(전역 설정이라
다른 `@Scheduled` 작업까지 바뀐다).
- **한 tick이 claim 한 번이 아니다(06-04).** claim gate는 aggregate마다 가장 앞 row 하나만 내보낸다.
예전에는 tick당 claim 한 번이라 한 aggregate가 poll 주기(기본 5초)마다 한 건씩만 나갔다(이벤트 100건 ≈
8분). 지금은 회차가 무언가를 발행하면 같은 tick 안에서 바로 다시 claim하고, 아무것도 발행하지 못하거나
claim이 비면 tick을 끝낸다. 한 tick의 상한은 `MAX_CYCLES_PER_TICK` = 50회차다.
- 처리량 상한(계산, 실측 아님): 한 aggregate는 poll 주기가 아니라 발행 왕복 시간에 묶인다(정상
broker에서 회차당 claim·완료 DB 왕복 + Kafka ack). 인스턴스 하나는 tick당 최대 50 × batch 20 =
1,000행을 보내고 다음 tick까지 5초 쉰다. 넘는 처리량이 필요하면 batch-size(NN-12의 lease 관계 확인)나
인스턴스 수로 늘린다.
- 버린 대안: poll 주기만 줄이기 — 빈 tick마다 claim·지표 질의가 는다.
- **지표 게이지는 relay와 따로 갱신한다(06-05).** `outbox.pending.size`·`outbox.publisher.lag`는
`OutboxMetrics.refreshGauges`가 poll 주기마다 갱신한다(`@Scheduled`, relay가 꺼져 있어도, 회차가 매번
예외로 끝나도). 예전에는 relay 회차 안에서만 갱신되어, relay가 꺼진 배포(기본값)나 매 회차 실패하는
장애에서 게이지가 멈췄고 `outbox_publisher_lag` 경보가 울리지 않았다. 카운터
`outbox.publisher.published.total`은 회차 결과로 relay가 기록한다. 발행 포트가 있는데 relay가 꺼져
있으면 `OutboxRelayOffWarning`이 기동 시 WARN 한 줄을 남긴다(별도 worker 배포가 relay를 돌리는 구성도
있으므로 기동 실패로 만들지 않았다).
### OutboxSettings
- **튜닝 값(poll 주기·batch·timeout·보존)은 코드 리터럴 기본값을 쓰고 env placeholder 를 두지 않는다.** 신규 env key 를
@@ -31,6 +31,12 @@ 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')) {
transitive = false
}
testImplementation 'org.mockito:mockito-core'
testImplementation 'ch.qos.logback:logback-classic'
testRuntimeOnly 'org.yaml:snakeyaml'
@@ -8,15 +8,25 @@ import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.MultiGauge;
import io.micrometer.core.instrument.Tags;
import java.time.Clock;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.scheduling.annotation.Scheduled;
/**
* Outbox relay metric collector. No-op when no {@link MeterRegistry} is present (resolved via
* {@link ObjectProvider}). See README for the design rationale.
* Outbox metric collector. No-op when no {@link MeterRegistry} is present (resolved via {@link
* ObjectProvider}). See README for the design rationale.
*
* <p>The gauges ({@code outbox.pending.size}, {@code outbox.publisher.lag}) refresh on their own
* schedule, not from the relay. They are how an operator sees rows piling up, and the two moments
* rows pile up are exactly the ones a relay-driven refresh missed: the relay is off — it is by
* default, and a deployment that forgot {@code APP_OUTBOX_RELAY_ENABLED} looked idle — or every
* cycle throws, which skipped the refresh and froze the gauges at their last value. The counter
* ({@code outbox.publisher.published.total}) is still recorded by the relay, from each cycle's
* outcomes.
*/
public final class OutboxMetrics {
@@ -25,12 +35,15 @@ public final class OutboxMetrics {
private static final String LAG_GAUGE = "outbox.publisher.lag";
private final OutboxStorePort store;
private final Clock clock;
private final MeterRegistry registry; // null when no Actuator on classpath
private final MultiGauge pendingSizeGauge;
private final MultiGauge publisherLagGauge;
public OutboxMetrics(OutboxStorePort store, ObjectProvider<MeterRegistry> meterRegistryProvider) {
public OutboxMetrics(
OutboxStorePort store, ObjectProvider<MeterRegistry> meterRegistryProvider, Clock clock) {
this.store = store;
this.clock = clock;
this.registry = meterRegistryProvider.getIfAvailable();
if (this.registry != null) {
@@ -70,6 +83,16 @@ public final class OutboxMetrics {
}
}
/**
* Refreshes the gauges every poll interval, whether or not the relay runs. Store failures are
* contained per gauge (a WARN through {@link RuntimeWarnings}), so a database outage leaves the
* scheduler thread alive for the next refresh.
*/
@Scheduled(fixedDelayString = "${app.outbox.poll-interval:PT5S}")
public void refreshGauges() {
refresh(clock.instant());
}
/**
* Uses {@code overwrite=true} so stale time-series tags from removed event types are replaced
* rather than left dangling.
@@ -84,7 +84,7 @@ public class OutboxRelayAutoConfiguration {
properties.batchSize(),
properties.inFlightTimeout(),
UUID.randomUUID().toString());
return new OutboxRelayScheduler(relayUseCase, metrics, clock);
return new OutboxRelayScheduler(relayUseCase, metrics);
}
/** Uses a {@code java.base} RNG so the relay also starts on the slim Temurin JRE image. */
@@ -99,10 +99,30 @@ public class OutboxRelayAutoConfiguration {
return new OutboxLeaderElectionToken();
}
/** Outbox metrics collector; no-op when {@link MeterRegistry} is absent. */
/**
* Outbox metrics collector; no-op when {@link MeterRegistry} is absent. Present whenever the
* store is, relay or not: its gauges refresh on their own schedule (see {@link OutboxMetrics}).
*/
@Bean
public OutboxMetrics outboxMetrics(
OutboxStorePort store, ObjectProvider<MeterRegistry> meterRegistryProvider) {
return new OutboxMetrics(store, meterRegistryProvider);
OutboxStorePort store,
ObjectProvider<MeterRegistry> meterRegistryProvider,
ObjectProvider<Clock> clock) {
return new OutboxMetrics(store, meterRegistryProvider, clock.getIfAvailable(Clock::systemUTC));
}
/**
* Says at startup that rows will be appended and nothing will send them: something can publish,
* but the relay is off. The default is off, so this is the deployment that selected messaging and
* forgot {@code APP_OUTBOX_RELAY_ENABLED}.
*/
@Bean
@ConditionalOnProperty(
name = "app.outbox.relay-enabled",
havingValue = "false",
matchIfMissing = true)
@ConditionalOnBean(OutboxMessagePublishPort.class)
public OutboxRelayOffWarning outboxRelayOffWarning() {
return new OutboxRelayOffWarning();
}
}
@@ -0,0 +1,32 @@
package dev.caskeleton.composition.outbox;
import static net.logstash.logback.argument.StructuredArguments.kv;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.SmartInitializingSingleton;
/**
* Logs one WARN at startup when the outbox store and a publish port exist but the relay is off:
* every appended event stays PENDING and nothing sends it. Registered by {@link
* OutboxRelayAutoConfiguration} only in that combination.
*
* <p>A warning rather than a startup failure: an instance that appends but does not relay is a
* legitimate split (a separate worker deployment runs the relay). It is not legitimate by accident,
* and the gauge {@code outbox.publisher.lag} is the alert that catches it in production; this line
* is the one an operator reads at deploy time.
*/
public final class OutboxRelayOffWarning implements SmartInitializingSingleton {
private static final Logger log = LoggerFactory.getLogger(OutboxRelayOffWarning.class);
@Override
public void afterSingletonsInstantiated() {
log.warn(
"outbox relay is off although a publish port exists — appended events stay PENDING until"
+ " a relay runs (set APP_OUTBOX_RELAY_ENABLED=true here or in a worker deployment)",
kv("capability", "outbox"),
kv("operation", "relay"),
kv("relay.enabled", false));
}
}
@@ -5,22 +5,30 @@ import static net.logstash.logback.argument.StructuredArguments.kv;
import dev.caskeleton.application.outbox.OutboxRelayResult;
import dev.caskeleton.application.outbox.PublishPendingOutboxEventsCommand;
import dev.caskeleton.application.outbox.PublishPendingOutboxEventsUseCase;
import java.time.Clock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.SmartLifecycle;
import org.springframework.scheduling.annotation.Scheduled;
/**
* Thin scheduler that drives the outbox relay use case on a fixed-delay polling loop, and stops
* ahead of the messaging platform on shutdown. Registered by {@link OutboxRelayAutoConfiguration}.
* See README for the design rationale.
* Drives the outbox relay use case on a fixed-delay polling loop, and stops ahead of the messaging
* platform on shutdown. Registered by {@link OutboxRelayAutoConfiguration}. See README for the
* design rationale.
*
* <p>A cycle publishes through the platform. The platform closes publish admission when its own
* shutdown phase runs ({@code MessagingShutdownLifecycle}, phase {@code Integer.MAX_VALUE - 1024}),
* and every publish after that is refused. So this scheduler is a {@link SmartLifecycle} in a
* higher phase: on stop it refuses new cycles and holds the shutdown until the running cycle has
* written its outcomes, and only then lets the lower phases close admission and the transports.
* higher phase: on stop it refuses new cycles, tells the running cycle to stop — it finishes the
* publish it is in and releases the claims it did not reach — and only then lets the lower phases
* close admission and the transports.
*
* <p>One tick is not one claim. The claim gate releases one row per aggregate at a time (the head),
* so a tick that claimed once moved an aggregate forward by one event per poll interval: an
* aggregate with a hundred queued events took over eight minutes to drain at the default {@code
* PT5S}. While a cycle publishes something — and so may have made the next row of an aggregate
* claimable — the tick claims again at once, up to {@link #MAX_CYCLES_PER_TICK} cycles. A cycle
* that claimed nothing, or published nothing, ends the tick: the rows left are waiting for their
* retry time, and polling for them again now would only repeat the claim query.
*/
public class OutboxRelayScheduler implements SmartLifecycle {
@@ -31,26 +39,37 @@ public class OutboxRelayScheduler implements SmartLifecycle {
*/
static final int PHASE = Integer.MAX_VALUE;
/**
* How many cycles one tick may run back to back. A bound rather than "until empty" so a steady
* stream of events still returns the thread to the scheduler, and the tick's duration stays
* bounded by roughly this many batches.
*/
static final int MAX_CYCLES_PER_TICK = 50;
private static final Logger log = LoggerFactory.getLogger(OutboxRelayScheduler.class);
private final PublishPendingOutboxEventsUseCase relayUseCase;
private final OutboxMetrics metrics;
private final Clock clock;
private final Object monitor = new Object();
private boolean running;
private boolean cycleInProgress;
private Runnable stopCallback;
/** Read by the running cycle before each row: the stop request reaches it without the monitor. */
private volatile boolean stopRequested;
private final PublishPendingOutboxEventsCommand command =
new PublishPendingOutboxEventsCommand(() -> stopRequested);
public OutboxRelayScheduler(
PublishPendingOutboxEventsUseCase relayUseCase, OutboxMetrics metrics, Clock clock) {
PublishPendingOutboxEventsUseCase relayUseCase, OutboxMetrics metrics) {
this.relayUseCase = relayUseCase;
this.metrics = metrics;
this.clock = clock;
}
/**
* Runs one relay cycle unless the scheduler is stopped. Unexpected exceptions are caught (not
* Runs relay cycles unless the scheduler is stopped. Unexpected exceptions are caught (not
* propagated) so the scheduler thread stays alive for the next tick.
*/
@Scheduled(fixedDelayString = "${app.outbox.poll-interval:PT5S}")
@@ -62,7 +81,7 @@ public class OutboxRelayScheduler implements SmartLifecycle {
cycleInProgress = true;
}
try {
runCycle();
runTick();
} finally {
Runnable pendingStop;
synchronized (monitor) {
@@ -76,19 +95,21 @@ public class OutboxRelayScheduler implements SmartLifecycle {
}
}
private void runCycle() {
private void runTick() {
try {
OutboxRelayResult result = relayUseCase.handle(PublishPendingOutboxEventsCommand.INSTANCE);
if (result.claimedCount() > 0) {
log.debug(
"outbox relay cycle: claimed={} outcomes={}",
result.claimedCount(),
result.outcomes().size());
}
metrics.recordRelayResult(result);
metrics.refresh(clock.instant());
int cycles = 0;
OutboxRelayResult result;
do {
result = relayUseCase.handle(command);
cycles++;
if (result.claimedCount() > 0) {
log.debug(
"outbox relay cycle: claimed={} outcomes={}",
result.claimedCount(),
result.outcomes().size());
}
metrics.recordRelayResult(result);
} while (!stopRequested && result.publishedAny() && cycles < MAX_CYCLES_PER_TICK);
} catch (Exception ex) {
log.error(
@@ -104,6 +125,7 @@ public class OutboxRelayScheduler implements SmartLifecycle {
@Override
public void start() {
synchronized (monitor) {
stopRequested = false;
running = true;
}
}
@@ -112,18 +134,22 @@ public class OutboxRelayScheduler implements SmartLifecycle {
@Override
public void stop() {
synchronized (monitor) {
stopRequested = true;
running = false;
}
}
/**
* Refuses new cycles and reports stopped once the running cycle, if any, has finished. Spring
* waits for the callback up to {@code spring.lifecycle.timeout-per-shutdown-phase}; a cycle still
* running then meets a closed admission gate and its rows are retried, not lost.
* Refuses new cycles, asks the running cycle to stop, and reports stopped once it has. The cycle
* finishes the publish it is in — at most one publish deadline — and releases its other claims,
* so the wait stays well inside {@code spring.lifecycle.timeout-per-shutdown-phase} (30s by
* default) however large the batch. Were the wait to run out anyway, the publish still running
* meets a closed admission gate and is retried, not lost.
*/
@Override
public void stop(Runnable callback) {
synchronized (monitor) {
stopRequested = true;
running = false;
if (cycleInProgress) {
stopCallback = callback;
@@ -0,0 +1,165 @@
package dev.caskeleton.composition.outbox;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;
import dev.caskeleton.application.outbox.OutboxMessagePublishPort;
import dev.caskeleton.application.outbox.OutboxStorePort;
import dev.caskeleton.application.outbox.testkit.InMemoryOutboxStore;
import dev.caskeleton.application.outbox.testkit.OutboxEvents;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.search.Search;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.UUID;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.support.StaticListableBeanFactory;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
/**
* The outbox gauges are how an operator sees rows piling up. They used to refresh only from inside
* a relay cycle, so with the relay off (the default) or failing every cycle they stood still
* (review 06-05).
*/
@ExtendWith(OutputCaptureExtension.class)
class OutboxMetricsTest {
private static final Instant NOW = Instant.parse("2026-11-01T09:00:00Z");
@Test
@DisplayName("relay가 꺼져 있어도 대기 행 게이지가 실제 PENDING 행 수를 보여 준다")
void withTheRelayOffThePendingGaugeShowsThePendingRows() {
// given: two rows appended, no relay
InMemoryOutboxStore store = new InMemoryOutboxStore();
store.append(OutboxEvents.event(UUID.randomUUID().toString(), NOW.minusSeconds(30)));
store.append(OutboxEvents.event(UUID.randomUUID().toString(), NOW.minusSeconds(20)));
SimpleMeterRegistry registry = new SimpleMeterRegistry();
ApplicationContextRunner runner =
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(OutboxRelayAutoConfiguration.class))
.withBean(OutboxStorePort.class, () -> store)
.withBean(MeterRegistry.class, () -> registry)
.withPropertyValues(
"app.outbox.enabled=true",
"app.outbox.relay-enabled=false",
"app.outbox.poll-interval=PT0.05S");
// when
runner.run(
context ->
await()
.atMost(Duration.ofSeconds(10))
.until(() -> pending(registry) != null && pending(registry) == 2.0));
// then
assertThat(pending(registry)).isEqualTo(2.0);
}
@Test
@DisplayName("게이지 갱신은 PUBLISHED를 세지 않고 지연 게이지는 가장 오래된 미발행 행의 나이다")
void aRefreshCountsUnpublishedRowsAndAgesTheOldest() {
// given
InMemoryOutboxStore store = new InMemoryOutboxStore();
store.append(OutboxEvents.event(UUID.randomUUID().toString(), NOW.minusSeconds(90)));
SimpleMeterRegistry registry = new SimpleMeterRegistry();
OutboxMetrics metrics = metrics(store, registry);
// when
metrics.refreshGauges();
// then
assertThat(pending(registry)).isEqualTo(1.0);
assertThat(Search.in(registry).name("outbox.pending.size").tag("status", "PUBLISHED").gauge())
.isNull();
assertThat(
registry
.get("outbox.publisher.lag")
.tag("event_type", OutboxEvents.CONTRACT_ID)
.gauge()
.value())
.isEqualTo(90.0);
}
@Test
@DisplayName("저장소가 실패해도 게이지 갱신은 예외를 밖으로 던지지 않는다")
void aFailingStoreDoesNotBreakTheRefresh() {
// given
OutboxStorePort broken = Mockito.mock(OutboxStorePort.class);
Mockito.when(broken.countByStatus()).thenThrow(new IllegalStateException("database down"));
Mockito.when(broken.oldestUnpublishedAgeSecondsByEventType(Mockito.any()))
.thenThrow(new IllegalStateException("database down"));
OutboxMetrics metrics = metrics(broken, new SimpleMeterRegistry());
// when
Throwable thrown = org.assertj.core.api.Assertions.catchThrowable(metrics::refreshGauges);
// then
assertThat(thrown).isNull();
}
@Test
@DisplayName("발행 포트가 있는데 relay가 꺼져 있으면 기동 시 WARN을 한 줄 남긴다")
void aPublishPortWithTheRelayOffWarnsAtStartup(CapturedOutput output) {
// given
ApplicationContextRunner runner =
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(OutboxRelayAutoConfiguration.class))
.withBean(OutboxStorePort.class, InMemoryOutboxStore::new)
.withBean(
OutboxMessagePublishPort.class, () -> Mockito.mock(OutboxMessagePublishPort.class))
.withPropertyValues("app.outbox.enabled=true", "app.outbox.poll-interval=PT1H");
// when
runner.run(context -> assertThat(context).hasSingleBean(OutboxRelayOffWarning.class));
// then
assertThat(output).contains("outbox relay is off although a publish port exists");
}
@Test
@DisplayName("relay가 켜져 있으면 relay 꺼짐 경고를 남기지 않는다")
void aRunningRelayDoesNotWarn() {
// given
ApplicationContextRunner runner =
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(OutboxRelayAutoConfiguration.class))
.withBean(OutboxStorePort.class, InMemoryOutboxStore::new)
.withBean(
OutboxMessagePublishPort.class, () -> Mockito.mock(OutboxMessagePublishPort.class))
.withBean(
dev.caskeleton.application.outbox.OutboxRelayFailureReportPort.class,
() -> report -> {})
.withBean(
dev.caskeleton.application.transaction.TransactionPort.class,
dev.caskeleton.application.transaction.testkit.DirectTransactionPort::new)
.withBean(Clock.class, Clock::systemUTC)
.withPropertyValues(
"app.outbox.enabled=true",
"app.outbox.relay-enabled=true",
"app.outbox.poll-interval=PT1H");
// when & then
runner.run(context -> assertThat(context).doesNotHaveBean(OutboxRelayOffWarning.class));
}
private static Double pending(MeterRegistry registry) {
var gauge = Search.in(registry).name("outbox.pending.size").tag("status", "PENDING").gauge();
return gauge == null ? null : gauge.value();
}
private static OutboxMetrics metrics(OutboxStorePort store, MeterRegistry registry) {
StaticListableBeanFactory registries = new StaticListableBeanFactory();
registries.addBean("meterRegistry", registry);
return new OutboxMetrics(
store, registries.getBeanProvider(MeterRegistry.class), Clock.fixed(NOW, ZoneOffset.UTC));
}
}
@@ -0,0 +1,198 @@
package dev.caskeleton.composition.outbox;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.application.outbox.OutboxBackoffPolicy;
import dev.caskeleton.application.outbox.OutboxEventStatus;
import dev.caskeleton.application.outbox.OutboxMessagePublishPort;
import dev.caskeleton.application.outbox.OutboxStorePort;
import dev.caskeleton.application.outbox.PublishPendingOutboxEventsUseCase;
import dev.caskeleton.application.outbox.testkit.InMemoryOutboxStore;
import dev.caskeleton.application.outbox.testkit.OutboxEvents;
import dev.caskeleton.application.transaction.testkit.DirectTransactionPort;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.support.StaticListableBeanFactory;
/**
* One relay tick against a backlog. The claim gate releases one row per aggregate at a time, so a
* tick that claimed once moved an aggregate forward by one event per poll interval (review 06-04).
*
* <p>The store below is the port owner's fake with that gate added: a row is claimable only while
* no earlier row of its aggregate is unpublished — the rule the PostgreSQL claim SQL carries.
*/
class OutboxRelaySchedulerDrainTest {
private static final Instant NOW = Instant.parse("2026-11-01T09:00:00Z");
@Test
@DisplayName("한 aggregate에 쌓인 이벤트는 poll 주기를 기다리지 않고 한 tick 안에 순서대로 모두 나간다")
void oneTickDrainsAnAggregatesBacklogInOrderWithoutWaitingForThePollInterval() {
// given: thirty events of one aggregate, each claimable only after the one before it
HeadOfAggregateStore store = new HeadOfAggregateStore();
List<String> appended = new ArrayList<>();
for (int sequence = 1; sequence <= 30; sequence++) {
String eventId = UUID.randomUUID().toString();
appended.add(eventId);
store.append(OutboxEvents.event(eventId, "order-1", sequence, NOW.minusSeconds(60)));
}
List<String> sent = new ArrayList<>();
OutboxRelayScheduler scheduler = scheduler(store, event -> sent.add(event.eventId()));
scheduler.start();
// when
scheduler.relay();
// then
assertThat(sent).containsExactlyElementsOf(appended);
}
@Test
@DisplayName("한 tick이 도는 회차 수에는 상한이 있다")
void aTickRunsAtMostItsBoundedNumberOfCycles() {
// given: more single-row cycles than one tick may run
HeadOfAggregateStore store = new HeadOfAggregateStore();
int backlog = OutboxRelayScheduler.MAX_CYCLES_PER_TICK + 5;
for (int sequence = 1; sequence <= backlog; sequence++) {
store.append(
OutboxEvents.event(
UUID.randomUUID().toString(), "order-1", sequence, NOW.minusSeconds(60)));
}
List<String> sent = new ArrayList<>();
OutboxRelayScheduler scheduler = scheduler(store, event -> sent.add(event.eventId()));
scheduler.start();
// when
scheduler.relay();
// then
assertThat(sent).hasSize(OutboxRelayScheduler.MAX_CYCLES_PER_TICK);
}
@Test
@DisplayName("아무것도 발행하지 못한 회차가 나오면 tick은 다시 claim하지 않고 끝난다")
void aCycleThatPublishedNothingEndsTheTick() {
// given: the broker refuses every publish for now
HeadOfAggregateStore store = new HeadOfAggregateStore();
store.append(OutboxEvents.event(UUID.randomUUID().toString(), NOW.minusSeconds(60)));
store.append(OutboxEvents.event(UUID.randomUUID().toString(), NOW.minusSeconds(59)));
List<String> attempted = new ArrayList<>();
OutboxRelayScheduler scheduler =
scheduler(
store,
event -> {
attempted.add(event.eventId());
throw new IllegalStateException("broker unavailable");
});
scheduler.start();
// when
scheduler.relay();
// then: each row was tried once; both now wait for their retry time
assertThat(attempted).hasSize(2).doesNotHaveDuplicates();
}
@Test
@DisplayName("relay는 회차마다 발행 결과를 카운터에 기록한다")
void everyCycleOfATickIsCountedInThePublishedCounter() {
// given
HeadOfAggregateStore store = new HeadOfAggregateStore();
for (int sequence = 1; sequence <= 3; sequence++) {
store.append(
OutboxEvents.event(
UUID.randomUUID().toString(), "order-1", sequence, NOW.minusSeconds(60)));
}
SimpleMeterRegistry registry = new SimpleMeterRegistry();
OutboxRelayScheduler scheduler = scheduler(store, event -> {}, registry);
scheduler.start();
// when
scheduler.relay();
// then
assertThat(
registry
.get("outbox.publisher.published.total")
.tag("outcome", "PUBLISHED")
.counter()
.count())
.isEqualTo(3.0);
}
private static OutboxRelayScheduler scheduler(
OutboxStorePort store, OutboxMessagePublishPort port) {
return scheduler(store, port, null);
}
private static OutboxRelayScheduler scheduler(
OutboxStorePort store, OutboxMessagePublishPort port, SimpleMeterRegistry registry) {
Clock clock = Clock.fixed(NOW, ZoneOffset.UTC);
StaticListableBeanFactory registries = new StaticListableBeanFactory();
if (registry != null) {
registries.addBean("meterRegistry", registry);
}
PublishPendingOutboxEventsUseCase relay =
new PublishPendingOutboxEventsUseCase(
store,
port,
report -> {},
new DirectTransactionPort(),
new OutboxBackoffPolicy(() -> 0L),
clock,
20,
Duration.ofMinutes(5),
"relay-under-test");
return new OutboxRelayScheduler(
relay,
new OutboxMetrics(
store,
registries.getBeanProvider(io.micrometer.core.instrument.MeterRegistry.class),
clock));
}
/** The fake store with the claim SQL's per-aggregate head gate. */
private static final class HeadOfAggregateStore extends InMemoryOutboxStore {
@Override
public List<dev.caskeleton.application.outbox.OutboxLease> claimBatch(
String owner, int batchSize, Instant now, Duration inFlightTimeout) {
List<String> heads = new ArrayList<>();
List<String> seenAggregates = new ArrayList<>();
appended().stream()
.sorted(
java.util.Comparator.comparingLong(
(dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent e) ->
e.order().sequence()))
.forEach(
event -> {
String aggregate = event.aggregate().aggregateId();
if (seenAggregates.contains(aggregate)) {
return;
}
OutboxEventStatus status = status(event.eventId().value());
if (status != OutboxEventStatus.PUBLISHED) {
seenAggregates.add(aggregate);
heads.add(event.eventId().value());
}
});
return super.claimBatch(owner, batchSize, now, inFlightTimeout).stream()
.filter(lease -> heads.contains(lease.eventId()) || unclaim(lease))
.toList();
}
/** A row the gate would not have returned: give the fake's claim back, unspent. */
private boolean unclaim(dev.caskeleton.application.outbox.OutboxLease lease) {
releaseLease(lease, lease.event().occurredAt());
return false;
}
}
}
@@ -1,6 +1,7 @@
package dev.caskeleton.composition.outbox;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -11,7 +12,6 @@ import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import dev.caskeleton.application.outbox.PublishPendingOutboxEventsCommand;
import dev.caskeleton.application.outbox.PublishPendingOutboxEventsUseCase;
import java.time.Clock;
import java.util.Arrays;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
@@ -24,11 +24,11 @@ class OutboxRelaySchedulerLoggingTest {
void outboxRelayUnexpectedFailureCarriesNextTickDispositionWithoutInventedErrorCode() {
PublishPendingOutboxEventsUseCase relay = mock(PublishPendingOutboxEventsUseCase.class);
OutboxMetrics metrics = mock(OutboxMetrics.class);
when(relay.handle(PublishPendingOutboxEventsCommand.INSTANCE))
when(relay.handle(any(PublishPendingOutboxEventsCommand.class)))
.thenThrow(new IllegalStateException("unexpected"));
try (CapturedLogger captured = capture(OutboxRelayScheduler.class)) {
OutboxRelayScheduler scheduler = new OutboxRelayScheduler(relay, metrics, Clock.systemUTC());
OutboxRelayScheduler scheduler = new OutboxRelayScheduler(relay, metrics);
scheduler.start();
scheduler.relay();
@@ -16,12 +16,15 @@ 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;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
@@ -36,8 +39,8 @@ import org.springframework.context.SmartLifecycle;
*/
class OutboxRelayShutdownOrderTest {
/** {@code MessagingShutdownLifecycle#getPhase()}; this leaf may not name the messaging type. */
private static final int PLATFORM_ADMISSION_PHASE = Integer.MAX_VALUE - 1024;
/** The platform's own constant; production code of this leaf may not name it, a test may. */
private static final int PLATFORM_ADMISSION_PHASE = MessagingShutdownLifecycle.PHASE;
private static final String EVENT_ID = "evt-shutdown-1";
@@ -49,19 +52,7 @@ class OutboxRelayShutdownOrderTest {
store.addClaimable(OutboxEvents.claimed(EVENT_ID, Instant.now().minusSeconds(60), 1));
BlockingPublishPort publishPort = new BlockingPublishPort();
PlatformAdmissionStandIn platform = new PlatformAdmissionStandIn(store);
ApplicationContextRunner runner =
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(OutboxRelayAutoConfiguration.class))
.withBean(OutboxStorePort.class, () -> store)
.withBean(OutboxMessagePublishPort.class, () -> publishPort)
.withBean(OutboxRelayFailureReportPort.class, () -> report -> {})
.withBean(TransactionPort.class, DirectTransactionPort::new)
.withBean(Clock.class, Clock::systemUTC)
.withBean(PlatformAdmissionStandIn.class, () -> platform)
.withPropertyValues(
"app.outbox.enabled=true",
"app.outbox.relay-enabled=true",
"app.outbox.poll-interval=PT1H");
ApplicationContextRunner runner = runner(store, publishPort, platform);
AtomicReference<CompletableFuture<Void>> closing = new AtomicReference<>();
runner.run(
@@ -88,13 +79,51 @@ class OutboxRelayShutdownOrderTest {
assertThat(store.status(EVENT_ID)).isEqualTo(OutboxEventStatus.PUBLISHED);
}
@Test
@DisplayName("종료 시 relay는 진행 중 발행만 끝내고 나머지 claim은 시도 없이 놓은 뒤 멈춘다")
void onShutdownTheRelayReleasesTheClaimsItDidNotReachBeforeThePlatformStops() throws Exception {
// given: one cycle claims three rows and is publishing the first when the context closes
RecordingStore store = new RecordingStore();
String publishing = "0193a000-0000-7000-8000-0000000000a1";
String second = "0193a000-0000-7000-8000-0000000000a2";
String third = "0193a000-0000-7000-8000-0000000000a3";
Instant occurred = Instant.now().minusSeconds(60);
store.append(OutboxEvents.event(publishing, occurred));
store.append(OutboxEvents.event(second, occurred.plusMillis(1)));
store.append(OutboxEvents.event(third, occurred.plusMillis(2)));
BlockingPublishPort publishPort = new BlockingPublishPort();
PlatformAdmissionStandIn platform = new PlatformAdmissionStandIn(store);
// when
runner(store, publishPort, platform)
.run(
context -> {
assertThat(publishPort.entered.await(10, TimeUnit.SECONDS)).isTrue();
CompletableFuture<Void> closing = CompletableFuture.runAsync(context::close);
platform.stopped.await(300, TimeUnit.MILLISECONDS);
publishPort.release.countDown();
closing.get(20, TimeUnit.SECONDS);
});
// then: the publish in progress landed, the other two are claimable again, unspent
assertThat(publishPort.calls.get()).as("no row was published after the stop").isEqualTo(1);
assertThat(store.status(publishing)).isEqualTo(OutboxEventStatus.PUBLISHED);
assertThat(store.released()).containsExactly(second, third);
assertThat(List.of(store.status(second), store.status(third)))
.containsOnly(OutboxEventStatus.PENDING);
assertThat(List.of(store.attemptCount(second), store.attemptCount(third))).containsOnly(0);
assertThat(platform.releasedWhenStopped.get())
.as("the claims were released before the platform closed admission")
.isEqualTo(2);
}
@Test
@DisplayName("멈춘 relay는 다음 tick이 와도 새 회차를 시작하지 않는다")
void aStoppedRelayStartsNoNewCycle() {
// given
PublishPendingOutboxEventsUseCase relayUseCase = mock(PublishPendingOutboxEventsUseCase.class);
OutboxRelayScheduler scheduler =
new OutboxRelayScheduler(relayUseCase, mock(OutboxMetrics.class), Clock.systemUTC());
new OutboxRelayScheduler(relayUseCase, mock(OutboxMetrics.class));
scheduler.start();
AtomicBoolean reportedStopped = new AtomicBoolean();
scheduler.stop(() -> reportedStopped.set(true));
@@ -108,6 +137,22 @@ class OutboxRelayShutdownOrderTest {
assertThat(scheduler.isRunning()).isFalse();
}
private static ApplicationContextRunner runner(
RecordingStore store, BlockingPublishPort publishPort, PlatformAdmissionStandIn platform) {
return new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(OutboxRelayAutoConfiguration.class))
.withBean(OutboxStorePort.class, () -> store)
.withBean(OutboxMessagePublishPort.class, () -> publishPort)
.withBean(OutboxRelayFailureReportPort.class, () -> report -> {})
.withBean(TransactionPort.class, DirectTransactionPort::new)
.withBean(Clock.class, Clock::systemUTC)
.withBean(PlatformAdmissionStandIn.class, () -> platform)
.withPropertyValues(
"app.outbox.enabled=true",
"app.outbox.relay-enabled=true",
"app.outbox.poll-interval=PT1H");
}
/** Records when the relay writes the row's completion. */
private static final class RecordingStore extends InMemoryOutboxStore {
@@ -134,6 +179,16 @@ class OutboxRelayShutdownOrderTest {
return completion;
}
@Override
public synchronized OutboxCompletion releaseLease(OutboxLease lease, Instant claimableAt) {
return super.releaseLease(lease, claimableAt);
}
@Override
public synchronized List<String> released() {
return super.released();
}
@Override
public synchronized OutboxEventStatus status(String eventId) {
return super.status(eventId);
@@ -145,9 +200,11 @@ class OutboxRelayShutdownOrderTest {
private final CountDownLatch entered = new CountDownLatch(1);
private final CountDownLatch release = new CountDownLatch(1);
private final AtomicInteger calls = new AtomicInteger();
@Override
public void publish(ClaimedOutboxEvent event) {
calls.incrementAndGet();
entered.countDown();
try {
if (!release.await(20, TimeUnit.SECONDS)) {
@@ -166,6 +223,7 @@ class OutboxRelayShutdownOrderTest {
private final RecordingStore store;
private final CountDownLatch stopped = new CountDownLatch(1);
private final AtomicBoolean rowCompletedWhenStopped = new AtomicBoolean();
private final AtomicInteger releasedWhenStopped = new AtomicInteger();
private volatile boolean running;
PlatformAdmissionStandIn(RecordingStore store) {
@@ -181,6 +239,7 @@ class OutboxRelayShutdownOrderTest {
public void stop() {
running = false;
rowCompletedWhenStopped.set(store.completed.get());
releasedWhenStopped.set(store.released().size());
stopped.countDown();
}
+12 -3
View File
@@ -18,9 +18,18 @@ composition:service-runtime
├─ metrics/ MetricsContractConfig(cardinality deny-list + SLO 분포 filter)
├─ context/ DomainContextConfig
├─ logging/ PseudonymizationConfig, PrivacySettings (user_principal HMAC 가명화)
└─ management/security/ ManagementSecurityConfig (actuator chain)
├─ management/security/ ManagementSecurityConfig (actuator chain)
└─ authorization/ PermissionEnforcementConfig(PermissionEnforcementGuard: @RequiresPermission
빈이 있는데 적용되는 advisor가 없으면 기동 실패)
```
- **권한 검사 장치 부재 = 기동 실패.** `@RequiresPermission`은 application-core 선언이고 검사는
web leaf의 `MethodSecurityConfig` advisor가 한다. web을 뺀 조립(gRPC 전용·배치 전용)은 예전엔
선언만 남은 채 정상 기동했다. 이제 `PermissionEnforcementGuard`가 선언 빈마다 pointcut이 맞는
advisor가 있는지 보고, 없으면 `REQUIRED_ADAPTER_DISABLED`(exit 72)로 기동을 멈춘다. 한계:
"어떤 advisor든 pointcut이 맞으면 통과"라 인가가 아닌 advisor를 구분하지 못한다. `new`로 만든
유스케이스는 검사 대상이 아니다(시스템 호출용은 `@SystemInvoked`).
- 모두 이 모듈의 `AutoConfiguration.imports`로 등록된다(설정 브리지와 tracing 스위치는
`spring.factories`의 `EnvironmentPostProcessor`·`AutoConfigurationImportFilter`). 구성 루트의
component scan에 기대지 않는다.
@@ -147,7 +156,7 @@ runtimeOnly project(':composition:service-runtime')
OpenTelemetry 규약대로 기준 주소에 `/v1/traces`를 붙인다(끝의 `/`는 하나로 정리). gRPC 전송이나 다른
경로가 필요하면 Boot 키(`management.opentelemetry.tracing.export.otlp.*`)를 직접 주며, 직접 준 값은
덮어쓰지 않는다. 예전 이름은 `TracingSamplingEnvironmentPostProcessor`다(순서 상수는
`StartupOrder.TRACING_SAMPLING` 그대로). 이를 통해 "프로파일별 기본값 + env override"라는
`StartupOrder.TRACING_PROPERTIES` 그대로). 이를 통해 "프로파일별 기본값 + env override"라는
우리 규약을 Spring Boot 의 기본 샘플링 메커니즘에 그대로 연결한다.
- **샘플링 브리지 우선순위.** (1) 사용자가 `management.tracing.sampling.probability`를 이미 명시했으면
덮어쓰지 않고 그대로 둔다, (2) `app.tracing.sample-rate`가 non-blank 면 그 값 사용, (3)
@@ -245,7 +254,7 @@ runtimeOnly project(':composition:service-runtime')
`app.privacy.*` 바인딩(원천 `APP_PRIVACY_PSEUDONYMIZATION_SALT`). 알고리즘은 HMAC-SHA-256
+ 90일 회전 salt 이고, 이 salt 는 `secret`-tier 값이라 prod 에서는 반드시 secret manager 에서
공급되어야 한다.
- **검증은 `LoggingSettings`와 일관되게 "warn-and-default"다.** blank salt 는 경고를 남기고, 명확히
- **검증은 "warn-and-default"다.** blank salt 는 경고를 남기고, 명확히
표시된 dev sentinel(`__LOCAL_DEV_` 접두사)로 폴백해 local/test 실행이 절대 기동에 실패하지 않게
한다.
- **이 sentinel 을 prod 로 승격하는 것은 별도 계약이 독립적으로
+7 -1
View File
@@ -37,7 +37,13 @@ dependencies {
// switches the whole of it off for app.tracing.enabled=false (TracingSwitchImportFilter).
implementation 'io.micrometer:micrometer-tracing-bridge-otel'
implementation 'org.springframework.boot:spring-boot-micrometer-tracing-opentelemetry'
implementation 'io.opentelemetry:opentelemetry-exporter-otlp'
// The OTLP exporter over the JDK's own HttpClient rather than OkHttp (09-11). The default sender
// brought okhttp, okio and kotlin-stdlib (about 3 MB) into every image for one HTTP POST the JDK
// already makes; the exporter picks whichever sender is on the classpath.
implementation('io.opentelemetry:opentelemetry-exporter-otlp') {
exclude group: 'io.opentelemetry', module: 'opentelemetry-exporter-sender-okhttp'
}
runtimeOnly 'io.opentelemetry:opentelemetry-exporter-sender-jdk'
// The actuator security chain.
implementation 'org.springframework.boot:spring-boot-starter-security'
@@ -10,6 +10,7 @@ com.fasterxml.jackson.core:jackson-core:2.21.5=compileClasspath,runtimeClasspath
com.fasterxml.jackson.core:jackson-databind:2.21.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.fasterxml.jackson:jackson-bom:2.21.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor
com.github.f4b6a3:uuid-creator:6.1.1=runtimeClasspath,testRuntimeClasspath
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
@@ -36,10 +37,6 @@ com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProce
com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins
com.jayway.jsonpath:json-path:2.10.0=testCompileClasspath,testRuntimeClasspath
com.puppycrawl.tools:checkstyle:13.5.0=checkstyle
com.squareup.okhttp3:okhttp-jvm:5.2.1=runtimeClasspath,testRuntimeClasspath
com.squareup.okhttp3:okhttp:5.2.1=runtimeClasspath,testRuntimeClasspath
com.squareup.okio:okio-jvm:3.16.1=runtimeClasspath,testRuntimeClasspath
com.squareup.okio:okio:3.16.1=runtimeClasspath,testRuntimeClasspath
com.vaadin.external.google:android-json:0.0.20131108.vaadin1=testCompileClasspath,testRuntimeClasspath
commons-beanutils:commons-beanutils:1.11.0=checkstyle
commons-collections:commons-collections:3.2.2=checkstyle
@@ -62,7 +59,7 @@ io.opentelemetry:opentelemetry-context:1.55.0=compileClasspath,runtimeClasspath,
io.opentelemetry:opentelemetry-exporter-common:1.55.0=runtimeClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-exporter-otlp-common:1.55.0=runtimeClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-exporter-otlp:1.55.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-exporter-sender-okhttp:1.55.0=runtimeClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-exporter-sender-jdk:1.55.0=runtimeClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-extension-trace-propagators:1.55.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-sdk-common:1.55.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-sdk-extension-autoconfigure-spi:1.55.0=runtimeClasspath,testRuntimeClasspath
@@ -110,8 +107,6 @@ org.dom4j:dom4j:2.2.0=spotbugs
org.hamcrest:hamcrest:3.0=testCompileClasspath,testRuntimeClasspath
org.hdrhistogram:HdrHistogram:2.2.2=runtimeClasspath,testRuntimeClasspath
org.javassist:javassist:3.28.0-GA=checkstyle
org.jetbrains.kotlin:kotlin-stdlib:2.2.21=runtimeClasspath,testRuntimeClasspath
org.jetbrains:annotations:13.0=runtimeClasspath,testRuntimeClasspath
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
@@ -0,0 +1,25 @@
package dev.caskeleton.composition.runtime.authorization;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Role;
/**
* Registers {@link PermissionEnforcementGuard}: a service that declares permission gates must also
* have something that enforces them.
*
* <p>{@code @RequiresPermission} is an application-core declaration; the advisor that checks it is
* {@code adapter:inbound:web}'s {@code MethodSecurityConfig}. A composition without the web adapter
* — gRPC-only, batch-only — used to start normally with every gate declared and none enforced. This
* guard makes that composition fail at startup instead.
*/
@AutoConfiguration
public class PermissionEnforcementConfig {
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
static PermissionEnforcementGuard permissionEnforcementGuard() {
return new PermissionEnforcementGuard();
}
}
@@ -0,0 +1,69 @@
package dev.caskeleton.composition.runtime.authorization;
import dev.caskeleton.adapter.outbound.support.startup.StartupFailures;
import dev.caskeleton.application.security.RequiresPermission;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.springframework.aop.Advisor;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.util.ClassUtils;
/**
* Fails startup when a bean declares {@link RequiresPermission} and no advisor in the context
* applies to it.
*
* <p>"Applies" is {@link AopUtils#canApply(Advisor, Class)}: the advisor's pointcut matches the
* bean's class. That is how the web adapter's advisor reaches a use case, so its absence is exactly
* the case this guard is for. The check cannot tell an authorization advisor from any other advisor
* whose pointcut happens to match; it closes the "adapter missing" gap, not every misconfiguration.
*
* <p>Only beans are checked. A use case built with {@code new} is never advised whatever the
* context holds — that is what {@code @SystemInvoked} declares for the use cases the system calls.
*/
final class PermissionEnforcementGuard implements SmartInitializingSingleton, BeanFactoryAware {
private ConfigurableListableBeanFactory beanFactory;
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = (ConfigurableListableBeanFactory) beanFactory;
}
@Override
public void afterSingletonsInstantiated() {
Collection<Advisor> advisors = beanFactory.getBeansOfType(Advisor.class, true, false).values();
List<String> unenforced = new ArrayList<>();
for (String name : beanFactory.getBeanDefinitionNames()) {
Class<?> type = beanFactory.getType(name, false);
if (type == null) {
continue;
}
Class<?> userClass = ClassUtils.getUserClass(type);
if (declaresPermission(userClass)
&& advisors.stream().noneMatch(advisor -> AopUtils.canApply(advisor, userClass))) {
unenforced.add(name + " (" + userClass.getName() + ")");
}
}
if (!unenforced.isEmpty()) {
throw StartupFailures.requiredAdapterDisabled(
"beans declare @RequiresPermission but no advisor enforces it — the composition is"
+ " missing the authorization adapter (adapter:inbound:web MethodSecurityConfig): "
+ String.join(", ", unenforced));
}
}
private static boolean declaresPermission(Class<?> type) {
return AnnotatedElementUtils.hasAnnotation(type, RequiresPermission.class)
|| Arrays.stream(type.getMethods())
.anyMatch(
method -> AnnotatedElementUtils.hasAnnotation(method, RequiresPermission.class));
}
}
@@ -69,6 +69,6 @@ public class TracingEnvironmentPostProcessor implements EnvironmentPostProcessor
// Declared rather than inherited. Implementing EnvironmentPostProcessor without Ordered means
// LOWEST_PRECEDENCE by default, which is the same value three other post-processors returned
// explicitly — four things claiming the same position, none of them saying so (BOOT-005).
return StartupOrder.TRACING_SAMPLING;
return StartupOrder.TRACING_PROPERTIES;
}
}
@@ -3,3 +3,4 @@ dev.caskeleton.composition.runtime.logging.PseudonymizationConfig
dev.caskeleton.composition.runtime.management.security.ManagementSecurityConfig
dev.caskeleton.composition.runtime.metrics.MetricsContractConfig
dev.caskeleton.composition.runtime.tracing.TracingConfig
dev.caskeleton.composition.runtime.authorization.PermissionEnforcementConfig
@@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.outbound.support.startup.StartupOrder;
import dev.caskeleton.application.observability.UserPrincipalPseudonymizerPort;
import dev.caskeleton.composition.runtime.authorization.PermissionEnforcementConfig;
import dev.caskeleton.composition.runtime.context.DomainContextConfig;
import dev.caskeleton.composition.runtime.logging.PseudonymizationConfig;
import dev.caskeleton.composition.runtime.management.security.ManagementSecurityConfig;
@@ -35,7 +36,8 @@ class ServiceRuntimeRegistrationTest {
PseudonymizationConfig.class,
ManagementSecurityConfig.class,
MetricsContractConfig.class,
TracingConfig.class);
TracingConfig.class,
PermissionEnforcementConfig.class);
@Test
void everyRootIsAnAutoConfigurationBootDiscoversFromThisModule() {
@@ -89,7 +91,7 @@ class ServiceRuntimeRegistrationTest {
int order = bridge.getOrder();
// then
assertThat(order).isEqualTo(StartupOrder.TRACING_SAMPLING);
assertThat(order).isEqualTo(StartupOrder.TRACING_PROPERTIES);
}
@ParameterizedTest
@@ -0,0 +1,69 @@
package dev.caskeleton.composition.runtime.authorization;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException;
import dev.caskeleton.application.security.RequiresPermission;
import org.aopalliance.intercept.MethodInterceptor;
import org.junit.jupiter.api.Test;
import org.springframework.aop.Advisor;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.aop.support.annotation.AnnotationMatchingPointcut;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
class PermissionEnforcementGuardTest {
private final ApplicationContextRunner runner =
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(PermissionEnforcementConfig.class));
@Test
void aGatedBeanWithNoEnforcingAdvisorFailsStartup() {
runner
.withUserConfiguration(GatedUseCaseConfig.class)
.run(
context ->
assertThat(context.getStartupFailure())
.isInstanceOf(StartupFailureException.class)
.hasMessageContaining("no advisor enforces it")
.hasMessageContaining(GatedUseCase.class.getName()));
}
@Test
void aGatedBeanWithAnAdvisorThatMatchesItStarts() {
runner
.withUserConfiguration(GatedUseCaseConfig.class, EnforcingAdvisorConfig.class)
.run(context -> assertThat(context).hasNotFailed().hasSingleBean(GatedUseCase.class));
}
@Test
void aContextWithoutGatedBeansNeedsNoAdvisor() {
runner.run(context -> assertThat(context).hasNotFailed());
}
@RequiresPermission("thing:write")
public static class GatedUseCase {
public void handle() {}
}
@Configuration(proxyBeanMethods = false)
static class GatedUseCaseConfig {
@Bean
GatedUseCase gatedUseCase() {
return new GatedUseCase();
}
}
@Configuration(proxyBeanMethods = false)
static class EnforcingAdvisorConfig {
@Bean
static Advisor enforcingAdvisor() {
return new DefaultPointcutAdvisor(
AnnotationMatchingPointcut.forClassAnnotation(RequiresPermission.class),
(MethodInterceptor) invocation -> invocation.proceed());
}
}
}