fix!: 성숙도 리뷰의 High·P1 결함 19건을 고친다

문제: 2026-11-01 성숙도 리뷰에서 High 21건·P1 25건이 나왔다. 결과를
모르는 일을 "확실함"으로 기록했다(발송 중 죽은 알림 재발송, 커밋 중
끊긴 쓰기를 재시도 가능으로 응답, 재시도 가능한 거부를 DEAD로). 중복을
DB가 아니라 코드 순서로 막았다(정산 job, 포스터 제목). 짝 프론트와
wire 계약이 달랐고(처리 중 409, Envelope null), JWT audience 검증이
기본으로 꺼져 있었고, 트레이스가 나가지 않았고, CI가 strict lane 14개를
한 번도 돌리지 않았다.

방법: 발견마다 실패하는 테스트를 먼저 쓰고 고쳤다. 주요 선택:
- 알림 attempt는 처음부터 "시작 여부 모름"으로 쓴다(호출 직전 갱신은
  쓰기가 하나 늘어 버림).
- 정산 job claim은 lease·fence를 갱신하는 UPDATE 한 문장(처리 전체를
  트랜잭션으로 감싸는 안은 외부 호출 동안 잠금을 잡아 버림).
- 커밋 단계 연결 끊김은 DB_COMPLETION_UNKNOWN(재시도 불가).
- 처리 중 409는 retryable=true + Retry-After: 2, Envelope null 필드는
  web Jackson mixin으로 생략(shared-contract는 stdlib only).
- 트레이싱은 자체 Tracer를 지우고 Boot 4 tracing·OTLP로.
- strict lane을 단계에 연결하고 verifyStrictLaneStages가 고아를 막는다.
발견별 RED·GREEN·버린 대안은 리뷰 README 13절 표에 있다.

위험·한계: JWT 모드는 APP_SECURITY_JWT_AUDIENCE가 없으면 기동하지
않는다. 짝 프론트는 409 retryable과 Envelope 키 규칙을 맞춰야 한다.
이 커밋 시점에는 MinIO 공식 이미지가 사라져 MinIO 2 lane이 실패한다
(다음 커밋에서 대체 이미지로 해결).

검증: ci 통과. mainCheck·integrationCheck는 MinIO 2 lane만 실패(이미지
pull 거부). -p optional-platforms ci integrationCheck, performanceCheck,
releaseCheck(-PgitRevision) 통과.

