Skip to content

Commit 9c8fbef

Browse files
committed
fix: bound HTTP response reads and handle overflowing retry dates
1 parent 2945560 commit 9c8fbef

2 files changed

Lines changed: 75 additions & 5 deletions

File tree

‎webrtc/src/main/java/dev/onvoid/webrtc/client/HttpCall.java‎

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -32,10 +32,10 @@
3232
import java.net.http.HttpTimeoutException;
3333
import java.nio.ByteBuffer;
3434
import java.nio.charset.StandardCharsets;
35+
import java.time.DateTimeException;
3536
import java.time.Duration;
3637
import java.time.ZonedDateTime;
3738
import java.time.format.DateTimeFormatter;
38-
import java.time.format.DateTimeParseException;
3939
import java.util.ArrayList;
4040
import java.util.Collections;
4141
import java.util.LinkedHashMap;
@@ -60,7 +60,7 @@
6060
* The request takes no thread while it waits. Its timeout counts from the
6161
* moment it is made and bounds it as a whole, redirects included: the head of
6262
* the response by the client's own request timeout, set to what is left, and
63-
* the body read by read, so that one that trickles in ends with it as well.
63+
* an independent deadline through the body, including when no more data arrives.
6464
* {@link #abort()} ends it from any thread: a body being read at once, and on
6565
* Java 16 and later a request still waiting for its head too; before that,
6666
* such a request ends with its timeout.
@@ -248,7 +248,23 @@ HttpCall followRedirects() {
248248
* passed.
249249
*/
250250
CompletableFuture<Response> send(String contentType, byte[] content, int maxBody, Consumer<Response> onHead) {
251-
exchange(uri, contentType, content, maxBody, onHead, 0);
251+
// The client's timeout ends at the response head. Keep a deadline
252+
// through the body and retries, even when the server goes silent.
253+
// Completing this guard removes its timeout from the JDK's timer.
254+
CompletableFuture<Void> deadline = new CompletableFuture<>();
255+
deadline.orTimeout(Math.max(0, remainingNanos()), TimeUnit.NANOSECONDS)
256+
.exceptionally(error -> {
257+
abort();
258+
return null;
259+
});
260+
result.whenComplete((response, error) -> deadline.complete(null));
261+
262+
try {
263+
exchange(uri, contentType, content, maxBody, onHead, 0);
264+
}
265+
catch (RuntimeException e) {
266+
result.completeExceptionally(e);
267+
}
252268

253269
return result;
254270
}
@@ -369,6 +385,11 @@ private void exchange(URI target, String contentType, byte[] content, int maxBod
369385
catch (IOException e) {
370386
result.completeExceptionally(e);
371387
}
388+
}).exceptionally(error -> {
389+
// A failure while processing a response must reach the caller,
390+
// rather than only the discarded completion stage.
391+
result.completeExceptionally(unwrap(error));
392+
return null;
372393
});
373394
}
374395

@@ -466,9 +487,9 @@ static long retryDelayMillis(String value, long nowMillis) {
466487
try {
467488
long date = ZonedDateTime.parse(field, DateTimeFormatter.RFC_1123_DATE_TIME).toInstant().toEpochMilli();
468489

469-
return Math.max(0, date - nowMillis);
490+
return Math.max(0, Math.subtractExact(date, nowMillis));
470491
}
471-
catch (DateTimeParseException e) {
492+
catch (DateTimeException | ArithmeticException e) {
472493
return -1;
473494
}
474495
}

‎webrtc/src/test/java/dev/onvoid/webrtc/client/HttpCallTests.java‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
import java.net.URI;
3232
import java.net.http.HttpClient;
3333
import java.net.http.HttpHeaders;
34+
import java.net.http.HttpTimeoutException;
3435
import java.nio.charset.StandardCharsets;
3536
import java.time.Duration;
3637
import java.time.Instant;
@@ -41,10 +42,13 @@
4142
import java.util.Collections;
4243
import java.util.List;
4344
import java.util.Map;
45+
import java.util.Set;
4446
import java.util.concurrent.CompletableFuture;
4547
import java.util.concurrent.CopyOnWriteArrayList;
4648
import java.util.concurrent.CountDownLatch;
4749
import java.util.concurrent.ExecutionException;
50+
import java.util.concurrent.Executors;
51+
import java.util.concurrent.ScheduledExecutorService;
4852
import java.util.concurrent.TimeUnit;
4953

5054
import javax.net.ssl.SSLHandshakeException;
@@ -131,6 +135,27 @@ void oversizedAnswerRefused() throws Exception {
131135
}
132136
}
133137

