diff --git a/docs/upgrade/2026-11-httpclient-failure-classification.md b/docs/upgrade/2026-11-httpclient-failure-classification.md new file mode 100644 index 00000000..6ba4065a --- /dev/null +++ b/docs/upgrade/2026-11-httpclient-failure-classification.md @@ -0,0 +1,26 @@ +# 업그레이드 안내 — 2026-11 HTTP client 전송 실패 분류 + +- 범위: Stable transport 두 개(Apache·JDK)의 전송 실패 분류를 공용 규칙 하나로 합친 변경. 설정 키와 공개 타입은 + 그대로다. 같은 실패에 두 transport가 같은 예외와 재시도 판정을 낸다. 따라 고칠 코드는 없다. +- 근거: 2026-11-21 리뷰 발견 REV-BE-0024(본문 중 끊김의 분류가 transport마다 달랐다). 본문 중 끊김이 + `HttpResponseTruncatedException`이라는 것은 `docs/httpclient/operations.md` 「예외」 표와 + `docs/httpclient/configuration-reference.md`가 이미 약속한 응답이다. + +## 1. 누가 읽나 + +이 템플릿을 `upstream` remote로 두고 merge해 받는 파생 서비스가 읽는다. 특히 HTTP client를 Apache transport로 +쓰는 서비스, 호출 thread를 interrupt해서 호출을 취소하는 서비스다. + +## 2. 바뀐 동작 (따라 할 일 없음) + +| # | 바뀐 것 | 전에는 | 해당 서비스 | +| --- | --- | --- | --- | +| 1 | Apache transport에서 응답 본문을 받다가 엔진이 알아보지 못한 이유(`connection reset` 등)로 끊기면 `HttpResponseTruncatedException`이다. 문서가 약속한 타입이고 JDK transport와 같다. 버퍼 본문 호출은 안전하게 멱등이면 재시도 예산 안에서 다시 보낸다. 넘긴 뒤의 스트리밍 본문은 `HttpBodyReadException`의 `failure()`가 이 타입이다 | `HttpUnknownTransportException`이었고 재시도하지 않았다 | Apache transport를 쓰는 서비스 | +| 2 | JDK transport에서 본문을 다 읽은 뒤(단계 `COMPLETE`) 알아보지 못한 실패는 `HttpUnknownTransportException`이다. Apache와 같다 | `HttpResponseTruncatedException`이었다 | JDK transport를 쓰는 서비스 | +| 3 | 호출 thread의 interrupt 플래그가 선 채 알아보지 못한 실패로 끝난 시도는 취소(category `CANCELLED`, 사유 `ATTEMPT_INTERRUPTED`)다. 호출자는 `HttpUnknownTransportException`을 받고, 재시도하지 않는다. virtual thread가 socket을 읽다 interrupt되면 JDK가 socket을 닫고 `SocketException`을 던지는 경우가 이것이다 | JDK transport에서는 본문 중이면 `HttpResponseTruncatedException`이라 버퍼 본문의 멱등 호출을 다시 보냈다. Apache transport는 `HttpUnknownTransportException`이었다 | 호출 thread를 interrupt해 호출을 취소하는 서비스 | + +## 3. 바뀌지 않은 것 + +- 예외 타입 목록, 설정 키, `DefaultRetryEligibilityEngine`의 재시도 판정 규칙은 그대로다. 바뀐 것은 어떤 실패가 어느 + category가 되느냐다. +- 실험 transport인 Jetty HTTP/3의 분류는 이번에 바꾸지 않았다. diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/apache/ApacheFailureClassifier.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/apache/ApacheFailureClassifier.java index d08a53fa..f35d0490 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/apache/ApacheFailureClassifier.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/apache/ApacheFailureClassifier.java @@ -1,19 +1,10 @@ package dev.caskeleton.adapter.outbound.httpclient.apache; import dev.caskeleton.adapter.outbound.httpclient.api.operation.AttemptStage; -import dev.caskeleton.adapter.outbound.httpclient.api.operation.ExecutionEvidence; import dev.caskeleton.adapter.outbound.httpclient.api.operation.FailureCategory; import dev.caskeleton.adapter.outbound.httpclient.transport.TransportFailure; import dev.caskeleton.adapter.outbound.httpclient.transport.TransportFailureClassifier; -import java.io.InterruptedIOException; -import java.net.ConnectException; -import java.net.NoRouteToHostException; -import java.net.SocketTimeoutException; -import java.net.UnknownHostException; -import java.security.cert.CertificateException; -import javax.net.ssl.SSLException; -import javax.net.ssl.SSLHandshakeException; -import javax.net.ssl.SSLPeerUnverifiedException; +import dev.caskeleton.adapter.outbound.httpclient.transport.TransportFailureRules; import org.apache.hc.client5.http.ConnectTimeoutException; import org.apache.hc.client5.http.HttpHostConnectException; import org.apache.hc.core5.http.ConnectionClosedException; @@ -21,28 +12,18 @@ import org.apache.hc.core5.http.ConnectionClosedException; /** * Maps Apache HttpClient 5 failures onto stable evidence (design §13.3, §13.4). * - *

