fix(observability)!: 지표·MDC·헤더 registry를 코드가 실제로 내는 것과 맞춘다
pr / done (pull_request) Canceled after 0s

관측 registry가 코드와 양쪽으로 어긋난다. metrics.yaml에는 아무 코드도
등록하지 않는 행 열하나와 코드에 없는 tag 값이 있고, 코드가 등록하는
graphql·notification·http.client·fileserver·mongodb·jpa.query 지표 다수가
없다. mdc-keys.yaml은 18키 중 코드가 넣는 5키만 맞고 required_in이 틀렸다.
headers.yaml은 X-Request-Id·X-Correlation-Id를 ulid로 적고 아무도 쓰지
않는 Deprecation·Sunset·tracestate를 적는다. 전송마다 correlation 규칙이
다른데 registry는 하나로 적는다. 단일 인스턴스 in-process lock은
lock.acquisition을 세지 않아 그 지표가 0이다. 밑줄 든 meter 이름 둘이
이름 규칙을 어긴다.

- 행마다 등록하는 main 파일(source)·상수(constant)·등록 주체
  (registered_by)를 적고, MetricsRegistryCodeAlignmentTest가 행 → 코드(이름이
  상수면 그 상수를 쓰는 곳까지)와 코드(글자·상수 이름의 builder·registry·
  Metrics 호출) → 행 두 방향을 본다. 템플릿이 부르지 않는 공개 메서드로만
  생기는 job.* 행은 emitted_when을 적는다. 버린 안: 행만 지우기(새 지표가
  다시 빠진다).
- mdc-keys는 5키와 전송별 표, headers는 source가 든 33행(서비스 controller용
  상수는 service: 출처), StructuredLog·HeaderRegistry 시험이 코드 상수와
  집합을 대조한다. 두 registry 시험은 시험 도우미 MainSources를 같이 쓴다.
- slo_driven 행은 MetricsDistributionMeterFilter 대상과 같은 집합이다(두
  방향 시험). histogram을 켜지 않는 hikaricp timer 행은 평균으로 경보한다.
  graphql.datafetcher·dataloader 행에 Spring 기본 tag를 적는다.
- in-process lock을 MeteredDistributedLock으로 감싼다.
- http.client.ratelimit.rejected, fileserver.upload.offset.mismatch로
  이름을 바꾸고 http.client.circuit.state.rejected를 상수로 둔다.
- CardinalityBounds(status 40·outcome 6·uri), MetricNaming 단위 규칙,
  SLO filter 대상(http.server.requests·jvm.gc.pause)을 문서와 맞춘다.

위험: 지표 이름 둘이 바뀌고 단일 인스턴스 lock 지표가 생긴다. 그 이름으로
만든 대시보드·경보를 옮겨야 한다(docs/upgrade/2026-11-round9-observability.md
8~13행). ApachePoolMetricsBinder·MongoTransactionRetry 지연은 다른 묶음이
맡는다.

검증: 위와 같은 desktop 실행(묶음 셋을 합친 트리) rc=0.

Refs: RR9-02-05, RR9-02-07, RR9-02-08, RR9-02-27, RR9-03-05
BREAKING CHANGE: http.client.rate_limit.rejected → http.client.ratelimit.rejected,
  fileserver.upload.offset_mismatch → fileserver.upload.offset.mismatch,
  CardinalityBounds 상수. docs/upgrade/2026-11-round9-observability.md 8~13행.