Refs: docs/reviews/2026-11-01-maturity-review/README.md 2·13절
BREAKING CHANGE: JWT 모드에서 APP_SECURITY_JWT_AUDIENCE가 필수가 되고 role은
audience client와 realm 것만 읽는다. IDEMPOTENT_IN_FLIGHT가 retryable=true,
Retry-After: 2로 바뀌고 Envelope는 null 필드를 보내지 않는다.
This commit is contained in:
DongHyeonka
2026-11-03 19:52:06 +09:00
parent 01a8a2a70f
commit 34565130e0
253 changed files with 13849 additions and 1140 deletions
@@ -2,9 +2,9 @@ package dev.caskeleton.composition.fileserver;
import dev.caskeleton.adapter.outbound.fileserver.platform.autoconfigure.FileserverMetricsSupport;
import dev.caskeleton.application.fileserver.api.metadata.FileMetadataPort;
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.api.security.OriginalFilenamePolicy;
import dev.caskeleton.application.fileserver.cleanup.CleanupQueuePort;
import dev.caskeleton.application.fileserver.download.DescribeFileApplicationUseCase;
import dev.caskeleton.application.fileserver.download.DownloadContentPort;
@@ -24,8 +24,10 @@ import dev.caskeleton.application.fileserver.port.in.MoveFileUseCase;
import dev.caskeleton.application.fileserver.port.in.OpenDownloadContentUseCase;
import dev.caskeleton.application.fileserver.port.in.PrepareDownloadUseCase;
import dev.caskeleton.application.fileserver.port.in.TransferDownloadContentUseCase;
import dev.caskeleton.application.fileserver.quota.TransferAdmissionController;
import dev.caskeleton.application.fileserver.recovery.StagingUploadLocatorPort;
import dev.caskeleton.application.fileserver.upload.UploadIdentifierPort;
import dev.caskeleton.application.fileserver.upload.UploadPolicies;
import dev.caskeleton.application.transaction.TransactionPort;
import java.time.Clock;
import java.util.Optional;
@@ -94,16 +96,18 @@ class FileserverFileUseCaseConfiguration {
CopyFileUseCase fileserverCopyFile(
FileMetadataPort metadataStore,
CopyContentPort copyGateway,
FileAccessPolicyPort accessPolicy,
OriginalFilenamePolicy filenamePolicy,
UploadPolicies policies,
FileQuotaPort quotaService,
TransferAdmissionController admissionController,
UploadIdentifierPort identifierFactory,
TransactionPort transactions,
Clock clock) {
return new CopyFileApplicationUseCase(
metadataStore,
copyGateway,
accessPolicy,
filenamePolicy,
policies,
quotaService,
admissionController,
identifierFactory,
transactions,
clock);
+16 -1
View File
@@ -15,7 +15,8 @@ composition:outbox-relay
└─ OutboxRelayAutoConfiguration app.outbox.enabled=true + OutboxStorePort 가 있을 때만
├─ OutboxSettings app.outbox.* strict 바인딩(오타는 기동 실패)
├─ OutboxRelayScheduler relay-enabled=true + OutboxMessagePublishPort 가 있을 때만,
│ PublishPendingOutboxEventsUseCase 를 fixed-delay 로 구동
│ PublishPendingOutboxEventsUseCase 를 fixed-delay 로 구동,
│ 종료 때 platform보다 먼저 멈춤(SmartLifecycle)
├─ OutboxMetrics outbox.pending.size / outbox.publisher.lag / published.total
└─ OutboxLeaderElectionToken SKIP LOCKED 가 리더 선출이라는 표시(로직 없음)
```
@@ -126,6 +127,20 @@ 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을 닫고, 그 뒤
발행은 `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`
결정까지 다시 열어야 해서 이번 범위보다 크다).
### OutboxSettings
- **튜닝 값(poll 주기·batch·timeout·보존)은 코드 리터럴 기본값을 쓰고 env placeholder 를 두지 않는다.** 신규 env key 를
@@ -29,6 +29,8 @@ dependencies {
implementation libs.logstash.logback.encoder
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'))
testImplementation 'org.mockito:mockito-core'
testImplementation 'ch.qos.logback:logback-classic'
testRuntimeOnly 'org.yaml:snakeyaml'
@@ -8,13 +8,28 @@ 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 bootstrap scheduler that drives the outbox relay use case on a fixed-delay polling loop.
* Registered by {@code OutboxConfig}. See README for the design rationale.
* 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.
*
* <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.
*/
public class OutboxRelayScheduler {
public class OutboxRelayScheduler implements SmartLifecycle {
/**
* Stops first, in the same phase as the platform's own outbox relay ({@code
* MessagingOutboxRelayLifecycle}): above the platform's admission gate, which this leaf cannot
* name.
*/
static final int PHASE = Integer.MAX_VALUE;
private static final Logger log = LoggerFactory.getLogger(OutboxRelayScheduler.class);
@@ -22,6 +37,11 @@ public class OutboxRelayScheduler {
private final OutboxMetrics metrics;
private final Clock clock;
private final Object monitor = new Object();
private boolean running;
private boolean cycleInProgress;
private Runnable stopCallback;
public OutboxRelayScheduler(
PublishPendingOutboxEventsUseCase relayUseCase, OutboxMetrics metrics, Clock clock) {
this.relayUseCase = relayUseCase;
@@ -30,11 +50,33 @@ public class OutboxRelayScheduler {
}
/**
* Unexpected exceptions are caught (not propagated) so the scheduler thread stays alive for the
* next tick.
* Runs one relay cycle 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}")
public void relay() {
synchronized (monitor) {
if (!running) {
return;
}
cycleInProgress = true;
}
try {
runCycle();
} finally {
Runnable pendingStop;
synchronized (monitor) {
cycleInProgress = false;
pendingStop = stopCallback;
stopCallback = null;
}
if (pendingStop != null) {
pendingStop.run();
}
}
}
private void runCycle() {
try {
OutboxRelayResult result = relayUseCase.handle(PublishPendingOutboxEventsCommand.INSTANCE);
@@ -58,4 +100,48 @@ public class OutboxRelayScheduler {
ex);
}
}
@Override
public void start() {
synchronized (monitor) {
running = true;
}
}
/** Refuses new cycles; does not wait. Context shutdown uses {@link #stop(Runnable)}. */
@Override
public void stop() {
synchronized (monitor) {
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.
*/
@Override
public void stop(Runnable callback) {
synchronized (monitor) {
running = false;
if (cycleInProgress) {
stopCallback = callback;
return;
}
}
callback.run();
}
@Override
public boolean isRunning() {
synchronized (monitor) {
return running;
}
}
@Override
public int getPhase() {
return PHASE;
}
}
@@ -28,7 +28,9 @@ class OutboxRelaySchedulerLoggingTest {
.thenThrow(new IllegalStateException("unexpected"));
try (CapturedLogger captured = capture(OutboxRelayScheduler.class)) {
new OutboxRelayScheduler(relay, metrics, Clock.systemUTC()).relay();
OutboxRelayScheduler scheduler = new OutboxRelayScheduler(relay, metrics, Clock.systemUTC());
scheduler.start();
scheduler.relay();
ILoggingEvent event = captured.singleEvent();
assertThat(event.getLevel()).isEqualTo(Level.ERROR);
@@ -0,0 +1,197 @@
package dev.caskeleton.composition.outbox;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
import dev.caskeleton.application.outbox.ClaimedOutboxEvent;
import dev.caskeleton.application.outbox.OutboxCompletion;
import dev.caskeleton.application.outbox.OutboxEventStatus;
import dev.caskeleton.application.outbox.OutboxLease;
import dev.caskeleton.application.outbox.OutboxMessagePublishPort;
import dev.caskeleton.application.outbox.OutboxRelayFailureReportPort;
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.TransactionPort;
import dev.caskeleton.application.transaction.testkit.DirectTransactionPort;
import java.time.Clock;
import java.time.Instant;
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.AtomicReference;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.SmartLifecycle;
/**
* The messaging platform closes publish admission at phase {@code Integer.MAX_VALUE - 1024} ({@code
* MessagingShutdownLifecycle}). A relay cycle still publishing after that is refused with {@code
* SHUTTING_DOWN} and spends an attempt. The relay must stop first and finish its cycle.
*/
class OutboxRelayShutdownOrderTest {
/** {@code MessagingShutdownLifecycle#getPhase()}; this leaf may not name the messaging type. */
private static final int PLATFORM_ADMISSION_PHASE = Integer.MAX_VALUE - 1024;
private static final String EVENT_ID = "evt-shutdown-1";
@Test
@DisplayName("종료 시 relay가 진행 중 회차를 끝내고 멈춘 뒤에 platform이 admission을 닫는다")
void relayFinishesItsRunningCycleBeforeThePlatformClosesAdmission() throws Exception {
// given
RecordingStore store = new RecordingStore();
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");
AtomicReference<CompletableFuture<Void>> closing = new AtomicReference<>();
runner.run(
context -> {
assertThat(publishPort.entered.await(10, TimeUnit.SECONDS))
.as("the first relay tick claims the row and starts publishing it")
.isTrue();
// when
closing.set(CompletableFuture.runAsync(context::close));
// The relay holds the shutdown while its cycle runs; release the publish either way so
// a wrong order fails the assertions below instead of hanging.
platform.stopped.await(300, TimeUnit.MILLISECONDS);
publishPort.release.countDown();
closing.get().get(20, TimeUnit.SECONDS);
});
// then
assertThat(platform.stopped.getCount()).as("the platform stand-in was stopped").isZero();
assertThat(platform.rowCompletedWhenStopped.get())
.as("the relay cycle wrote its outcome before the platform closed admission")
.isTrue();
assertThat(store.status(EVENT_ID)).isEqualTo(OutboxEventStatus.PUBLISHED);
}
@Test
@DisplayName("멈춘 relay는 다음 tick이 와도 새 회차를 시작하지 않는다")
void aStoppedRelayStartsNoNewCycle() {
// given
PublishPendingOutboxEventsUseCase relayUseCase = mock(PublishPendingOutboxEventsUseCase.class);
OutboxRelayScheduler scheduler =
new OutboxRelayScheduler(relayUseCase, mock(OutboxMetrics.class), Clock.systemUTC());
scheduler.start();
AtomicBoolean reportedStopped = new AtomicBoolean();
scheduler.stop(() -> reportedStopped.set(true));
// when
scheduler.relay();
// then
verifyNoInteractions(relayUseCase);
assertThat(reportedStopped).as("no cycle was running, so stop reported at once").isTrue();
assertThat(scheduler.isRunning()).isFalse();
}
/** Records when the relay writes the row's completion. */
private static final class RecordingStore extends InMemoryOutboxStore {
private final AtomicBoolean completed = new AtomicBoolean();
@Override
public synchronized OutboxCompletion markPublished(OutboxLease lease) {
OutboxCompletion completion = super.markPublished(lease);
completed.set(true);
return completion;
}
@Override
public synchronized OutboxCompletion markFailed(OutboxLease lease, Instant nextAttemptAt) {
OutboxCompletion completion = super.markFailed(lease, nextAttemptAt);
completed.set(true);
return completion;
}
@Override
public synchronized OutboxCompletion markDead(OutboxLease lease) {
OutboxCompletion completion = super.markDead(lease);
completed.set(true);
return completion;
}
@Override
public synchronized OutboxEventStatus status(String eventId) {
return super.status(eventId);
}
}
/** A publish that blocks until the test releases it, like a slow broker. */
private static final class BlockingPublishPort implements OutboxMessagePublishPort {
private final CountDownLatch entered = new CountDownLatch(1);
private final CountDownLatch release = new CountDownLatch(1);
@Override
public void publish(ClaimedOutboxEvent event) {
entered.countDown();
try {
if (!release.await(20, TimeUnit.SECONDS)) {
throw new IllegalStateException("publish was never released");
}
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
throw new IllegalStateException("publish interrupted", interrupted);
}
}
}
/** Stands in for the platform's admission gate: same phase, records what it found on stop. */
private static final class PlatformAdmissionStandIn implements SmartLifecycle {
private final RecordingStore store;
private final CountDownLatch stopped = new CountDownLatch(1);
private final AtomicBoolean rowCompletedWhenStopped = new AtomicBoolean();
private volatile boolean running;
PlatformAdmissionStandIn(RecordingStore store) {
this.store = store;
}
@Override
public void start() {
running = true;
}
@Override
public void stop() {
running = false;
rowCompletedWhenStopped.set(store.completed.get());
stopped.countDown();
}
@Override
public boolean isRunning() {
return running;
}
@Override
public int getPhase() {
return PLATFORM_ADMISSION_PHASE;
}
}
}
+46 -15
View File
@@ -12,16 +12,21 @@ runtime 배선이다. 예전에는 app-bootstrap에 있었고 sample이 그 복
```
composition:service-runtime
├─ tracing/ TracingConfig(+ Tracer·SpanErrorRecorder·sampling gauge), TracingSettings,
│ TracingSampleRateResolver, TracingSamplingEnvironmentPostProcessor
├─ tracing/ TracingConfig(SpanErrorRecorder·ActiveTrace·sampling gauge), TracingSettings,
│ TracingSampleRateResolver, TracingEnvironmentPostProcessor(app.tracing.* →
│ Boot 키), TracingSwitchImportFilter(enabled=false면 Boot tracing 제외)
├─ metrics/ MetricsContractConfig(cardinality deny-list + SLO 분포 filter)
├─ context/ DomainContextConfig
├─ logging/ PseudonymizationConfig, PrivacySettings (user_principal HMAC 가명화)
└─ management/security/ ManagementSecurityConfig (actuator chain)
```
- 모두 이 모듈의 `AutoConfiguration.imports`로 등록된다(sampling bridge는 `spring.factories`의
`EnvironmentPostProcessor`). 구성 루트의 component scan에 기대지 않는다.
- 모두 이 모듈의 `AutoConfiguration.imports`로 등록된다(설정 브리지와 tracing 스위치는
`spring.factories`의 `EnvironmentPostProcessor`·`AutoConfigurationImportFilter`). 구성 루트의
component scan에 기대지 않는다.
- Tracer·span processor·OTLP exporter는 이 모듈이 만들지 않는다. Spring Boot 4의
`spring-boot-micrometer-tracing-opentelemetry`(+ `opentelemetry-exporter-otlp`)가 만들고, 이 모듈은
`app.tracing.*` 값을 Boot 키로 옮기고 끄는 스위치만 둔다(아래 "tracing" 절).
- 설정 키는 옮기지 않았다: `app.tracing.*`, `app.privacy.*`. 값은 각 구성 루트의 `application.yml`/`config/observability.yml`에 있다.
- actuator chain은 servlet 웹 애플리케이션에서만 만들어지고, 구성 루트가 같은 이름
`actuatorSecurityFilterChain`의 bean을 두면 물러난다. sample-portfolio는 공개 데모라 그렇게
@@ -57,9 +62,26 @@ runtimeOnly project(':composition:service-runtime')
### tracing — 분산 트레이싱 wiring과 샘플링 정책
#### Boot tracing으로 바꾼 이유 (리뷰 07-01, 2026-11-01)
- **예전에는 `TracingConfig`가 `Tracer`를 직접 만들었다.** `SdkTracerProvider`에 sampler만 있고 span
processor·exporter가 없었고, Boot tracing 자동 설정은 classpath에 없었다. 그래서 HTTP 요청이 span을
만들지 않았고 `OTEL_EXPORTER_OTLP_ENDPOINT`를 넣어도 아무것도 나가지 않았다.
- **고른 방법:** 직접 조립을 지우고 Boot 4의 `spring-boot-micrometer-tracing-opentelemetry`를 쓴다.
Boot가 SDK, `BatchSpanProcessor`, observation→span 핸들러, propagator, 그리고
`management.opentelemetry.tracing.export.otlp.endpoint`가 있을 때만 OTLP exporter를 만든다.
`spring-boot-starter-opentelemetry`는 쓰지 않는다 — OTLP 메트릭 push(`micrometer-registry-otlp`)까지
켜서 이 템플릿의 Prometheus scrape 계약 밖의 전송이 생긴다.
- **버린 대안:** (1) 직접 만든 `SdkTracerProvider`에 processor·exporter를 붙이기 — observation→span 연결과
propagator까지 다시 짜야 한다. (2) tracing을 빼고 로그 상관만 제공 — 소유자가 관측 기본 제공을 정했다.
- **trace id 하나로 맞추기:** Boot의 서버 observation(`HIGHEST_PRECEDENCE + 1`)이 span을 연 뒤에
`WebMvcRequestIdFilter`(`+ 10`)가 돈다. 필터는 `ActiveTrace`로 그 span의 id를 받아 `meta.traceId`,
로그 `trace_id`·`span_id`, 응답 `traceparent`에 쓴다. tracer가 없으면 예전처럼 들어온
`traceparent`를 쓰거나 새로 만든다.
#### TracingConfig
- **컴포지션 루트에서 트레이싱을 조립한다.** 두 가지를 한다: (1) 시작 시 `tracing.sampling.rate`
게이지 등록, (2) `SpanErrorRecorder` 빈 등록.
- **컴포지션 루트의 트레이싱 부속을 등록한다.** 세 가지를 한다: (1) 시작 시 `tracing.sampling.rate`
게이지 등록, (2) `SpanErrorRecorder` 빈 등록, (3) `ActiveTrace` 빈 등록(`Tracer`가 없으면 `NONE`).
Boot의 `OpenTelemetryTracingAutoConfiguration` 뒤에 돈다.
- **`SpanErrorRecorder` 빈은 `@ConditionalOnBean(Tracer.class)`가 아니라 `ObjectProvider<Tracer>`로
런타임 존재 여부를 직접 조회한다.** 이유: `@ConditionalOnBean`은 사용자 정의 `@Configuration`에서
autoconfiguration 이 만드는 빈(여기서는 `Tracer`)을 조건으로 쓸 때 빈 등록 순서가 보장되지 않아
@@ -69,10 +91,14 @@ runtimeOnly project(':composition:service-runtime')
`SpanErrorRecorder` 빈을 이미 등록한 경우 이 빈은 backoff 한다.** adapter-web 의
`GlobalExceptionHandler`는 `ObjectProvider`로 `SpanErrorRecorder`를 조회하므로, 자기 자신의 NOOP
self-default 에서 여기서 등록한 실제 구현으로 자동 교체된다.
- **OTel/Micrometer tracer 런타임은 이 repo 에서 seam 이 활성 상태다.** `micrometer-tracing-bridge-otel`
+ `opentelemetry-exporter-otlp`가 `app-bootstrap/build.gradle`에 실제로 wiring 되어 있다. 단, span
exporter 는 `OTEL_EXPORTER_OTLP_ENDPOINT`가 비어 있는 동안 꺼져 있고, 엔드포인트를 설정하면
export 가 시작된다.
- **span export는 `OTEL_EXPORTER_OTLP_ENDPOINT`가 정한다.** 비어 있으면 Boot exporter 키가 생기지
않아 exporter bean이 없다(기본 주소로 보내지도 않는다). 값이 있으면 OTLP/HTTP로 `<값>/v1/traces`에
보낸다. `TracingExportSystemTest`가 로컬 수신기로 이것을 확인한다.
- **`APP_TRACING_ENABLED=false`면 `Tracer` bean이 없다.** `TracingSwitchImportFilter`가
`org.springframework.boot.micrometer.tracing.` 아래 자동 설정을 모두 뺀다. Boot의
`management.tracing.export.enabled=false`는 export만 끄고 tracer와 span은 그대로 만들기 때문에 쓰지
않았다. `spring.autoconfigure.exclude`에 넣는 방법은 운영자가 쓴 exclude 목록과 덮어쓰기 경쟁을
해서 버렸다.
- **게이지 등록 시 active profile 은 `Environment.getActiveProfiles()`의 첫 번째 값을 쓴다.** 멀티
프로파일 배포에서는 맨 앞에 나열된 프로파일이 권위 있는 배포 환경이라는 규약이다. `MeterRegistry`가
classpath 에 없으면(Actuator 미탑재) 게이지 등록은 조용히 no-op 이 된다.
@@ -87,7 +113,7 @@ runtimeOnly project(':composition:service-runtime')
- **`sampleRate`가 blank 이면 숫자 검증을 건너뛴다.** blank 는 "값이 잘못됐다"가 아니라 "프로파일별
기본값에 위임하라"는 신호이기 때문이다. 실제 런타임별 기본값(prod=0.01, dev/local=1.0)은 `TracingSampleRateResolver`가 적용하고,
profile vocabulary 자체는 `RuntimeEnvironment`가 소유한다. resolved 된 값은
`TracingSamplingEnvironmentPostProcessor`가 Spring Boot 네이티브
`TracingEnvironmentPostProcessor`가 Spring Boot 네이티브
`management.tracing.sampling.probability`로 브리지한다.
- **검증은 시작 시 fail-fast 다.** `sampleRate`가 non-blank 인데 [0.0, 1.0] float 이 아니면 시작이
실패하고, `otlpEndpoint`가 non-empty 인데 scheme 없는 잘못된 URL 이면 시작이 실패한다. `enabled`는
@@ -114,11 +140,16 @@ runtimeOnly project(':composition:service-runtime')
- **`MeterRegistry`를 `ObjectProvider`로 조회하며, Actuator 미탑재로 빈이 없으면 등록을 조용히
건너뛴다.** 이는 `BackgroundJobMetrics` / `OutboxMetrics`의 선례를 그대로 따른다.
#### TracingSamplingEnvironmentPostProcessor
- **resolved 된 유효 샘플 비율을 Spring Boot 네이티브 키 `management.tracing.sampling.probability`로
단일화(브리지)하는 `EnvironmentPostProcessor`다.** 이를 통해 "프로파일별 기본값 + env override"라는
#### TracingEnvironmentPostProcessor
- **`app.tracing.*`을 Boot tracing 키로 옮기는 `EnvironmentPostProcessor`다.** (1) resolved 된 유효 샘플
비율 → `management.tracing.sampling.probability`, (2) `app.tracing.exporter.otlp-endpoint`(=
`OTEL_EXPORTER_OTLP_ENDPOINT`) → `management.opentelemetry.tracing.export.otlp.endpoint`. (2)는
OpenTelemetry 규약대로 기준 주소에 `/v1/traces`를 붙인다(끝의 `/`는 하나로 정리). gRPC 전송이나 다른
경로가 필요하면 Boot 키(`management.opentelemetry.tracing.export.otlp.*`)를 직접 주며, 직접 준 값은
덮어쓰지 않는다. 예전 이름은 `TracingSamplingEnvironmentPostProcessor`다(순서 상수는
`StartupOrder.TRACING_SAMPLING` 그대로). 이를 통해 "프로파일별 기본값 + env override"라는
우리 규약을 Spring Boot 의 기본 샘플링 메커니즘에 그대로 연결한다.
- **브리지 우선순위.** (1) 사용자가 `management.tracing.sampling.probability`를 이미 명시했으면
- **샘플링 브리지 우선순위.** (1) 사용자가 `management.tracing.sampling.probability`를 이미 명시했으면
덮어쓰지 않고 그대로 둔다, (2) `app.tracing.sample-rate`가 non-blank 면 그 값 사용, (3)
blank 면 `TracingSampleRateResolver.defaultRateForProfile(...)`로 active profile 기본값 적용.
- **`META-INF/spring.factories`에 `org.springframework.boot.EnvironmentPostProcessor` 키로 등록된다.**
+7 -1
View File
@@ -30,8 +30,14 @@ dependencies {
// MeterRegistryCustomizer, EndpointRequest and the actuator types the chains match on.
implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'io.micrometer:micrometer-core'
// Distributed tracing is Boot's: its auto-configuration builds the OTel SDK, the span processor,
// the observation handlers that turn each HTTP observation into a span, and — only once
// management.opentelemetry.tracing.export.otlp.endpoint is set — the OTLP exporter. This module
// translates the app.tracing.* keys into those (TracingEnvironmentPostProcessor) and
// switches the whole of it off for app.tracing.enabled=false (TracingSwitchImportFilter).
implementation 'io.micrometer:micrometer-tracing-bridge-otel'
implementation 'io.opentelemetry:opentelemetry-sdk'
implementation 'org.springframework.boot:spring-boot-micrometer-tracing-opentelemetry'
implementation 'io.opentelemetry:opentelemetry-exporter-otlp'
// The actuator security chain.
implementation 'org.springframework.boot:spring-boot-starter-security'
@@ -36,6 +36,10 @@ 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
@@ -55,8 +59,13 @@ io.opentelemetry.semconv:opentelemetry-semconv:1.37.0=compileClasspath,runtimeCl
io.opentelemetry:opentelemetry-api:1.55.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-common:1.55.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-context:1.55.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
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-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
io.opentelemetry:opentelemetry-sdk-logs:1.55.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-sdk-metrics:1.55.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-sdk-trace:1.55.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
@@ -101,6 +110,8 @@ 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
@@ -142,6 +153,9 @@ org.springframework.boot:spring-boot-http-converter:4.0.8=testCompileClasspath,t
org.springframework.boot:spring-boot-jackson:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-micrometer-metrics:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-micrometer-observation:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-micrometer-tracing-opentelemetry:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-micrometer-tracing:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-opentelemetry:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-resttestclient:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-security:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-servlet:4.0.8=testCompileClasspath,testRuntimeClasspath
@@ -0,0 +1,35 @@
package dev.caskeleton.composition.runtime.tracing;
import dev.caskeleton.shared.tracing.ActiveTrace;
import dev.caskeleton.shared.tracing.TraceParent;
import io.micrometer.tracing.Span;
import io.micrometer.tracing.TraceContext;
import io.micrometer.tracing.Tracer;
import java.util.Optional;
/** Micrometer-backed {@link ActiveTrace}: the context of {@link Tracer#currentSpan()}. */
public final class MicrometerActiveTrace implements ActiveTrace {
private final Tracer tracer;
public MicrometerActiveTrace(Tracer tracer) {
this.tracer = tracer;
}
@Override
public Optional<TraceParent> current() {
Span span = tracer.currentSpan();
if (span == null) {
return Optional.empty();
}
TraceContext context = span.context();
// An invalid (all-zero) context is what a no-op span reports; it names no trace.
if (!TraceParent.isValidTraceId(context.traceId())
|| !TraceParent.isValidSpanId(context.spanId())) {
return Optional.empty();
}
return Optional.of(
TraceParent.of(
context.traceId(), context.spanId(), Boolean.TRUE.equals(context.sampled())));
}
}
@@ -2,25 +2,27 @@ package dev.caskeleton.composition.runtime.tracing;
import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot;
import dev.caskeleton.shared.runtime.RuntimeEnvironment;
import dev.caskeleton.shared.tracing.ActiveTrace;
import dev.caskeleton.shared.tracing.SpanErrorRecorder;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.tracing.Tracer;
import io.micrometer.tracing.otel.bridge.OtelBaggageManager;
import io.micrometer.tracing.otel.bridge.OtelCurrentTraceContext;
import io.micrometer.tracing.otel.bridge.OtelTracer;
import io.opentelemetry.sdk.OpenTelemetrySdk;
import io.opentelemetry.sdk.trace.SdkTracerProvider;
import io.opentelemetry.sdk.trace.samplers.Sampler;
import java.util.List;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
/** Composition-root wiring for distributed tracing. See README for the design rationale. */
@AutoConfiguration
/**
* Composition-root wiring for distributed tracing: the sampling-rate gauge and the {@link
* SpanErrorRecorder}. The {@link Tracer} itself, the span processor and the OTLP exporter are
* Spring Boot's tracing auto-configuration; this class runs after it so the recorder sees the
* tracer it built. See README for the design rationale.
*/
@AutoConfiguration(
afterName =
"org.springframework.boot.micrometer.tracing.opentelemetry.autoconfigure"
+ ".OpenTelemetryTracingAutoConfiguration")
public class TracingConfig {
/**
@@ -64,32 +66,6 @@ public class TracingConfig {
effectiveRate);
}
@Bean
@ConditionalOnMissingBean(Tracer.class)
@ConditionalOnProperty(
prefix = "app.tracing",
name = "enabled",
havingValue = "true",
matchIfMissing = true)
Tracer micrometerTracer() {
double sampleRate =
new TracingSampleRateResolver()
.resolve(
RuntimeProfileSnapshot.from(environment).activeProfiles(), properties.sampleRate());
SdkTracerProvider tracerProvider =
SdkTracerProvider.builder()
.setSampler(Sampler.parentBased(Sampler.traceIdRatioBased(sampleRate)))
.build();
OpenTelemetrySdk openTelemetry =
OpenTelemetrySdk.builder().setTracerProvider(tracerProvider).build();
OtelCurrentTraceContext currentTraceContext = new OtelCurrentTraceContext();
return new OtelTracer(
openTelemetry.getTracer("dev.caskeleton"),
currentTraceContext,
event -> {},
new OtelBaggageManager(currentTraceContext, List.of(), List.of()));
}
/**
* {@link ObjectProvider}, not {@code @ConditionalOnBean(Tracer.class)}: a missing {@link Tracer}
* yields {@link SpanErrorRecorder#NOOP} rather than no bean, so downstream injection points never
@@ -105,6 +81,21 @@ public class TracingConfig {
return new MicrometerSpanErrorRecorder(tracer);
}
/**
* The tracer's active span for the inbound adapters that name a request's trace id. Same {@link
* ObjectProvider} reasoning as {@link #micrometerSpanErrorRecorder}: without a {@link Tracer} it
* is {@link ActiveTrace#NONE}, and the web filter falls back to the inbound {@code traceparent}.
*/
@Bean
@ConditionalOnMissingBean(ActiveTrace.class)
ActiveTrace micrometerActiveTrace(ObjectProvider<Tracer> tracerProvider) {
Tracer tracer = tracerProvider.getIfAvailable();
if (tracer == null) {
return ActiveTrace.NONE;
}
return new MicrometerActiveTrace(tracer);
}
/** Exists so tests can inspect what was registered without a live MeterRegistry. */
public record TracingSamplingRateGaugeRegistrar(
String activeProfile, double effectiveSampleRate) {}
@@ -0,0 +1,74 @@
package dev.caskeleton.composition.runtime.tracing;
import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot;
import dev.caskeleton.adapter.outbound.support.startup.StartupOrder;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.springframework.boot.EnvironmentPostProcessor;
import org.springframework.boot.SpringApplication;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
/**
* Translates this template's {@code app.tracing.*} keys into the Spring Boot keys its tracing
* auto-configuration reads: the resolved sample rate into {@code
* management.tracing.sampling.probability}, and the OTLP endpoint into {@code
* management.opentelemetry.tracing.export.otlp.endpoint}. Boot creates the span exporter only when
* that second key is set, so a blank endpoint means no exporter rather than an exporter aimed at a
* default address. Registered via {@code META-INF/spring.factories}. See README for the design
* rationale.
*/
public class TracingEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered {
static final String SAMPLING_KEY = "management.tracing.sampling.probability";
static final String OTLP_ENDPOINT_KEY = "management.opentelemetry.tracing.export.otlp.endpoint";
private static final String CA_SAMPLE_RATE_KEY = "app.tracing.sample-rate";
private static final String CA_OTLP_ENDPOINT_KEY = "app.tracing.exporter.otlp-endpoint";
/**
* The OTLP/HTTP trace signal path. {@code OTEL_EXPORTER_OTLP_ENDPOINT} is, by the OpenTelemetry
* specification, the base address shared by every signal, and the exporter appends the signal's
* path to it; Boot's key is the full trace URL. Translating one into the other is this suffix.
*/
private static final String OTLP_HTTP_TRACES_PATH = "/v1/traces";
private final TracingSampleRateResolver resolver = new TracingSampleRateResolver();
@Override
public void postProcessEnvironment(
ConfigurableEnvironment environment, SpringApplication application) {
// A value the operator set on Boot's own key takes precedence over the translation.
Map<String, Object> bridged = new LinkedHashMap<>();
if (!environment.containsProperty(SAMPLING_KEY)) {
List<String> activeProfiles = RuntimeProfileSnapshot.from(environment).activeProfiles();
String configured = environment.getProperty(CA_SAMPLE_RATE_KEY);
bridged.put(SAMPLING_KEY, String.valueOf(resolver.resolve(activeProfiles, configured)));
}
String endpoint = environment.getProperty(CA_OTLP_ENDPOINT_KEY, "").trim();
if (!endpoint.isEmpty() && !environment.containsProperty(OTLP_ENDPOINT_KEY)) {
bridged.put(OTLP_ENDPOINT_KEY, tracesUrl(endpoint));
}
if (!bridged.isEmpty()) {
environment.getPropertySources().addLast(new MapPropertySource("tracingBridge", bridged));
}
}
private static String tracesUrl(String baseEndpoint) {
String base =
baseEndpoint.endsWith("/")
? baseEndpoint.substring(0, baseEndpoint.length() - 1)
: baseEndpoint;
return base + OTLP_HTTP_TRACES_PATH;
}
@Override
public int getOrder() {
// 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;
}
}
@@ -1,49 +0,0 @@
package dev.caskeleton.composition.runtime.tracing;
import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot;
import dev.caskeleton.adapter.outbound.support.startup.StartupOrder;
import java.util.List;
import java.util.Map;
import org.springframework.boot.EnvironmentPostProcessor;
import org.springframework.boot.SpringApplication;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
/**
* Bridges the resolved tracing sample rate into Spring Boot's native {@code
* management.tracing.sampling.probability}. Registered via {@code META-INF/spring.factories}. See
* README for the design rationale.
*/
public class TracingSamplingEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered {
private static final String NATIVE_KEY = "management.tracing.sampling.probability";
private static final String CA_SAMPLE_RATE_KEY = "app.tracing.sample-rate";
private final TracingSampleRateResolver resolver = new TracingSampleRateResolver();
@Override
public void postProcessEnvironment(
ConfigurableEnvironment environment, SpringApplication application) {
// A user-supplied value takes precedence.
if (environment.containsProperty(NATIVE_KEY)) {
return;
}
List<String> activeProfiles = RuntimeProfileSnapshot.from(environment).activeProfiles();
String configured = environment.getProperty(CA_SAMPLE_RATE_KEY);
double rate = resolver.resolve(activeProfiles, configured);
environment
.getPropertySources()
.addLast(
new MapPropertySource(
"tracingSamplingBridge", Map.of(NATIVE_KEY, String.valueOf(rate))));
}
@Override
public int getOrder() {
// 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;
}
}
@@ -0,0 +1,45 @@
package dev.caskeleton.composition.runtime.tracing;
import org.springframework.boot.autoconfigure.AutoConfigurationImportFilter;
import org.springframework.boot.autoconfigure.AutoConfigurationMetadata;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
/**
* Leaves Spring Boot's tracing auto-configuration out of the context when {@code
* app.tracing.enabled=false}, so "tracing off" means no {@code Tracer} bean at all — not Boot's
* no-op tracer, and not a real one that merely exports nothing.
*
* <p>Boot has no property for that: {@code management.tracing.export.enabled=false} stops export
* but still builds the tracer and opens a span per observation. An import filter is Boot's own
* extension point for dropping auto-configurations by condition, and unlike {@code
* spring.autoconfigure.exclude} it does not compete with an exclusion list the operator writes.
*
* <p>Every tracing auto-configuration Boot ships lives under one package, so the filter names that
* package rather than a list of classes that would go stale when Boot adds one. Registered via
* {@code META-INF/spring.factories}.
*/
public final class TracingSwitchImportFilter
implements AutoConfigurationImportFilter, EnvironmentAware {
static final String BOOT_TRACING_PACKAGE = "org.springframework.boot.micrometer.tracing.";
private boolean tracingEnabled = true;
@Override
public void setEnvironment(Environment environment) {
this.tracingEnabled = environment.getProperty("app.tracing.enabled", Boolean.class, true);
}
@Override
public boolean[] match(
String[] autoConfigurationClasses, AutoConfigurationMetadata autoConfigurationMetadata) {
boolean[] matches = new boolean[autoConfigurationClasses.length];
for (int i = 0; i < autoConfigurationClasses.length; i++) {
String candidate = autoConfigurationClasses[i];
matches[i] =
tracingEnabled || candidate == null || !candidate.startsWith(BOOT_TRACING_PACKAGE);
}
return matches;
}
}
@@ -1,2 +1,5 @@
org.springframework.boot.EnvironmentPostProcessor=\
dev.caskeleton.composition.runtime.tracing.TracingSamplingEnvironmentPostProcessor
dev.caskeleton.composition.runtime.tracing.TracingEnvironmentPostProcessor
org.springframework.boot.autoconfigure.AutoConfigurationImportFilter=\
dev.caskeleton.composition.runtime.tracing.TracingSwitchImportFilter
@@ -9,7 +9,8 @@ import dev.caskeleton.composition.runtime.logging.PseudonymizationConfig;
import dev.caskeleton.composition.runtime.management.security.ManagementSecurityConfig;
import dev.caskeleton.composition.runtime.metrics.MetricsContractConfig;
import dev.caskeleton.composition.runtime.tracing.TracingConfig;
import dev.caskeleton.composition.runtime.tracing.TracingSamplingEnvironmentPostProcessor;
import dev.caskeleton.composition.runtime.tracing.TracingEnvironmentPostProcessor;
import dev.caskeleton.composition.runtime.tracing.TracingSwitchImportFilter;
import dev.caskeleton.shared.concurrency.DomainContextPropagator;
import dev.caskeleton.shared.tracing.SpanErrorRecorder;
import java.io.IOException;
@@ -60,13 +61,29 @@ class ServiceRuntimeRegistrationTest {
// then
assertThat(registrations.getProperty("org.springframework.boot.EnvironmentPostProcessor"))
.contains(TracingSamplingEnvironmentPostProcessor.class.getName());
.contains(TracingEnvironmentPostProcessor.class.getName());
}
@Test
@DisplayName("tracing 스위치는 auto-configuration import filter로 등록된다")
void theTracingSwitchIsRegisteredAsAnImportFilter() throws IOException {
// given
ClassPathResource factories = new ClassPathResource("META-INF/spring.factories");
// when
Properties registrations = PropertiesLoaderUtils.loadProperties(factories);
// then
assertThat(
registrations.getProperty(
"org.springframework.boot.autoconfigure.AutoConfigurationImportFilter"))
.contains(TracingSwitchImportFilter.class.getName());
}
@Test
void theSamplingBridgeTakesItsCentralStartupOrderPosition() {
// given
TracingSamplingEnvironmentPostProcessor bridge = new TracingSamplingEnvironmentPostProcessor();
TracingEnvironmentPostProcessor bridge = new TracingEnvironmentPostProcessor();
// when
int order = bridge.getOrder();
@@ -0,0 +1,68 @@
package dev.caskeleton.composition.runtime.tracing;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import dev.caskeleton.shared.tracing.TraceParent;
import io.micrometer.tracing.Span;
import io.micrometer.tracing.TraceContext;
import io.micrometer.tracing.Tracer;
import java.util.Optional;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
class MicrometerActiveTraceTest {
private final Tracer tracer = mock(Tracer.class);
@Test
@DisplayName("열린 span이 있으면 그 span의 trace id·span id·sampled를 W3C 값으로 돌려준다")
void theCurrentSpanIsReturnedAsATraceParent() {
// given
givenCurrentSpan("4bf92f3577b34da6a3ce929d0e0e4736", "00f067aa0ba902b7", true);
// when
Optional<TraceParent> active = new MicrometerActiveTrace(tracer).current();
// then
assertThat(active)
.contains(TraceParent.of("4bf92f3577b34da6a3ce929d0e0e4736", "00f067aa0ba902b7", true));
}
@Test
@DisplayName("열린 span이 없으면 비어 있다")
void noCurrentSpanIsEmpty() {
// given
when(tracer.currentSpan()).thenReturn(null);
// when
Optional<TraceParent> active = new MicrometerActiveTrace(tracer).current();
// then
assertThat(active).isEmpty();
}
@Test
@DisplayName("no-op span의 0 값 context는 trace로 치지 않는다")
void anInvalidContextIsEmpty() {
// given
givenCurrentSpan("00000000000000000000000000000000", "0000000000000000", false);
// when
Optional<TraceParent> active = new MicrometerActiveTrace(tracer).current();
// then
assertThat(active).isEmpty();
}
private void givenCurrentSpan(String traceId, String spanId, boolean sampled) {
Span span = mock(Span.class);
TraceContext context = mock(TraceContext.class);
when(tracer.currentSpan()).thenReturn(span);
when(span.context()).thenReturn(context);
when(context.traceId()).thenReturn(traceId);
when(context.spanId()).thenReturn(spanId);
when(context.sampled()).thenReturn(sampled);
}
}
@@ -0,0 +1,107 @@
package dev.caskeleton.composition.runtime.tracing;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.springframework.boot.SpringApplication;
import org.springframework.mock.env.MockEnvironment;
/**
* D-1 (ISSUE-1 해소): {@link TracingEnvironmentPostProcessor}가 유효 샘플링 비율을 {@code
* management.tracing.sampling.probability}로 브리지하는지 검증.
*/
class TracingEnvironmentPostProcessorTest {
private final TracingEnvironmentPostProcessor epp = new TracingEnvironmentPostProcessor();
@Test
void prodProfileBlankRateResolvesToOnePercent() {
MockEnvironment env = new MockEnvironment();
env.setActiveProfiles("prod");
// APP_TRACING_SAMPLE_RATE 미설정(blank) — per-profile 기본값이 적용돼야 한다.
epp.postProcessEnvironment(env, new SpringApplication());
assertThat(env.getProperty("management.tracing.sampling.probability")).isEqualTo("0.01");
}
@Test
void profilelessContextDoesNotInventALocalRuntimeButUsesTheSafeNonProductionRate() {
MockEnvironment env = new MockEnvironment();
epp.postProcessEnvironment(env, new SpringApplication());
assertThat(env.getProperty("management.tracing.sampling.probability")).isEqualTo("1.0");
}
@Test
void explicitRateWins() {
MockEnvironment env = new MockEnvironment();
env.setActiveProfiles("prod");
env.setProperty("app.tracing.sample-rate", "0.25");
epp.postProcessEnvironment(env, new SpringApplication());
assertThat(env.getProperty("management.tracing.sampling.probability")).isEqualTo("0.25");
}
@Test
void doesNotOverrideExplicitProbability() {
MockEnvironment env = new MockEnvironment();
env.setActiveProfiles("prod");
env.setProperty("management.tracing.sampling.probability", "0.5");
epp.postProcessEnvironment(env, new SpringApplication());
assertThat(env.getProperty("management.tracing.sampling.probability")).isEqualTo("0.5");
}
@ParameterizedTest
@ValueSource(strings = {"http://collector:4318", "http://collector:4318/"})
@DisplayName("OTEL_EXPORTER_OTLP_ENDPOINT 기준 주소에 trace 경로를 붙여 Boot의 exporter 키로 넘긴다")
void theOtlpBaseEndpointBecomesBootsTraceExportUrl(String baseEndpoint) {
// given
MockEnvironment env = new MockEnvironment();
env.setProperty("app.tracing.exporter.otlp-endpoint", baseEndpoint);
// when
epp.postProcessEnvironment(env, new SpringApplication());
// then
assertThat(env.getProperty(TracingEnvironmentPostProcessor.OTLP_ENDPOINT_KEY))
.isEqualTo("http://collector:4318/v1/traces");
}
@Test
@DisplayName("endpoint가 비어 있으면 Boot exporter 키를 만들지 않아 exporter가 생기지 않는다")
void aBlankEndpointLeavesBootsExporterKeyUnset() {
// given
MockEnvironment env = new MockEnvironment();
env.setProperty("app.tracing.exporter.otlp-endpoint", " ");
// when
epp.postProcessEnvironment(env, new SpringApplication());
// then
assertThat(env.containsProperty(TracingEnvironmentPostProcessor.OTLP_ENDPOINT_KEY)).isFalse();
}
@Test
@DisplayName("운영자가 Boot exporter 키를 직접 주면 그 값을 덮어쓰지 않는다")
void anExplicitBootEndpointWins() {
// given
MockEnvironment env = new MockEnvironment();
env.setProperty("app.tracing.exporter.otlp-endpoint", "http://collector:4318");
env.setProperty(TracingEnvironmentPostProcessor.OTLP_ENDPOINT_KEY, "http://other:4318/x");
// when
epp.postProcessEnvironment(env, new SpringApplication());
// then
assertThat(env.getProperty(TracingEnvironmentPostProcessor.OTLP_ENDPOINT_KEY))
.isEqualTo("http://other:4318/x");
}
}
@@ -1,59 +0,0 @@
package dev.caskeleton.composition.runtime.tracing;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.springframework.boot.SpringApplication;
import org.springframework.mock.env.MockEnvironment;
/**
* D-1 (ISSUE-1 해소): {@link TracingSamplingEnvironmentPostProcessor}가 유효 샘플링 비율을 {@code
* management.tracing.sampling.probability}로 브리지하는지 검증.
*/
class TracingSamplingEnvironmentPostProcessorTest {
private final TracingSamplingEnvironmentPostProcessor epp =
new TracingSamplingEnvironmentPostProcessor();
@Test
void prodProfileBlankRateResolvesToOnePercent() {
MockEnvironment env = new MockEnvironment();
env.setActiveProfiles("prod");
// APP_TRACING_SAMPLE_RATE 미설정(blank) — per-profile 기본값이 적용돼야 한다.
epp.postProcessEnvironment(env, new SpringApplication());
assertThat(env.getProperty("management.tracing.sampling.probability")).isEqualTo("0.01");
}
@Test
void profilelessContextDoesNotInventALocalRuntimeButUsesTheSafeNonProductionRate() {
MockEnvironment env = new MockEnvironment();
epp.postProcessEnvironment(env, new SpringApplication());
assertThat(env.getProperty("management.tracing.sampling.probability")).isEqualTo("1.0");
}
@Test
void explicitRateWins() {
MockEnvironment env = new MockEnvironment();
env.setActiveProfiles("prod");
env.setProperty("app.tracing.sample-rate", "0.25");
epp.postProcessEnvironment(env, new SpringApplication());
assertThat(env.getProperty("management.tracing.sampling.probability")).isEqualTo("0.25");
}
@Test
void doesNotOverrideExplicitProbability() {
MockEnvironment env = new MockEnvironment();
env.setActiveProfiles("prod");
env.setProperty("management.tracing.sampling.probability", "0.5");
epp.postProcessEnvironment(env, new SpringApplication());
assertThat(env.getProperty("management.tracing.sampling.probability")).isEqualTo("0.5");
}
}
@@ -0,0 +1,54 @@
package dev.caskeleton.composition.runtime.tracing;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.mock.env.MockEnvironment;
class TracingSwitchImportFilterTest {
private static final String[] CANDIDATES = {
"org.springframework.boot.micrometer.tracing.opentelemetry.autoconfigure"
+ ".OpenTelemetryTracingAutoConfiguration",
"org.springframework.boot.micrometer.tracing.autoconfigure.NoopTracerAutoConfiguration",
"org.springframework.boot.micrometer.observation.autoconfigure.ObservationAutoConfiguration",
"dev.caskeleton.composition.runtime.tracing.TracingConfig"
};
@Test
@DisplayName("app.tracing.enabled=false면 Boot tracing 자동 설정만 빠지고 나머지는 남는다")
void disabledTracingDropsOnlyBootsTracingAutoConfigurations() {
// given
TracingSwitchImportFilter filter = filterWith("false");
// when
boolean[] matches = filter.match(CANDIDATES, null);
// then
assertThat(matches).containsExactly(false, false, true, true);
}
@Test
@DisplayName("app.tracing.enabled가 없거나 true면 아무것도 빼지 않는다")
void enabledTracingKeepsEverything() {
// given
TracingSwitchImportFilter filter = filterWith(null);
// when
boolean[] matches = filter.match(CANDIDATES, null);
// then
assertThat(matches).containsExactly(true, true, true, true);
}
private static TracingSwitchImportFilter filterWith(String enabled) {
MockEnvironment environment = new MockEnvironment();
if (enabled != null) {
environment.setProperty("app.tracing.enabled", enabled);
}
TracingSwitchImportFilter filter = new TracingSwitchImportFilter();
filter.setEnvironment(environment);
return filter;
}
}