The classifier is deliberately asymmetric: {@code NOT_SENT} is only produced for stages that - * prove nothing left the process. Once the request write has begun, an ambiguous I/O error stays - * {@code SENT_NO_RESPONSE}, because guessing "not sent" is what turns a timeout into a duplicate - * payment. + *

Only Apache's own exception types are recognised here. The cause chain, the JDK socket and TLS + * exceptions, and the stage rules are shared with the JDK engine in {@link TransportFailureRules}. */ public final class ApacheFailureClassifier implements TransportFailureClassifier { @Override public TransportFailure classify(Throwable failure, AttemptStage lastObservedStage) { - // The whole cause chain is inspected, not just the outermost throwable: Spring wraps engine - // exceptions, and a wrapped ConnectException still proves the request was never sent. Matching - // only the outer type would downgrade a provable NOT_SENT to an ambiguous SENT_NO_RESPONSE. - for (Throwable cause : chain(failure)) { - TransportFailure recognized = recognize(cause, lastObservedStage); - if (recognized != null) { - return recognized; - } - } - return conservative(lastObservedStage, FailureCategory.UNKNOWN, "TRANSPORT_FAILURE"); + return TransportFailureRules.classify( + failure, lastObservedStage, ApacheFailureClassifier::recognize); } - private TransportFailure recognize(Throwable cause, AttemptStage lastObservedStage) { + private static TransportFailure recognize(Throwable cause, AttemptStage lastObservedStage) { if (cause instanceof org.apache.hc.core5.concurrent.CancellableDependency) { return TransportFailure.notSent( AttemptStage.POOL_ACQUIRE, FailureCategory.POOL_ACQUIRE_TIMEOUT, "POOL_ACQUIRE_TIMEOUT"); @@ -51,90 +32,21 @@ public final class ApacheFailureClassifier implements TransportFailureClassifier return TransportFailure.notSent( AttemptStage.POOL_ACQUIRE, FailureCategory.POOL_ACQUIRE_TIMEOUT, "POOL_ACQUIRE_TIMEOUT"); } - if (cause instanceof UnknownHostException) { - return TransportFailure.notSent( - AttemptStage.DNS, FailureCategory.DNS, "DNS_RESOLUTION_FAILED"); - } - if (cause instanceof ConnectTimeoutException - || cause instanceof HttpHostConnectException - || cause instanceof ConnectException - || cause instanceof NoRouteToHostException) { + // Both connect failures. ConnectTimeoutException is a SocketTimeoutException, so it is + // recognised here, before the shared timeout rule would classify it by the stage. + if (cause instanceof ConnectTimeoutException || cause instanceof HttpHostConnectException) { return TransportFailure.notSent( AttemptStage.CONNECT, FailureCategory.CONNECT, "CONNECT_FAILED"); } - if (cause instanceof SSLPeerUnverifiedException || cause instanceof CertificateException) { - return TransportFailure.notSent( - AttemptStage.TLS_HANDSHAKE, FailureCategory.TLS_PERMANENT, "TLS_TRUST_FAILED"); - } - if (cause instanceof SSLHandshakeException) { - return TransportFailure.notSent( - AttemptStage.TLS_HANDSHAKE, FailureCategory.TLS_PERMANENT, "TLS_HANDSHAKE_FAILED"); - } - if (cause instanceof SSLException - && !lastObservedStage.isAtLeast(AttemptStage.REQUEST_HEADERS)) { - return TransportFailure.notSent( - AttemptStage.TLS_HANDSHAKE, FailureCategory.TLS_TRANSIENT, "TLS_TRANSIENT_FAILURE"); - } - if (cause instanceof SocketTimeoutException) { - return timeout(lastObservedStage); - } - if (cause instanceof InterruptedIOException) { - // Not a timeout. A SocketTimeoutException means the peer went quiet; a bare - // InterruptedIOException usually means this thread was interrupted — a cancellation, from a - // caller or a shutdown. Treating the two alike classified a cancellation as a transient - // timeout, which the retry engine then retried, so cancelling a call could produce more - // requests than not cancelling it. The interrupt flag is restored because swallowing it - // leaves the thread unable to observe its own cancellation. - Thread.currentThread().interrupt(); - return conservative(lastObservedStage, FailureCategory.CANCELLED, "ATTEMPT_INTERRUPTED"); - } if (cause instanceof ConnectionClosedException) { - return conservative( + return TransportFailureRules.conservative( lastObservedStage, FailureCategory.RESPONSE_TRUNCATED, "CONNECTION_CLOSED"); } return null; } - private java.util.List chain(Throwable failure) { - java.util.List chain = new java.util.ArrayList<>(); - Throwable current = failure; - while (current != null && !chain.contains(current)) { - chain.add(current); - current = current.getCause(); - } - return chain; - } - - private boolean isPoolAcquireTimeout(Throwable cause) { + private static boolean isPoolAcquireTimeout(Throwable cause) { String typeName = cause.getClass().getName(); return typeName.endsWith("ConnectionRequestTimeoutException"); } - - private TransportFailure timeout(AttemptStage lastObservedStage) { - if (lastObservedStage.provesNotSent()) { - return TransportFailure.notSent( - lastObservedStage, FailureCategory.CONNECT, "CONNECT_TIMEOUT"); - } - if (lastObservedStage.isAtLeast(AttemptStage.RESPONSE_BODY)) { - return new TransportFailure( - lastObservedStage, - ExecutionEvidence.PARTIAL_RESPONSE, - FailureCategory.RESPONSE_TIMEOUT, - "RESPONSE_BODY_TIMEOUT"); - } - return TransportFailure.sentNoResponse( - AttemptStage.RESPONSE_HEADERS, FailureCategory.RESPONSE_TIMEOUT, "RESPONSE_HEADER_TIMEOUT"); - } - - private TransportFailure conservative( - AttemptStage lastObservedStage, FailureCategory category, String reason) { - if (lastObservedStage.provesNotSent()) { - return TransportFailure.notSent(lastObservedStage, category, reason); - } - if (lastObservedStage.isAtLeast(AttemptStage.RESPONSE_BODY)) { - return new TransportFailure( - lastObservedStage, ExecutionEvidence.PARTIAL_RESPONSE, category, reason); - } - return TransportFailure.sentNoResponse(lastObservedStage, category, reason); - } } diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/JdkFailureClassifier.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/JdkFailureClassifier.java index 234b5919..994da83b 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/JdkFailureClassifier.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/JdkFailureClassifier.java @@ -1,120 +1,40 @@ package dev.caskeleton.adapter.outbound.httpclient.jdk; import dev.caskeleton.adapter.outbound.httpclient.api.operation.AttemptStage; -import dev.caskeleton.adapter.outbound.httpclient.api.operation.ExecutionEvidence; import dev.caskeleton.adapter.outbound.httpclient.api.operation.FailureCategory; import dev.caskeleton.adapter.outbound.httpclient.transport.TransportFailure; import dev.caskeleton.adapter.outbound.httpclient.transport.TransportFailureClassifier; -import java.io.InterruptedIOException; -import java.net.ConnectException; -import java.net.NoRouteToHostException; -import java.net.SocketTimeoutException; -import java.net.UnknownHostException; +import dev.caskeleton.adapter.outbound.httpclient.transport.TransportFailureRules; import java.net.http.HttpConnectTimeoutException; import java.net.http.HttpTimeoutException; -import java.security.cert.CertificateException; -import javax.net.ssl.SSLException; -import javax.net.ssl.SSLHandshakeException; -import javax.net.ssl.SSLPeerUnverifiedException; /** * Maps JDK HttpClient failures onto stable evidence (design §13.3, §13.5). * *

