Files
clean-architecture-backend-…/docs/httpclient/configuration-reference.md
T
DongHyeonka 45d2a478b8 fix!: 리뷰가 기록만 하고 남겨 둔 결함을 모두 고친다
문제: 확인 리뷰들이 찾은 Minor와 "남음" 항목을 고치지 않고 기록만 했다.
그중 동작에 닿는 것이 여럿이었다. verifyStrictLaneStages가 `./gradlew ci
|| true`, `| tee`, `if ./gradlew …` 같은 실패를 막지 못하는 명령을 실행으로
세는 거짓 통과, Redis 멱등 저장소가 lease가 지난 CLAIMED의 시작을 받아
주던 것(PostgreSQL은 거절), gRPC가 INTERNAL_ERROR 실패를 아무 데도 남기지
않고 STOMP가 SQL 원인까지 로그에 쓰던 것, 잠금 대기 검사기가 Flyway가
트랜잭션 밖에서 돌리는 VACUUM FULL을 몰라 통과시키던 것, 템플릿 패키지
목록과 버전 판정 정규식이 두 곳에 갈라져 있던 것.

방법: 영역별 4묶음이 실패 테스트를 먼저 확인하고 고쳤다(재리뷰 README
16절).
- workflow run 스크립트를 bash 문법으로 읽고, 실패를 막지 못하는 명령과
  셸이 실행하지 않는 줄의 cd는 이유를 대며 세지 않는다.
- 두 멱등 저장소가 lease가 지난 시작을 LEASE_EXPIRED로 거절하고,
  executor는 아무것도 실행하지 않았으므로 503으로 답한다.
- web·GraphQL·gRPC·STOMP가 shared-contract ServerFailureLog로 같은 실패
  로그 줄을 쓴다(persistence 실패는 분류만).
- @SystemCaller 규칙이 인터페이스로 주입한 경로도 보고, 조립 설정은 사용자
  전송으로 세지 않는다.
- 갈라진 복사본은 하나로: 템플릿 패키지 표가 정본이고 클래스를 대조하며,
  버전 판정 코드는 grpc 빌드가 Sync로 가져와 컴파일한다.
- httpclient 장애 주입 lane이 main 단계에서 두 번 돌던 것을 한 번으로.
- 게이트에서 드러난 httpclient drain 스레드 경쟁: close()가 스레드를 join하고,
  런타임이 닫기를 거부해도 drain 스레드를 먼저 멈춘다.

위험·한계: 목록에 넣지 않은 새 템플릿 패키지는 기능 패키지와 구별할 수
없다(문서화). 서브셸·eval·source 안의 cd 뒤 명령과 `|| exit 1`은 세지 않는다
(거짓 실패 쪽). Gradle 옵션 판독은 Gradle 9.0 동작을 TestKit으로 고정했다.

검증: 첫 ci가 httpclient ClientRuntimeRegistryTest 1건으로 실패(기존 코드의
drain 스레드 경쟁, README 16.1절) — 고친 뒤 ci 재실행 통과. 두 빌드
verifyStrictLaneStages, mainCheck, :integrationCheck, -p optional-platforms ci
integrationCheck performanceCheck, :performanceCheck, :releaseCheck, compose
18 lane 통과. httpclient check·testQualityCheck·failure injection·performance
lane을 수정 뒤 다시 돌려 통과.

Refs: docs/reviews/2026-11-03-rereview/README.md 16절
BREAKING CHANGE: 멱등 저장소 시작·renew 결과에 LEASE_EXPIRED가 생겼고,
lease가 지난 시작은 503 IDEMPOTENCY_UNAVAILABLE이다. verifyStrictLaneStages가
실패를 막지 못하는 workflow 명령을 세지 않는다.
2026-11-04 22:46:05 +09:00