This commit is contained in:
DongHyeonka
2026-11-13 13:12:27 +09:00
parent a7f44d8a8d
commit 354b7fc959
30 changed files with 2158 additions and 708 deletions
+3 -3
View File
@@ -43,7 +43,7 @@ paths:
## 이 분야에서 실패는 이렇게 보인다
- [ ] 새 구조화 칸은 `docs/observability/log-fields.md`에, 새 MDC 키는 `docs/registries/mdc-keys.yaml`에, 새 지표는 `docs/registries/metrics.yaml`에 먼저 있다. 헤더와 짝이면 `docs/registries/headers.yaml`도. — 각 파일 머리말
- [ ] 지표 이름은 dot.case에 단위 접미사(`.seconds`·`.bytes`·`.total`)이고, tag마다 cardinality 상한이 있다. `error_code` tag는 registry 행 수를 넘지 않는다. — `docs/registries/metrics.yaml`
- [ ] 지표 이름은 dot.case이고 단위는 registry 행의 `unit`(`seconds`·`bytes`·`total`)이 말한다. tag마다 cardinality 상한이 있다. `error_code` tag는 registry 행 수를 넘지 않는다. — `docs/registries/metrics.yaml`
- [ ] 레벨: 클라이언트 탓 WARN, 서버 탓 ERROR + `ServerFailureLog`, 기동 실패는 `StartupFailures`(`startup.phase`, `error.code`). — A8, `docs/observability/log-fields.md`
- [ ] 메시지 문장은 사람용, 칸은 기계용이다. 검색·필터·경보는 칸으로 한다. — `docs/observability/log-fields.md`
- [ ] 예외는 원인(cause)을 잃지 않게 감싸되, 메시지에 입력값을 넣지 않는다. — 일반 원칙, A8
@@ -58,8 +58,8 @@ paths:
Gradle은 desktop에서 돈다(`docs/work/operate.md` 4.1절).
- registry와 코드 대조: app-bootstrap `test`의 `MetricsAlertingContractTest`, `StructuredLogFieldContractTest`, `DistributedTracingContractTest`, `HeaderRegistryRuntimeAlignmentTest`, `RunbookCoverageContractTest`, `OperationalErrorRegistryContractTest` → `scripts/verify.sh leaf :app-bootstrap`
- 새어 나감: `SqlLoggingForbiddenContractTest`, `PiiTokenBodyForbiddenContractTest`(같은 leaf), `:adapter:inbound:web:jpaPersistenceRedactionContractTest`(DB 실패가 로그·span에 닿지 않음)
- registry 파일을 읽는 대조는 `document-contract` 태그라 `test`에서 빠지고 `:app-bootstrap:documentContractTest`(main 단계)에서 돈다: `HeaderRegistryRuntimeAlignmentTest`, `RunbookCoverageContractTest`, `OperationalErrorRegistryContractTest`, `MetricsRegistryCodeAlignmentTest`(지표 행 ↔ 등록 코드 두 방향), `SecretsClassificationRegistryTest`(가림 규칙이 실제로 가리는지), 그리고 `MetricsAlertingContractTest`·`StructuredLogFieldContractTest`·`DistributedTracingContractTest`의 태그 붙은 메서드. 그 세 클래스의 나머지 메서드는 app-bootstrap `test` → `scripts/verify.sh leaf :app-bootstrap`
- 새어 나감: `SqlLoggingForbiddenContractTest`(`repository-contract` → `:app-bootstrap:repositoryContractTest`), `PiiTokenBodyForbiddenContractTest`(app-bootstrap `test`, 그 안의 `requestLoggingHasNoBodyCapturePath`는 `repository-contract`), `:adapter:inbound:web:jpaPersistenceRedactionContractTest`(DB 실패가 로그·span에 닿지 않음)
- runtime 배선: `scripts/verify.sh leaf :composition:service-runtime`, span 내보내기는 app-bootstrap `systemTest`의 `TracingExportSystemTest`
- runbook 숫자·SQL이 문서와 맞는지: document-contract lane(`:app-bootstrap:documentContractTest`, main 단계)과 runbook SQL을 실 PostgreSQL에서 도는 lane(`:adapter:outbound:persistence-jpa:postgresqlOutboxDispositionRunbookIntegrationTest` 등)
+17 -10
View File
@@ -13,19 +13,26 @@
| `http.client.timeout` | 단계별 시간 초과 |
| `http.client.request.bytes` | 요청 wire 바이트 |
| `http.client.response.bytes` | 응답 바이트 |
| `http.client.active` | 진행 중인 시도 |
| `http.client.pool.connections` | 빌려 간 connection과 남은 connection |
| `http.client.pool.pending` | pool 대기자 |
| `http.client.pool.acquire.duration` | pool 대기 시간 |
| `http.client.dns.duration` | DNS 시간 |
| `http.client.connect.duration` | 연결 시간 |
| `http.client.tls.duration` | TLS 시간 |
| `http.client.circuit.state` | circuit 상태 |
| `http.client.circuit.state` | circuit 상태(1 = open) |
| `http.client.circuit.state.rejected` | circuit이 열려 거부한 호출 |
| `http.client.bulkhead.rejected` | bulkhead 거부 |
| `http.client.rate_limit.rejected` | 로컬 속도 제한 거부 |
| `http.client.oauth.refresh` | token 갱신 결과 |
| `http.client.ratelimit.rejected` | 로컬 속도 제한 거부 |
| `http.client.ssrf.rejected` | dynamic target 거부 |
이름은 정했지만 아직 아무 코드도 내지 않는 metric이다(`HttpClientObservationNames` 상수, `DeclaredMetricsAreEmittedTest`의
「아직 안 냄」 목록). 대시보드·경보에 쓰지 않는다. `docs/registries/metrics.yaml`에도 행이 없다.
| Metric | 내려면 필요한 것 |
|---|---|
| `http.client.active` | 논리 호출 observation 수명에 묶인 진행 중 gauge |
| `http.client.pool.acquire.duration` | engine마다 요청 단계 시간 |
| `http.client.dns.duration` | engine마다 요청 단계 시간 |
| `http.client.connect.duration` | engine마다 요청 단계 시간 |
| `http.client.tls.duration` | engine마다 요청 단계 시간 |
| `http.client.oauth.refresh` | token loader가 `MeterRegistry`를 받는 것 |
`http.client.requests`는 시도를 세고 `http.client.logical.calls`는 사용자 호출을 센다. 둘이 벌어지면 재시도가
실패를 흡수하고 있다는 뜻이다. 장애 때 가장 먼저 볼 곳이다.
@@ -35,8 +42,8 @@
|---|---|---|
| 논리 호출은 괜찮은데 시도가 치솟는다 | upstream이 나빠졌고 재시도가 흡수하고 있다 | 이유별 `http.client.retry.count` |
| `http.client.ambiguous`가 0이 아니다 | 멱등이 아닌 쓰기가 `SENT_NO_RESPONSE`에 닿는다 | upstream과 맞춰 본다. 멱등 key를 검토한다 |
| pool 대기가 오른다 | pool이 작거나 upstream이 느리다 | `http.client.pool.acquire.duration`, `pool.connections` |
| circuit이 열렸다 | 계속된 upstream 실패: transport 오류, 5xx, 408, 429 | `http.client.circuit.state`. 로컬 거부와 그 밖의 4xx는 circuit을 열지 않는다 |
| pool 대기가 오른다 | pool이 작거나 upstream이 느리다 | `http.client.pool.pending`, `pool.connections` |
| circuit이 열렸다 | 계속된 upstream 실패: transport 오류, 5xx, 408, 429 | `http.client.circuit.state`, `http.client.circuit.state.rejected`. 로컬 거부와 그 밖의 4xx는 circuit을 열지 않는다 |
| `http.client.ssrf.rejected`가 0이 아니다 | 호출자가 내부 URL을 넣고 있다 | Dynamic Target 정책과 감사 기록 |
## Actuator
+309 -30
View File
@@ -7,13 +7,19 @@
# - W3C 표준 헤더: 소문자 (traceparent, tracestate)
# - mdc_key: snake_case (foundation이 정본)
# - envelope_meta_field: camelCase (envelope이 정본)
# - 행은 코드가 실제로 읽거나 쓰는 헤더다. `source`는 셋 중 하나다(HeaderRegistryRuntimeAlignmentTest가 대조한다).
# - main 파일 경로: 그 이름 글자를 가지고 실제로 쓰는 파일. 이름이 상수면 그 상수를 쓰는 곳이 있어야 한다.
# - `service: <경로>`: 서비스 controller가 읽으라고 둔 `ApiHeaders` 상수다. 템플릿 main은 그 상수를 쓰지 않는다
# (파일 서버는 If-Match·If-None-Match를 Spring `HttpHeaders` 상수로 읽는다). 시험이 정한 헤더만 이 출처를 쓴다.
# - `framework: …`: Spring·라이브러리가 읽거나 쓴다.
headers:
# source: feature-operational-error-observability-foundation.md L97
# "request_id | inbound filter (생성 또는 X-Request-Id 헤더) | response header X-Request-Id"
- name: X-Request-Id
direction: both
type: ulid
type: uuid-or-caller-token
format: "UUID; 받는 값은 [A-Za-z0-9._-]{1,128}"
required: false
generated_if_missing: true
mdc_key: request_id
@@ -22,6 +28,7 @@ headers:
case_style: kebab
compatibility_impact: none
required_test: contract-verification:envelope-headers
source: "src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/filter/WebMvcRequestIdFilter.java"
# source: feature-api-contract-baseline.md L77 / feature-rate-limit-idempotency-contract.md L66-67
# "idempotency header 이름은 Idempotency-Key" / "기본 scope는 (authenticatedPrincipal, idempotencyKey, useCaseName)"
@@ -36,6 +43,7 @@ headers:
case_style: kebab
compatibility_impact: additive
required_test: contract-verification:idempotency-replay
source: "service: src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/ApiHeaders.java"
# source: feature-rate-limit-idempotency-contract.md L85 / foundation L85
# "RATE_LIMIT | ... | 429 | true (Retry-After 이후)" / "retry-after 기준 없이 429를 반환하면 실패"
@@ -50,6 +58,7 @@ headers:
case_style: kebab
compatibility_impact: additive
required_test: contract-verification:rate-limit-headers
source: "src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/ApiHeaders.java"
# source: feature-rate-limit-idempotency-contract.md scope L26 (rate limit response/log 기준)
# app.rate-limit.enabled=true인 요청 경로에서만 생성되는 rate-limit 응답 표면
@@ -64,6 +73,7 @@ headers:
case_style: kebab
compatibility_impact: additive
required_test: contract-verification:rate-limit-headers
source: "src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/ApiHeaders.java"
# source: feature-rate-limit-idempotency-contract.md scope L26 (rate limit response/log 기준)
- name: X-RateLimit-Remaining
@@ -77,6 +87,7 @@ headers:
case_style: kebab
compatibility_impact: additive
required_test: contract-verification:rate-limit-headers
source: "src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/ApiHeaders.java"
# source: feature-rate-limit-idempotency-contract.md scope L26 (rate limit response/log 기준)
- name: X-RateLimit-Reset
@@ -90,34 +101,7 @@ headers:
case_style: kebab
compatibility_impact: additive
required_test: contract-verification:rate-limit-headers
# source: feature-api-compatibility-deprecation-contract.md L87
# "deprecation marker | OpenAPI deprecated: true + design record | response header optional"
- name: Deprecation
direction: outbound
type: http-date
required: false
generated_if_missing: false
mdc_key: null
envelope_meta_field: null
owner_branch: feature-api-compatibility-deprecation-contract
case_style: kebab
compatibility_impact: additive
required_test: contract-verification:deprecation-marker
# source: feature-api-compatibility-deprecation-contract.md L87
# "deprecation marker | OpenAPI deprecated: true + design record | response header optional" (RFC 8594 Sunset)
- name: Sunset
direction: outbound
type: http-date
required: false
generated_if_missing: false
mdc_key: null
envelope_meta_field: null
owner_branch: feature-api-compatibility-deprecation-contract
case_style: kebab
compatibility_impact: additive
required_test: contract-verification:deprecation-marker
source: "src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/ApiHeaders.java"
# source: feature-distributed-tracing-contract.md L64, L85
# "propagation header는 W3C traceparent default" / "HTTP | traceparent, tracestate (W3C)"
@@ -132,6 +116,7 @@ headers:
case_style: kebab
compatibility_impact: none
required_test: contract-verification:trace-propagation
source: "src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/filter/WebMvcRequestIdFilter.java"
# source: feature-distributed-tracing-contract.md L66, L85
# "propagation format = W3C traceparent + tracestate only. B3 propagation은 forbidden"
@@ -146,12 +131,14 @@ headers:
case_style: kebab
compatibility_impact: none
required_test: contract-verification:trace-propagation
source: "framework: Micrometer Tracing(OTel)의 W3C 전파가 traceparent와 함께 읽고 쓴다"
# source: feature-operational-error-observability-foundation.md L100
# "correlation_id | inbound header X-Correlation-Id 또는 생성 | HTTP X-Correlation-Id, message header correlation_id"
- name: X-Correlation-Id
direction: both
type: ulid
type: uuid-or-caller-token
format: "UUID; 받는 값은 [A-Za-z0-9._-]{1,128}"
required: false
generated_if_missing: true
mdc_key: correlation_id
@@ -160,6 +147,7 @@ headers:
case_style: kebab
compatibility_impact: none
required_test: contract-verification:envelope-headers
source: "src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/filter/WebMvcRequestIdFilter.java"
# source: feature-security-operational-baseline.md L66
# "JWT Resource Server를 baseline security model로 둠" (Authorization 헤더의 Bearer 토큰)
@@ -174,6 +162,7 @@ headers:
case_style: kebab
compatibility_impact: none
required_test: contract-verification:jwt-resource-server
source: "framework: Spring Security bearer token resolver가 읽는다"
# source: feature-security-operational-baseline.md L83-90 (AuthN/AuthZ Decision Matrix)
# 401 응답 시 WWW-Authenticate (Bearer realm/error) — Spring Security JWT Resource Server의 표준 challenge 헤더
@@ -188,3 +177,293 @@ headers:
case_style: kebab
compatibility_impact: none
required_test: contract-verification:jwt-resource-server
source: "framework: HttpHeaders.WWW_AUTHENTICATE(AuthErrorResponseWriter가 401에 쓴다)"
# === web 응답·조건부 요청 (adapter:inbound:web) ===
# 모든 응답에 no-store(CacheControlFilter). 파일 다운로드는 자기 값을 쓴다.
- name: Cache-Control
direction: outbound
type: string
required: false
generated_if_missing: true
mdc_key: null
envelope_meta_field: null
owner_branch: web-platform
case_style: kebab
compatibility_impact: none
required_test: contract-verification:envelope-headers
source: "src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/ApiHeaders.java"
- name: Vary
direction: outbound
type: comma-separated
required: false
generated_if_missing: true
mdc_key: null
envelope_meta_field: null
owner_branch: web-platform
case_style: kebab
compatibility_impact: none
required_test: contract-verification:envelope-headers
source: "src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/ApiHeaders.java"
# 405 응답(GlobalExceptionHandler).
- name: Allow
direction: outbound
type: comma-separated
required: false
generated_if_missing: false
mdc_key: null
envelope_meta_field: null
owner_branch: web-platform
case_style: kebab
compatibility_impact: none
required_test: contract-verification:envelope-headers
source: "framework: Spring HttpHeaders.setAllow — GlobalExceptionHandler가 405 응답에 쓴다(ApiHeaders.ALLOW는 쓰지 않는다)"
# 201 생성 응답(durable operation, 파일 업로드).
- name: Location
direction: outbound
type: uri
required: false
generated_if_missing: false
mdc_key: null
envelope_meta_field: null
owner_branch: web-platform
case_style: kebab
compatibility_impact: none
required_test: contract-verification:envelope-headers
source: "src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/ApiHeaders.java"
- name: ETag
direction: outbound
type: entity-tag
required: false
generated_if_missing: false
mdc_key: null
envelope_meta_field: null
owner_branch: web-platform
case_style: kebab
compatibility_impact: none
required_test: contract-verification:envelope-headers
source: "src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/ApiHeaders.java"
- name: If-Match
direction: inbound
type: entity-tag
required: false
generated_if_missing: false
mdc_key: null
envelope_meta_field: null
owner_branch: web-platform
case_style: kebab
compatibility_impact: none
required_test: contract-verification:envelope-headers
source: "service: src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/ApiHeaders.java"
- name: If-None-Match
direction: inbound
type: entity-tag
required: false
generated_if_missing: false
mdc_key: null
envelope_meta_field: null
owner_branch: web-platform
case_style: kebab
compatibility_impact: none
required_test: contract-verification:envelope-headers
source: "service: src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/ApiHeaders.java"
# Redis 세션(쿠키) 모드의 CSRF 헤더 기본 이름.
- name: X-XSRF-TOKEN
direction: inbound
type: string
required: false
generated_if_missing: false
mdc_key: null
envelope_meta_field: null
owner_branch: web-platform
case_style: kebab
compatibility_impact: none
required_test: contract-verification:envelope-headers
source: "src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/settings/SecuritySettings.java"
# === 파일 서버 업로드·다운로드 (composition:fileserver-platform을 켤 때) ===
# Range·If-Range·Content-Range·Accept-Ranges·Content-Disposition·Last-Modified·If-Modified-Since·If-Unmodified-Since는
# HTTP 표준 헤더를 Spring HttpHeaders 상수로 쓴다(MvcDownloadResponseWriter, MvcConditionalRequestFactory). 아래는 이 플랫폼이
# 이름을 정한 헤더다.
- name: Tus-Resumable
direction: both
type: string
required: false
generated_if_missing: false
mdc_key: null
envelope_meta_field: null
owner_branch: fileserver-platform
case_style: kebab
compatibility_impact: none
required_test: contract-verification:envelope-headers
source: "src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusHeaders.java"
- name: Tus-Version
direction: outbound
type: string
required: false
generated_if_missing: false
mdc_key: null
envelope_meta_field: null
owner_branch: fileserver-platform
case_style: kebab
compatibility_impact: none
required_test: contract-verification:envelope-headers
source: "src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusHeaders.java"
- name: Tus-Extension
direction: outbound
type: string
required: false
generated_if_missing: false
mdc_key: null
envelope_meta_field: null
owner_branch: fileserver-platform
case_style: kebab
compatibility_impact: none
required_test: contract-verification:envelope-headers
source: "src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusHeaders.java"
- name: Tus-Max-Size
direction: outbound
type: string
required: false
generated_if_missing: false
mdc_key: null
envelope_meta_field: null
owner_branch: fileserver-platform
case_style: kebab
compatibility_impact: none
required_test: contract-verification:envelope-headers
source: "src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusHeaders.java"
- name: Upload-Defer-Length
direction: inbound
type: string
required: false
generated_if_missing: false
mdc_key: null
envelope_meta_field: null
owner_branch: fileserver-platform
case_style: kebab
compatibility_impact: none
required_test: contract-verification:envelope-headers
source: "src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusHeaders.java"
- name: Upload-Metadata
direction: inbound
type: string
required: false
generated_if_missing: false
mdc_key: null
envelope_meta_field: null
owner_branch: fileserver-platform
case_style: kebab
compatibility_impact: none
required_test: contract-verification:envelope-headers
source: "src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusHeaders.java"
- name: Upload-Expires
direction: outbound
type: string
required: false
generated_if_missing: false
mdc_key: null
envelope_meta_field: null
owner_branch: fileserver-platform
case_style: kebab
compatibility_impact: none
required_test: contract-verification:envelope-headers
source: "src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusHeaders.java"
- name: Upload-Checksum
direction: inbound
type: string
required: false
generated_if_missing: false
mdc_key: null
envelope_meta_field: null
owner_branch: fileserver-platform
case_style: kebab
compatibility_impact: none
required_test: contract-verification:envelope-headers
source: "src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusHeaders.java"
- name: Upload-Offset
direction: both
type: string
required: false
generated_if_missing: false
mdc_key: null
envelope_meta_field: null
owner_branch: fileserver-platform
case_style: kebab
compatibility_impact: none
required_test: contract-verification:envelope-headers
source: "src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/draft12/Draft12Headers.java"
- name: Upload-Length
direction: both
type: string
required: false
generated_if_missing: false
mdc_key: null
envelope_meta_field: null
owner_branch: fileserver-platform
case_style: kebab
compatibility_impact: none
required_test: contract-verification:envelope-headers
source: "src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/draft12/Draft12Headers.java"
- name: Upload-Complete
direction: both
type: string
required: false
generated_if_missing: false
mdc_key: null
envelope_meta_field: null
owner_branch: fileserver-platform
case_style: kebab
compatibility_impact: none
required_test: contract-verification:envelope-headers
source: "src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/draft12/Draft12Headers.java"
- name: Upload-Limit
direction: outbound
type: string
required: false
generated_if_missing: false
mdc_key: null
envelope_meta_field: null
owner_branch: fileserver-platform
case_style: kebab
compatibility_impact: none
required_test: contract-verification:envelope-headers
source: "src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/draft12/Draft12Headers.java"
# raw·draft-12 업로드의 원래 파일 이름.
- name: X-Filename
direction: inbound
type: string
required: false
generated_if_missing: false
mdc_key: null
envelope_meta_field: null
owner_branch: fileserver-platform
case_style: kebab
compatibility_impact: none
required_test: contract-verification:envelope-headers
source: "src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/draft12/Draft12UploadController.java"
- name: X-Content-Sha256
direction: inbound
type: string
required: false
generated_if_missing: false
mdc_key: null
envelope_meta_field: null
owner_branch: fileserver-platform
case_style: kebab
compatibility_impact: none
required_test: contract-verification:envelope-headers
source: "src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/mapper/RawUploadRequestMapper.java"
# 앞단 nginx에만 주는 내부 헤더다. nginx가 지우고 client에는 가지 않는다.
- name: X-Accel-Redirect
direction: outbound
type: uri
required: false
generated_if_missing: false
mdc_key: null
envelope_meta_field: null
owner_branch: fileserver-platform
case_style: kebab
compatibility_impact: none
required_test: contract-verification:envelope-headers
source: "src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/nginx/NginxDownloadStrategy.java"
+30 -220
View File
@@ -1,23 +1,38 @@
# Registry: MDC / Log Keys
# Schema owner: feature-contract-registry-governance
# MDC SSOT: feature-operational-error-observability-foundation
# Last updated: 2026-05-22
# Last updated: 2026-11-13
#
# 표기 규칙
# - MDC key 이름: snake_case (foundation L93 "snake_case 강제. camelCase / dot.case 금지.")
# - cardinality_safe_for_metric=true 인 key만 metric tag로 사용 가능
# - foundation L93-102 표 "MDC Key Standard (final)"의 key들이 핵심 정본이다
# - 행은 코드가 실제로 MDC에 넣는 key다. 코드의 정본은 `MdcKeys`(shared-contract)이고, 이 파일의 key 집합과
# `MdcKeys` 상수 집합이 같은지 `StructuredLogFieldContractTest`가 본다. `written_by`가 넣는 곳이다.
# - 구조화 로그 칸(`error.code`, `capability`, `operation`, `warning.kind` 등, dot.case 포함)은 MDC key가 아니라
# logstash `kv(...)` 인자다. 그 칸의 정본은 `docs/observability/log-fields.md`다. method·status·duration_ms·uri_template은
# 요청 로그 줄의 메시지 글자다(`RequestLoggingFilter`).
#
# 전송마다 넣는 key (전송마다 다르다. 같게 맞추지 않고 여기 적는다)
# | 전송 | request_id | correlation_id | trace_id·span_id |
# | --- | --- | --- | --- |
# | web(`WebMvcRequestIdFilter`) | 새 UUID. `app.web.mvc.trust-inbound-request-id=true`일 때만 caller의 `X-Request-Id`(`[A-Za-z0-9._-]{1,128}`) | caller의 `X-Correlation-Id`(같은 문법), 없거나 틀리면 새 UUID | 활성 span, 없으면 caller `traceparent`, 없으면 새로 만든다 |
# | gRPC(`GrpcCorrelationInterceptor`) | 호출마다 새 UUID(caller 값을 받지 않는다) | 넣지 않는다(연결·세션 개념이 없다) | 유효한 `traceparent` metadata가 있을 때만 |
# | STOMP(`WebSocketCorrelationInterceptor`) | frame마다 새 UUID | STOMP session id(한 연결의 frame을 잇는다) | 넣지 않는다 |
# | GraphQL(HTTP) | web filter가 넣은 값을 그대로 쓴다 | 같음 | 같음 |
# - user_principal은 web 요청 로그 줄을 쓰는 동안만 있다(HMAC 가명). 비동기 작업은 `AsyncContextTaskDecorator`가
# 호출한 쪽 MDC 전체를 옮긴다.
mdc_keys:
# source: feature-operational-error-observability-foundation.md L97
# "request_id | inbound filter (생성 또는 X-Request-Id 헤더) | response header X-Request-Id"
- key: request_id
type: ulid
type: uuid-or-caller-token
format: "UUID; web은 trust-inbound-request-id=true일 때 [A-Za-z0-9._-]{1,128}"
source: inbound_filter
written_by: [WebMvcRequestIdFilter, GrpcCorrelationInterceptor, WebSocketCorrelationInterceptor]
required_in: [request, dependency, security, application]
http_header_mapping: X-Request-Id
envelope_field: meta.requestId
propagation: [http, async, message]
propagation: [http, async]
owner_branch: feature-operational-error-observability-foundation
cardinality_safe_for_metric: false
case_style: snake
@@ -25,26 +40,26 @@ mdc_keys:
required_test: contract-verification:log-mdc-keys
# source: feature-operational-error-observability-foundation.md L98
# "trace_id | Micrometer Tracing | W3C traceparent header"
- key: trace_id
type: string
format: "W3C trace-id, 32 lowercase hex"
source: observation_context
written_by: [WebMvcRequestIdFilter, GrpcCorrelationInterceptor]
required_in: [request, dependency, application]
http_header_mapping: traceparent
envelope_field: meta.traceId
propagation: [http, async, message]
propagation: [http, async]
owner_branch: feature-operational-error-observability-foundation
cardinality_safe_for_metric: false
case_style: snake
compatibility_impact: none
required_test: contract-verification:log-mdc-keys
# source: feature-operational-error-observability-foundation.md L99
# "span_id | Micrometer Tracing | W3C traceparent"
# NOTE: background-job-async-contract L71 "span_id는 Micrometer Observation context에서 자동 전파(MDC explicit copy 불필요)"
- key: span_id
type: string
format: "W3C parent-id, 16 lowercase hex"
source: observation_context
written_by: [WebMvcRequestIdFilter, GrpcCorrelationInterceptor]
required_in: [request, dependency]
http_header_mapping: traceparent
envelope_field: null
@@ -56,10 +71,11 @@ mdc_keys:
required_test: contract-verification:log-mdc-keys
# source: feature-operational-error-observability-foundation.md L100
# "correlation_id | inbound header X-Correlation-Id 또는 생성 | HTTP X-Correlation-Id, message header correlation_id"
- key: correlation_id
type: ulid
type: uuid-or-caller-token
format: "web: caller X-Correlation-Id [A-Za-z0-9._-]{1,128} 또는 UUID; STOMP: session id"
source: inbound_filter
written_by: [WebMvcRequestIdFilter, WebSocketCorrelationInterceptor]
required_in: [request, dependency, application]
http_header_mapping: X-Correlation-Id
envelope_field: meta.correlationId
@@ -70,28 +86,12 @@ mdc_keys:
compatibility_impact: none
required_test: contract-verification:log-mdc-keys
# source: feature-operational-error-observability-foundation.md L101 + feature-tenant-context-policy.md L70
# "tenant_id | tenant context (활성 시) | downstream HTTP X-Tenant-Id (with allowlist)" /
# "tenant ID format = opaque ULID (26 chars Crockford base32)"
# NOTE: tenant L73 "tenant_id ULID 원본은 metric tag에 직접 사용 금지"
- key: tenant_id
type: ulid
source: security_context
required_in: [request, dependency, security, audit]
http_header_mapping: X-Tenant-Id
envelope_field: null
propagation: [http, async, message]
owner_branch: feature-tenant-context-policy
cardinality_safe_for_metric: false
case_style: snake
compatibility_impact: additive
required_test: contract-verification:tenant-leakage
# source: feature-operational-error-observability-foundation.md L102
# "user_principal | security context (pseudonymized only) | log only, headers forbidden"
- key: user_principal
type: string
format: "HMAC 가명(PrivacySettings)"
source: security_context
written_by: [RequestLoggingFilter]
required_in: [security, audit]
http_header_mapping: null
envelope_field: null
@@ -101,193 +101,3 @@ mdc_keys:
case_style: snake
compatibility_impact: none
required_test: contract-verification:log-mdc-keys
# ── 로그 종류별 확장 (log-management-contract L101-109 "Log Type별 필수 필드") ──
# source: feature-log-management-contract.md L105 "request | request_id, trace_id, method, uri_template, status, duration_ms"
# 참고: application-port-usecase-contract / 업무 쪽 operation 식별자 (uri_template과 따로 application이 정한다)
- key: operation
type: string
source: application_set
required_in: [application, dependency]
http_header_mapping: null
envelope_field: null
propagation: [none]
owner_branch: feature-log-management-contract
cardinality_safe_for_metric: true
case_style: snake
compatibility_impact: none
required_test: contract-verification:log-fields
# source: feature-log-management-contract.md L105 "request | request_id, trace_id, method, uri_template, status, duration_ms"
- key: method
type: string
source: inbound_filter
required_in: [request]
http_header_mapping: null
envelope_field: null
propagation: [none]
owner_branch: feature-log-management-contract
cardinality_safe_for_metric: true
case_style: snake
compatibility_impact: none
required_test: contract-verification:log-fields
# source: feature-log-management-contract.md L105 "request | request_id, trace_id, method, uri_template, status, duration_ms"
# 참고: metrics L86 "status_code | 7 (1xx-5xx + ok/other)" — 값 개수가 정해져 있다
- key: status
type: numeric
source: inbound_filter
required_in: [request]
http_header_mapping: null
envelope_field: null
propagation: [none]
owner_branch: feature-log-management-contract
cardinality_safe_for_metric: true
case_style: snake
compatibility_impact: none
required_test: contract-verification:log-fields
# source: feature-log-management-contract.md L105-106 "request | ... duration_ms" / "dependency | ... duration_ms"
- key: duration_ms
type: numeric
source: application_set
required_in: [request, dependency]
http_header_mapping: null
envelope_field: null
propagation: [none]
owner_branch: feature-log-management-contract
cardinality_safe_for_metric: false
case_style: snake
compatibility_impact: none
required_test: contract-verification:log-fields
# source: feature-log-management-contract.md L106 "dependency | dependency_name, dependency_type, duration_ms, outcome, error_code"
# 참고: metrics L88 "dependency_name | 50" — 값 개수가 정해져 있다
- key: dependency_name
type: string
source: application_set
required_in: [dependency]
http_header_mapping: null
envelope_field: null
propagation: [none]
owner_branch: feature-log-management-contract
cardinality_safe_for_metric: true
case_style: snake
compatibility_impact: none
required_test: contract-verification:log-fields
# source: feature-log-management-contract.md L106 "dependency | dependency_name, dependency_type, ..."
- key: dependency_type
type: string
source: application_set
required_in: [dependency]
http_header_mapping: null
envelope_field: null
propagation: [none]
owner_branch: feature-log-management-contract
cardinality_safe_for_metric: true
case_style: snake
compatibility_impact: none
required_test: contract-verification:log-fields
# source: feature-log-management-contract.md L106 + metrics L91 "outcome (resilience4j) | 5 (SUCCESS/FAILURE/CIRCUIT_OPEN/TIMEOUT/REJECTED)"
- key: outcome
type: string
source: application_set
required_in: [dependency]
http_header_mapping: null
envelope_field: null
propagation: [none]
owner_branch: feature-log-management-contract
cardinality_safe_for_metric: true
case_style: snake
compatibility_impact: none
required_test: contract-verification:log-fields
# source: feature-log-management-contract.md L106 "dependency | ... error_code (실패 시)"
# 참고: metrics L89 "error_code | 100 — error registry row 상한과 정합" — 값 개수가 정해져 있다
- key: error_code
type: string
source: application_set
required_in: [dependency]
http_header_mapping: null
envelope_field: null
propagation: [none]
owner_branch: feature-log-management-contract
cardinality_safe_for_metric: true
case_style: snake
compatibility_impact: none
required_test: contract-verification:log-fields
# source: feature-log-management-contract.md L107
# "security | event_type, user_principal (pseudonymized), source_ip (anonymized — last octet zeroed)"
- key: event_type
type: string
source: application_set
required_in: [security, audit]
http_header_mapping: null
envelope_field: null
propagation: [none]
owner_branch: feature-log-management-contract
cardinality_safe_for_metric: true
case_style: snake
compatibility_impact: none
required_test: contract-verification:log-fields
# source: feature-log-management-contract.md L107 "security | ... source_ip (anonymized — last octet zeroed)"
# NOTE: metrics L93 "high-cardinality 금지 tag: ... ip_address"
- key: source_ip_anon
type: string
source: inbound_filter
required_in: [security]
http_header_mapping: null
envelope_field: null
propagation: [none]
owner_branch: feature-log-management-contract
cardinality_safe_for_metric: false
case_style: snake
compatibility_impact: none
required_test: contract-verification:log-fields
# source: feature-log-management-contract.md L108 "audit | actor, action, target, before_hash, after_hash, occurred_at"
- key: actor
type: string
source: security_context
required_in: [audit]
http_header_mapping: null
envelope_field: null
propagation: [none]
owner_branch: feature-log-management-contract
cardinality_safe_for_metric: false
case_style: snake
compatibility_impact: none
required_test: contract-verification:log-fields
# source: feature-log-management-contract.md L108 "audit | actor, action, target, ..."
- key: action
type: string
source: application_set
required_in: [audit]
http_header_mapping: null
envelope_field: null
propagation: [none]
owner_branch: feature-log-management-contract
cardinality_safe_for_metric: true
case_style: snake
compatibility_impact: none
required_test: contract-verification:log-fields
# source: feature-log-management-contract.md L108 "audit | actor, action, target, ..."
- key: target
type: string
source: application_set
required_in: [audit]
http_header_mapping: null
envelope_field: null
propagation: [none]
owner_branch: feature-log-management-contract
cardinality_safe_for_metric: false
case_style: snake
compatibility_impact: none
required_test: contract-verification:log-fields
+1150 -265
View File
File diff suppressed because it is too large Load Diff
+3 -4
View File
@@ -25,11 +25,10 @@ status: 초안
## 진단
1. 경합 비율. `APP_MULTI_INSTANCE_ENABLED=true`이면 JDBC 락에 메트릭이 붙는다.
1. 경합 비율. 프로세스 안 락(`APP_MULTI_INSTANCE_ENABLED=false`, 기본값)과 JDBC 락 모두 메트릭이 붙는다.
`lock.acquisition{outcome="timeout"}`을 `lock.acquisition{outcome="acquired"}`와 비교한다. 이 counter에는
락 이름도 대기 시간도 없다. 키는 메트릭 태그가 되지 않는다(`docs/registries/metrics.yaml`). 프로세스 안 락
(`APP_MULTI_INSTANCE_ENABLED=false`, 기본값)은 메트릭이 없고 DB에 아무것도 남기지 않는다. 아래 단계는 JDBC
락에만 해당한다.
락 이름도 대기 시간도 없다. 키는 메트릭 태그가 되지 않는다(`docs/registries/metrics.yaml`). 프로세스 안 락은
DB에 아무것도 남기지 않는다. 아래 단계는 JDBC 락에만 해당한다.
2. 지금 누가 락을 쥐고 있나. `INT_LOCK`에는 쥔 락마다 한 행이 있다. `CLIENT_ID`는 쥔 인스턴스의 락 저장소 id이고,
시각은 UTC다. `EXPIRED_AFTER`가 지난 행은 죽은 lease다. 그 키를 다음에 잡는 쪽이 넘겨받는다. 가장 오래된
살아 있는 행이 오래 쥔 쪽이다.
+11 -4
View File
@@ -1,8 +1,9 @@
# 업그레이드 안내 — 2026-11 관측 registry·로그 내용·로컬 비밀 기본값
- 범위: 2026-11-12 전체 리뷰의 로그 내용 묶음과 비밀·IP 문서 묶음을 고친 변경. 로그 줄이 원본 경로·SQL·요청 값을 덜
싣게 했고, 로컬 비밀 기본값을 `__LOCAL_DEV_` 규칙에 맞췄다.
- 근거: 2026-11-12 전체 리뷰(`docs/reviews/2026-11-12-round9-review/`)의 RR9-02-09·10·12·13·15·21·22·26
- 범위: 2026-11-12 전체 리뷰의 관측 registry 묶음, 로그 내용 묶음, 비밀·IP 문서 묶음을 고친 변경. 지표·MDC·헤더 registry를 코드에
맞췄고, 로그 줄이 원본 경로·SQL·요청 값을 덜 싣게 했고, 로컬 비밀 기본값을 `__LOCAL_DEV_` 규칙에 맞췄다.
- 근거: 2026-11-12 전체 리뷰(`docs/reviews/2026-11-12-round9-review/`)의 RR9-02-05·07·08·09·10·12·13·15·21·22·26·27,
RR9-03-05
## 1. 누가 읽나
@@ -20,7 +21,13 @@ compose로 개발하는 사람이다.
| 5 | web `HeaderSanitizer`(로그용 헤더 가림 공개 유틸리티)와 그 시험을 지웠다. 운영 코드가 부르지 않았고, 요청 로그는 헤더를 싣지 않는다 | 그 클래스를 부르던 서비스는 자기 코드로 옮긴다(마지막으로 있던 커밋은 `docs/capability-status.md` 제거 표) | 컴파일이 실패한다 | `HeaderSanitizer`를 부르던 서비스 |
| 6 | 로컬 비밀 기본값이 `__LOCAL_DEV_` 접두어다: DB 비밀번호 `__LOCAL_DEV_db_password__`(compose·lane·`application-local.yml`), MinIO root `__LOCAL_DEV_minio_root__`, Keycloak admin `__LOCAL_DEV_keycloak_admin__`. prod에서 이 값이면 기동이 실패한다 | 옛 기본값으로 만든 로컬 volume(Postgres `caskeleton-db-data`, MinIO `caskeleton-minio-data`)이 있으면 저장소 루트 `.env`(compose 보간과 `bootRun`이 읽는 파일)에 옛 값을 `APP_DATASOURCE_PASSWORD`·`MINIO_ROOT_PASSWORD`로 두거나 volume을 지우고 다시 만든다(`docker compose down -v`). Keycloak은 volume이 없어 컨테이너를 다시 만들면 새 비밀번호로 들어간다 | 로컬 앱이 DB 인증에 실패하고 `minio-init`이 bucket을 만들지 못한다 | 로컬 compose를 쓰는 사람 |
| 7 | `docs/registries/secrets-classification.yaml`의 `masking_rule`은 `full`·`userinfo`·`none`뿐이다(`full_except_last_4`는 구현이 없었다). Layer 1 가림이 salt·PEM·HMAC/signing/encryption/credential/private key 이름, 여러 줄 PEM 블록 전체, URI 사용자 정보 비밀번호(`scheme://user:****@host`)도 가린다. `required_test`는 app-bootstrap 시험 폴더에 있는 시험 클래스 이름이어야 한다(옛 `secrets-contract:*` 표지는 안 된다). 쓰지 않는 행 넷(`APP_PROFILE`, `SERVER_PORT`, `APP_NOTIFICATION_SLACK_WEBHOOK_URL`, `APP_SECURITY_GOOGLE_OAUTH_CLIENT_ID`)을 지웠다 | 자기 행에 `full_except_last_4`를 쓴 서비스는 `full`이나 `userinfo`로, `secrets-contract:*`는 시험 클래스 이름으로 바꾼다 | `SecretsClassificationRegistryTest`가 실패한다 | registry에 행을 더한 서비스 |
| 8 | 지표 이름 둘을 이름 규칙(dot.case, 밑줄 없음)에 맞췄다: `http.client.rate_limit.rejected` → `http.client.ratelimit.rejected`, `fileserver.upload.offset_mismatch` → `fileserver.upload.offset.mismatch` | 그 이름을 쓰는 대시보드·경보를 새 이름으로 바꾼다 | 그 패널이 비고 경보가 울리지 않는다 | httpclient·파일 서버를 켠 서비스 |
| 9 | `docs/registries/metrics.yaml`에서 아무 코드도 등록하지 않던 행 열하나를 지웠다(`http.server.requests.latency`, `dependency.client.requests`, `db.query.duration`, `resilience4j.*` 셋, `cache.*` 다섯). `http.server.requests`의 tag는 Spring Framework 기본 convention이 다는 값(`method`, `uri`, 숫자 `status`, `outcome`, `exception`, `error`)이다 | 그 이름·tag(`uri_template`, `2xx`)로 만든 경보를 실제 이름으로 바꾼다. 지연 경보는 `http.server.requests`로 건다 | 경보가 없는 시계열을 본다 | registry를 보고 경보를 만든 서비스 |
| 10 | `MetricsDistributionMeterFilter`의 SLO 대상이 `http.server.requests`·`jvm.gc.pause` 둘이다. 아무도 등록하지 않던 `http.server.requests.latency`·`dependency.client.requests`·`db.query.duration`은 대상에서 빠졌다 | 그 셋 이름으로 timer를 직접 만들었으면 자기 `MeterFilter`로 SLO histogram을 켠다 | 그 timer의 `_bucket` 시계열(인스턴스 사이 p99)이 사라진다 | 그 셋 이름으로 timer를 직접 만든 서비스 |
| 11 | 단일 인스턴스(in-process) lock도 `lock.acquisition`을 센다 | 단일 인스턴스 배포의 lock 경보 기준선을 다시 잡는다 | 새로 생긴 값으로 경보가 울릴 수 있다 | persistence-jpa를 켠 서비스 |
| 12 | `docs/registries/mdc-keys.yaml`은 코드가 MDC에 넣는 다섯 key(`request_id`, `trace_id`, `span_id`, `correlation_id`, `user_principal`)만 적는다. `headers.yaml`에서 아무도 쓰지 않던 `Deprecation`·`Sunset`을 지우고 쓰는 헤더 행을 더했다(`tracestate`는 W3C 전파가 쓰므로 `framework:` 행으로 둔다). 지표·헤더 행마다 `source`가 있다 | 자기 MDC key·헤더·지표를 더한 서비스는 `MdcKeys`·행을 같이 더하고 `source`를 적는다 | 새 정합 시험이 실패한다 | registry에 행을 더한 서비스 |
| 13 | testFixtures `CardinalityBounds`: `STATUS_CODE`가 7에서 40(숫자 HTTP status)으로, `RESILIENCE4J_OUTCOME`(5)이 `OUTCOME`(6)으로 바뀌었고 `uri` key가 더해졌다. `MetricNaming.ALLOWED_UNITS`는 이름 접미사가 아니라 `unit` 칸의 값이다 | 그 상수를 쓰던 시험을 새 이름·값으로 고친다 | 시험 컴파일이 실패한다 | 그 fixture를 쓰는 서비스 |
## 3. 바뀌지 않은 것
- 지표·MDC key·헤더 이름과 응답 모양은 그대로다.
- 지표·MDC key·헤더 이름은 위 8번 둘 말고 그대로다. 응답 모양도 그대로다.
@@ -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
+9 -7
View File
@@ -484,13 +484,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` 은 없다.
---
@@ -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() {
@@ -131,8 +131,9 @@ class DistributedTracingContractTest {
/**
* Asserts the {@code traceparent} row in {@code headers.yaml} has {@code generated_if_missing:
* true}, {@code mdc_key: trace_id}, {@code envelope_meta_field: traceId}, and that the {@code
* tracestate} row exists with {@code generated_if_missing: false}; AND that code agrees: {@code
* MdcKeys.TRACE_ID == "trace_id"} and {@link ResponseMeta} has a {@code traceId} component.
* tracestate} row is the framework's (the W3C propagator carries it next to traceparent; no
* template code reads it); AND that code agrees: {@code MdcKeys.TRACE_ID == "trace_id"} and
* {@link ResponseMeta} has a {@code traceId} component.
*/
@Tag("document-contract")
@Test
@@ -157,15 +158,11 @@ class DistributedTracingContractTest {
.as("traceparent: envelope_meta_field must be 'traceId'")
.isEqualTo("traceId");
// tracestate row: generated_if_missing=false
Map<String, Object> tracestateRow =
headers.stream()
.filter(h -> "tracestate".equals(h.get("name")))
.findFirst()
.orElseThrow(() -> new AssertionError("headers.yaml must contain a 'tracestate' row"));
assertThat(tracestateRow.get("generated_if_missing"))
.as("tracestate: generated_if_missing must be false")
.isEqualTo(false);
// tracestate travels with traceparent through the W3C propagator; no template code reads it.
assertThat(headers)
.filteredOn(h -> "tracestate".equals(h.get("name")))
.singleElement()
.satisfies(row -> assertThat(String.valueOf(row.get("source"))).startsWith("framework:"));
// Code alignment: MdcKeys.TRACE_ID constant must match the registry mdc_key value
assertThat(MdcKeys.TRACE_ID)
@@ -3,13 +3,18 @@ package dev.caskeleton.bootstrap.contract;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.inbound.web.ratelimit.RateLimitWebConfig;
import dev.caskeleton.bootstrap.contract.support.MainSources;
import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
@@ -18,6 +23,16 @@ import org.yaml.snakeyaml.Yaml;
@Tag("document-contract")
class HeaderRegistryRuntimeAlignmentTest {
/** A source prefix: a constant the template declares for service controllers to read. */
private static final String SERVICE = "service: ";
/**
* The only headers a {@code service:} row may name — README 「ApiHeaders」's constants for service
* controllers. Anything else must name the main file that reads or writes it.
*/
private static final Set<String> FOR_SERVICE_CONTROLLERS =
Set.of("Idempotency-Key", "If-Match", "If-None-Match");
private static List<Map<String, Object>> headers;
@BeforeAll
@@ -40,12 +55,48 @@ class HeaderRegistryRuntimeAlignmentTest {
}
@Test
void deprecationDatesUseTheHttpDateWireType() {
assertThat(row("Deprecation").get("type")).isEqualTo("http-date");
assertThat(row("Sunset").get("type")).isEqualTo("http-date");
void theRateLimitResetUsesTheRfc3339WireType() {
assertThat(row("X-RateLimit-Reset").get("type")).isEqualTo("rfc3339-date");
}
@Test
@DisplayName("headers.yaml 의 행마다 그 헤더를 쓰는 main 파일이 있다 — 선언만 있는 상수는 정해 둔 서비스용 상수일 때만 된다")
void everyRowNamesTheMainFileThatReadsOrWritesIt() throws IOException {
// given
Path root = RepositoryContractResources.fromSystemProperty().repositoryRoot();
MainSources main = MainSources.under(root);
// when
List<String> unbacked = new ArrayList<>();
for (Map<String, Object> header : headers) {
String name = String.valueOf(header.get("name"));
String source = String.valueOf(header.get("source"));
if (source.startsWith("framework:")) {
continue;
}
boolean forServices = source.startsWith(SERVICE);
Path file = root.resolve(forServices ? source.substring(SERVICE.length()) : source);
if (!file.toString().contains("/src/main/")
|| !Files.isRegularFile(file)
|| !Files.readString(file).contains("\"" + name + "\"")
|| (forServices && !FOR_SERVICE_CONTROLLERS.contains(name))
|| (forServices && main.valueIsUsed(file, name))
|| (!forServices && !main.valueIsUsed(file, name))) {
unbacked.add(name + " <- " + source);
}
}
// then
assertThat(unbacked).isEmpty();
}
@Test
@DisplayName("X-Request-Id·X-Correlation-Id 형식은 filter 가 받는 문법이다(ulid 가 아니다)")
void requestAndCorrelationIdsCarryTheFiltersGrammar() {
assertThat(List.of(row("X-Request-Id").get("type"), row("X-Correlation-Id").get("type")))
.containsOnly("uuid-or-caller-token");
}
@Test
void rateLimitHeadersAreGeneratedOnlyInsideTheEnabledRateLimitCapability() {
for (String name : List.of("X-RateLimit-Limit", "X-RateLimit-Remaining", "X-RateLimit-Reset")) {
@@ -18,6 +18,8 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
@@ -215,82 +217,75 @@ class MetricsAlertingContractTest {
@Tag("document-contract")
@Test
@DisplayName("§테스트 계약 #1: http.server.requests row exists with method/status/uri_template tags")
void httpServerRequestsRowExistsWithRequiredTags() throws Exception {
@DisplayName(
"http.server.requests 행은 Spring Framework convention 이 실제로 다는 tag(method·status·uri·outcome)를 적는다")
void httpServerRequestsRowNamesTheTagsSpringRecords() throws Exception {
// given
loadRegistry();
// when
Map<String, Object> row = findRow("http.server.requests");
// then
assertThat(row).as("metrics.yaml must contain an 'http.server.requests' row").isNotNull();
List<String> tagNames = tagNames(row);
assertThat(tagNames)
.as("http.server.requests must have tags: method, status, uri_template")
.contains("method", "status", "uri_template");
assertThat(tagNames(row))
.as("the tags Spring MVC's request observation records, not uri_template or 2xx buckets")
.contains("method", "status", "uri", "outcome")
.doesNotContain("uri_template");
}
@Tag("document-contract")
@Test
@DisplayName(
"§테스트 계약 #2: dependency.client.requests row exists with dependency_name/dependency_type tags and P1 alert")
@SuppressWarnings(
"unchecked") // SnakeYAML returns untyped Object; the registry shape is fixed by the
// metrics.yaml contract
void dependencyClientRequestsRowExistsWithRequiredTagsAndP1Alert() throws Exception {
"outbound HTTP 행은 httpclient 가 내는 http.client.requests 이고 clientName·outcome tag 를 적는다")
void outboundHttpRowIsTheOneTheClientRecords() throws Exception {
// given
loadRegistry();
// when
Map<String, Object> row = findRow("http.client.requests");
// then
assertThat(row).as("metrics.yaml must contain an 'http.client.requests' row").isNotNull();
assertThat(tagNames(row)).contains("clientName", "outcome");
}
@Tag("document-contract")
@Test
@DisplayName("아무 코드도 등록하지 않는 dependency.client.requests 행은 없다")
void theUnregisteredDependencyClientRowIsGone() throws Exception {
// given
loadRegistry();
// when
Map<String, Object> row = findRow("dependency.client.requests");
assertThat(row).as("metrics.yaml must contain a 'dependency.client.requests' row").isNotNull();
List<String> tagNames = tagNames(row);
assertThat(tagNames)
.as("dependency.client.requests must have tags: dependency_name, dependency_type")
.contains("dependency_name", "dependency_type");
//noinspection unchecked
Map<String, Object> thresholds = (Map<String, Object>) row.get("alert_severity_thresholds");
assertThat(thresholds)
.as("dependency.client.requests must have non-empty alert_severity_thresholds (§테스트 계약 #4)")
.isNotNull()
.isNotEmpty();
assertThat(thresholds)
.as(
"dependency.client.requests must have a P1 alert entry (§테스트 계약 #4 — dependency outage)")
.containsKey("p1");
// then
assertThat(row)
.as("no code registers dependency.client.requests; the row was removed")
.isNull();
}
@Tag("document-contract")
@Test
@DisplayName(
"§테스트 계약 #3: hikaricp.connections.acquire row exists with outcome tag containing TIMEOUT and non-empty alerts")
@DisplayName("DB pool 고갈은 HikariCP 의 hikaricp.connections.timeout counter 로 P1 경보를 건다")
@SuppressWarnings(
"unchecked") // SnakeYAML returns untyped Object; the registry shape is fixed by the
// metrics.yaml contract
void hikaricpConnectionsAcquireRowExistsWithTimeoutOutcome() throws Exception {
void hikaricpTimeoutRowCarriesThePoolExhaustionAlert() throws Exception {
// given
loadRegistry();
Map<String, Object> row = findRow("hikaricp.connections.acquire");
// when
Map<String, Object> row = findRow("hikaricp.connections.timeout");
// then
assertThat(row)
.as(
"metrics.yaml must contain a 'hikaricp.connections.acquire' row (DB pool exhaustion metric)")
.as("metrics.yaml must contain a 'hikaricp.connections.timeout' row")
.isNotNull();
//noinspection unchecked
List<Map<String, Object>> tags = (List<Map<String, Object>>) row.get("tags");
Map<String, Object> outcomeTag =
tags.stream().filter(t -> "outcome".equals(t.get("name"))).findFirst().orElse(null);
assertThat(outcomeTag)
.as("hikaricp.connections.acquire must have an 'outcome' tag")
.isNotNull();
//noinspection unchecked
List<String> allowedValues = (List<String>) outcomeTag.get("allowed_values");
assertThat(allowedValues)
.as("hikaricp.connections.acquire outcome tag must contain 'TIMEOUT'")
.contains("TIMEOUT");
//noinspection unchecked
Map<String, Object> thresholds = (Map<String, Object>) row.get("alert_severity_thresholds");
assertThat(thresholds)
.as("hikaricp.connections.acquire must have non-empty alert_severity_thresholds")
.isNotNull()
.isNotEmpty();
assertThat((Map<String, Object>) row.get("alert_severity_thresholds"))
.as("pool exhaustion is a P1 alert")
.containsKey("p1");
}
@Tag("document-contract")
@@ -375,6 +370,26 @@ class MetricsAlertingContractTest {
.isNull();
}
@Tag("document-contract")
@Test
@DisplayName("metrics.yaml 의 slo_driven 행과 MetricsDistributionMeterFilter 의 대상은 같은 집합이다")
void theSloDrivenRowsAreExactlyTheFiltersTargets() throws Exception {
// given
loadRegistry();
// when
Set<String> sloDrivenRows = new TreeSet<>();
for (Map<String, Object> row : metrics) {
if ("slo_driven".equals(row.get("histogram_buckets"))) {
sloDrivenRows.add((String) row.get("name"));
}
}
// then
assertThat(sloDrivenRows)
.isEqualTo(new TreeSet<>(MetricsDistributionMeterFilter.sloDrivenTimers()));
}
@Tag("document-contract")
@Test
@DisplayName(
@@ -0,0 +1,188 @@
package dev.caskeleton.bootstrap.contract;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.bootstrap.contract.support.MainSources;
import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.yaml.snakeyaml.Yaml;
/**
* Every row of {@code docs/registries/metrics.yaml} is a meter some code registers.
*
* <p>A row's {@code source} is either {@code framework: …} — Spring Boot, Micrometer or HikariCP
* registers it — or the repository path of the main file that holds the meter name as a string
* literal. When that file only declares the name as a constant, the row also names the {@code
* constant} and the {@code registered_by} file that uses it; a name constant nothing uses does not
* count. In the other direction, every meter a main file registers has a row: under a literal name,
* a constant of the same file or {@code SomeClass.CONSTANT}, through a builder, a registry
* shortcut, the global {@code Metrics} shortcut or {@code Observation.createNotStarted}. A name
* passed in a variable cannot be resolved and is not checked; a scan that resolves one name of each
* form proves the scan itself still works. The registry used to list eleven meters nothing
* registered and miss dozens that the code did (review 2026-11-12); without this check the two
* drift apart again the first time a meter is renamed.
*/
@Tag("document-contract")
class MetricsRegistryCodeAlignmentTest {
private static final String FRAMEWORK = "framework:";
/**
* A meter registration and its name argument: a builder, a registry shortcut, the global {@code
* Metrics} shortcut, or an observation (its timer carries the observation's name). The argument
* is a literal, a constant, or {@code SomeClass.CONSTANT}.
*/
static final Pattern REGISTRATION =
Pattern.compile(
"(?:(?:Counter|Timer|Gauge|DistributionSummary|LongTaskTimer|FunctionCounter|FunctionTimer"
+ "|TimeGauge|MultiGauge)\\.builder"
+ "|\\b(?:\\w*[rR]egistry|Metrics)\\.(?:counter|timer|gauge|summary)"
+ "|\\bObservation\\.createNotStarted)"
+ "\\(\\s*(\"[^\"]+\"|[A-Za-z_][\\w.]*)");
/** A string constant that holds a dotted meter name. */
private static final Pattern NAME_CONSTANT =
Pattern.compile("\\b([A-Z][A-Z0-9_]*)\\s*=\\s*\"([a-z][a-z0-9_]*(?:\\.[a-z0-9_]+)+)\"");
@Test
@DisplayName("metrics.yaml 의 행마다 등록하는 main 파일이 있고 그 파일에 meter 이름 글자가 있다")
void everyRowNamesTheMainFileThatRegistersIt() throws IOException {
// given
RepositoryContractResources repository = RepositoryContractResources.fromSystemProperty();
List<Map<String, Object>> rows = rows(repository);
MainSources main = MainSources.under(repository.repositoryRoot());
// when
List<String> unbacked = new ArrayList<>();
for (Map<String, Object> row : rows) {
String name = String.valueOf(row.get("name"));
String source = String.valueOf(row.get("source"));
if (source.startsWith(FRAMEWORK)) {
continue;
}
Path file = repository.repositoryRoot().resolve(source);
if (!source.startsWith("src/")
|| !source.contains("/src/main/")
|| !Files.isRegularFile(file)
|| !Files.readString(file).contains("\"" + name + "\"")) {
unbacked.add(name + " <- " + source);
continue;
}
Object constant = row.get("constant");
if (constant == null && !main.valueIsUsed(file, name)) {
unbacked.add(name + " <- " + source + " only declares it in a constant nothing uses");
continue;
}
if (constant != null) {
String simpleConstant =
String.valueOf(constant).substring(String.valueOf(constant).indexOf('.') + 1);
Path user = repository.repositoryRoot().resolve(String.valueOf(row.get("registered_by")));
if (!Files.readString(file).contains(simpleConstant + " = \"" + name + "\"")
|| !Files.isRegularFile(user)
|| !Files.readString(user).contains(String.valueOf(constant))) {
unbacked.add(name + " <- " + constant + " used by " + row.get("registered_by"));
}
}
}
// then
assertThat(unbacked).as("rows whose source does not register the meter").isEmpty();
}
@Test
@DisplayName("main 파일이 글자·상수 이름으로 등록하는 meter 는 모두 metrics.yaml 행이 있다")
void everyMeterRegisteredUnderAResolvableNameHasARow() throws IOException {
// given
RepositoryContractResources repository = RepositoryContractResources.fromSystemProperty();
Set<String> rows = new TreeSet<>();
rows(repository).forEach(row -> rows.add(String.valueOf(row.get("name"))));
// when
Set<String> registered = registeredMeters(repository);
// then
assertThat(rows).containsAll(registered);
}
@Test
@DisplayName("등록 형태마다 meter 하나씩을 찾는다 — 아무것도 못 찾는 scan 은 위 시험을 거짓으로 통과시킨다")
void theScanResolvesOneMeterOfEachRegistrationForm() throws IOException {
// given
RepositoryContractResources repository = RepositoryContractResources.fromSystemProperty();
// when
Set<String> registered = registeredMeters(repository);
// then
assertThat(registered)
.contains(
"fileserver.upload.duration", // a literal builder name
"executor.rejected.total", // a constant of the same file
"http.client.circuit.state.rejected", // SomeClass.CONSTANT
"log.appender.dropped.total", // the global Metrics shortcut
"notification.callback"); // an observation
}
/** Every meter name a main file registers that the scan can resolve. */
private static Set<String> registeredMeters(RepositoryContractResources repository) {
Map<Path, String> sources = MainSources.under(repository.repositoryRoot()).all();
Map<String, String> qualifiedConstants = new HashMap<>();
sources.forEach(
(file, text) ->
constants(text)
.forEach(
(constant, value) ->
qualifiedConstants.put(
MainSources.simpleName(file) + "." + constant, value)));
Set<String> registered = new TreeSet<>();
sources.forEach(
(file, text) -> {
Map<String, String> local = constants(text);
Matcher matcher = REGISTRATION.matcher(text);
while (matcher.find()) {
String argument = matcher.group(1);
String meter =
argument.startsWith("\"")
? argument.substring(1, argument.length() - 1)
: local.getOrDefault(argument, qualifiedConstants.get(argument));
if (meter != null) {
registered.add(meter);
}
}
});
return registered;
}
private static Map<String, String> constants(String text) {
Map<String, String> constants = new HashMap<>();
Matcher matcher = NAME_CONSTANT.matcher(text);
while (matcher.find()) {
constants.put(matcher.group(1), matcher.group(2));
}
return constants;
}
@SuppressWarnings("unchecked") // SnakeYAML returns untyped maps; the registry shape is fixed
private static List<Map<String, Object>> rows(RepositoryContractResources repository)
throws IOException {
Path registry = repository.requireTrackedFile("docs/registries/metrics.yaml");
try (InputStream in = Files.newInputStream(registry)) {
Map<String, Object> root = new Yaml().load(in);
return (List<Map<String, Object>>) root.get("metrics");
}
}
}
@@ -3,13 +3,17 @@ package dev.caskeleton.bootstrap.contract;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources;
import dev.caskeleton.shared.observability.MdcKeys;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.jupiter.api.DisplayName;
@@ -72,6 +76,25 @@ class StructuredLogFieldContractTest {
.containsAll(emittedFields);
}
@Tag("document-contract")
@Test
@DisplayName("mdc-keys.yaml 의 key 는 코드가 MDC 에 넣는 MdcKeys 상수와 같은 집합이다")
void theRegistryListsExactlyTheKeysTheCodePutsOnMdc() throws Exception {
// given
Set<String> codeKeys = new TreeSet<>();
for (Field field : MdcKeys.class.getFields()) {
if (Modifier.isStatic(field.getModifiers()) && field.getType() == String.class) {
codeKeys.add((String) field.get(null));
}
}
// when
Set<String> registryKeys = new TreeSet<>(registryKeys());
// then
assertThat(registryKeys).isEqualTo(codeKeys);
}
@Test
@DisplayName("Logback은 로깅 설정을 app.logging.* 한 곳에서 읽고, 프로필·앱 이름은 env 이름으로 읽는다")
void logbackReadsLoggingKnobsFromTheSettingsTreeAndIdentityFromTheEnvironment()
@@ -0,0 +1,89 @@
package dev.caskeleton.bootstrap.contract.support;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
/**
* The repository's main Java sources, read once, for registry tests that ask whether a name the
* registry lists is really used by shipped code.
*
* <p>A registry row that points at a file holding its name only proves the name is declared. When
* the name sits in a constant ({@code DEPRECATION = "Deprecation"}), the row is backed only if
* something uses that constant: it appears again in its own file, or another main file names it as
* {@code DeclaringClass.CONSTANT}.
*/
public final class MainSources {
private final Map<Path, String> sources;
private MainSources(Map<Path, String> sources) {
this.sources = sources;
}
/** Reads every {@code src/**}{@code /src/main/java/**}{@code .java} file under the root. */
public static MainSources under(Path repositoryRoot) {
Map<Path, String> sources = new LinkedHashMap<>();
try (Stream<Path> files = Files.walk(repositoryRoot.resolve("src"))) {
for (Path file :
files
.filter(path -> path.toString().endsWith(".java"))
.filter(path -> path.toString().contains("/src/main/java/"))
.toList()) {
sources.put(file, Files.readString(file));
}
} catch (IOException failure) {
throw new UncheckedIOException(failure);
}
return new MainSources(sources);
}
/** File → text, in walk order. */
public Map<Path, String> all() {
return sources;
}
/**
* Whether {@code value}, held by {@code file}, is used: a literal that is not a constant counts
* as used; a constant must appear again in the file or as {@code FileClass.CONSTANT} elsewhere.
*/
public boolean valueIsUsed(Path file, String value) {
String text = sources.get(file);
if (text == null) {
return false;
}
Matcher declaration =
Pattern.compile("\\b([A-Z][A-Z0-9_]*)\\s*=\\s*\"" + Pattern.quote(value) + "\"")
.matcher(text);
if (!declaration.find()) {
return true;
}
String constant = declaration.group(1);
if (occurrences(text, constant) > 1) {
return true;
}
String qualified = simpleName(file) + "." + constant;
return sources.values().stream().anyMatch(other -> other.contains(qualified));
}
/** The simple class name of a source file. */
public static String simpleName(Path file) {
String name = file.getFileName().toString();
return name.substring(0, name.length() - ".java".length());
}
private static int occurrences(String text, String identifier) {
Matcher uses = Pattern.compile("\\b" + Pattern.quote(identifier) + "\\b").matcher(text);
int count = 0;
while (uses.find()) {
count++;
}
return count;
}
}
@@ -0,0 +1,59 @@
package dev.caskeleton.bootstrap.contract.support;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
class MainSourcesTest {
@TempDir Path root;
@Test
@DisplayName("이름을 선언만 한 상수는 쓰이지 않은 것이고, 같은 파일이나 다른 파일의 Class.CONST 로 쓰면 쓰인 것이다")
void aDeclaredOnlyConstantIsNotUsedButOneReferencedAnywhereIs() throws IOException {
// given
Path names =
write(
"src/lib/src/main/java/demo/Names.java",
"""
class Names {
static final String DECLARED = "declared.only";
static final String LOCAL = "used.here";
static final String SHARED = "used.elsewhere";
void record() { count(LOCAL); }
void count(String name) {}
String literal() { return "no.constant"; }
}
""");
write(
"src/app/src/main/java/demo/Recorder.java",
"class Recorder { void record() { new Names().count(Names.SHARED); } }\n");
write(
"src/lib/src/test/java/demo/NamesTest.java",
"class NamesTest { void t() { new Names().count(Names.DECLARED); } }\n");
MainSources main = MainSources.under(root);
// when
List<Boolean> used =
List.of(
main.valueIsUsed(names, "declared.only"),
main.valueIsUsed(names, "used.here"),
main.valueIsUsed(names, "used.elsewhere"),
main.valueIsUsed(names, "no.constant"));
// then
assertThat(used).containsExactly(false, true, true, true);
}
private Path write(String relative, String text) throws IOException {
Path file = root.resolve(relative);
Files.createDirectories(file.getParent());
return Files.writeString(file, text);
}
}
+4 -6
View File
@@ -210,12 +210,10 @@ runtimeOnly project(':composition:service-runtime')
`SimpleMeterRegistry`에 대해 직접 구동할 수 있게 하기 위함이다.
#### MetricsDistributionMeterFilter
- **소유한(owned) 타이머 메트릭 5종에만 SLO 기반 히스토그램·백분위 설정을 적용한다.** 대상:
`http.server.requests`, `http.server.requests.latency`, `dependency.client.requests`,
`db.query.duration`, `jvm.gc.pause`. 이들은 `metrics.yaml`에서 이 브랜치가 소유하고
`histogram_buckets: slo_driven`인 행이다. `resilience4j.circuitbreaker.calls`,
`hikaricp.connections.acquire`처럼 소비만 하고 소유하지 않는(consumed-but-not-owned) 행은 다른
브랜치 소유라 의도적으로 제외 — 덮어쓰면 안 된다.
- **소유한(owned) 타이머 메트릭 둘에만 SLO 기반 히스토그램·백분위 설정을 적용한다.** 대상:
`http.server.requests`, `jvm.gc.pause`. `metrics.yaml`에서 `histogram_buckets: slo_driven`인 행은 정확히 이 둘이다
(`MetricsAlertingContractTest`가 두 집합을 대조한다). `hikaricp.connections.acquire`처럼 다른 라이브러리가 내는 timer는
histogram을 켜지 않고, 그 행은 평균(sum/count)으로 경보를 적는다.
- **히스토그램 전략은 두 축이다.**
- *인스턴스 간 집계 가능한 진실의 원천*: `percentilesHistogram(true)`(= `publishPercentileHistogram`)가
`_bucket` 시계열을 생성하고, Prometheus 에서 `histogram_quantile()`로 인스턴스 간 집계할 수 있다.
@@ -15,18 +15,27 @@ import java.util.Set;
*/
public final class MetricsDistributionMeterFilter implements MeterFilter {
/**
* The owned timers some code registers. Three more names stood here — {@code
* http.server.requests.latency}, {@code dependency.client.requests}, {@code db.query.duration} —
* that nothing registered, so the filter configured meters that never existed (review
* 2026-11-12). Latency alerts use {@code http.server.requests}.
*/
private static final Set<String> SLO_DRIVEN_TIMERS =
Set.of(
"http.server.requests",
"http.server.requests.latency",
"dependency.client.requests",
"db.query.duration",
"jvm.gc.pause");
Set.of("http.server.requests", "jvm.gc.pause");
public MetricsDistributionMeterFilter() {
// public no-arg constructor — required by MetricsContractConfig.install()
}
/**
* The timers this filter gives an SLO histogram; {@code docs/registries/metrics.yaml} marks
* exactly these {@code slo_driven}.
*/
public static Set<String> sloDrivenTimers() {
return SLO_DRIVEN_TIMERS;
}
@Override
public DistributionStatisticConfig configure(Meter.Id id, DistributionStatisticConfig config) {
if (!SLO_DRIVEN_TIMERS.contains(id.getName())) {
@@ -113,9 +113,9 @@ class MetricsContractConfigTest {
.isNull();
// Clean metric: registered (D9 applied for timers)
registry.timer("db.query.duration", "operation", "select", "outcome", "SUCCESS");
assertThat(registry.find("db.query.duration").timer())
.as("db.query.duration timer with clean tags must be registered")
registry.timer("http.server.requests", "method", "GET", "outcome", "SUCCESS");
assertThat(registry.find("http.server.requests").timer())
.as("http.server.requests timer with clean tags must be registered")
.isNotNull();
}
}
@@ -26,14 +26,7 @@ class MetricsDistributionMeterFilterTest {
// ----------------------------------------------------------------
@ParameterizedTest(name = "D9: configure() applies SLO histogram to owned timer ''{0}''")
@ValueSource(
strings = {
"http.server.requests",
"http.server.requests.latency",
"dependency.client.requests",
"db.query.duration",
"jvm.gc.pause"
})
@ValueSource(strings = {"http.server.requests", "jvm.gc.pause"})
void configureAppliesSloHistogramToOwnedTimers(String metricName) {
Meter.Id id = new Meter.Id(metricName, Tags.empty(), null, null, Meter.Type.TIMER);
DistributionStatisticConfig result = filter.configure(id, DistributionStatisticConfig.DEFAULT);
@@ -44,14 +37,7 @@ class MetricsDistributionMeterFilterTest {
}
@ParameterizedTest(name = "D9: configure() sets non-empty SLO boundaries for owned timer ''{0}''")
@ValueSource(
strings = {
"http.server.requests",
"http.server.requests.latency",
"dependency.client.requests",
"db.query.duration",
"jvm.gc.pause"
})
@ValueSource(strings = {"http.server.requests", "jvm.gc.pause"})
void configureSetsSloBoundariesForOwnedTimers(String metricName) {
Meter.Id id = new Meter.Id(metricName, Tags.empty(), null, null, Meter.Type.TIMER);
DistributionStatisticConfig result = filter.configure(id, DistributionStatisticConfig.DEFAULT);
@@ -66,14 +52,7 @@ class MetricsDistributionMeterFilterTest {
}
@ParameterizedTest(name = "D9: configure() sets client-side percentiles for owned timer ''{0}''")
@ValueSource(
strings = {
"http.server.requests",
"http.server.requests.latency",
"dependency.client.requests",
"db.query.duration",
"jvm.gc.pause"
})
@ValueSource(strings = {"http.server.requests", "jvm.gc.pause"})
void configureSetsPercentilesForOwnedTimers(String metricName) {
Meter.Id id = new Meter.Id(metricName, Tags.empty(), null, null, Meter.Type.TIMER);
DistributionStatisticConfig result = filter.configure(id, DistributionStatisticConfig.DEFAULT);
@@ -86,14 +65,7 @@ class MetricsDistributionMeterFilterTest {
}
@ParameterizedTest(name = "D9: configure() sets min/max expected value for owned timer ''{0}''")
@ValueSource(
strings = {
"http.server.requests",
"http.server.requests.latency",
"dependency.client.requests",
"db.query.duration",
"jvm.gc.pause"
})
@ValueSource(strings = {"http.server.requests", "jvm.gc.pause"})
void configureSetsMinMaxExpectedValueForOwnedTimers(String metricName) {
Meter.Id id = new Meter.Id(metricName, Tags.empty(), null, null, Meter.Type.TIMER);
DistributionStatisticConfig result = filter.configure(id, DistributionStatisticConfig.DEFAULT);
+12 -14
View File
@@ -383,11 +383,12 @@ Spring/Lettuce 타입을 노출하지 않는다.
> `ForbiddenMetricTags` 하나다(`MetricsCardinalityMeterFilter` 가 쓴다).
### MetricNaming
- **Micrometer dot.case 메트릭 이름의 작명/단위 접미사 규칙**(D2/D3 + §3).
- **Micrometer dot.case 메트릭 이름의 작명·단위 규칙**(D2/D3 + §3).
- **이름 규칙(D2):** 소문자 영문+숫자만, 단일 점으로 segment 구분, 각 segment 는 영문자로 시작
(예: `http.server.requests`). 정확한 규칙은 `VALID_NAME_PATTERN` 정규식에 있다.
- **단위 접미사(D2):** 이름의 마지막 segment 로 `seconds`/`bytes`/`total` 중 하나를 붙인다
(timer=seconds, byte 게이지=bytes, counter=total). 이 집합 밖의 접미사는 금지.
- **단위(D2):** registry 행의 `unit` 칸은 `seconds`/`bytes`/`total` 중 하나다(`ALLOWED_UNITS`). 이름에 단위를 다시
붙이지 않는다. Prometheus로 내보낼 때 Micrometer가 `_seconds`·`_bytes`·`_total`을 붙인다(`docs/registries/metrics.yaml`
머리말).
- **Prometheus base-name 변환(§3):** dot.case 이름의 `.` 을 `_` 로 바꾼다
(`http.server.requests` → `http_server_requests`).
- **INFERENCE / 운영 메모:** Spring Boot 3 Prometheus exporter 는 런타임에 추가 접미사
@@ -396,23 +397,20 @@ Spring/Lettuce 타입을 노출하지 않는다.
### CardinalityBounds
- **스켈레톤에 등록되는 메트릭의 tag 별 cardinality 상한**(§Cardinality Bounds 표의 Java mirror).
`limitFor(key)` 로 magic number 하드코딩 없이 상한을 조회한다(MeterFilter 설정, cardinality
계약 테스트).
- 상수값(프로젝트 선택): `STATUS_CODE`=7(1xx~5xx + ok/other), `URI_TEMPLATE`=200
`limitFor(key)` 로 magic number 하드코딩 없이 상한을 조회한다. 읽는 곳은 registry 계약 테스트
(`MetricsAlertingContractTest`)뿐이다. test fixture 라 런타임 `MeterFilter` 는 이것을 쓰지 않는다(런타임 filter 는
금지 tag 를 거절할 뿐 개수를 세지 않는다.).
- 상수값(프로젝트 선택): `STATUS_CODE`=40(Spring `http.server.requests` 가 다는 숫자 status 코드 수), `URI_TEMPLATE`=200
(라우트는 `/users/{id}` 처럼 템플릿 정규화 필수, raw path 는 `ForbiddenMetricTags` 로 금지),
`DEPENDENCY_NAME`=50, `ERROR_CODE`=100, `TENANT_ID`=1000, `RESILIENCE4J_OUTCOME`=5
(SUCCESS/FAILURE/CIRCUIT_OPEN/TIMEOUT/REJECTED).
`DEPENDENCY_NAME`=50, `ERROR_CODE`=100, `TENANT_ID`=1000, `OUTCOME`=6(Spring HTTP outcome 여섯 값).
- **`ERROR_CODE`=100 은 `error-codes.yaml` 의 행 수 상한과 동기화한다.** 레지스트리가 100행을 넘으면
이 상수와 레지스트리 메모를 함께 갱신해야 한다.
- **`TENANT_ID`=1000:** 메트릭 라벨은 bounded mapping-table ID 나 cohort bucket 을 써야 한다 —
raw UUID tenant 식별자는 라벨로 금지. 이 상수는 상한 값일 뿐이다: 1000개를 넘는 tenant 값을 접어
주는(bucket folding) 코드는 없으므로, 상한을 지키는 매핑은 메트릭을 등록하는 쪽이 만든다.
- **tag-key 매핑 quirk 2가지**(`limitFor` 에서 명시 처리): (1) HTTP 메트릭 레지스트리 행의 tag 이름은
`status_code` 가 아니라 `status` 다 — 혼동을 막으려 `status`/`status_code` 둘 다 `STATUS_CODE`(7)로
매핑. (2) Resilience4j bound 는 `outcome` tag(5값)에 적용 — 상수명은 명료성을 위해
`RESILIENCE4J_OUTCOME` 이지만 lookup 키는 레지스트리 tag 이름인 `outcome` 다. 다른 메트릭의
`outcome` tag 는 실제 cardinality 가 다를 수 있으나(db 3, outbox 4), lookup 은 보수적 출발점으로
Resilience4j bound 를 돌려준다.
- **tag-key 매핑**(`limitFor`): `status`/`status_code` 는 `STATUS_CODE`, `uri`/`uri_template` 은 `URI_TEMPLATE`,
`outcome` 은 `OUTCOME` 이다. 다른 메트릭의 `outcome` tag 는 실제 값이 더 적을 수 있으나(httpclient 3, outbox 5),
lookup 은 가장 넓은 집합을 돌려준다.
### ForbiddenMetricTags
- **스켈레톤 전역에서 금지된 high-cardinality 메트릭 tag 키**(D8): `user_id`, `request_id`,
@@ -15,8 +15,8 @@ class CardinalityBoundsTest {
// ----------------------------------------------------------------
@Test
void statusCodeConstantIs7() {
assertThat(CardinalityBounds.STATUS_CODE).isEqualTo(7);
void statusCodeConstantIs40() {
assertThat(CardinalityBounds.STATUS_CODE).isEqualTo(40);
}
@Test
@@ -40,8 +40,8 @@ class CardinalityBoundsTest {
}
@Test
void resilience4jOutcomeConstantIs5() {
assertThat(CardinalityBounds.RESILIENCE4J_OUTCOME).isEqualTo(5);
void outcomeConstantIs6() {
assertThat(CardinalityBounds.OUTCOME).isEqualTo(6);
}
// ----------------------------------------------------------------
@@ -49,14 +49,14 @@ class CardinalityBoundsTest {
// ----------------------------------------------------------------
@Test
void limitForStatusCodeReturns7() {
assertThat(CardinalityBounds.limitFor("status_code")).hasValue(7);
void limitForStatusCodeReturns40() {
assertThat(CardinalityBounds.limitFor("status_code")).hasValue(40);
}
@Test
void limitForStatusAlsoReturns7() {
// registry HTTP row tag is named "status", not "status_code"; both map to 7
assertThat(CardinalityBounds.limitFor("status")).hasValue(7);
void limitForStatusAlsoReturns40() {
// registry HTTP row tag is named "status", not "status_code"; both map to 40
assertThat(CardinalityBounds.limitFor("status")).hasValue(40);
}
@Test
@@ -64,6 +64,12 @@ class CardinalityBoundsTest {
assertThat(CardinalityBounds.limitFor("uri_template")).hasValue(200);
}
@Test
void limitForUriReturnsTheUriTemplateBound() {
// Spring's http.server.requests names the route tag "uri"
assertThat(CardinalityBounds.limitFor("uri")).hasValue(CardinalityBounds.URI_TEMPLATE);
}
@Test
void limitForDependencyNameReturns50() {
assertThat(CardinalityBounds.limitFor("dependency_name")).hasValue(50);
@@ -80,9 +86,9 @@ class CardinalityBoundsTest {
}
@Test
void limitForOutcomeReturns5() {
// resilience4j uses tag named "outcome"
assertThat(CardinalityBounds.limitFor("outcome")).hasValue(5);
void limitForOutcomeReturns6() {
// Spring's http.server.requests outcome has six values
assertThat(CardinalityBounds.limitFor("outcome")).hasValue(6);
}
// ----------------------------------------------------------------
@@ -6,19 +6,24 @@ import java.util.OptionalInt;
/**
* Per-tag cardinality upper bounds for metrics registered in this skeleton — a Java mirror of the
* registry's cardinality table. {@link #limitFor(String)} gives the bound for a known tag key
* without hard-coding magic numbers (used by {@code MeterFilter} config and cardinality contract
* tests). Java stdlib only.
* without hard-coding magic numbers. Only the registry contract test reads it (it is a test
* fixture); no runtime {@code MeterFilter} does — the runtime filter refuses forbidden tags, it
* does not cap counts. This Javadoc used to say a MeterFilter used it (review 2026-11-12). Java
* stdlib only.
*
* <p>The numeric values are operational assumptions, not an external standard. See the module
* README for the rationale, the {@code error-codes.yaml} sync rule, and the two tag-key mapping
* quirks ({@code status}/{@code status_code} and {@code outcome}).
* README for the rationale, the {@code error-codes.yaml} sync rule, and the tag-key mappings
* ({@code status}/{@code status_code}, {@code outcome} and {@code uri}).
*/
public final class CardinalityBounds {
private CardinalityBounds() {}
/** HTTP status-class tag bound (1xx–5xx + ok/other). */
public static final int STATUS_CODE = 7;
/**
* HTTP status tag bound: the numeric codes a service answers with ({@code 200}, {@code 404}, …),
* which is what Spring's {@code http.server.requests} records — not five status classes.
*/
public static final int STATUS_CODE = 40;
/** URI template tag bound — routes must be template-normalised (e.g. {@code /users/{id}}). */
public static final int URI_TEMPLATE = 200;
@@ -32,8 +37,11 @@ public final class CardinalityBounds {
/** Tenant id tag bound — bounded mapping-table id / cohort bucket only, no raw UUID. */
public static final int TENANT_ID = 1000;
/** Resilience4j {@code outcome} tag bound (SUCCESS/FAILURE/CIRCUIT_OPEN/TIMEOUT/REJECTED). */
public static final int RESILIENCE4J_OUTCOME = 5;
/**
* {@code outcome} tag bound: Spring's six HTTP outcomes (INFORMATIONAL … UNKNOWN), the widest set
* a registered meter uses.
*/
public static final int OUTCOME = 6;
/** Registry tag name → cardinality bound. See the module README for the mapping quirks. */
private static final Map<String, Integer> LIMITS =
@@ -41,16 +49,17 @@ public final class CardinalityBounds {
"status_code", STATUS_CODE,
"status", STATUS_CODE,
"uri_template", URI_TEMPLATE,
"uri", URI_TEMPLATE,
"dependency_name", DEPENDENCY_NAME,
"error_code", ERROR_CODE,
"tenant_id", TENANT_ID,
"outcome", RESILIENCE4J_OUTCOME);
"outcome", OUTCOME);
/**
* Returns the cardinality upper bound for a known registry tag key, or {@link
* OptionalInt#empty()} for unknown or {@code null} keys.
*
* <p>Known keys: {@code status_code}, {@code status}, {@code uri_template}, {@code
* <p>Known keys: {@code status_code}, {@code status}, {@code uri_template}, {@code uri}, {@code
* dependency_name}, {@code error_code}, {@code tenant_id}, {@code outcome}.
*
* @param tagKey the registry tag name; {@code null} returns empty
@@ -16,8 +16,10 @@ public final class MetricNaming {
private MetricNaming() {}
/**
* Allowed Micrometer unit suffixes — every registry metric name must end with one of these:
* {@code seconds} (timers), {@code bytes} (byte gauges), {@code total} (counters).
* Allowed values of a registry row's {@code unit}: {@code seconds} (timers), {@code bytes} (byte
* gauges and summaries), {@code total} (counters and count gauges). The name does not repeat the
* unit. Micrometer's Prometheus naming appends {@code _seconds} to a timer and {@code _total} to
* a counter; a count gauge gets no suffix.
*/
public static final Set<String> ALLOWED_UNITS = Set.of("seconds", "bytes", "total");