The JDK exposes fewer stage-specific exceptions than Apache, so anything other than a proven - * pre-send failure stays conservative. + * pre-send failure stays conservative. Only the client's own timeout types are recognised here; the + * cause chain, the socket and TLS exceptions, and the stage rules are shared with the Apache engine + * in {@link TransportFailureRules}. */ public final class JdkFailureClassifier implements TransportFailureClassifier { @Override public TransportFailure classify(Throwable failure, AttemptStage lastObservedStage) { - // Spring and the JDK both wrap engine exceptions; the chain is inspected so a wrapped - // ConnectException still classifies as provably NOT_SENT. - for (Throwable cause : chain(failure)) { - TransportFailure recognized = recognize(cause, lastObservedStage); - if (recognized != null) { - return recognized; - } - } - return fallback(lastObservedStage); + return TransportFailureRules.classify( + failure, lastObservedStage, JdkFailureClassifier::recognize); } - private TransportFailure recognize(Throwable cause, AttemptStage lastObservedStage) { - if (cause instanceof HttpConnectTimeoutException - || cause instanceof ConnectException - || cause instanceof NoRouteToHostException) { + private static TransportFailure recognize(Throwable cause, AttemptStage lastObservedStage) { + // HttpConnectTimeoutException extends HttpTimeoutException, so the connect case comes first. + if (cause instanceof HttpConnectTimeoutException) { return TransportFailure.notSent( AttemptStage.CONNECT, FailureCategory.CONNECT, "CONNECT_FAILED"); } - if (cause instanceof UnknownHostException) { - return TransportFailure.notSent( - AttemptStage.DNS, FailureCategory.DNS, "DNS_RESOLUTION_FAILED"); - } - if (cause instanceof SSLPeerUnverifiedException || cause instanceof CertificateException) { - return TransportFailure.notSent( - AttemptStage.TLS_HANDSHAKE, FailureCategory.TLS_PERMANENT, "TLS_TRUST_FAILED"); - } - if (cause instanceof SSLHandshakeException) { - return TransportFailure.notSent( - AttemptStage.TLS_HANDSHAKE, FailureCategory.TLS_PERMANENT, "TLS_HANDSHAKE_FAILED"); - } - if (cause instanceof SSLException - && !lastObservedStage.isAtLeast(AttemptStage.REQUEST_HEADERS)) { - return TransportFailure.notSent( - AttemptStage.TLS_HANDSHAKE, FailureCategory.TLS_TRANSIENT, "TLS_TRANSIENT_FAILURE"); - } - // HttpTimeoutException is an IOException, never an InterruptedIOException, so only the socket - // timeout needs excluding here; the JDK client's own timeouts are classified below. - if (cause instanceof InterruptedIOException && !(cause instanceof SocketTimeoutException)) { - // Cancellation, not a timeout. Classifying it as a timeout let the retry engine reissue a - // request the caller had just cancelled, and dropped the interrupt so the thread could not - // see its own cancellation either. - Thread.currentThread().interrupt(); - if (lastObservedStage.provesNotSent()) { - return TransportFailure.notSent( - lastObservedStage, FailureCategory.CANCELLED, "ATTEMPT_INTERRUPTED"); - } - return TransportFailure.sentNoResponse( - lastObservedStage, FailureCategory.CANCELLED, "ATTEMPT_INTERRUPTED"); - } - if (cause instanceof HttpTimeoutException || cause instanceof SocketTimeoutException) { - if (lastObservedStage.isAtLeast(AttemptStage.RESPONSE_BODY)) { - return new TransportFailure( - lastObservedStage, - ExecutionEvidence.PARTIAL_RESPONSE, - FailureCategory.RESPONSE_TIMEOUT, - "RESPONSE_BODY_TIMEOUT"); - } - return TransportFailure.sentNoResponse( - AttemptStage.RESPONSE_HEADERS, - FailureCategory.RESPONSE_TIMEOUT, - "RESPONSE_HEADER_TIMEOUT"); + // An IOException, never an InterruptedIOException, so the shared cancellation rule would not + // see it; it is the client's request timeout and reads like a socket timeout. + if (cause instanceof HttpTimeoutException) { + return TransportFailureRules.timeout(lastObservedStage); } return null; } - - private TransportFailure fallback(AttemptStage lastObservedStage) { - if (lastObservedStage.provesNotSent()) { - return TransportFailure.notSent( - lastObservedStage, FailureCategory.UNKNOWN, "TRANSPORT_FAILURE"); - } - if (lastObservedStage.isAtLeast(AttemptStage.RESPONSE_BODY)) { - return new TransportFailure( - lastObservedStage, - ExecutionEvidence.PARTIAL_RESPONSE, - FailureCategory.RESPONSE_TRUNCATED, - "TRANSPORT_FAILURE"); - } - return TransportFailure.sentNoResponse( - lastObservedStage, FailureCategory.UNKNOWN, "TRANSPORT_FAILURE"); - } - - private java.util.List chain(Throwable failure) { - java.util.List chain = new java.util.ArrayList<>(); - Throwable current = failure; - while (current != null && !chain.contains(current)) { - chain.add(current); - current = current.getCause(); - } - return chain; - } } diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/transport/TransportFailureRules.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/transport/TransportFailureRules.java new file mode 100644 index 00000000..da27a0e9 --- /dev/null +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/transport/TransportFailureRules.java @@ -0,0 +1,184 @@ +package dev.caskeleton.adapter.outbound.httpclient.transport; + +import dev.caskeleton.adapter.outbound.httpclient.api.operation.AttemptStage; +import dev.caskeleton.adapter.outbound.httpclient.api.operation.ExecutionEvidence; +import dev.caskeleton.adapter.outbound.httpclient.api.operation.FailureCategory; +import java.io.InterruptedIOException; +import java.net.ConnectException; +import java.net.NoRouteToHostException; +import java.net.SocketTimeoutException; +import java.net.UnknownHostException; +import java.security.cert.CertificateException; +import java.util.ArrayList; +import java.util.List; +import javax.net.ssl.SSLException; +import javax.net.ssl.SSLHandshakeException; +import javax.net.ssl.SSLPeerUnverifiedException; + +/** + * The classification rules the Stable engines, Apache and JDK, share (design §13.3). + * + *

An engine classifier contributes only what is particular to its engine: the exception types it + * alone throws. The rest lives here once — walking the cause chain, the JDK socket and TLS + * exceptions both engines surface, and the rules that turn a stage into evidence. Each engine used + * to carry its own copy of all of it, and the copies drifted: a failure nobody recognised while the + * response body was arriving was {@code UNKNOWN} on Apache and {@code RESPONSE_TRUNCATED} on JDK, + * so the same connection reset was a permanent failure on one engine and a retryable one on the + * other. {@code TransportFailureClassifierContractTest} holds both engines to one table. The + * experimental HTTP/3 classifier does not use these rules yet. + */ +public final class TransportFailureRules { + + private TransportFailureRules() {} + + /** + * One engine's recognition of its own exception types. + * + *

Answers {@code null} for a cause that is not one of them, so the shared rules try it next. + */ + @FunctionalInterface + public interface EngineRecognizer { + + TransportFailure recognize(Throwable cause, AttemptStage lastObservedStage); + } + + /** + * Classifies {@code failure} by the first cause in its chain that the engine or the shared rules + * recognise, outermost first. When none is recognised, a thread whose interrupt flag is set makes + * it a cancellation; otherwise the stage alone decides. + * + *

The whole chain is read because Spring and the engines wrap their exceptions: a wrapped + * {@code ConnectException} still proves the request never left, and matching only the outer type + * would downgrade that to an ambiguous {@code SENT_NO_RESPONSE}. For each cause the engine's + * types are tried before the shared ones, so an engine exception that extends a JDK one is read + * as the engine meant it: Apache's pool timeout is an {@code InterruptedIOException} the shared + * rules would read as a cancellation, and its connect timeout a {@code SocketTimeoutException} + * they would read by the stage. + */ + public static TransportFailure classify( + Throwable failure, AttemptStage lastObservedStage, EngineRecognizer engine) { + for (Throwable cause : causeChain(failure)) { + TransportFailure recognized = engine.recognize(cause, lastObservedStage); + if (recognized == null) { + recognized = recognizeShared(cause, lastObservedStage); + } + if (recognized != null) { + return recognized; + } + } + if (Thread.currentThread().isInterrupted()) { + // Failures are classified on the thread that made the attempt, so a set flag means + // the attempt was cancelled, and a cancellation must not be retried. Interrupting a + // virtual thread blocked on a socket closes the socket: the read fails with + // SocketException("Closed by interrupt"), or ClosedByInterruptException on a channel, + // and the flag stays set. Neither is an InterruptedIOException, so read by the stage + // alone it was a truncated body, which the retry engine retries: cancelling a call + // sent it again. The flag is left as it is. + return conservative(lastObservedStage, FailureCategory.CANCELLED, "ATTEMPT_INTERRUPTED"); + } + return unrecognized(lastObservedStage); + } + + /** + * A timeout, read against the stage it happened in. + * + *

Before anything left it was the connect; while the body was arriving the response was partly + * received; anywhere between, the request may have been processed and no headers came back. + */ + public static TransportFailure timeout(AttemptStage lastObservedStage) { + if (lastObservedStage.provesNotSent()) { + return TransportFailure.notSent( + lastObservedStage, FailureCategory.CONNECT, "CONNECT_TIMEOUT"); + } + if (lastObservedStage.isAtLeast(AttemptStage.RESPONSE_BODY)) { + return new TransportFailure( + lastObservedStage, + ExecutionEvidence.PARTIAL_RESPONSE, + FailureCategory.RESPONSE_TIMEOUT, + "RESPONSE_BODY_TIMEOUT"); + } + return TransportFailure.sentNoResponse( + AttemptStage.RESPONSE_HEADERS, FailureCategory.RESPONSE_TIMEOUT, "RESPONSE_HEADER_TIMEOUT"); + } + + /** + * A failure whose evidence only the stage can give. + * + *

Deliberately asymmetric: {@code NOT_SENT} is only produced for a stage that proves nothing + * left the process. Once the request write has begun the failure stays {@code SENT_NO_RESPONSE}, + * because guessing "not sent" is what turns a timeout into a duplicate payment; once the body was + * arriving, the response was partly received. + */ + public static TransportFailure conservative( + AttemptStage lastObservedStage, FailureCategory category, String reason) { + if (lastObservedStage.provesNotSent()) { + return TransportFailure.notSent(lastObservedStage, category, reason); + } + if (lastObservedStage.isAtLeast(AttemptStage.RESPONSE_BODY)) { + return new TransportFailure( + lastObservedStage, ExecutionEvidence.PARTIAL_RESPONSE, category, reason); + } + return TransportFailure.sentNoResponse(lastObservedStage, category, reason); + } + + private static TransportFailure recognizeShared(Throwable cause, AttemptStage lastObservedStage) { + if (cause instanceof UnknownHostException) { + return TransportFailure.notSent( + AttemptStage.DNS, FailureCategory.DNS, "DNS_RESOLUTION_FAILED"); + } + if (cause instanceof ConnectException || cause instanceof NoRouteToHostException) { + return TransportFailure.notSent( + AttemptStage.CONNECT, FailureCategory.CONNECT, "CONNECT_FAILED"); + } + if (cause instanceof SSLPeerUnverifiedException || cause instanceof CertificateException) { + return TransportFailure.notSent( + AttemptStage.TLS_HANDSHAKE, FailureCategory.TLS_PERMANENT, "TLS_TRUST_FAILED"); + } + if (cause instanceof SSLHandshakeException) { + return TransportFailure.notSent( + AttemptStage.TLS_HANDSHAKE, FailureCategory.TLS_PERMANENT, "TLS_HANDSHAKE_FAILED"); + } + if (cause instanceof SSLException + && !lastObservedStage.isAtLeast(AttemptStage.REQUEST_HEADERS)) { + return TransportFailure.notSent( + AttemptStage.TLS_HANDSHAKE, FailureCategory.TLS_TRANSIENT, "TLS_TRANSIENT_FAILURE"); + } + if (cause instanceof SocketTimeoutException) { + return timeout(lastObservedStage); + } + if (cause instanceof InterruptedIOException) { + // Not a timeout. A SocketTimeoutException means the peer went quiet; a bare + // InterruptedIOException usually means this thread was interrupted — a cancellation, from a + // caller or a shutdown. Treating the two alike classified a cancellation as a transient + // timeout, which the retry engine then retried, so cancelling a call could produce more + // requests than not cancelling it. The interrupt flag is restored because swallowing it + // leaves the thread unable to observe its own cancellation. + Thread.currentThread().interrupt(); + return conservative(lastObservedStage, FailureCategory.CANCELLED, "ATTEMPT_INTERRUPTED"); + } + return null; + } + + private static TransportFailure unrecognized(AttemptStage lastObservedStage) { + // While the body was arriving, a failure nobody recognised is a response that stopped short — + // RESPONSE_TRUNCATED in the design's category table, and what Apache already reported for its + // own ConnectionClosedException. At any other stage, COMPLETE included, it proves nothing + // beyond + // what the stage proves: a read body did not stop short. + FailureCategory category = + lastObservedStage == AttemptStage.RESPONSE_BODY + ? FailureCategory.RESPONSE_TRUNCATED + : FailureCategory.UNKNOWN; + return conservative(lastObservedStage, category, "TRANSPORT_FAILURE"); + } + + private static List causeChain(Throwable failure) { + List chain = new ArrayList<>(); + Throwable current = failure; + while (current != null && !chain.contains(current)) { + chain.add(current); + current = current.getCause(); + } + return chain; + } +} diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/apache/ApachePoolSaturationTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/apache/ApachePoolSaturationTest.java index ccc2891a..7a9baf5b 100644 --- a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/apache/ApachePoolSaturationTest.java +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/apache/ApachePoolSaturationTest.java @@ -1,17 +1,19 @@ package dev.caskeleton.adapter.outbound.httpclient.apache; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.adapter.outbound.httpclient.api.operation.AttemptStage; import dev.caskeleton.adapter.outbound.httpclient.api.operation.ExecutionEvidence; +import dev.caskeleton.adapter.outbound.httpclient.api.operation.FailureCategory; import dev.caskeleton.adapter.outbound.httpclient.profile.ClientProfile; import dev.caskeleton.adapter.outbound.httpclient.profile.PoolSettings; +import dev.caskeleton.adapter.outbound.httpclient.profile.RuntimeGeneration; import dev.caskeleton.adapter.outbound.httpclient.testkit.ClientProfiles; import dev.caskeleton.adapter.outbound.httpclient.testkit.MockHttpServer; import dev.caskeleton.adapter.outbound.httpclient.testkit.NoopLifecycleListener; import dev.caskeleton.adapter.outbound.httpclient.transport.TransportFailure; import java.time.Duration; -import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; @@ -20,56 +22,77 @@ import org.springframework.web.client.RestClient; class ApachePoolSaturationTest { + /** + * The stage handed to the classifier is one at which the request may already have left. A pool + * stage would make {@code NOT_SENT} come out whether or not the classifier recognised the + * timeout, and an unrecognised one is classified as a cancellation: not retried, and the calling + * thread left interrupted. Only recognising the exception gives this answer. + */ @Test - void poolAcquireTimeoutIsClassifiedAsNotSent() throws Exception { + void aPoolWaitTimeoutIsAPoolAcquireTimeoutProvenNotSentEvenWhenTheWriteMayHaveBegun() + throws Exception { + // given + Throwable saturated = failureOfACallThatFindsThePoolFull(); + + // when + TransportFailure failure = + new ApacheFailureClassifier().classify(saturated, AttemptStage.REQUEST_HEADERS); + + // then + assertThat(failure) + .extracting( + TransportFailure::stage, + TransportFailure::evidence, + TransportFailure::category, + TransportFailure::safeReason) + .containsExactly( + AttemptStage.POOL_ACQUIRE, + ExecutionEvidence.NOT_SENT, + FailureCategory.POOL_ACQUIRE_TIMEOUT, + "POOL_ACQUIRE_TIMEOUT"); + } + + /** + * One pooled connection, held by a call whose response body is late, and a second call that waits + * for it longer than the pool allows. Everything is shut down before the failure is returned, so + * classifying it is the only thing left to observe. + */ + private static Throwable failureOfACallThatFindsThePoolFull() throws Exception { ApacheBlockingTransportProvider provider = new ApacheBlockingTransportProvider(); - ExecutorService executor = Executors.newFixedThreadPool(2); + RuntimeGeneration generation = new RuntimeGeneration(1); + ExecutorService executor = Executors.newSingleThreadExecutor(); + Throwable saturated; try (MockHttpServer server = MockHttpServer.start()) { server.enqueueDelayedBody(200, "{\"slow\":true}", Duration.ofSeconds(2)); server.enqueueJson(200, "{\"fast\":true}"); - ClientProfile profile = singleConnectionProfile(server.uri("/")); RestClient client = RestClient.builder() - .requestFactory( - provider.create( - profile, - new dev.caskeleton.adapter.outbound.httpclient.profile.RuntimeGeneration(1), - NoopLifecycleListener.INSTANCE)) + .requestFactory(provider.create(profile, generation, NoopLifecycleListener.INSTANCE)) .build(); - - CountDownLatch firstStarted = new CountDownLatch(1); executor.execute( () -> { - firstStarted.countDown(); try { client.get().uri(server.uri("/slow")).retrieve().body(String.class); } catch (RuntimeException ignored) { // The holding request is only needed to occupy the single pooled connection. } }); - assertThat(firstStarted.await(2, TimeUnit.SECONDS)).isTrue(); - Thread.sleep(200); + // The server has the slow request once its connection is leased, so the next call waits. + server.takeRequest(Duration.ofSeconds(2)); - Throwable captured = null; - try { - client.get().uri(server.uri("/fast")).retrieve().body(String.class); - } catch (RuntimeException saturated) { - captured = saturated; - } + saturated = + catchThrowable(() -> client.get().uri(server.uri("/fast")).retrieve().body(String.class)); - assertThat(captured).isNotNull(); - TransportFailure failure = - new ApacheFailureClassifier().classify(captured, AttemptStage.POOL_ACQUIRE); - assertThat(failure.stage()).isEqualTo(AttemptStage.POOL_ACQUIRE); - assertThat(failure.evidence()).isEqualTo(ExecutionEvidence.NOT_SENT); - - provider.close( - profile, new dev.caskeleton.adapter.outbound.httpclient.profile.RuntimeGeneration(1)); + provider.close(profile, generation); } finally { executor.shutdownNow(); assertThat(executor.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); } + if (saturated == null) { + throw new AssertionError("the second call was expected to time out waiting for the pool"); + } + return saturated; } private static ClientProfile singleConnectionProfile(java.net.URI baseUrl) { diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/contract/TransportFailureClassifierContractTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/contract/TransportFailureClassifierContractTest.java new file mode 100644 index 00000000..cbee59a6 --- /dev/null +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/contract/TransportFailureClassifierContractTest.java @@ -0,0 +1,228 @@ +package dev.caskeleton.adapter.outbound.httpclient.contract; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.params.provider.Arguments.argumentSet; + +import dev.caskeleton.adapter.outbound.httpclient.apache.ApacheFailureClassifier; +import dev.caskeleton.adapter.outbound.httpclient.api.operation.AttemptStage; +import dev.caskeleton.adapter.outbound.httpclient.api.operation.ExecutionEvidence; +import dev.caskeleton.adapter.outbound.httpclient.api.operation.FailureCategory; +import dev.caskeleton.adapter.outbound.httpclient.jdk.JdkFailureClassifier; +import dev.caskeleton.adapter.outbound.httpclient.testkit.HttpClientContract; +import dev.caskeleton.adapter.outbound.httpclient.transport.TransportFailure; +import dev.caskeleton.adapter.outbound.httpclient.transport.TransportFailureClassifier; +import java.io.InterruptedIOException; +import java.net.ConnectException; +import java.net.SocketException; +import java.net.SocketTimeoutException; +import java.net.UnknownHostException; +import java.util.List; +import java.util.stream.Stream; +import javax.net.ssl.SSLException; +import javax.net.ssl.SSLHandshakeException; +import javax.net.ssl.SSLPeerUnverifiedException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.Parameter; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.springframework.web.client.ResourceAccessException; + +/** + * One classification table every selected Stable engine answers alike (design §13.3). + * + *

The table covers what the engines share: the cause chain, the JDK socket and TLS exceptions + * every engine surfaces, and the rules that turn a stage into evidence. An engine's own exception + * types are not in it. The engines used to keep a copy of these rules each, and the copies drifted + * with no test seeing it: a connection reset while the body was arriving was {@code UNKNOWN}, a + * permanent failure, on Apache and a retryable {@code RESPONSE_TRUNCATED} on JDK. A unit test per + * engine would only have pinned the two answers apart; one table for both pins them together. + * + *

Selection follows the transport contract lane ({@link HttpClientContract}). The scripted fake + * is not held to this table: its classifier answers a script rather than a stage, and the fake is + * held to the transport contract instead ({@code ScriptedTransportContractTest}). + */ +@Tag("httpclient-contract") +@ParameterizedClass +@MethodSource("transports") +class TransportFailureClassifierContractTest { + + private static final String RESET = "Connection reset"; + + @Parameter String transport; + + static List transports() { + return HttpClientContract.selectedTransports(); + } + + static Stream sharedClassifications() { + return Stream.of( + argumentSet( + "본문을 받다 연결이 reset되면 덜 온 응답이다", + new SocketException(RESET), + AttemptStage.RESPONSE_BODY, + new TransportFailure( + AttemptStage.RESPONSE_BODY, + ExecutionEvidence.PARTIAL_RESPONSE, + FailureCategory.RESPONSE_TRUNCATED, + "TRANSPORT_FAILURE")), + argumentSet( + "쓰기를 시작한 뒤 reset은 보냈을 수 있는 모르는 실패다", + new SocketException(RESET), + AttemptStage.REQUEST_BODY, + TransportFailure.sentNoResponse( + AttemptStage.REQUEST_BODY, FailureCategory.UNKNOWN, "TRANSPORT_FAILURE")), + argumentSet( + "본문을 다 읽은 뒤 모르는 실패는 덜 온 응답이 아니다", + new SocketException(RESET), + AttemptStage.COMPLETE, + new TransportFailure( + AttemptStage.COMPLETE, + ExecutionEvidence.PARTIAL_RESPONSE, + FailureCategory.UNKNOWN, + "TRANSPORT_FAILURE")), + argumentSet( + "아무것도 나가기 전 모르는 실패는 안 보냄이다", + new SocketException(RESET), + AttemptStage.CONNECT, + TransportFailure.notSent( + AttemptStage.CONNECT, FailureCategory.UNKNOWN, "TRANSPORT_FAILURE")), + argumentSet( + "감싼 연결 거부는 stage가 쓰기 뒤여도 안 보냄이다", + new ResourceAccessException("I/O error", new ConnectException("Connection refused")), + AttemptStage.REQUEST_BODY, + TransportFailure.notSent( + AttemptStage.CONNECT, FailureCategory.CONNECT, "CONNECT_FAILED")), + argumentSet( + "이름 풀이 실패는 DNS 단계의 안 보냄이다", + new UnknownHostException("users.internal"), + AttemptStage.POOL_ACQUIRE, + TransportFailure.notSent( + AttemptStage.DNS, FailureCategory.DNS, "DNS_RESOLUTION_FAILED")), + argumentSet( + "인증서를 믿지 못하면 영구 TLS 실패다", + new SSLPeerUnverifiedException("peer not authenticated"), + AttemptStage.TLS_HANDSHAKE, + TransportFailure.notSent( + AttemptStage.TLS_HANDSHAKE, FailureCategory.TLS_PERMANENT, "TLS_TRUST_FAILED")), + argumentSet( + "handshake 거절은 영구 TLS 실패다", + new SSLHandshakeException("handshake failure"), + AttemptStage.TLS_HANDSHAKE, + TransportFailure.notSent( + AttemptStage.TLS_HANDSHAKE, FailureCategory.TLS_PERMANENT, "TLS_HANDSHAKE_FAILED")), + argumentSet( + "header 전 TLS 오류는 일시 TLS 실패다", + new SSLException("record overflow"), + AttemptStage.CONNECT, + TransportFailure.notSent( + AttemptStage.TLS_HANDSHAKE, + FailureCategory.TLS_TRANSIENT, + "TLS_TRANSIENT_FAILURE")), + argumentSet( + "쓰기를 시작한 뒤 TLS 오류는 모르는 실패다", + new SSLException("record overflow"), + AttemptStage.REQUEST_BODY, + TransportFailure.sentNoResponse( + AttemptStage.REQUEST_BODY, FailureCategory.UNKNOWN, "TRANSPORT_FAILURE")), + argumentSet( + "나가기 전 socket timeout은 connect timeout이다", + new SocketTimeoutException("connect timed out"), + AttemptStage.CONNECT, + TransportFailure.notSent( + AttemptStage.CONNECT, FailureCategory.CONNECT, "CONNECT_TIMEOUT")), + argumentSet( + "쓰기 뒤 socket timeout은 header 대기 timeout이다", + new SocketTimeoutException("read timed out"), + AttemptStage.REQUEST_BODY, + TransportFailure.sentNoResponse( + AttemptStage.RESPONSE_HEADERS, + FailureCategory.RESPONSE_TIMEOUT, + "RESPONSE_HEADER_TIMEOUT")), + argumentSet( + "본문 중 socket timeout은 본문 timeout이다", + new SocketTimeoutException("read timed out"), + AttemptStage.RESPONSE_BODY, + new TransportFailure( + AttemptStage.RESPONSE_BODY, + ExecutionEvidence.PARTIAL_RESPONSE, + FailureCategory.RESPONSE_TIMEOUT, + "RESPONSE_BODY_TIMEOUT")), + argumentSet( + "쓰기 뒤 interrupt는 보냈을 수 있는 취소다", + new InterruptedIOException("interrupted"), + AttemptStage.REQUEST_BODY, + TransportFailure.sentNoResponse( + AttemptStage.REQUEST_BODY, FailureCategory.CANCELLED, "ATTEMPT_INTERRUPTED")), + argumentSet( + "본문 중 interrupt는 덜 받은 응답의 취소다", + new InterruptedIOException("interrupted"), + AttemptStage.RESPONSE_BODY, + new TransportFailure( + AttemptStage.RESPONSE_BODY, + ExecutionEvidence.PARTIAL_RESPONSE, + FailureCategory.CANCELLED, + "ATTEMPT_INTERRUPTED"))); + } + + @AfterEach + void clearTheInterruptFlag() { + Thread.interrupted(); + } + + @ParameterizedTest + @MethodSource("sharedClassifications") + void everyEngineClassifiesASharedFailureAlike( + Throwable failure, AttemptStage lastObservedStage, TransportFailure expected) { + // when + TransportFailure classified = classifier().classify(failure, lastObservedStage); + + // then + assertThat(classified).isEqualTo(expected); + } + + @Test + void aCancelledAttemptLeavesTheThreadInterrupted() { + // given + // An interrupt leaked from earlier work would make the flag below true without this call. + Thread.interrupted(); + + // when + classifier().classify(new InterruptedIOException("interrupted"), AttemptStage.REQUEST_BODY); + + // then + assertThat(Thread.currentThread().isInterrupted()).isTrue(); + } + + /** + * What a virtual thread sees when it is interrupted in a socket read: the JDK closes the socket, + * throws a plain {@code SocketException}, and leaves the flag set. Read by the stage alone that + * was a truncated body, which the retry engine retries. + */ + @Test + void anUnrecognisedFailureOnAnInterruptedThreadIsACancellation() { + // given + Thread.currentThread().interrupt(); + + // when + TransportFailure classified = + classifier() + .classify(new SocketException("Closed by interrupt"), AttemptStage.RESPONSE_BODY); + + // then + assertThat(classified) + .isEqualTo( + new TransportFailure( + AttemptStage.RESPONSE_BODY, + ExecutionEvidence.PARTIAL_RESPONSE, + FailureCategory.CANCELLED, + "ATTEMPT_INTERRUPTED")); + } + + private TransportFailureClassifier classifier() { + return "jdk".equals(transport) ? new JdkFailureClassifier() : new ApacheFailureClassifier(); + } +}