138+
@Test
139+
void deadlineEndsSilentBody() throws Exception {
140+
try (TestHttpEndpoint endpoint = new TestHttpEndpoint(offer -> "v=0 and the rest", 201)) {
141+
endpoint.stallBodies();
142+
CountDownLatch head = new CountDownLatch(1);
143+
HttpCall call = new HttpCall(HttpCall.newClient(false), endpoint.uri(), "POST", null,
144+
Duration.ofSeconds(2));
145+
CompletableFuture<HttpCall.Response> response = call.send("application/sdp", new byte[] { 'o' },
146+
1024, received -> head.countDown());
147+
try {
148+
assertTrue(head.await(TIMEOUT_SECONDS, TimeUnit.SECONDS));
149+
ExecutionException failed = assertThrows(ExecutionException.class, () -> await(response));
150+
assertInstanceOf(HttpTimeoutException.class, failed.getCause());
151+
endpoint.awaitHangUp(TIMEOUT_SECONDS);
152+
}
153+
finally {
154+
call.abort();
155+
}
156+
}
157+
}
158+
134159
@Test
135160
void abortEndsRead() throws Exception {
136161
// The server sends the head and half the answer, then waits. An abort
@@ -276,6 +301,29 @@ void tunnelRefusesBasicByDefault() throws Exception {
276301
}
277302
}
278303

304+
@Test
305+
void overflowingRetryDateReturnsResponse() throws Exception {
306+
ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor();
307+
try (TestHttpEndpoint endpoint = new TestHttpEndpoint(offer -> "come back later", 201)) {
308+
endpoint.answerStatus = 503;
309+
endpoint.answerHeaders = "Retry-After: 31 Dec 999999999 23:59:59 GMT\r\n";
310+
HttpCall call = post(HttpCall.newClient(false), endpoint.uri()).retry(timer, Set.of(503));
311+
try {
312+
HttpCall.Response response = await(call.send("application/sdp", new byte[] { 'o' }, 1024,
313+
head -> { }));
314+
assertEquals(503, response.status);
315+
assertEquals("come back later", response.body);
316+
assertEquals(1, endpoint.requests.size());
317+
}
318+
finally {
319+
call.abort();
320+
}
321+
}
322+
finally {
323+
timer.shutdownNow();
324+
}
325+
}
326+
279327
@Test
280328
void retryAfterRead() {
281329
long now = 1_000_000_000_000L;
@@ -289,6 +337,7 @@ void retryAfterRead() {
289337
assertEquals(5000, HttpCall.retryDelayMillis(inFive, now));
290338
assertEquals(0, HttpCall.retryDelayMillis(past, now));
291339
assertEquals(Long.MAX_VALUE, HttpCall.retryDelayMillis("99999999999999999999", now));
340+
assertEquals(-1, HttpCall.retryDelayMillis("31 Dec 999999999 23:59:59 GMT", now));
292341
assertEquals(-1, HttpCall.retryDelayMillis("soon", now));
293342
assertEquals(-1, HttpCall.retryDelayMillis("", now));
294343
assertEquals(-1, HttpCall.retryDelayMillis(null, now));

0 commit comments

Comments
 (0)