Merge branch 'main' into claude/r9-wallclock-tests
pr / done (pull_request) Successful in 12m59s

This commit is contained in:
2026-11-13 06:28:57 +00:00
67 changed files with 3122 additions and 907 deletions
@@ -14,7 +14,11 @@ import java.util.function.Supplier;
import org.slf4j.MDC;
/**
* Puts a call's correlation on MDC under the same keys the HTTP path uses (review X2-P2-5).
* Puts a call's correlation on MDC under the HTTP path's key names (review X2-P2-5) — a subset of
* them: {@code request_id}, and {@code trace_id}/{@code span_id} only when the caller sent a {@code
* traceparent}. No {@code correlation_id}: a gRPC call has no session to join, and the
* per-transport table in {@code docs/registries/mdc-keys.yaml} records that (this line used to say
* "the same keys", review 2026-11-12).
*
* <p>Correlation used to stop at the servlet filter: a log line written while a gRPC call ran
* carried no {@code request_id}, so it could not be joined to anything. Each call gets its own
+19 -15
View File
@@ -490,13 +490,15 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML
필터는 KEYED 가 아닌 엔드포인트까지 막아 버렸다.
### ApiHeaders
- 인바운드 web 어댑터 전역의 HTTP 헤더명 상수 — `docs/registries/headers.yaml`의
코드 미러. 리터럴을 중앙집중해 controller/filter/advice 가 casing 으로 drift 하지 않게 하고, 레지스트리
일관성 테스트가 단일 출처를 참조하게 한다.
- 소유권: `X-Api-Version`(D2)·`Idempotency-Key`(D3 — 이름만; key shape/scope/replay 정책은
application-core 소유)는 여기서 생산. conditional-request(D15)·cache(D16)·method/negotiation/
LRO(D12/D17)·pagination(D18)·rate-limit signaling(generated_if_missing=true; Limit/Remaining 은 numeric, Reset 은
rfc3339 = fixed-window end)·deep-offset deprecation marker(D18)·always-emitted(D24)는 표준 RFC 9110/9111 이름 참조.
- 인바운드 web 어댑터가 쓰는 HTTP 헤더명 상수. 리터럴을 한 곳에 모아 controller/filter/advice 가 casing 으로
drift 하지 않게 한다. `docs/registries/headers.yaml` 의 web 행은 이 파일을 `source` 로 가리키고,
`HeaderRegistryRuntimeAlignmentTest` 가 그 이름 글자가 이 파일에 있고 그 상수를 쓰는 main 코드가 있는지 본다
(`service:` 행은 서비스용 상수라 쓰는 곳을 보지 않는다).
- 템플릿 main 이 쓰는 상수: `Retry-After`, rate-limit 신호(`X-RateLimit-Limit`·`-Remaining` 은 숫자, `-Reset` 은
rfc3339 = fixed window 끝), `Cache-Control`·`Vary`, `ETag`·`Location`(CORS 노출 목록).
- 서비스 controller 가 읽으라고 둔 상수: `Idempotency-Key`(이름만. key shape/scope/replay 정책은 application-core 소유),
`If-Match`·`If-None-Match`(조건부 요청, 비교는 `conditional.ETags`), `Allow`. `Deprecation`·`Date` 상수는 있지만 아무
코드도 쓰지 않는다. `X-Api-Version` 은 없다.
---
@@ -508,20 +510,22 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML
같은 논리 ID 의 envelope 형태(camelCase)와 HTTP 헤더 형태(kebab-case)는 D19 projection 이며,
변환 단일 지점은 `ResponseMetaFactory`.
### LoggedPath
- 서버 로그 줄이 요청을 부르는 경로 하나다. 401·403 보안 줄의 `path=`(`AuthErrorResponseWriter`), 요청 로그 줄의
`uri_template=`(`RequestLoggingFilter`), 처리하지 못한 예외 줄(`GlobalExceptionHandler`)이 같이 쓴다.
- DispatcherServlet이 handler를 고르면 그 pattern(`/v1/orders/{id}`)이다. 정적 자원 handler가 받은 없는 경로는
`/**`다. 그 밖(보안 chain이 dispatch 전에 거부한 요청, 어떤 handler mapping도 받지 않은 요청)은 요청 경로에서
값이 들 수 있는 마디를 `{}`로 가린다. 글자·하이픈만인 마디와 API 버전(`v1`)만 남기고, 8마디까지만 쓴다.
- 모양으로 가르는 규칙이라 가장자리가 둘이다. 글자만인 값(`/users/alice`)은 남으니 경로에 이름을 넣는 route는 id로
바꾼다. 숫자나 점이 든 route 글자(`oauth2`, `.well-known`)는 값처럼 가려진다. handler가 고른 요청은 pattern으로
남아 둘 다 해당하지 않는다.
### MdcCorrelationIdPortAdapter
- `WebMvcRequestIdFilter`가 무해화하고 MDC `correlation_id`에 넣은 값을 application-core의
`CorrelationIdPort`로 투영한다.
- absent/blank는 `Optional.empty()`로 반환한다. application 계층은 SLF4J/MDC를 직접
참조하지 않고 event-id fallback 정책만 소유한다.
### HeaderSanitizer
- 이제 `X-Correlation-Id` 는 쓰지 않는다(요청 id 규칙으로 바뀜, 리뷰 02-11). 공개 유틸리티로 남아 있다.
- 인바운드 헤더 값을 MDC/로그 도달 전에 무해화(D14, OWASP-LOG-C3/C5, CWE-117). 스켈레톤은 구조화 JSON 로깅을
가정하므로 위협은 CR/LF/제어문자를 통한 로그 라인 위조 — 값은 보존하되 `\r`/`\n`/ASCII 제어문자(`< 0x20`)를
제거 후 길이 제한.
- `프로젝트 선택`: 구체 문자셋 정책(strip vs encode)과 최대 길이는 ca-tmpl 트레이드오프. OWASP 는
원칙만 규정하고 정규식/한계는 규정하지 않는다.
### ResponseMetaFactory
- snake_case MDC 진단 키를 camelCase `ResponseMeta` wire 객체로 projection 하는 D19 단일 변환 지점. adapter-web
에 위치하는 이유: shared-contract 는 프레임워크 중립이라 MDC 를 읽으면 안 된다.
@@ -1,6 +1,7 @@
package dev.caskeleton.adapter.inbound.web.auth;
import dev.caskeleton.adapter.inbound.web.error.EnvelopeResponseWriter;
import dev.caskeleton.adapter.inbound.web.observability.LoggedPath;
import dev.caskeleton.adapter.inbound.web.observability.RetryAfterAdvisor;
import dev.caskeleton.shared.error.OperationalError;
import jakarta.servlet.http.HttpServletRequest;
@@ -29,7 +30,9 @@ class AuthErrorResponseWriter {
void write(HttpServletRequest request, HttpServletResponse response, OperationalError code)
throws IOException {
// Log only safe metadata — never the token or the raw failure message. A 5xx is the server's
// Log only safe metadata — never the token, the raw failure message or the raw path: the chain
// refuses before dispatch, so there is no route template, and the path is redacted. A 5xx is
// the server's
// own failure (the key service is down, the decoder is misconfigured) and is an ERROR, as a 5xx
// is on every other path (ServerFailureLog); a 4xx is the caller's and stays a WARN.
log.atLevel(code.httpStatus() >= 500 ? Level.ERROR : Level.WARN)
@@ -38,7 +41,7 @@ class AuthErrorResponseWriter {
code.code(),
code.category(),
request.getMethod(),
request.getRequestURI());
LoggedPath.of(request));
// A 401 response carries a minimal WWW-Authenticate header (no issuer / token detail).
if (code.httpStatus() == 401) {
@@ -3,6 +3,7 @@ package dev.caskeleton.adapter.inbound.web.error;
import dev.caskeleton.adapter.inbound.web.auth.SecurityErrorClassifier;
import dev.caskeleton.adapter.inbound.web.conditional.PreconditionFailedException;
import dev.caskeleton.adapter.inbound.web.http.ApiHeaders;
import dev.caskeleton.adapter.inbound.web.observability.LoggedPath;
import dev.caskeleton.adapter.inbound.web.observability.RetryAfterAdvisor;
import dev.caskeleton.adapter.inbound.web.pagination.PageValidationException;
import dev.caskeleton.shared.error.ApiErrorCarrier;
@@ -212,11 +213,18 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
if (carrier.isPresent()) {
return handleCarrier(carrier.get());
}
log.error("unhandled exception on {}", req.getDescription(false), ex);
// The redacted path, not getDescription(false): that is "uri=" plus the raw request URI.
log.error("unhandled exception on {}", loggedPath(req), ex);
spanErrorRecorder.recordException(ex, OperationalError.INTERNAL_ERROR.code());
return ErrorResponseFactory.envelope(OperationalError.INTERNAL_ERROR, null);
}
private static String loggedPath(WebRequest request) {
return request instanceof ServletWebRequest servlet
? LoggedPath.of(servlet.getRequest())
: LoggedPath.HIDDEN;
}
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex,
@@ -1,6 +1,7 @@
package dev.caskeleton.adapter.inbound.web.filter;
import dev.caskeleton.adapter.inbound.web.auth.AuthenticatedPrincipal;
import dev.caskeleton.adapter.inbound.web.observability.LoggedPath;
import dev.caskeleton.application.observability.UserPrincipalPseudonymizerPort;
import dev.caskeleton.shared.observability.MdcKeys;
import jakarta.servlet.FilterChain;
@@ -15,7 +16,6 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.HandlerMapping;
/**
* Logs one structured line per HTTP request. The correlation ids on MDC ({@code request_id}, {@code
@@ -60,12 +60,11 @@ public class RequestLoggingFilter extends OncePerRequestFilter {
}
/**
* Returns the low-cardinality matched route template ({@code BEST_MATCHING_PATTERN_ATTRIBUTE}),
* falling back to the raw request URI for unmatched requests (e.g. 404s).
* Returns the low-cardinality matched route template, falling back to the redacted request path
* for unmatched requests (e.g. 404s) — {@link LoggedPath}. The fallback used to be the raw URI.
*/
private static String resolveUriTemplate(HttpServletRequest req) {
Object pattern = req.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
return pattern instanceof String s ? s : req.getRequestURI();
return LoggedPath.of(req);
}
/**
@@ -1,25 +0,0 @@
package dev.caskeleton.adapter.inbound.web.observability;
/**
* Neutralizes inbound header values before they reach MDC / logs by stripping every {@code \r},
* {@code \n} and ASCII control char ({@code < 0x20}) and length-capping the result. See README for
* the design rationale.
*/
public final class HeaderSanitizer {
private HeaderSanitizer() {}
public static String sanitize(String raw, int maxLength) {
if (raw == null) {
return null;
}
StringBuilder sb = new StringBuilder(Math.min(raw.length(), maxLength));
for (int i = 0; i < raw.length() && sb.length() < maxLength; i++) {
char c = raw.charAt(i);
if (c >= 0x20) {
sb.append(c);
}
}
return sb.toString();
}
}
@@ -0,0 +1,70 @@
package dev.caskeleton.adapter.inbound.web.observability;
import jakarta.servlet.http.HttpServletRequest;
import java.util.StringJoiner;
import java.util.regex.Pattern;
import org.springframework.web.servlet.HandlerMapping;
/**
* The path a server log line names a request by.
*
* <p>The matched pattern when the dispatcher found a handler ({@code /v1/orders/{id}}): low
* cardinality and free of identifiers. An unmatched path that Boot's static-resource handler takes
* is named {@code /**} that way. Otherwise — a request the security chain refused before dispatch,
* a request no handler mapping took — the request path with every segment that could carry an
* identifier or a personal value replaced by {@value #HIDDEN}: only a segment of letters and
* hyphens ({@code orders}, {@code notificationTemplates}) or an API version ({@code v1}) stays, and
* at most {@value #MAX_SEGMENTS} segments are kept. The raw {@code getRequestURI()} used to be
* logged on those paths (review 2026-11-12), so an email address, a token or an object id in the
* path reached the log.
*
* <p>The rule is by shape, so it has two known edges. A segment of letters only stays even when it
* is a value ({@code /users/alice}): a service that puts names in paths gets them in these lines
* and should give such routes ids instead. A route literal with a digit or a dot ({@code oauth2},
* {@code .well-known}) is hidden like a value. A matched request is named by its template and has
* neither edge.
*/
public final class LoggedPath {
/** What a segment that may carry a value is replaced by. */
public static final String HIDDEN = "{}";
/** Segments kept before the rest is cut to {@code /...}. */
static final int MAX_SEGMENTS = 8;
private static final Pattern PLAIN_SEGMENT =
Pattern.compile("[A-Za-z][A-Za-z-]{0,39}|v[0-9]{1,3}");
private LoggedPath() {}
/** The matched route template, or the redacted request path. */
public static String of(HttpServletRequest request) {
Object template = request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
if (template instanceof String matched && !matched.isBlank()) {
return matched;
}
return redacted(request.getRequestURI());
}
/** The path with every segment outside the plain form replaced. */
public static String redacted(String path) {
if (path == null || path.isEmpty() || "/".equals(path)) {
return "/";
}
String[] segments = path.split("/", -1);
StringJoiner out = new StringJoiner("/");
int kept = 0;
for (String segment : segments) {
if (segment.isEmpty()) {
out.add("");
continue;
}
if (kept++ == MAX_SEGMENTS) {
out.add("...");
break;
}
out.add(PLAIN_SEGMENT.matcher(segment).matches() ? segment : HIDDEN);
}
return out.toString();
}
}
@@ -9,6 +9,7 @@ import dev.caskeleton.shared.error.Category;
import dev.caskeleton.shared.error.ClientErrorMessages;
import java.io.IOException;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.slf4j.LoggerFactory;
@@ -178,13 +179,18 @@ class EnvelopeAuthenticationEntryPointTest {
/** The lines the security writer logs while the entry point answers {@code failure}. */
private List<ILoggingEvent> writerLinesFor(AuthenticationException failure) throws Exception {
return writerLinesFor(failure, "/v1/things");
}
private List<ILoggingEvent> writerLinesFor(AuthenticationException failure, String path)
throws Exception {
Logger logger = (Logger) LoggerFactory.getLogger(AuthErrorResponseWriter.class);
ListAppender<ILoggingEvent> appender = new ListAppender<>();
appender.start();
logger.addAppender(appender);
try {
entryPoint.commence(
new MockHttpServletRequest("GET", "/v1/things"), new MockHttpServletResponse(), failure);
new MockHttpServletRequest("GET", path), new MockHttpServletResponse(), failure);
} finally {
logger.detachAppender(appender);
appender.stop();
@@ -192,6 +198,25 @@ class EnvelopeAuthenticationEntryPointTest {
return appender.list;
}
@Test
@DisplayName("보안 실패 줄은 원본 경로 대신 식별자를 가린 경로를 남긴다(route 를 찾기 전이라 template 이 없다)")
void theSecurityLineNamesARedactedPathNotTheRawOne() throws Exception {
// given
AuthenticationException missing =
new org.springframework.security.authentication.InsufficientAuthenticationException("x");
// when
List<ILoggingEvent> lines = writerLinesFor(missing, "/v1/users/alice@example.com/orders/42");
// then
assertThat(lines)
.singleElement()
.extracting(ILoggingEvent::getFormattedMessage)
.isEqualTo(
"security failure: code=AUTH_TOKEN_MISSING category=AUTH method=GET"
+ " path=/v1/users/{}/orders/{}");
}
@Test
void tokenValueNeverLeaksIntoResponseBodyOrLogs(CapturedOutput output) throws Exception {
// §테스트 계약: a JWT value must never appear in the response or the log output.
@@ -365,6 +365,33 @@ class GlobalExceptionHandlerTest {
}
}
@Test
@DisplayName("처리하지 못한 예외의 ERROR 줄은 원본 경로가 아니라 식별자 마디를 가린 경로를 싣는다")
void anUnhandledFailureIsLoggedWithTheRedactedPathNotTheRawUri() {
// given
ch.qos.logback.classic.Logger logger =
(ch.qos.logback.classic.Logger) LoggerFactory.getLogger(GlobalExceptionHandler.class);
ListAppender<ILoggingEvent> appender = new ListAppender<>();
appender.start();
logger.addAppender(appender);
// when
try {
handler.handleUnknown(
new RuntimeException("boom"),
new ServletWebRequest(new MockHttpServletRequest("GET", "/v1/orders/SECRET-0042/items")));
} finally {
logger.detachAppender(appender);
appender.stop();
}
// then
assertThat(appender.list)
.singleElement()
.extracting(ILoggingEvent::getFormattedMessage)
.isEqualTo("unhandled exception on /v1/orders/{}/items");
}
@Test
void internalErrorIsNotRetryableAndHidesMessage() {
ResponseEntity<Envelope<Void>> response =
@@ -12,6 +12,7 @@ import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
@@ -93,6 +94,27 @@ class RequestLoggingFilterTest {
}
}
@Test
@DisplayName("route 를 못 찾은 요청 줄은 원본 경로가 아니라 식별자 마디를 가린 경로를 싣는다")
void anUnmatchedRequestIsLoggedWithTheRedactedPath() throws Exception {
// given
MockHttpServletRequest req = new MockHttpServletRequest("GET", "/v1/orders/SECRET-0042/items");
MockHttpServletResponse res = new MockHttpServletResponse();
ListAppender<ILoggingEvent> listAppender = attachAppender();
// when
String msg;
try {
filter.doFilter(req, res, (rq, rs) -> {});
msg = httpRequestEvent(listAppender).getFormattedMessage();
} finally {
detach(listAppender);
}
// then
assertThat(msg).contains("uri_template=/v1/orders/{}/items").doesNotContain("SECRET-0042");
}
// DRIFT-6: user_principal on MDC must be pseudonymized, never raw
@Test
void putsPseudonymizedUserPrincipalOnMdcNotRawId() throws Exception {
@@ -1,39 +0,0 @@
package dev.caskeleton.adapter.inbound.web.observability;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
class HeaderSanitizerTest {
@Test
void stripsCrLfSoALogForgingPayloadStaysOneLine() {
String sanitized = HeaderSanitizer.sanitize("foo\r\nFAKE LOG ENTRY", 200);
assertThat(sanitized).isEqualTo("fooFAKE LOG ENTRY");
assertThat(sanitized).doesNotContain("\r").doesNotContain("\n");
}
@Test
void stripsAsciiControlCharactersButKeepsNormalSpace() {
// \t (0x09) and  are control chars (< 0x20) and are removed;
// a normal space (0x20) is preserved.
String sanitized = HeaderSanitizer.sanitize("abc\td e", 200);
assertThat(sanitized).isEqualTo("abcd e");
}
@Test
void capsLength() {
String sanitized = HeaderSanitizer.sanitize("abcdef", 3);
assertThat(sanitized).isEqualTo("abc");
}
@Test
void nullInNullOut() {
assertThat(HeaderSanitizer.sanitize(null, 10)).isNull();
}
@Test
void preservesNormalPrintableValue() {
assertThat(HeaderSanitizer.sanitize("01HZX9-ok_value", 64)).isEqualTo("01HZX9-ok_value");
}
}
@@ -0,0 +1,48 @@
package dev.caskeleton.adapter.inbound.web.observability;
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.CsvSource;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.web.servlet.HandlerMapping;
class LoggedPathTest {
@ParameterizedTest
@CsvSource({
"/v1/things, /v1/things",
"/api/users/alice@example.com, /api/users/{}",
"/api/orders/42/items, /api/orders/{}/items",
"/internal/notification/callbacks/ses/ses-events, /internal/notification/callbacks/ses/ses-events",
"/files/01J9ZP3QX8, /files/{}",
"/a/b/c/d/e/f/g/h/i/j, /a/b/c/d/e/f/g/h/...",
"/notificationTemplates/tpl_1, /notificationTemplates/{}"
})
@DisplayName("route 를 못 찾은 요청은 식별자가 들 수 있는 마디를 {} 로 가린 경로로 남는다")
void anUnmatchedPathKeepsOnlyPlainSegments(String raw, String logged) {
// given
MockHttpServletRequest request = new MockHttpServletRequest("GET", raw);
// when
String path = LoggedPath.of(request);
// then
assertThat(path).isEqualTo(logged);
}
@Test
void aMatchedRequestIsNamedByItsRouteTemplate() {
// given
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/v1/orders/42");
request.setAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, "/v1/orders/{id}");
// when
String path = LoggedPath.of(request);
// then
assertThat(path).isEqualTo("/v1/orders/{id}");
}
}
@@ -103,7 +103,7 @@ public final class MicrometerFileserverMetrics implements FileserverMetricsPort
@Override
public void recordOffsetMismatch(UploadMode mode, String clientType) {
increment(
"fileserver.upload.offset_mismatch",
"fileserver.upload.offset.mismatch",
Tags.of("mode", tag(mode.name()), "client_type", tag(clientType)));
}
@@ -26,8 +26,9 @@ public final class HttpClientObservationNames {
public static final String CONNECT_DURATION = "http.client.connect.duration";
public static final String TLS_DURATION = "http.client.tls.duration";
public static final String CIRCUIT_STATE = "http.client.circuit.state";
public static final String CIRCUIT_REJECTED = "http.client.circuit.state.rejected";
public static final String BULKHEAD_REJECTED = "http.client.bulkhead.rejected";
public static final String RATE_LIMIT_REJECTED = "http.client.rate_limit.rejected";
public static final String RATE_LIMIT_REJECTED = "http.client.ratelimit.rejected";
public static final String OAUTH_REFRESH = "http.client.oauth.refresh";
public static final String SSRF_REJECTED = "http.client.ssrf.rejected";
@@ -11,7 +11,7 @@ import java.util.function.Supplier;
/**
* Publishes the local back-pressure signals the platform already produced but never recorded.
*
* <p>{@code http.client.rate_limit.rejected}, {@code http.client.bulkhead.rejected} and {@code
* <p>{@code http.client.ratelimit.rejected}, {@code http.client.bulkhead.rejected} and {@code
* http.client.circuit.state} were declared in the metric vocabulary, documented in the support
* matrix, and emitted by nothing. That is the worst arrangement of the three possibilities: an
* operator building a dashboard finds the names, charts them, and sees a flat zero during the exact
@@ -76,7 +76,7 @@ public interface ResilienceRejectionRecorder {
return new ResilienceRejectionRecorder() {
@Override
public void circuitOpen() {
registry.counter(HttpClientObservationNames.CIRCUIT_STATE + ".rejected", tags).increment();
registry.counter(HttpClientObservationNames.CIRCUIT_REJECTED, tags).increment();
}
@Override
@@ -24,8 +24,8 @@ bean과 함께 Boot의 JDBC·Hibernate·Spring Data JPA·Flyway 자동 설정도
필요한 다른 capability(notification·fileserver 저장소, messaging JDBC outbox/inbox 등)와 함께 끌 수는 없다)
- 포트 구현: `TransactionPort`(`SpringTransaction`), `DistributedLockPort`(단일 인스턴스는
in-process, `APP_MULTI_INSTANCE_ENABLED=true`면 JDBC `INT_LOCK` + `MeteredDistributedLock`
데코레이터 = `distributedLockProvider`), outbox store(`OutboxStorePort`, `APP_OUTBOX_ENABLED=true`),
in-process, `APP_MULTI_INSTANCE_ENABLED=true`면 JDBC `INT_LOCK` = `distributedLockProvider`. 둘 다
`MeteredDistributedLock` 데코레이터 안에 있다), outbox store(`OutboxStorePort`, `APP_OUTBOX_ENABLED=true`),
PostgreSQL 멱등성 store(`APP_IDEMPOTENCY_PROVIDER=postgresql`), audit·operation·live-event store.
- 엔티티/리포지토리 스캔, vendor 조립(PostgreSQL 기본, H2는 개발용), Flyway 위치.
- 기동 정책(`startup` 패키지, `JpaStartupAutoConfiguration`): Flyway 마이그레이션 전략
@@ -540,7 +540,8 @@ provider 선택(flag → bean → registry)의 정본은 설정 코드 `lock/Dis
### `DistributedLockPersistenceConfig` 와이어링 결정
- `jdbcDistributedLock` 빈은 일부러 `@Primary` 가 아니다. 같은 설정이 이를 metrics
데코레이터(`MeteredDistributedLock`, package-private)로 감싸 `@Primary`
`distributedLockProvider` 빈으로 노출한다. 예전에는 app-bootstrap의 `DistributedLockConfig`가
`distributedLockProvider` 빈으로 노출한다. 단일 인스턴스의 `inProcessDistributedLock` 도 같은 데코레이터 안에 있어
`lock.acquisition` 이 두 경로를 모두 센다. 예전에는 app-bootstrap의 `DistributedLockConfig`가
감쌌지만, JDBC 락이 있을 때만 의미가 있는 코드라 이 모듈로 옮겼다. SI 타입은 여전히 이 모듈
밖으로 보이지 않는다(SI 는 `implementation` 의존).
- `DefaultLockRepository` 는 `InitializingBean`/`SmartLifecycle` 을 구현해 Spring 이 lifecycle 을
@@ -37,7 +37,14 @@ public class DistributedLockPersistenceConfig {
return LockSettings.bind(environment);
}
/** In-process adapter; active when {@code multi-instance-enabled} is {@code false} or absent. */
/**
* In-process adapter; active when {@code multi-instance-enabled} is {@code false} or absent.
*
* <p>Behind the same metrics decorator as the JDBC one, so {@code lock.acquisition} counts every
* call on both paths. It used to be the bare adapter, and on the default single-instance path the
* meter stayed at zero while the registry and README said it counted every call (review
* 2026-11-12).
*/
@Bean
@Primary
@ConditionalOnProperty(
@@ -45,8 +52,11 @@ public class DistributedLockPersistenceConfig {
name = "multi-instance-enabled",
havingValue = "false",
matchIfMissing = true)
DistributedLockPort inProcessDistributedLock(LockSettings settings) {
return new LockRegistryDistributedLock(new DefaultLockRegistry(), settings.leaseTtl());
DistributedLockPort inProcessDistributedLock(
LockSettings settings, ObjectProvider<MeterRegistry> meterRegistry) {
return new MeteredDistributedLock(
new LockRegistryDistributedLock(new DefaultLockRegistry(), settings.leaseTtl()),
meterRegistry);
}
/**
@@ -4,6 +4,9 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import dev.caskeleton.application.lock.DistributedLockPort;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import java.time.Duration;
import javax.sql.DataSource;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
@@ -35,6 +38,32 @@ class DistributedLockPersistenceConfigTest {
});
}
@Test
@DisplayName("단일 인스턴스의 in-process lock 도 lock.acquisition 을 센다")
void theInProcessLockIsMeteredToo() {
contextRunner
.withBean(MeterRegistry.class, SimpleMeterRegistry::new)
.withPropertyValues("app.runtime.multi-instance-enabled=false")
.run(
context -> {
// when
context
.getBean(DistributedLockPort.class)
.tryAcquire("orders", Duration.ZERO, Duration.ofSeconds(5))
.close();
// then
assertThat(
context
.getBean(MeterRegistry.class)
.get("lock.acquisition")
.tag("outcome", "acquired")
.counter()
.count())
.isEqualTo(1.0);
});
}
@Test
@DisplayName("app.lock 아래 오타 키는 기동을 실패시킨다")
void aMisspelledLockKeyFailsStartup() {