fix!: 재리뷰가 찾은 결함과 색인에서 빠졌던 발견 5건을 고친다
문제: 성숙도 리뷰 수정을 다시 읽은 재리뷰(Critical 0, 회귀 0)가 Important 27건·Minor 41건을 찾았다. 수정이 새로 만든 결함이 많았다. @SystemInvoked가 권한 규칙의 탈출구가 됐고, 데모 계정 거부가 정확히 prod일 때만 걸렸고, outbox 순서 번호가 업그레이드 때 뒤로 갔고, GraphQL union 아래 복잡도가 0이었고, 서블릿 오류 응답이 success:true로 나갔고, 호출자 deadline이 breaker를 열었다. 원래 리뷰 색인이 06 영역 발견 5건(06-10~14)을 빠뜨려 그동안 처리되지 않았다. 방법: 영역별 7묶음이 test-driven-development 절차로 실패 테스트를 먼저 쓰고 고쳤다. 결정은 재리뷰 README 4절에 적었다: 순서 번호는 V21이 기록한 전역 floor부터, 데모 계정은 local·test·demo 허용 목록, @SystemInvoked bean은 기동 실패, complete 단계 실패는 IDEMPOTENCY_COMPLETION_UNKNOWN(결과 불명), 캐시 조건부 쓰기는 별도 SCRIPT lane, strict lane 정책은 build cache 입력, 끝나지 않는 재시도 행은 원인 코드·지표·PARKED 절차. 레지스트리가 선언만 하고 아무 코드도 내보내지 않던 redis.capability.* 지표 6개는 빼고 runbook을 실제 지표(redis.lane.*) 기준으로 고쳤다. 위험·한계: V21을 V22 없이 직접 고쳤다(어느 배포에도 아직 없음). 이 브랜치의 V21을 적용한 개발 DB는 다시 만들어야 한다. 서블릿 오류 디스패치를 보안 체인이 허용한다. 발행·저장소 포트 시그니처가 바뀌어 파생 서비스 코드가 깨진다. prod에서 fixture-로 시작하는 설정값은 기동을 막는다. httpclient failure-injection lane의 main 단계 중복 실행은 이전 결정대로 남겼다. 실제 CI runner 실행은 확인하지 못했다. 검증: ci, mainCheck, :integrationCheck, -p optional-platforms ci integrationCheck performanceCheck, :performanceCheck, :releaseCheck (-PgitRevision), verify-compose-profile-contracts(18 lane) 통과. 첫 실행의 실패 2건(FindSecBugs 1, sample 동시 생성 테스트의 v4 event id)은 고친 뒤 ci·integrationCheck·mainCheck를 다시 돌려 통과했다. Refs: docs/reviews/2026-11-03-rereview/README.md 3·4·6·7절 BREAKING CHANGE: outbox 발행 포트와 저장소 포트 시그니처, 순서 번호 첫 값(V21 floor 다음), 샘플 데모 계정 프로필 허용 목록, 새 오류 코드 IDEMPOTENCY_COMPLETION_UNKNOWN, prod의 fixture- 값 거부, 기동 rule은 static·의존 없음이어야 한다.
This commit is contained in:
+5
-2
@@ -6,6 +6,7 @@ import dev.caskeleton.application.fileserver.api.metadata.FileQuotaPort;
|
||||
import dev.caskeleton.application.fileserver.api.metadata.UploadSessionPort;
|
||||
import dev.caskeleton.application.fileserver.api.security.FileAccessPolicyPort;
|
||||
import dev.caskeleton.application.fileserver.cleanup.CleanupQueuePort;
|
||||
import dev.caskeleton.application.fileserver.cleanup.QuotaReclaimPort;
|
||||
import dev.caskeleton.application.fileserver.download.DescribeFileApplicationUseCase;
|
||||
import dev.caskeleton.application.fileserver.download.DownloadContentPort;
|
||||
import dev.caskeleton.application.fileserver.download.OpenDownloadContentApplicationUseCase;
|
||||
@@ -120,10 +121,12 @@ class FileserverFileUseCaseConfiguration {
|
||||
@ConditionalOnMissingBean
|
||||
MoveFileUseCase fileserverMoveFile(
|
||||
FileMetadataPort metadataStore,
|
||||
FileAccessPolicyPort accessPolicy,
|
||||
UploadPolicies policies,
|
||||
TargetNamespacePolicy targetNamespaces,
|
||||
FileQuotaPort quotaService,
|
||||
QuotaReclaimPort quotaReclaim,
|
||||
TransactionPort transactions) {
|
||||
return new MoveFileApplicationUseCase(
|
||||
metadataStore, accessPolicy, targetNamespaces, transactions);
|
||||
metadataStore, policies, targetNamespaces, quotaService, quotaReclaim, transactions);
|
||||
}
|
||||
}
|
||||
|
||||
+14
-1
@@ -2,6 +2,7 @@ package dev.caskeleton.composition.idempotency;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.support.StrictSettingsBinder;
|
||||
import dev.caskeleton.adapter.outbound.support.startup.StartupFailures;
|
||||
import dev.caskeleton.application.idempotency.IdempotencyExecutor;
|
||||
import java.time.Duration;
|
||||
import java.util.Set;
|
||||
import org.springframework.core.env.Environment;
|
||||
@@ -17,7 +18,9 @@ import org.springframework.core.env.Environment;
|
||||
* instead of leaving its default silently in force.
|
||||
*
|
||||
* @param provider which store is composed: {@code disabled}, {@code redis} or {@code postgresql}
|
||||
* @param processingLease how long one attempt holds a claim before another may take it over
|
||||
* @param processingLease how long one attempt holds a claim before another may take it over; longer
|
||||
* than the in-flight 409's {@code Retry-After} ({@link
|
||||
* IdempotencyExecutor#IN_FLIGHT_RETRY_AFTER})
|
||||
* @param replayTtl how long a completed response is replayable (at most 72h, D6)
|
||||
* @param failureRetention how long a failed attempt's evidence is kept
|
||||
* @param responseCodecId identifier of the codec the stored payload is written with
|
||||
@@ -49,6 +52,16 @@ public record IdempotencySettings(
|
||||
"processing-lease",
|
||||
orDefault(processingLease, Duration.ofSeconds(30)),
|
||||
MAX_PROCESSING_LEASE);
|
||||
// A duplicate is told to come back after IN_FLIGHT_RETRY_AFTER. With a lease no longer than
|
||||
// that, the resend always arrives after the attempt it was waiting for has lost its claim.
|
||||
if (processingLease.compareTo(IdempotencyExecutor.IN_FLIGHT_RETRY_AFTER) <= 0) {
|
||||
throw StartupFailures.envValidation(
|
||||
PREFIX
|
||||
+ ".processing-lease must be longer than "
|
||||
+ IdempotencyExecutor.IN_FLIGHT_RETRY_AFTER
|
||||
+ " (the in-flight Retry-After), was "
|
||||
+ processingLease);
|
||||
}
|
||||
replayTtl = bounded("replay-ttl", orDefault(replayTtl, Duration.ofHours(24)), MAX_REPLAY_TTL);
|
||||
failureRetention =
|
||||
bounded(
|
||||
|
||||
+25
@@ -151,6 +151,31 @@ class IdempotencySettingsTest {
|
||||
.hasMessageContaining("app.capabilities.idempotency." + message);
|
||||
}
|
||||
|
||||
/**
|
||||
* The in-flight 409 tells the client to come back after {@code Retry-After} (2 seconds). A lease
|
||||
* no longer than that sends every resend past the attempt it was meant to wait for, so the rule
|
||||
* fails startup rather than living in prose (re-review 2026-11-03, RR-02-05).
|
||||
*/
|
||||
@ParameterizedTest
|
||||
@CsvSource({"PT1S", "PT2S"})
|
||||
@DisplayName("processing-lease 가 처리 중 409 의 Retry-After 이하면 기동을 거부한다")
|
||||
void aProcessingLeaseNoLongerThanTheInFlightRetryAfterIsRefused(Duration lease) {
|
||||
// when
|
||||
Throwable thrown =
|
||||
catchThrowable(
|
||||
() ->
|
||||
new IdempotencySettings(
|
||||
IdempotencySettings.Provider.REDIS, lease, null, null, null, null, null));
|
||||
|
||||
// then
|
||||
assertThat(thrown)
|
||||
.isInstanceOfSatisfying(
|
||||
StartupFailureException.class,
|
||||
e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
|
||||
.hasMessageContaining(
|
||||
"app.capabilities.idempotency.processing-lease must be longer than PT2S");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"'', response-codec-id must contain 1-64 characters", "' ', response-codec-id"})
|
||||
void blankCodecIdIsRefused(String codecId, String message) {
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
# composition:outbox-relay
|
||||
|
||||
- Module ID `composition-outbox-relay`, Gradle path `:composition:outbox-relay`. Registry SSOT:
|
||||
`src/config/architecture/modules.json`.
|
||||
- Responsibility: assemble and drive the application's outbox relay. It builds
|
||||
`PublishPendingOutboxEventsUseCase` by hand from `app.outbox.*` (`OutboxSettings`, strict binding),
|
||||
runs it from `OutboxRelayScheduler` (fixed-delay ticks, a `SmartLifecycle` that stops above the
|
||||
messaging platform's admission phase), and owns the outbox metrics (`OutboxMetrics`: gauges on a
|
||||
thread of their own, the cycle-outcome counter from the relay).
|
||||
- Boundaries: it names ports only — `OutboxStorePort`, `OutboxMessagePublishPort`,
|
||||
`OutboxRelayFailureReportPort`, `TransactionPort` — never a module type, so removing the
|
||||
persistence or messaging line removes the relay. No business rule, no SQL, no broker type. The
|
||||
relay use case is never a bean (`@SystemInvoked`, no permission gate). Allowed edges come only from
|
||||
the registry entry.
|
||||
- Startup refusals live here because only here do the settings meet the ports: a batch whose worst
|
||||
case (`batch-size` × the publish port's `longestAttempt`) reaches `in-flight-timeout` fails startup.
|
||||
- Tests: `./gradlew :composition:outbox-relay:check`. The shutdown order is pinned against the
|
||||
platform's own phase constant (`OutboxRelayShutdownOrderTest`); the end-to-end relay → bridge → real
|
||||
Kafka path is `:adapter:outbound:messaging-kafka:messagingKafkaRelayIntegrationTest`.
|
||||
- Design and rejected alternatives: `README.md`. Operations: `docs/runbooks/outbox-publish-failed.md`,
|
||||
`docs/runbooks/outbox-dead-letter.md`.
|
||||
@@ -18,12 +18,15 @@ composition:outbox-relay
|
||||
│ PublishPendingOutboxEventsUseCase 를 fixed-delay 로 구동,
|
||||
│ 발행이 이어지는 동안 한 tick 안에서 바로 다시 claim(최대 50회차),
|
||||
│ 종료 때 platform보다 먼저 멈추고 남은 claim을 놓음(SmartLifecycle)
|
||||
├─ OutboxMetrics outbox.pending.size / outbox.publisher.lag(relay와 무관하게
|
||||
│ poll 주기마다 갱신) / published.total(relay 회차 결과)
|
||||
├─ OutboxRelayOffWarning 발행 포트가 있는데 relay가 꺼져 있으면 기동 시 WARN 한 줄
|
||||
└─ OutboxLeaderElectionToken SKIP LOCKED 가 리더 선출이라는 표시(로직 없음)
|
||||
├─ OutboxMetrics outbox.pending.size / outbox.publisher.lag / outbox.retry.long.*
|
||||
│ (자기 스레드에서 poll 주기마다 갱신) / published.total(relay 회차 결과)
|
||||
└─ OutboxRelayOffWarning 발행 포트가 있는데 relay가 꺼져 있으면 기동 시 WARN 한 줄
|
||||
```
|
||||
|
||||
여러 인스턴스가 함께 relay를 돌려도 조정자는 없다. claim SQL의 `FOR UPDATE SKIP LOCKED`가 인스턴스마다
|
||||
겹치지 않는 행을 주고, lease token이 늦은 완료를 막는다(`PostgreSqlOutboxClaimRepository`, V17). 리더를
|
||||
뽑지 않는다.
|
||||
|
||||
- 조립 순서: `PersistenceJpaAutoConfiguration`(store)과 `MessagingBridgeRootAutoConfiguration`(발행
|
||||
포트) 뒤에 온다(`afterName`, 문자열이라 컴파일 의존이 없다). 둘 다 포트라서 이 모듈은 어떤 모듈
|
||||
타입도 이름으로 부르지 않는다.
|
||||
@@ -73,7 +76,8 @@ poll 주기·batch 크기·in-flight timeout·보존 기간은 env 키 없이 `a
|
||||
relay 생성자에 전달한다.
|
||||
- **릴레이 use case 를 독립 컨텍스트 빈으로 등록하지 않는다.** relay는 스케줄러만 부르는
|
||||
`@SystemInvoked` 유스케이스라 권한 선언이 없다. 빈으로 올리면 전송 계층이 권한 검사 없이 닿을
|
||||
수 있다. 스케줄러 스레드에는 `Authentication`이 없으므로 권한 게이트를 달아도 매 틱 거부될 뿐이다.
|
||||
수 있으므로, 빈으로 등록된 `@SystemInvoked` 유스케이스는 `composition:service-runtime`의
|
||||
`PermissionEnforcementGuard`가 기동을 실패시킨다. 스케줄러 스레드에는 `Authentication`이 없으므로 권한 게이트를 달아도 매 틱 거부될 뿐이다.
|
||||
- **`outboxRelayScheduler` 빈은 `app.outbox.relay-enabled=true`일 때만 만든다(기본
|
||||
false).** 키가 없으면 꺼진 것으로 본다. 모듈 기본값(`persistence-jpa.yml`의
|
||||
`${APP_OUTBOX_RELAY_ENABLED:false}`), `@ConditionalOnProperty`, `OutboxSettings`의 null 기본값이
|
||||
@@ -90,28 +94,31 @@ poll 주기·batch 크기·in-flight timeout·보존 기간은 env 키 없이 `a
|
||||
코드다. driven adapter인 persistence-jpa가 use case를 만들거나 호출하면
|
||||
`PERSISTENCE_DOES_NOT_DEPEND_ON_APPLICATION_SERVICES` 규칙 위반이다. 모듈 타입은 하나도 이름으로
|
||||
부르지 않고 포트만 쓰므로, persistence-jpa 한 줄을 지우면 릴레이도 함께 꺼진다.
|
||||
- **`outboxLeaderElection` 토큰 빈은 outbox capability 안에서 조건 없이 등록한다.** SKIP LOCKED 는
|
||||
멀티 인스턴스 전역 스위치와 무관하게 outbox relay 자체의 리더십/claim 메커니즘이라, outbox가 켜진
|
||||
상태에서 별도 하위 토글로 끌 수 있게 만들지 않는다. 이 토큰은 outbox 조립의 자기 설명용 marker이지
|
||||
`APP_MULTI_INSTANCE_ENABLED`의 전역 필수 빈이 아니다.
|
||||
- **`outboxLeaderElection` 토큰 빈은 지웠다(리뷰 2026-11-01 06-13).** 로직 없는 marker였고, Javadoc은
|
||||
"있기만 하면 멀티 인스턴스 조정 요구를 채운다"고 했지만 그 빈을 요구하는 검사도, 리더 선출도 없었다
|
||||
(claim은 행 단위다). 버린 대안: 이름을 실제 동작(`OutboxClaimStrategy`)으로 바꾸기 — 여전히 아무도
|
||||
읽지 않는 marker다. 동작 설명은 위 트리 아래 문단과 `PostgreSqlOutboxClaimRepository`에 있다.
|
||||
- **relay 조립은 배치가 lease 안에 다 나가는지 확인한다(06-12).** 한 회차는 batch 전체를 lease 하나로
|
||||
잡고 차례로 발행한다. `batch-size` × 발행 포트의 `longestAttempt()`(bridge: platform 발행 기한의 두 배,
|
||||
기본 10초)가 `in-flight-timeout` 이상이면 기동을 거부한다. lease가 먼저 끝나면 다른 인스턴스가 같은 행을
|
||||
다시 보내기 때문이다(fencing은 상태 덮어쓰기만 막는다). 기본값은 20 × 10초 = 200초 < 5분이다. 포트가
|
||||
최악 시간을 모르면(`Optional.empty()`) 검사하지 않는다. 버린 대안: relay가 회차 중 남은 lease를 보고
|
||||
남은 행을 놓기 — 설정 실수를 운영 중 중복 대신 기동 실패로 드러내는 쪽을 골랐다.
|
||||
- **`outboxMetrics` 빈은 `MeterRegistry`가 없을 때 no-op 이다.** Actuator 가 클래스패스에 없는
|
||||
환경에서도 와이어링이 깨지지 않도록 `ObjectProvider`로 레지스트리를 선택적으로 주입한다.
|
||||
|
||||
### OutboxLeaderElectionToken
|
||||
- **로직이 전혀 없는 마커(documentation artifact) 빈이다.** 이 타입은 동작을 갖지 않고, Spring
|
||||
컨텍스트에 존재한다는 사실만으로 멀티 인스턴스 조정 빈 요구사항을 충족시킨다.
|
||||
- **리더 선출을 외부 코디네이터 없이 PostgreSQL `FOR UPDATE SKIP LOCKED`로 구현한다는 것을
|
||||
표현한다.** claim 쿼리에 SKIP LOCKED 를 걸면 각 릴레이 인스턴스가 서로 겹치지 않는(disjoint) 행
|
||||
집합을 가져가므로, 별도 코디네이터 없이도 "각 인스턴스가 자기 파티션의 리더" 형태로 리더 선출
|
||||
의미가 성립한다.
|
||||
|
||||
### OutboxMetrics
|
||||
- **`MeterRegistry`가 없으면 모든 메트릭 연산이 no-op 이다.** Actuator 가 없는 환경에서도 릴레이가
|
||||
정상 동작해야 하므로, 생성자에서 `ObjectProvider`로 레지스트리를 조회해 없으면 게이지도 만들지
|
||||
않고 기록도 건너뛴다.
|
||||
- **카운터는 PUBLISHED/FAILED/DEAD 만 집계하고 IN_FLIGHT 는 제외한다.** IN_FLIGHT 는 릴레이 사이클의
|
||||
종료 결과(terminal outcome)가 아니라 처리 중을 나타내는 일시적 상태라 카운터 outcome 으로 의미가
|
||||
없다.
|
||||
- **카운터 outcome은 relay 회차 결과(`OutboxRelayResult.Outcome`) 다섯 값이다: PUBLISHED, FAILED, DEAD,
|
||||
STALE, RELEASED.** IN_FLIGHT는 행 상태이지 회차 결과가 아니라 세지 않는다. `docs/registries/metrics.yaml`의
|
||||
허용 값과 enum이 같은지 `OutboxStatusRegistryContractTest`가 비교한다(재리뷰 2026-11-03 RR-05-06).
|
||||
- **오래 재시도 중인 행을 따로 센다(RR-05-03).** 응답 없음·지금만 거부는 시도 예산을 쓰지 않아 끝이 없다.
|
||||
`outbox.retry.long.size`는 미룬 claim이 `LONG_RETRY_DEFERRED_CLAIMS`(10)번 이상인 FAILED 행 수,
|
||||
`outbox.retry.long.age`는 그중 가장 오래된 행의 나이다. 10번은 backoff 상한 5분 기준으로 적어도 약 35분
|
||||
동안 실패했다는 뜻이라 broker 재시작·credential 교체는 넘긴다. publish-failed runbook §4.1의 조회가 같은
|
||||
기준을 쓴다.
|
||||
- **MultiGauge 갱신 시 `overwrite=true`로 등록한다.** 매 스케줄러 틱마다 store 를 다시 조회해
|
||||
게이지를 갱신하는데, 이전 틱에 있었지만 지금은 사라진 event type 같은 오래된 time-series 태그를
|
||||
덮어써 제거하기 위함이다.
|
||||
@@ -151,13 +158,18 @@ poll 주기·batch 크기·in-flight timeout·보존 기간은 env 키 없이 `a
|
||||
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 관계 확인)나
|
||||
1,000행을 보내고 다음 tick까지 5초 쉰다. 넘는 처리량이 필요하면 batch-size(06-12: lease보다 길면 기동이 거부된다)나
|
||||
인스턴스 수로 늘린다.
|
||||
- 버린 대안: poll 주기만 줄이기 — 빈 tick마다 claim·지표 질의가 는다.
|
||||
- **지표 게이지는 relay와 따로 갱신한다(06-05).** `outbox.pending.size`·`outbox.publisher.lag`는
|
||||
`OutboxMetrics.refreshGauges`가 poll 주기마다 갱신한다(`@Scheduled`, relay가 꺼져 있어도, 회차가 매번
|
||||
예외로 끝나도). 예전에는 relay 회차 안에서만 갱신되어, relay가 꺼진 배포(기본값)나 매 회차 실패하는
|
||||
장애에서 게이지가 멈췄고 `outbox_publisher_lag` 경보가 울리지 않았다. 카운터
|
||||
- **지표 게이지는 relay와 따로, 자기 스레드에서 갱신한다(06-05, RR-05-05).** `outbox.pending.size`·
|
||||
`outbox.publisher.lag`·`outbox.retry.long.*`는 `OutboxMetrics`가 poll 주기마다 갱신한다(relay가 꺼져
|
||||
있어도, 회차가 매번 예외로 끝나도). 예전에는 relay 회차 안에서만 갱신되어, relay가 꺼진 배포(기본값)나
|
||||
매 회차 실패하는 장애에서 게이지가 멈췄다. 그다음에는 `@Scheduled`로 떼었지만 Spring의 fixed-delay 작업은
|
||||
모두 스레드 하나(virtual thread면 `SimpleAsyncTaskScheduler`의 fixedDelayExecutor, 아니면 pool 1)에서
|
||||
줄을 서서, relay tick이 50회차를 도는 동안(느린 broker면 몇 분) 게이지가 기다렸다 — 적체를 봐야 할 바로
|
||||
그때다. 지금은 `OutboxMetrics`가 `SmartLifecycle`로 자기 단일 daemon 스레드(`outbox-gauges`)를 시작하고
|
||||
멈춘다. 버린 대안: tick 상한을 회차 수 대신 시간으로 — 게이지가 여전히 relay 뒤에 줄을 선다. Micrometer
|
||||
지연 조회 gauge — scrape마다 DB 질의가 나가고, event type별 series를 덮어쓸 수 없다. 카운터
|
||||
`outbox.publisher.published.total`은 회차 결과로 relay가 기록한다. 발행 포트가 있는데 relay가 꺼져
|
||||
있으면 `OutboxRelayOffWarning`이 기동 시 WARN 한 줄을 남긴다(별도 worker 배포가 relay를 돌리는 구성도
|
||||
있으므로 기동 실패로 만들지 않았다).
|
||||
|
||||
-21
@@ -1,21 +0,0 @@
|
||||
package dev.caskeleton.composition.outbox;
|
||||
|
||||
/**
|
||||
* Marker bean: presence in the context satisfies the multi-instance coordination requirement (no
|
||||
* logic; SKIP LOCKED is the leadership mechanism). See README for the design rationale.
|
||||
*/
|
||||
public final class OutboxLeaderElectionToken {
|
||||
|
||||
private static final String STRATEGY_DESCRIPTION =
|
||||
"SKIP LOCKED claim — each relay instance claims a disjoint row partition; "
|
||||
+ "no external coordinator required (PostgreSQL FOR UPDATE SKIP LOCKED, I3/D8)";
|
||||
|
||||
public String strategyDescription() {
|
||||
return STRATEGY_DESCRIPTION;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "OutboxLeaderElectionToken{strategy=SKIP_LOCKED}";
|
||||
}
|
||||
}
|
||||
+130
-16
@@ -1,49 +1,91 @@
|
||||
package dev.caskeleton.composition.outbox;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.support.startup.RuntimeWarnings;
|
||||
import dev.caskeleton.application.outbox.OutboxBackoffPolicy;
|
||||
import dev.caskeleton.application.outbox.OutboxEventStatus;
|
||||
import dev.caskeleton.application.outbox.OutboxLongRetries;
|
||||
import dev.caskeleton.application.outbox.OutboxRelayResult;
|
||||
import dev.caskeleton.application.outbox.OutboxStorePort;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Gauge;
|
||||
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.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.context.SmartLifecycle;
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* <p>The gauges ({@code outbox.pending.size}, {@code outbox.publisher.lag}, {@code
|
||||
* outbox.retry.long.size}, {@code outbox.retry.long.age}) refresh every poll interval on a thread
|
||||
* of their own, not from the relay and not on the scheduler the relay runs on. They are how an
|
||||
* operator sees rows piling up, and rows pile up exactly when the relay is off — it is by default —
|
||||
* when every cycle throws, or when the broker is slow: a relay tick runs up to {@link
|
||||
* OutboxRelayScheduler#MAX_CYCLES_PER_TICK} cycles back to back, and every fixed-delay task of the
|
||||
* application scheduler waits behind it on one thread (review 06-05, re-review 2026-11-03
|
||||
* RR-05-05). The counter ({@code outbox.publisher.published.total}) is still recorded by the relay,
|
||||
* from each cycle's outcomes.
|
||||
*/
|
||||
public final class OutboxMetrics {
|
||||
public final class OutboxMetrics implements SmartLifecycle {
|
||||
|
||||
/**
|
||||
* How many deferred claims make a FAILED row long-retrying. A deferred claim does not spend the
|
||||
* attempt budget, so such a row is retried until someone looks; ten of them, with the backoff
|
||||
* capped at {@link OutboxBackoffPolicy#MAX_DELAY}, is at least about 35 minutes of failing — past
|
||||
* any broker restart or credential rotation. The publish-failed runbook's query uses the same
|
||||
* number.
|
||||
*/
|
||||
static final int LONG_RETRY_DEFERRED_CLAIMS = 10;
|
||||
|
||||
private static final String COUNTER_NAME = "outbox.publisher.published.total";
|
||||
private static final String SIZE_GAUGE = "outbox.pending.size";
|
||||
private static final String LAG_GAUGE = "outbox.publisher.lag";
|
||||
private static final String LONG_RETRY_SIZE_GAUGE = "outbox.retry.long.size";
|
||||
private static final String LONG_RETRY_AGE_GAUGE = "outbox.retry.long.age";
|
||||
|
||||
private final OutboxStorePort store;
|
||||
private final Clock clock;
|
||||
private final Duration refreshInterval;
|
||||
private final MeterRegistry registry; // null when no Actuator on classpath
|
||||
private final MultiGauge pendingSizeGauge;
|
||||
private final MultiGauge publisherLagGauge;
|
||||
private final AtomicLong longRetryRows = new AtomicLong();
|
||||
private final AtomicLong longRetryOldestAge = new AtomicLong();
|
||||
|
||||
private final Object monitor = new Object();
|
||||
private ScheduledExecutorService refresher;
|
||||
private ScheduledFuture<?> refreshing;
|
||||
|
||||
/**
|
||||
* Creates the collector.
|
||||
*
|
||||
* @param store the outbox store the gauges read
|
||||
* @param meterRegistryProvider the registry, when Actuator is present
|
||||
* @param clock wall clock for the age gauges
|
||||
* @param refreshInterval how often the gauges refresh once started; the relay's poll interval
|
||||
*/
|
||||
public OutboxMetrics(
|
||||
OutboxStorePort store, ObjectProvider<MeterRegistry> meterRegistryProvider, Clock clock) {
|
||||
OutboxStorePort store,
|
||||
ObjectProvider<MeterRegistry> meterRegistryProvider,
|
||||
Clock clock,
|
||||
Duration refreshInterval) {
|
||||
this.store = store;
|
||||
this.clock = clock;
|
||||
this.refreshInterval = Objects.requireNonNull(refreshInterval, "refreshInterval");
|
||||
this.registry = meterRegistryProvider.getIfAvailable();
|
||||
|
||||
if (this.registry != null) {
|
||||
@@ -56,13 +98,26 @@ public final class OutboxMetrics {
|
||||
.description("Age in seconds of the oldest unpublished row per event type")
|
||||
.baseUnit("seconds")
|
||||
.register(this.registry);
|
||||
Gauge.builder(LONG_RETRY_SIZE_GAUGE, longRetryRows, AtomicLong::get)
|
||||
.description(
|
||||
"FAILED outbox rows deferred at least "
|
||||
+ LONG_RETRY_DEFERRED_CLAIMS
|
||||
+ " times: retried without end until someone looks")
|
||||
.register(this.registry);
|
||||
Gauge.builder(LONG_RETRY_AGE_GAUGE, longRetryOldestAge, AtomicLong::get)
|
||||
.description("Age in seconds of the oldest long-retrying outbox row; 0 when none")
|
||||
.baseUnit("seconds")
|
||||
.register(this.registry);
|
||||
} else {
|
||||
this.pendingSizeGauge = null;
|
||||
this.publisherLagGauge = null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Counts each per-event outcome (PUBLISHED, FAILED, DEAD, STALE; never IN_FLIGHT). */
|
||||
/**
|
||||
* Counts each per-event outcome of a relay cycle: PUBLISHED, FAILED, DEAD, STALE and RELEASED.
|
||||
* IN_FLIGHT is a row status, never a cycle outcome.
|
||||
*/
|
||||
public void recordRelayResult(OutboxRelayResult result) {
|
||||
if (registry == null || result == null) {
|
||||
return;
|
||||
@@ -84,11 +139,9 @@ 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.
|
||||
* Refreshes the gauges once. Store failures are contained per gauge (a WARN through {@link
|
||||
* RuntimeWarnings}), so a database outage leaves the refresh thread alive for the next one.
|
||||
*/
|
||||
@Scheduled(fixedDelayString = "${app.outbox.poll-interval:PT5S}")
|
||||
public void refreshGauges() {
|
||||
refresh(clock.instant());
|
||||
}
|
||||
@@ -97,7 +150,7 @@ public final class OutboxMetrics {
|
||||
* Uses {@code overwrite=true} so stale time-series tags from removed event types are replaced
|
||||
* rather than left dangling.
|
||||
*
|
||||
* @param now current wall-clock instant (for the lag gauge age computation)
|
||||
* @param now current wall-clock instant (for the age gauges)
|
||||
*/
|
||||
public void refresh(Instant now) {
|
||||
if (registry == null) {
|
||||
@@ -105,6 +158,57 @@ public final class OutboxMetrics {
|
||||
}
|
||||
refreshPendingSize();
|
||||
refreshPublisherLag(now);
|
||||
refreshLongRetries(now);
|
||||
}
|
||||
|
||||
/** Starts the gauges' own refresh thread; nothing to start without a registry. */
|
||||
@Override
|
||||
public void start() {
|
||||
synchronized (monitor) {
|
||||
if (registry == null || refresher != null) {
|
||||
return;
|
||||
}
|
||||
refresher =
|
||||
Executors.newSingleThreadScheduledExecutor(
|
||||
task -> {
|
||||
Thread thread = new Thread(task, "outbox-gauges");
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
});
|
||||
// A periodic task that throws is never run again, silently; each gauge already contains its
|
||||
// own store failure, and anything else is contained here so the next refresh still happens.
|
||||
refreshing =
|
||||
refresher.scheduleWithFixedDelay(
|
||||
() -> {
|
||||
try {
|
||||
refreshGauges();
|
||||
} catch (RuntimeException unexpected) {
|
||||
RuntimeWarnings.meterUnavailable("outbox", "gauge refresh", unexpected);
|
||||
}
|
||||
},
|
||||
0,
|
||||
refreshInterval.toMillis(),
|
||||
TimeUnit.MILLISECONDS);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
synchronized (monitor) {
|
||||
if (refresher != null) {
|
||||
refreshing.cancel(true);
|
||||
refresher.shutdownNow();
|
||||
refresher = null;
|
||||
refreshing = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isRunning() {
|
||||
synchronized (monitor) {
|
||||
return refresher != null;
|
||||
}
|
||||
}
|
||||
|
||||
private void refreshPendingSize() {
|
||||
@@ -138,4 +242,14 @@ public final class OutboxMetrics {
|
||||
RuntimeWarnings.meterUnavailable("outbox", "publisher-lag gauge", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private void refreshLongRetries(Instant now) {
|
||||
try {
|
||||
OutboxLongRetries longRetries = store.longRetries(LONG_RETRY_DEFERRED_CLAIMS, now);
|
||||
longRetryRows.set(longRetries.rows());
|
||||
longRetryOldestAge.set(longRetries.oldestAgeSeconds());
|
||||
} catch (Exception ex) {
|
||||
RuntimeWarnings.meterUnavailable("outbox", "long-retry gauges", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+14
-11
@@ -20,8 +20,8 @@ import org.springframework.core.env.Environment;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
|
||||
/**
|
||||
* The transactional outbox relay: assembles the relay use case manually and registers the leader
|
||||
* election token, metrics, and scheduler.
|
||||
* The transactional outbox relay: assembles the relay use case manually and registers its metrics
|
||||
* and scheduler.
|
||||
*
|
||||
* <p>Application composition: it wires application-core ports into a use case and drives it on a
|
||||
* timer, which is why it is a composition module rather than part of the persistence module — a
|
||||
@@ -71,6 +71,9 @@ public class OutboxRelayAutoConfiguration {
|
||||
RandomGenerator outboxRandomGenerator,
|
||||
OutboxSettings properties,
|
||||
OutboxMetrics metrics) {
|
||||
// A batch that cannot be sent within its lease is sent twice; refused here, where the port that
|
||||
// knows how long a publish can take meets the settings (review 06-12).
|
||||
publishPort.longestAttempt().ifPresent(properties::requireLeaseOutlastsBatch);
|
||||
// One lease owner per relay instance. Its claims record it, and a completion applies only while
|
||||
// this owner's lease still holds the row (V17 fencing).
|
||||
PublishPendingOutboxEventsUseCase relayUseCase =
|
||||
@@ -93,22 +96,22 @@ public class OutboxRelayAutoConfiguration {
|
||||
return new SplittableRandom();
|
||||
}
|
||||
|
||||
/** Registered unconditionally so the SKIP LOCKED leadership mechanism is always present. */
|
||||
@Bean(name = "outboxLeaderElection")
|
||||
public OutboxLeaderElectionToken outboxLeaderElection() {
|
||||
return new OutboxLeaderElectionToken();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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}).
|
||||
* store is, relay or not: its gauges refresh every poll interval on a thread of their own (see
|
||||
* {@link OutboxMetrics}).
|
||||
*/
|
||||
@Bean
|
||||
public OutboxMetrics outboxMetrics(
|
||||
OutboxStorePort store,
|
||||
ObjectProvider<MeterRegistry> meterRegistryProvider,
|
||||
ObjectProvider<Clock> clock) {
|
||||
return new OutboxMetrics(store, meterRegistryProvider, clock.getIfAvailable(Clock::systemUTC));
|
||||
ObjectProvider<Clock> clock,
|
||||
OutboxSettings settings) {
|
||||
return new OutboxMetrics(
|
||||
store,
|
||||
meterRegistryProvider,
|
||||
clock.getIfAvailable(Clock::systemUTC),
|
||||
settings.pollInterval());
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+35
@@ -62,6 +62,41 @@ public record OutboxSettings(
|
||||
return StrictSettingsBinder.bind(environment, PREFIX, OutboxSettings.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses a batch whose worst case does not fit in its lease (review 2026-11-01 06-12).
|
||||
*
|
||||
* <p>A cycle claims {@link #batchSize()} rows under one lease of {@link #inFlightTimeout()} and
|
||||
* publishes them one after another. If every publish takes its longest, the last one starts
|
||||
* {@code batchSize × longestAttempt} after the claim; past the lease, another instance has
|
||||
* already reclaimed the row and sent it, and this one sends it again. The lease fence keeps the
|
||||
* row's status right, not the broker from seeing the event twice. Each value is fine on its own,
|
||||
* so only the pair can be checked, and it is checked when the relay is assembled — the publish
|
||||
* port is what knows how long an attempt can take.
|
||||
*
|
||||
* @param longestAttempt the longest one publish can take before its port answers
|
||||
* @throws dev.caskeleton.adapter.outbound.support.startup.StartupFailureException when the
|
||||
* batch's worst case reaches the lease
|
||||
*/
|
||||
public void requireLeaseOutlastsBatch(Duration longestAttempt) {
|
||||
Duration worstBatch = longestAttempt.multipliedBy(batchSize);
|
||||
if (worstBatch.compareTo(inFlightTimeout) >= 0) {
|
||||
throw StartupFailures.envValidation(
|
||||
PREFIX
|
||||
+ ".in-flight-timeout ("
|
||||
+ inFlightTimeout
|
||||
+ ") must be longer than "
|
||||
+ PREFIX
|
||||
+ ".batch-size ("
|
||||
+ batchSize
|
||||
+ ") times the longest publish ("
|
||||
+ longestAttempt
|
||||
+ "), "
|
||||
+ worstBatch
|
||||
+ ": a lease that ends before its batch is sent lets another instance send the same"
|
||||
+ " rows again — lower batch-size or raise in-flight-timeout");
|
||||
}
|
||||
}
|
||||
|
||||
private static Duration positive(String key, Duration value, Duration fallback) {
|
||||
if (value == null) {
|
||||
return fallback;
|
||||
|
||||
+88
-1
@@ -3,10 +3,14 @@ package dev.caskeleton.composition.outbox;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.awaitility.Awaitility.await;
|
||||
|
||||
import dev.caskeleton.application.outbox.OutboxLongRetries;
|
||||
import dev.caskeleton.application.outbox.OutboxMessagePublishPort;
|
||||
import dev.caskeleton.application.outbox.OutboxRelayFailureReportPort;
|
||||
import dev.caskeleton.application.outbox.OutboxStorePort;
|
||||
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 io.micrometer.core.instrument.MeterRegistry;
|
||||
import io.micrometer.core.instrument.search.Search;
|
||||
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
|
||||
@@ -14,6 +18,7 @@ import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -64,6 +69,83 @@ class OutboxMetricsTest {
|
||||
assertThat(pending(registry)).isEqualTo(2.0);
|
||||
}
|
||||
|
||||
/**
|
||||
* A relay tick can run fifty cycles back to back, and against a slow broker that takes minutes —
|
||||
* exactly when the backlog gauges matter. Refreshed on the scheduler's single fixed-delay thread,
|
||||
* they waited for the tick to end (re-review 2026-11-03 RR-05-05).
|
||||
*/
|
||||
@Test
|
||||
@DisplayName("relay tick이 발행 중에 멈춰 있어도 게이지는 그동안 쌓인 행을 보여 준다")
|
||||
void theGaugesRefreshWhileARelayTickIsStuckInAPublish() throws Exception {
|
||||
// given: a relay whose broker call blocks until the test lets it go
|
||||
InMemoryOutboxStore store = new InMemoryOutboxStore();
|
||||
store.append(OutboxEvents.event(UUID.randomUUID().toString(), Instant.now().minusSeconds(5)));
|
||||
java.util.concurrent.CountDownLatch publishing = new java.util.concurrent.CountDownLatch(1);
|
||||
java.util.concurrent.CountDownLatch release = new java.util.concurrent.CountDownLatch(1);
|
||||
OutboxMessagePublishPort stalled =
|
||||
event -> {
|
||||
publishing.countDown();
|
||||
try {
|
||||
release.await();
|
||||
} catch (InterruptedException interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
};
|
||||
SimpleMeterRegistry registry = new SimpleMeterRegistry();
|
||||
ApplicationContextRunner runner =
|
||||
new ApplicationContextRunner()
|
||||
.withConfiguration(AutoConfigurations.of(OutboxRelayAutoConfiguration.class))
|
||||
.withBean(OutboxStorePort.class, () -> store)
|
||||
.withBean(MeterRegistry.class, () -> registry)
|
||||
.withBean(OutboxMessagePublishPort.class, () -> stalled)
|
||||
.withBean(OutboxRelayFailureReportPort.class, () -> report -> {})
|
||||
.withBean(TransactionPort.class, DirectTransactionPort::new)
|
||||
.withBean(Clock.class, Clock::systemUTC)
|
||||
.withPropertyValues(
|
||||
"app.outbox.enabled=true",
|
||||
"app.outbox.relay-enabled=true",
|
||||
"app.outbox.poll-interval=PT0.05S");
|
||||
|
||||
// when: the tick is inside the broker call, and two more rows arrive
|
||||
runner.run(
|
||||
context -> {
|
||||
try {
|
||||
publishing.await(10, java.util.concurrent.TimeUnit.SECONDS);
|
||||
store.append(OutboxEvents.event(UUID.randomUUID().toString(), Instant.now()));
|
||||
store.append(OutboxEvents.event(UUID.randomUUID().toString(), Instant.now()));
|
||||
await()
|
||||
.atMost(Duration.ofSeconds(5))
|
||||
.until(() -> pending(registry) != null && pending(registry) == 2.0);
|
||||
} finally {
|
||||
release.countDown();
|
||||
}
|
||||
});
|
||||
|
||||
// then
|
||||
assertThat(pending(registry)).isEqualTo(2.0);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("오래 재시도 중인 행 게이지는 저장소가 센 행 수와 가장 오래된 행의 나이를 보여 준다")
|
||||
void theLongRetryGaugesShowTheStoresCountAndOldestAge() {
|
||||
// given
|
||||
OutboxStorePort store = Mockito.mock(OutboxStorePort.class);
|
||||
Mockito.when(store.longRetries(OutboxMetrics.LONG_RETRY_DEFERRED_CLAIMS, NOW))
|
||||
.thenReturn(new OutboxLongRetries(3, 7200));
|
||||
SimpleMeterRegistry registry = new SimpleMeterRegistry();
|
||||
OutboxMetrics metrics = metrics(store, registry);
|
||||
|
||||
// when
|
||||
metrics.refreshGauges();
|
||||
|
||||
// then
|
||||
assertThat(
|
||||
List.of(
|
||||
registry.get("outbox.retry.long.size").gauge().value(),
|
||||
registry.get("outbox.retry.long.age").gauge().value()))
|
||||
.containsExactly(3.0, 7200.0);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("게이지 갱신은 PUBLISHED를 세지 않고 지연 게이지는 가장 오래된 미발행 행의 나이다")
|
||||
void aRefreshCountsUnpublishedRowsAndAgesTheOldest() {
|
||||
@@ -97,6 +179,8 @@ class OutboxMetricsTest {
|
||||
Mockito.when(broken.countByStatus()).thenThrow(new IllegalStateException("database down"));
|
||||
Mockito.when(broken.oldestUnpublishedAgeSecondsByEventType(Mockito.any()))
|
||||
.thenThrow(new IllegalStateException("database down"));
|
||||
Mockito.when(broken.longRetries(Mockito.anyInt(), Mockito.any()))
|
||||
.thenThrow(new IllegalStateException("database down"));
|
||||
OutboxMetrics metrics = metrics(broken, new SimpleMeterRegistry());
|
||||
|
||||
// when
|
||||
@@ -160,6 +244,9 @@ class OutboxMetricsTest {
|
||||
StaticListableBeanFactory registries = new StaticListableBeanFactory();
|
||||
registries.addBean("meterRegistry", registry);
|
||||
return new OutboxMetrics(
|
||||
store, registries.getBeanProvider(MeterRegistry.class), Clock.fixed(NOW, ZoneOffset.UTC));
|
||||
store,
|
||||
registries.getBeanProvider(MeterRegistry.class),
|
||||
Clock.fixed(NOW, ZoneOffset.UTC),
|
||||
Duration.ofHours(1));
|
||||
}
|
||||
}
|
||||
|
||||
+32
@@ -2,6 +2,7 @@ package dev.caskeleton.composition.outbox;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import dev.caskeleton.application.outbox.OutboxMessagePublishPort;
|
||||
import dev.caskeleton.application.outbox.OutboxRelayFailureReportPort;
|
||||
@@ -9,7 +10,10 @@ import dev.caskeleton.application.outbox.OutboxStorePort;
|
||||
import dev.caskeleton.application.transaction.TransactionPort;
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.Optional;
|
||||
import java.util.random.RandomGenerator;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.AutoConfigurations;
|
||||
@@ -84,6 +88,34 @@ class OutboxRelayAutoConfigurationTest {
|
||||
.run(context -> assertThat(context).hasSingleBean(OutboxRelayScheduler.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("발행 포트가 말한 최악 발행 시간으로 한 배치가 lease를 넘으면 relay 조립이 기동을 거부한다")
|
||||
void aBatchThePublishPortCannotSendWithinTheLeaseFailsStartup() {
|
||||
// given: a port whose publish can take ten seconds, forty rows a batch, a five-minute lease
|
||||
OutboxMessagePublishPort tenSecondPublisher = mock(OutboxMessagePublishPort.class);
|
||||
when(tenSecondPublisher.longestAttempt()).thenReturn(Optional.of(Duration.ofSeconds(10)));
|
||||
ApplicationContextRunner runner =
|
||||
new ApplicationContextRunner()
|
||||
.withConfiguration(AutoConfigurations.of(OutboxRelayAutoConfiguration.class))
|
||||
.withBean(OutboxStorePort.class, OutboxRelayAutoConfigurationTest::unusedStore)
|
||||
.withBean(OutboxRelayFailureReportPort.class, () -> report -> {})
|
||||
.withBean(TransactionPort.class, () -> mock(TransactionPort.class))
|
||||
.withBean(Clock.class, Clock::systemUTC)
|
||||
.withBean(OutboxMessagePublishPort.class, () -> tenSecondPublisher)
|
||||
.withPropertyValues(
|
||||
"app.outbox.enabled=true",
|
||||
"app.outbox.relay-enabled=true",
|
||||
"app.outbox.batch-size=40",
|
||||
"app.outbox.in-flight-timeout=PT5M");
|
||||
|
||||
// when & then
|
||||
runner.run(
|
||||
context ->
|
||||
assertThat(context)
|
||||
.getFailure()
|
||||
.hasStackTraceContaining("app.outbox.in-flight-timeout"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void withoutTheRelayKeyTheRelaySchedulerIsNotAssembled() {
|
||||
new ApplicationContextRunner()
|
||||
|
||||
+2
-1
@@ -156,7 +156,8 @@ class OutboxRelaySchedulerDrainTest {
|
||||
new OutboxMetrics(
|
||||
store,
|
||||
registries.getBeanProvider(io.micrometer.core.instrument.MeterRegistry.class),
|
||||
clock));
|
||||
clock,
|
||||
Duration.ofHours(1)));
|
||||
}
|
||||
|
||||
/** The fake store with the claim SQL's per-aggregate head gate. */
|
||||
|
||||
+5
-4
@@ -166,15 +166,16 @@ class OutboxRelayShutdownOrderTest {
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized OutboxCompletion markFailed(OutboxLease lease, Instant nextAttemptAt) {
|
||||
OutboxCompletion completion = super.markFailed(lease, nextAttemptAt);
|
||||
public synchronized OutboxCompletion markFailed(
|
||||
OutboxLease lease, Instant nextAttemptAt, String failureCode) {
|
||||
OutboxCompletion completion = super.markFailed(lease, nextAttemptAt, failureCode);
|
||||
completed.set(true);
|
||||
return completion;
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized OutboxCompletion markDead(OutboxLease lease) {
|
||||
OutboxCompletion completion = super.markDead(lease);
|
||||
public synchronized OutboxCompletion markDead(OutboxLease lease, String failureCode) {
|
||||
OutboxCompletion completion = super.markDead(lease, failureCode);
|
||||
completed.set(true);
|
||||
return completion;
|
||||
}
|
||||
|
||||
+45
@@ -6,6 +6,7 @@ import static org.assertj.core.api.Assertions.catchThrowable;
|
||||
import dev.caskeleton.adapter.outbound.support.startup.StartupErrorCode;
|
||||
import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException;
|
||||
import java.time.Duration;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
@@ -99,4 +100,48 @@ class OutboxSettingsTest {
|
||||
e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
|
||||
.hasMessageContaining("app.outbox." + message);
|
||||
}
|
||||
|
||||
/**
|
||||
* A cycle holds every row of its batch under one lease while it publishes them one after another,
|
||||
* so the batch's worst case has to fit in the lease. Past it, another instance reclaims rows this
|
||||
* one is still going to send, and the event goes out twice (review 2026-11-01 06-12).
|
||||
*/
|
||||
@ParameterizedTest(name = "batch {0} x {1}s against a {2}s lease")
|
||||
@CsvSource({"40, 10, 300", "30, 10, 300", "20, 10, 120"})
|
||||
@DisplayName("한 배치를 다 보내는 최악 시간이 lease 이상인 설정은 기동을 거부한다")
|
||||
void aBatchWhoseWorstCaseReachesTheLeaseIsRefusedAtStartup(
|
||||
int batchSize, long longestAttemptSeconds, long leaseSeconds) {
|
||||
// given
|
||||
OutboxSettings settings =
|
||||
new OutboxSettings(
|
||||
true, true, null, batchSize, Duration.ofSeconds(leaseSeconds), null, null);
|
||||
|
||||
// when
|
||||
Throwable thrown =
|
||||
catchThrowable(
|
||||
() -> settings.requireLeaseOutlastsBatch(Duration.ofSeconds(longestAttemptSeconds)));
|
||||
|
||||
// then
|
||||
assertThat(thrown)
|
||||
.isInstanceOfSatisfying(
|
||||
StartupFailureException.class,
|
||||
failure ->
|
||||
assertThat(failure.errorCode())
|
||||
.isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
|
||||
.hasMessageContaining("app.outbox.in-flight-timeout");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("기본값(배치 20, 발행 최악 10초, lease 5분)은 기동을 막지 않는다")
|
||||
void theDefaultsLeaveTheLeaseLongerThanABatch() {
|
||||
// given
|
||||
OutboxSettings settings = new OutboxSettings(true, true, null, null, null, null, null);
|
||||
|
||||
// when
|
||||
Throwable thrown =
|
||||
catchThrowable(() -> settings.requireLeaseOutlastsBatch(Duration.ofSeconds(10)));
|
||||
|
||||
// then
|
||||
assertThat(thrown).isNull();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,7 +28,9 @@ composition:service-runtime
|
||||
선언만 남은 채 정상 기동했다. 이제 `PermissionEnforcementGuard`가 선언 빈마다 pointcut이 맞는
|
||||
advisor가 있는지 보고, 없으면 `REQUIRED_ADAPTER_DISABLED`(exit 72)로 기동을 멈춘다. 한계:
|
||||
"어떤 advisor든 pointcut이 맞으면 통과"라 인가가 아닌 advisor를 구분하지 못한다. `new`로 만든
|
||||
유스케이스는 검사 대상이 아니다(시스템 호출용은 `@SystemInvoked`).
|
||||
유스케이스는 검사 대상이 아니다(시스템 호출용은 `@SystemInvoked`). 반대로 `@SystemInvoked`
|
||||
유스케이스가 빈으로 등록돼 있으면 같은 가드가 기동을 멈춘다 — 권한 검사가 없는 쓰기를 전송 계층이
|
||||
닿는 곳에 두는 조립이기 때문이다(review 2026-11-03 RR-01-02).
|
||||
|
||||
- 모두 이 모듈의 `AutoConfiguration.imports`로 등록된다(설정 브리지와 tracing 스위치는
|
||||
`spring.factories`의 `EnvironmentPostProcessor`·`AutoConfigurationImportFilter`). 구성 루트의
|
||||
|
||||
+21
-5
@@ -2,6 +2,7 @@ package dev.caskeleton.composition.runtime.authorization;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.support.startup.StartupFailures;
|
||||
import dev.caskeleton.application.security.RequiresPermission;
|
||||
import dev.caskeleton.application.security.SystemInvoked;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
@@ -17,16 +18,21 @@ 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.
|
||||
* Fails startup when a write use case would run with no permission check: a bean that declares
|
||||
* {@link RequiresPermission} with no advisor in the context that applies to it, or a bean of a
|
||||
* {@link SystemInvoked} use case at all.
|
||||
*
|
||||
* <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.
|
||||
* <p>A {@code @SystemInvoked} use case carries no permission by design — only the system calls it,
|
||||
* on a thread with no {@code Authentication} — and its composition constructs it with {@code new}
|
||||
* and hands it to that caller. Registered as a bean, it is a write any transport can reach with no
|
||||
* check, whatever advisor the context holds, so its presence fails startup (review 2026-11-03
|
||||
* RR-01-02). {@code INBOUND_ADAPTERS_DO_NOT_REACH_SYSTEM_INVOKED_USE_CASES} closes the other path,
|
||||
* an inbound adapter that constructs one itself.
|
||||
*/
|
||||
final class PermissionEnforcementGuard implements SmartInitializingSingleton, BeanFactoryAware {
|
||||
|
||||
@@ -40,6 +46,7 @@ final class PermissionEnforcementGuard implements SmartInitializingSingleton, Be
|
||||
@Override
|
||||
public void afterSingletonsInstantiated() {
|
||||
Collection<Advisor> advisors = beanFactory.getBeansOfType(Advisor.class, true, false).values();
|
||||
List<String> systemInvoked = new ArrayList<>();
|
||||
List<String> unenforced = new ArrayList<>();
|
||||
for (String name : beanFactory.getBeanDefinitionNames()) {
|
||||
Class<?> type = beanFactory.getType(name, false);
|
||||
@@ -47,11 +54,20 @@ final class PermissionEnforcementGuard implements SmartInitializingSingleton, Be
|
||||
continue;
|
||||
}
|
||||
Class<?> userClass = ClassUtils.getUserClass(type);
|
||||
if (declaresPermission(userClass)
|
||||
if (AnnotatedElementUtils.hasAnnotation(userClass, SystemInvoked.class)) {
|
||||
systemInvoked.add(name + " (" + userClass.getName() + ")");
|
||||
} else if (declaresPermission(userClass)
|
||||
&& advisors.stream().noneMatch(advisor -> AopUtils.canApply(advisor, userClass))) {
|
||||
unenforced.add(name + " (" + userClass.getName() + ")");
|
||||
}
|
||||
}
|
||||
if (!systemInvoked.isEmpty()) {
|
||||
throw StartupFailures.requiredAdapterDisabled(
|
||||
"@SystemInvoked use cases are registered as beans, where a transport can reach a write"
|
||||
+ " that has no permission check — a system-invoked use case must be constructed by"
|
||||
+ " its composition, not registered as a bean: "
|
||||
+ String.join(", ", systemInvoked));
|
||||
}
|
||||
if (!unenforced.isEmpty()) {
|
||||
throw StartupFailures.requiredAdapterDisabled(
|
||||
"beans declare @RequiresPermission but no advisor enforces it — the composition is"
|
||||
|
||||
+30
@@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException;
|
||||
import dev.caskeleton.application.security.RequiresPermission;
|
||||
import dev.caskeleton.application.security.SystemInvoked;
|
||||
import org.aopalliance.intercept.MethodInterceptor;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.aop.Advisor;
|
||||
@@ -39,6 +40,22 @@ class PermissionEnforcementGuardTest {
|
||||
.run(context -> assertThat(context).hasNotFailed().hasSingleBean(GatedUseCase.class));
|
||||
}
|
||||
|
||||
/**
|
||||
* A system-invoked use case carries no permission, so a bean of it is a write a transport can
|
||||
* reach with no check at all — whatever advisor the context holds (review 2026-11-03 RR-01-02).
|
||||
*/
|
||||
@Test
|
||||
void aSystemInvokedUseCaseRegisteredAsABeanFailsStartupEvenWithAnAdvisor() {
|
||||
runner
|
||||
.withUserConfiguration(SystemInvokedUseCaseConfig.class, EnforcingAdvisorConfig.class)
|
||||
.run(
|
||||
context ->
|
||||
assertThat(context.getStartupFailure())
|
||||
.isInstanceOf(StartupFailureException.class)
|
||||
.hasMessageContaining("must be constructed by its composition")
|
||||
.hasMessageContaining(SystemInvokedUseCase.class.getName()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aContextWithoutGatedBeansNeedsNoAdvisor() {
|
||||
runner.run(context -> assertThat(context).hasNotFailed());
|
||||
@@ -57,6 +74,19 @@ class PermissionEnforcementGuardTest {
|
||||
}
|
||||
}
|
||||
|
||||
@SystemInvoked(reason = "a scheduler calls it")
|
||||
public static class SystemInvokedUseCase {
|
||||
public void handle() {}
|
||||
}
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
static class SystemInvokedUseCaseConfig {
|
||||
@Bean
|
||||
SystemInvokedUseCase systemInvokedUseCase() {
|
||||
return new SystemInvokedUseCase();
|
||||
}
|
||||
}
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
static class EnforcingAdvisorConfig {
|
||||
@Bean
|
||||
|
||||
Reference in New Issue
Block a user