295 lines
18 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# HTTP Client Platform — Configuration Reference
Every outbound call resolves exactly one **Named Client Profile**. The whole capability lives under
the `app.httpclient` prefix: profiles under `app.httpclient.clients[N]`, Dynamic Target policies
under `app.httpclient.dynamic-targets[N]`.
Design §30.1 forbids a production profile from inheriting large framework defaults. Anything a
production deployment must decide has either no default or an unusable one, and
`HttpClientStartupValidator` fails the context rather than guessing.
## The master switch
| Property | Type | Default | Environment |
|---|---|---|---|
| `app.httpclient.enabled` | boolean | `true` | `APP_HTTPCLIENT_ENABLED` |
The module is on when present: a service adds `runtimeOnly project(':adapter:outbound:httpclient')`
to `app-bootstrap/build.gradle`, and the module's own `config/module-defaults/httpclient.yml` (loaded at the lowest
precedence by the support leaf's `ModuleDefaultsEnvironmentPostProcessor`) supplies `enabled: true`. Absent from the
build is the ordinary off state. `false` is the explicit off: `HttpClientPlatformAutoConfiguration`
is then never processed and neither is anything it imports — no property is bound, and no transport
provider, connection pool, TLS context, credential, thread, gateway or actuator endpoint exists. A
malformed HTTP client setting cannot fail the startup of a deployment that switched it off.
Anything that is not exactly `true` — `yes`, `1`, blank — turns the platform off. On with no client
declared is a startup failure carrying `HTTPCLIENT_ACTIVE_WITHOUT_CLIENTS`: a platform with nothing
to call still holds transport providers and gateways no caller can reach.
## Declaring clients from the environment
Clients are an indexed list carrying their own `name`, not a map keyed by name. A map key becomes a
segment of the environment variable and the relaxed binder normalises it, so `payment-api` and
`payment_api` would arrive as one entry with nothing said about the one that was lost. Both a
duplicate name and a name that collides once normalised fail startup.
```dotenv
APP_HTTPCLIENT_ENABLED=true
APP_HTTPCLIENT_CLIENTS_0_NAME=payment
APP_HTTPCLIENT_CLIENTS_0_BASE_URL=https://payment.example
APP_HTTPCLIENT_CLIENTS_0_ALLOWED_HOSTS_0=payment.example
APP_HTTPCLIENT_CLIENTS_0_ALLOWED_PORTS_0=443
APP_HTTPCLIENT_CLIENTS_0_REQUEST_MAX_BODY_BYTES=1048576
APP_HTTPCLIENT_CLIENTS_0_TLS_PROFILE_ID=payment
APP_HTTPCLIENT_DYNAMIC_TARGETS_0_NAME=webhook
APP_HTTPCLIENT_DYNAMIC_TARGETS_0_ALLOWED_SCHEMES_0=https
```
`docs/httpclient/env-fields.yaml` is the registry of accepted variable names. It is
derived from the settings record and held to it in both directions, and the platform refuses to
start on an `APP_HTTPCLIENT_` variable that is not in it — so
`APP_HTTPCLIENT_CLIENTS_0_TIMEUOT_TOTAL_CALL` fails startup instead of silently leaving the client
on its default budget. Unknown keys supplied through a configuration file rather than the
environment are refused by strict binding for the same reason.
Only `APP_HTTPCLIENT_ENABLED` appears in `src/.env` and `docs/registries/env-keys.yaml`. It is the
one key with a deployment-independent value; templating an indexed client in `application.yml` would
materialise a nameless client in every deployment, which the aggregate validation refuses.
## `app.httpclient.clients[N]`
| Property | Type | Default | Notes |
|---|---|---|---|
| `name` | string | — | Required, unique, and distinct from every other name once normalised for the environment |
| `mode` | `TRUSTED` \| `DYNAMIC` | `TRUSTED` | A dynamic profile may not carry a default credential |
| `base-url` | URI | — | Required for a trusted profile; no userinfo, no query |
| `allowed-hosts` | list | empty | Required in production |
| `allowed-ports` | list | empty | Compared against the effective port |
| `transport` | `APACHE` \| `JDK` \| `JETTY` \| `SIMPLE` | `APACHE` | `SIMPLE` is rejected in production; `JETTY` needs a deployment-registered provider |
| `protocols` | list | `HTTP_1_1` | The default transport is Apache, whose classic client is HTTP/1.1 only; a profile that wants HTTP/2 declares it together with a transport that can deliver it. `HTTP_3` requires the experimental acknowledgement |
| `experimental-acknowledgement` | string | — | Must equal `I_ACCEPT_HTTP3_EXPERIMENTAL_SEMANTICS` |
### `pool`
| Property | Default | Meaning |
|---|---|---|
| `max-total-connections` | `50` | Socket ceiling for the runtime |
| `max-connections-per-route` | `25` | Per-upstream ceiling |
| `max-pending-acquires` | `100` | Waiting-request memory ceiling |
| `pending-acquire-timeout` | `200ms` | Pool or stream wait ceiling |
| `max-idle-time` | `30s` | Idle eviction |
| `max-life-time` | `5m` | Picks up DNS, load-balancer, and certificate changes |
| `validate-after-inactivity` | `5s` | Stale and half-open detection |
| `requires-route-pool` | `false` | Set when route-scoped limits are mandatory; the JDK transport then refuses the profile |
| `requires-bounded-pending-queue` | `false` | Same, for a bounded pending queue |
### `timeout`
| Property | Default | Meaning |
|---|---|---|
| `dns` | `300ms` | Hostname resolution |
| `connect` | `500ms` | Socket connect |
| `tls-handshake` | `1s` | TLS and ALPN |
| `response-header` | `2s` | Until final response headers |
| `read-idle` | `3s` | Between response chunks |
| `total-call` | `4s` | The whole logical call, including retry backoff |
`total-call` must not be shorter than `connect` or `response-header`; the validator emits
`INVALID_TIMEOUT_BUDGET` otherwise. Every timeout above, and `pool.pending-acquire-timeout`, must be
greater than zero (`TIMEOUT_NOT_POSITIVE`): both engines read zero as "wait forever".
`total-call` also bounds the setup of a streaming download — connect, send, and the wait for
response headers. Once the stream is handed over, each gap of the body is bounded by `read-idle`
instead, so a long download is not cut at an arbitrary total (design §15.3). This holds on both
transports. The JDK transport keeps its exchange-wide timeout off a streamed body, and a per-stream
watchdog bounds each read's wait by `read-idle`, because the JDK client has no socket read timeout.
The watchdog wakes on one daemon thread of its own (`httpclient-jdk-read-idle`), not on the common
`ForkJoinPool`, so a service that fills that pool with blocking work does not delay it (re-review
2026-11-04 RR3-03-01). That thread ends 60 s after the last wake it had queued and the next stream
starts it again; it inherits no thread-locals from the request thread that starts it and uses the
module's class loader as its context loader, so an idle service keeps no thread and a redeployed
application's loader is not pinned (RR4-03-04). Before review 2026-11-03 RR-04-03 every JDK download longer than
`response-header` was cut mid-body. A body failure after hand-over is thrown from `read` as `HttpBodyReadException` — an `IOException`, as
`InputStream` promises, so `catch (IOException)` still sees it — whose `failure()` is
`HttpResponseTimeoutException` (a wait longer than `read-idle`) or `HttpResponseTruncatedException`
(the connection ended early), stage `RESPONSE_BODY`, evidence `PARTIAL_RESPONSE` (re-review
2026-11-04 RR-03-14). On the JDK transport `read-idle` bounds each read's wait, `skip` included, and
time the caller spends between reads does not count (RR-03-12).
### Removed settings
Six keys were removed because they were bound and reached no transport (review 2026-11-01 05-15).
Setting one now fails startup with a bind error naming the key (`The elements
[app.httpclient.clients[0].timeout.request-write-idle] were left unbound.`), instead of being
accepted and ignored.
| Removed key | Why |
|---|---|
| `timeout.request-write-idle` | Neither engine can bound a blocking socket write |
| `timeout.proxy-connect`, `proxy.connect-timeout` | The TCP connect to a proxy is governed by `timeout.connect` |
| `pool.eviction-interval` | Apache's idle evictor runs at `max-idle-time` |
| `pool.shutdown-timeout` | A retired runtime drains for `app.httpclient.rotation-drain-timeout` |
| `observability.operation-name-required` | An operation name is mandatory in the API; the switch could only be true |
### `circuit-breaker`
What counts as a failure is fixed: a 5xx, 408 or 429 response — whether the call throws or returns
it as a result — and every transport failure. Every other 4xx is a healthy answer. These settings
only say how many failures, out of how many calls, open the circuit. Defaults are Resilience4j's own,
which every profile ran with before the keys existed.
Two deadlines can end an attempt in flight, and they are counted differently (review 2026-11-03
RR-04-01):
| Ended by | Breaker | Why |
|---|---|---|
| The caller's own deadline (`HttpOperation.deadline()`, when earlier than `total-call`) | Not recorded; the permission is given back | The caller ran out of time. Counting it opened the circuit on a healthy upstream whenever callers passed short budgets |
| The profile's `timeout.total-call` | Recorded as a failure | `total-call` is the operator's statement of how long a healthy upstream may take; a slow-drip upstream that never trips a per-gap timeout is seen only through it |
The first row has a blind spot (re-review 2026-11-04 RR-03-16). The attempt is let off whenever the
caller's deadline was the earlier one and had passed when the attempt failed — the code does not ask
whether the upstream was still answering within the profile's limits. If every caller of a profile
passes a budget shorter than `connect` or `response-header`, an upstream that hangs (drops packets,
never answers) ends every attempt at the caller's deadline first, so no attempt is recorded and the
circuit never opens; every call waits out its own budget. A failure that comes before the caller's
deadline — a refused connection — is still counted. For such a profile, set `connect` and
`response-header` shorter than the shortest caller budget.
| Property | Default | Meaning |
|---|---|---|
| `failure-rate-threshold` | `50` | Percent of failed calls in the window that opens the circuit, 1–100 |
| `minimum-number-of-calls` | `100` | Calls recorded before the rate is evaluated; at most `sliding-window-size` |
| `sliding-window-size` | `100` | The last N calls the rate is computed over (count-based) |
| `wait-duration-in-open-state` | `60s` | How long an open circuit rejects before trial calls; positive |
| `permitted-calls-in-half-open-state` | `10` | Trial calls while half-open; at least 1 |
An out-of-range value fails startup with `CIRCUIT_BREAKER_SETTING_INVALID`. The breaker belongs to
the profile, not to a runtime generation, so a certificate rotation keeps its state.
### `redirect`, `request`, `response`
| Property | Default | Meaning |
|---|---|---|
| `redirect.enabled` | `false` | Engine redirect handling is always off; the platform follows hops itself |
| `redirect.max-hops` | `0` | Enabling redirects with zero hops is a configuration error |
| `redirect.allow-cross-origin` | `false` | When enabled, credentials are stripped on the hop |
| `request.max-body-bytes` | `0` | Required in production |
| `request.compression` | `false` | |
| `response.max-wire-bytes` | `5242880` | Bytes on the wire |
| `response.max-decoded-bytes` | `10485760` | Bytes after decoding; hard maximum is 64 MiB |
| `response.allowed-content-types` | JSON + problem+json | Empty means "any" |
### `authentication`
| Property | Default | Meaning |
|---|---|---|
| `type` | `NONE` | One of the design §20.1 methods |
| `registration-id` | — | Required for OAuth2 |
| `scopes` | empty | Part of the token cache key |
| `audience` | — | Part of the token cache key |
| `header-name` | — | Required for `API_KEY_HEADER`; must be on the allowlist |
| `secret-reference` | — | Resolved by the deployment's secret loader, never a literal |
### `retry`
| Property | Default | Meaning |
|---|---|---|
| `policy` | `none` | Named policy for reporting |
| `max-attempts` | `1` | Attempts, not retries; at most 5 (`RETRY_MAX_ATTEMPTS_EXCEEDED`) |
| `base-backoff` | `50ms` | |
| `max-backoff` | `200ms` | |
| `jitter` | `FULL` | `NONE` \| `FULL` \| `DECORRELATED` |
| `retry-after` | `HONOR` | `HONOR` \| `IGNORE` \| `CAP` |
| `budget` | — | Shared token bucket name. A retrying profile that names none gets its own bucket, with the same pool-derived capacity (`max-total-connections / 10`, at least 1, refilled each minute) |
### `tls`
| Property | Default | Meaning |
|---|---|---|
| `profile-id` | — | Required in production; the only TLS identifier the actuator exposes |
| `protocols` | `TLSv1.3, TLSv1.2` | Anything else is rejected |
| `hostname-verification` | `true` | Setting it false fails startup |
| `trust-all` | `false` | Exists only so the unsafe intent is rejectable; nothing acts on `true` |
| `allow-plain-http` | `false` | Plaintext fallback fails startup in production |
| `trust-material-reference` | — | Custom CA, resolved by the secret loader |
| `key-material-reference` | — | Client certificate for mTLS |
### `proxy` and `observability`
| Property | Default | Meaning |
|---|---|---|
| `proxy.enabled` | `false` | |
| `proxy.host` / `proxy.port` / `proxy.type` | — / `0` / `HTTP` | |
| `proxy.credential-provider` | — | Proxy authentication is separate from target authentication |
| `proxy.import-ambient-no-proxy` | `false` | Ambient `NO_PROXY` never widens a validated profile |
| `observability.full-url-recording` | `false` | |
| `observability.body-logging` | `false` | |
## `app.httpclient.dynamic-targets[N]`
| Property | Default | Meaning |
|---|---|---|
| `name` | — | Required, unique, and subject to the same normalisation rule as a client name |
| `allowed-schemes` | `https` | |
| `allowed-ports` | `443` | |
| `allowed-host-suffixes` | empty | |
| `allowed-hosts` | empty | Empty means "any host that survives address validation" |
| `max-redirect-hops` | `0` | Each hop repeats the full validation flow |
| `trace-propagation` | `false` | Off by default for dynamic targets |
| `blocked-cidrs` | empty | Organisation-defined internal ranges |
## Startup violation codes
`TRUSTED_BASE_URL_REQUIRED`, `BASE_URL_USERINFO_FORBIDDEN`, `BASE_URL_QUERY_FORBIDDEN`,
`PLAINTEXT_PRODUCTION_TARGET`, `ALLOWED_HOST_MISMATCH`, `ALLOWED_PORT_MISMATCH`,
`REDIRECT_POLICY_INVALID`, `REDIRECT_CROSS_ORIGIN_CREDENTIAL_POLICY_REQUIRED`,
`INVALID_TIMEOUT_BUDGET`, `RESPONSE_HARD_MAXIMUM_EXCEEDED`, `PRODUCTION_SIMPLE_FACTORY_FORBIDDEN`,
`JDK_FINE_GRAINED_POOL_UNSUPPORTED`, `HTTP3_STABLE_FORBIDDEN`,
`DYNAMIC_TARGET_TRANSPORT_UNSUPPORTED`, `DYNAMIC_DEFAULT_CREDENTIAL_FORBIDDEN`,
`OAUTH2_REGISTRATION_REQUIRED`, `API_KEY_HEADER_NAME_REQUIRED`, `TRUST_ALL_FORBIDDEN`,
`HOSTNAME_VERIFICATION_REQUIRED`, `PLAINTEXT_FALLBACK_FORBIDDEN`, `TLS_PROTOCOL_FORBIDDEN`,
`RETRY_BACKOFF_REQUIRED`, `MISSING_PRODUCTION_SETTING`, `DUPLICATE_CLIENT_NAME`,
`HTTPCLIENT_ACTIVE_WITHOUT_CLIENTS`, `DYNAMIC_BASE_URL_REQUIRED`,
`DYNAMIC_TARGET_PROXY_UNSUPPORTED`,
`HTTP2_REQUIRED_TRANSPORT_UNSUPPORTED`, `POOL_ROUTE_EXCEEDS_TOTAL`,
`TLS_PROTOCOL_SET_REQUIRED`,
`RETRY_POLICY_CONTRADICTS_ATTEMPTS`, `FULL_URL_RECORDING_FORBIDDEN`, `BODY_LOGGING_FORBIDDEN`,
`DNS_TIMEOUT_UNSUPPORTED`, `PROXY_CREDENTIAL_UNSUPPORTED`, `PROXY_AMBIENT_NO_PROXY_UNSUPPORTED`,
`TIMEOUT_NOT_POSITIVE`, `RETRY_MAX_ATTEMPTS_EXCEEDED`, `CIRCUIT_BREAKER_SETTING_INVALID`.
A key that names no setting is not a violation code: the shared strict binder
(`adapter:outbound:support` `StrictSettingsBinder`) refuses it while binding, at any depth. Spring's
own unbound-key check stops at the first level under a list element, so `clients[0].timeout.<typo>`
used to bind nothing and fail nothing; the binder now refuses a key under `clients[N]` or
`dynamic-targets[N]` that bound nothing, for every capability rather than for this platform alone
(review 2026-11-01 05-15). The platform's own guard for it, and its `HTTPCLIENT_UNKNOWN_SETTING`
code, were removed with that change.
`DNS_TIMEOUT_UNSUPPORTED`, `PROXY_CREDENTIAL_UNSUPPORTED` and `PROXY_AMBIENT_NO_PROXY_UNSUPPORTED` name settings the platform binds but cannot yet honour. Neither the Apache classic
client nor the JDK client exposes a DNS-resolution timeout, and no proxy-credential path exists, so
a non-default value is refused rather than accepted and ignored. Leaving the defaults alone is
unaffected — only a deliberate, unmet request fails.
Three of these are about a guarantee that used to be silently unmet rather than refused:
- `HTTP2_REQUIRED_TRANSPORT_UNSUPPORTED` — declaring `protocols: [HTTP_2]` alone states that HTTP/2
is required. No transport can be configured to offer H2 and nothing else; the JDK client treats it
as a preference and negotiates HTTP/1.1, and Apache's classic client is HTTP/1.1 only.
- `POOL_ROUTE_EXCEEDS_TOTAL` — a per-route ceiling above the total is incoherent.
- `TLS_PROTOCOL_SET_REQUIRED` — an empty `tls.protocols` used to pass and then let the JVM choose,
so emptying the list to "tighten" a profile loosened it.
- `RETRY_POLICY_CONTRADICTS_ATTEMPTS` — `retry.policy` was read by nothing on the execution path, so
the actuator could report `none` for a profile retrying three times. The two settings must now
agree: `policy: none` requires `max-attempts: 1`, and any other policy requires more than one.
- `FULL_URL_RECORDING_FORBIDDEN` / `BODY_LOGGING_FORBIDDEN` — both settings were bindable and inert.
Recording an expanded URL puts path identifiers and query strings into unbounded metric tags;
recording bodies puts someone else's data into logs. Representable so the intent is rejectable,
refused under a production profile.
`DYNAMIC_TARGET_PROXY_UNSUPPORTED` is worth spelling out: a forward proxy resolves the hostname on
its own side, so the addresses this platform validated and pinned are not the addresses the
connection reaches. The SSRF defence would be present, correct, and bypassed — so the combination is
refused rather than served with a guarantee it cannot keep.