Skip to content

Commit 7092af8

Browse files
committed
feat: retry WHIP/WHEP offers after Retry-After
A 503 answer, and for WHEP a 409 one, with Retry-After sends the offer again after that wait, at least a second, as long as it fits within the session's timeout. Cancelling the session ends the wait.
1 parent 625bcba commit 7092af8

8 files changed

Lines changed: 318 additions & 10 deletions

File tree

‎docs/guide/client-api.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -598,7 +598,7 @@ Whep.Session viewer = Whep.from(URI.create("https://example.com/live/whep"))
598598
viewer.peer().onTrack(track -> System.out.println("Receiving " + track.kind()));
599599
```
600600

601-
The offer goes to the endpoint with the local candidates, as WHIP and WHEP servers expect, and the future completes once the peer is connected. If the endpoint refuses the offer, or the peer does not connect within the timeout (15 seconds by default), the future fails, and the session is deleted on the server again. Cancelling the future, say once `get` gave up waiting, ends the session the same way. `onTrack` hands over tracks that already arrived, so a handler added once the future completed misses none.
601+
The offer goes to the endpoint with the local candidates, as WHIP and WHEP servers expect, and the future completes once the peer is connected. If the endpoint refuses the offer, or the peer does not connect within the timeout (15 seconds by default), the future fails, and the session is deleted on the server again. An endpoint that is busy, with status 503, or a WHEP endpoint whose stream has yet to start, with status 409, gets the offer again after the wait its `Retry-After` names, at least a second, as long as that fits within the timeout; without `Retry-After` the session fails at once. Cancelling the future, say once `get` gave up waiting, ends the session the same way. `onTrack` hands over tracks that already arrived, so a handler added once the future completed misses none.
602602

603603
The timeout bounds the requests as a whole, not each read, so a server that sends its answer a byte at a time cannot stretch it. A request still out when the session times out or is cancelled is cut off at once; one still waiting for the head of its answer only from Java 16 on, and before that at its timeout. Once the server has named the session, in the head of its answer, it is deleted all the same; a session the server created for an answer that had not come yet is left for the server to time out.
604604

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

Lines changed: 121 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,13 +31,21 @@
3131
import java.nio.ByteBuffer;
3232
import java.nio.charset.StandardCharsets;
3333
import java.time.Duration;
34+
import java.time.ZonedDateTime;
35+
import java.time.format.DateTimeFormatter;
36+
import java.time.format.DateTimeParseException;
3437
import java.util.Collections;
3538
import java.util.List;
3639
import java.util.Map;
40+
import java.util.Set;
3741
import java.util.concurrent.CompletableFuture;
3842
import java.util.concurrent.CompletionException;
3943
import java.util.concurrent.CompletionStage;
4044
import java.util.concurrent.Flow;
45+
import java.util.concurrent.Future;
46+
import java.util.concurrent.RejectedExecutionException;
47+
import java.util.concurrent.ScheduledExecutorService;
48+
import java.util.concurrent.TimeUnit;
4149
import java.util.function.Consumer;
4250

4351
import javax.net.ssl.SSLContext;
@@ -54,7 +62,8 @@
5462
* such a request ends with its timeout.
5563
* <p>
5664
* Redirects are followed only when asked for, and only those with status 307
57-
* and 308, which keep the method and body.
65+
* and 308, which keep the method and body. Likewise, a request is only sent
66+
* again when asked for, after the wait a server names in Retry-After.
5867
*/
5968
final class HttpCall {
6069

@@ -64,6 +73,12 @@ final class HttpCall {
6473
/** How much of an error response is read, for a message. */
6574
static final int MAX_ERROR_BODY = 1024;
6675

76+
/**
77+
* The shortest wait before a request is sent again, so that a server that
78+
* says to come back at once is not asked many times a second.
79+
*/
80+
static final long MIN_RETRY_MILLIS = 1000;
81+
6782
private final HttpClient client;
6883

6984
private final String method;
@@ -84,9 +99,16 @@ final class HttpCall {
8499

85100
private boolean followRedirects;
86101

102+
private ScheduledExecutorService retryTimer;
103+
104+
private Set<Integer> retryStatuses = Collections.emptySet();
105+
87106
/** The exchange under way, which an abort cancels. */
88107
private CompletableFuture<?> exchange;
89108

109+
/** The wait before the request is sent again, which an abort ends. */
110+
private Future<?> retry;
111+
90112
/** The body being read, which an abort ends. */
91113
private Body body;
92114

@@ -144,6 +166,24 @@ static HttpClient newClient(boolean authenticates) {
144166
return builder.build();
145167
}
146168

169+
/**
170+
* Sends the request again when the server answers with one of the given
171+
* statuses and a Retry-After header field, after the time it names, at
172+
* least {@link #MIN_RETRY_MILLIS}, and as often as that fits within the
173+
* timeout. Without the field, or once the wait would not fit, the answer
174+
* is the response.
175+
*
176+
* @param timer the timer the waits are on.
177+
* @param statuses the statuses to send the request again for.
178+
*
179+
* @return this request.
180+
*/
181+
HttpCall retry(ScheduledExecutorService timer, Set<Integer> statuses) {
182+
this.retryTimer = timer;
183+
this.retryStatuses = statuses;
184+
return this;
185+
}
186+
147187
/**
148188
* Follows redirects with status 307 and 308, up to {@link #MAX_REDIRECTS}
149189
* of them, with the bearer token. One from https to plain http fails.
@@ -187,6 +227,7 @@ void abort() {
187227
: new IOException("The request to " + uri + " was aborted");
188228
CompletableFuture<?> exchange;
189229
Body body;
230+
Future<?> retry;
190231

191232
synchronized (this) {
192233
if (aborted) {
@@ -196,10 +237,14 @@ void abort() {
196237
aborted = true;
197238
exchange = this.exchange;
198239
body = this.body;
240+
retry = this.retry;
199241
}
200242

201243
result.completeExceptionally(reason);
202244

245+
if (retry != null) {
246+
retry.cancel(false);
247+
}
203248
if (body != null) {
204249
body.stop(reason);
205250
}
@@ -263,7 +308,15 @@ private void exchange(URI target, String contentType, byte[] content, int maxBod
263308
String location = value.headers().firstValue("Location").orElse(null);
264309

265310
if (!isRedirect(value.statusCode(), location)) {
266-
result.complete(new Response(target, value.statusCode(), value.headers(), value.body()));
311+
long wait = retryStatuses.contains(value.statusCode())
312+
? retryDelayMillis(value.headers().firstValue("Retry-After").orElse(null),
313+
System.currentTimeMillis())
314+
: -1;
315+
316+
if (wait < 0 || !retryLater(Math.max(wait, MIN_RETRY_MILLIS),
317+
() -> exchange(target, contentType, content, maxBody, onHead, redirects))) {
318+
result.complete(new Response(target, value.statusCode(), value.headers(), value.body()));
319+
}
267320
return;
268321
}
269322
if (redirects == MAX_REDIRECTS) {
@@ -316,6 +369,72 @@ private HttpResponse.BodySubscriber<String> head(HttpResponse.ResponseInfo info,
316369
return body;
317370
}
318371

372+
/**
373+
* Sends the request again after the wait, if that leaves time for it.
374+
*
375+
* @return false if the request is not sent again.
376+
*/
377+
private boolean retryLater(long waitMillis, Runnable send) {
378+
if (TimeUnit.MILLISECONDS.toNanos(waitMillis) >= remainingNanos()) {
379+
return false;
380+
}
381+
382+
synchronized (this) {
383+
if (aborted) {
384+
// Failed already.
385+
return true;
386+
}
387+
388+
try {
389+
retry = retryTimer.schedule(send, waitMillis, TimeUnit.MILLISECONDS);
390+
}
391+
catch (RejectedExecutionException e) {
392+
// The runtime is closing.
393+
return false;
394+
}
395+
396+
exchange = null;
397+
body = null;
398+
}
399+
400+
return true;
401+
}
402+
403+
/**
404+
* Reads a Retry-After header field, in seconds or as an HTTP date.
405+
*
406+
* @param value the field, or null.
407+
* @param nowMillis the time, as {@link System#currentTimeMillis()}.
408+
*
409+
* @return how long to wait in milliseconds, or -1 if the field says
410+
* nothing that can be read.
411+
*/
412+
static long retryDelayMillis(String value, long nowMillis) {
413+
if (value == null) {
414+
return -1;
415+
}
416+
417+
String field = value.trim();
418+
419+
if (!field.isEmpty() && field.chars().allMatch(Character::isDigit)) {
420+
try {
421+
return Math.multiplyExact(Long.parseLong(field), 1000);
422+
}
423+
catch (NumberFormatException | ArithmeticException e) {
424+
return Long.MAX_VALUE;
425+
}
426+
}
427+
428+
try {
429+
long date = ZonedDateTime.parse(field, DateTimeFormatter.RFC_1123_DATE_TIME).toInstant().toEpochMilli();
430+
431+
return Math.max(0, date - nowMillis);
432+
}
433+
catch (DateTimeParseException e) {
434+
return -1;
435+
}
436+
}
437+
319438
private boolean isRedirect(int status, String location) {
320439
return followRedirects && (status == 307 || status == 308) && location != null;
321440
}

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

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
import java.net.URI;
2222
import java.nio.charset.StandardCharsets;
2323
import java.time.Duration;
24+
import java.util.Set;
2425
import java.util.concurrent.CancellationException;
2526
import java.util.concurrent.CompletableFuture;
2627
import java.util.concurrent.RejectedExecutionException;
@@ -133,15 +134,18 @@ public void close() {
133134
* a server that does not answer holds no thread; what it creates for an
134135
* offer it had yet to answer is left for it to time out.
135136
*
137+
* @param retried the statuses of an answer to the offer, together with a
138+
* Retry-After header field, after which the offer is sent
139+
* again, as long as the wait fits within the timeout.
136140
* @param factory makes the session of the connected peer.
137141
*
138142
* @return the future handed to the application.
139143
*/
140144
static <S extends HttpSession> CompletableFuture<S> start(WebRtc rtc, PeerImpl peer, URI endpoint,
141-
String bearerToken, Duration timeout, Factory<S> factory) {
145+
String bearerToken, Duration timeout, Set<Integer> retried, Factory<S> factory) {
142146
CompletableFuture<Void> abandoned = new CompletableFuture<>();
143-
CompletableFuture<S> session = peer.toPublic(negotiate(rtc, peer, endpoint, bearerToken, timeout, abandoned)
144-
.thenApply(resource -> factory.create(rtc, peer, resource, bearerToken, timeout)),
147+
CompletableFuture<S> session = peer.toPublic(negotiate(rtc, peer, endpoint, bearerToken, timeout, retried,
148+
abandoned).thenApply(resource -> factory.create(rtc, peer, resource, bearerToken, timeout)),
145149
HttpSession::close);
146150

147151
// Once the session was handed out, this finds the negotiation finished.
@@ -160,7 +164,7 @@ static <S extends HttpSession> CompletableFuture<S> start(WebRtc rtc, PeerImpl p
160164
* @return a future with the resource the server named, or null.
161165
*/
162166
private static CompletableFuture<URI> negotiate(WebRtc rtc, Peer peer, URI endpoint, String bearerToken,
163-
Duration timeout, CompletableFuture<?> abandoned) {
167+
Duration timeout, Set<Integer> retried, CompletableFuture<?> abandoned) {
164168
CompletableFuture<URI> result = new CompletableFuture<>();
165169
// The resource the server created. Whoever takes it out owns it: the
166170
// session that connected, or whoever deletes it.
@@ -169,7 +173,7 @@ private static CompletableFuture<URI> negotiate(WebRtc rtc, Peer peer, URI endpo
169173
// Made now, so that it ends with the session's deadline at the latest,
170174
// however long the offer takes.
171175
HttpCall offerRequest = new HttpCall(rtc.httpClient(bearerToken != null), endpoint, "POST", bearerToken,
172-
timeout).followRedirects();
176+
timeout).followRedirects().retry(rtc.timer, retried);
173177

174178
// Either way the session ends, once: connected, failed or timed out.
175179
Consumer<Throwable> fail = error -> {

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

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,14 @@
4949
*/
5050
public final class Whep {
5151

52+
/**
53+
* An endpoint under load answers 503, and one whose stream has yet to
54+
* start 409, both with Retry-After (draft-ietf-wish-whep-05, 4.7 and
55+
* 4.3.9).
56+
*/
57+
private static final Set<Integer> RETRIED = Set.of(409, 503);
58+
59+
5260
private Whep() {
5361
}
5462

@@ -172,7 +180,7 @@ public CompletableFuture<Session> play(WebRtc rtc) {
172180
PeerImpl peer = (PeerImpl) rtc.createPeer(options.build());
173181

174182
try {
175-
return HttpSession.start(rtc, peer, endpoint, token, limit, Session::new);
183+
return HttpSession.start(rtc, peer, endpoint, token, limit, RETRIED, Session::new);
176184
}
177185
catch (RuntimeException | Error e) {
178186
// Until the session has it, no one else would close the peer.

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

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
import java.time.Duration;
2323
import java.util.ArrayList;
2424
import java.util.List;
25+
import java.util.Set;
2526
import java.util.concurrent.CompletableFuture;
2627

2728
import dev.onvoid.webrtc.internal.Timeouts;
@@ -47,6 +48,10 @@
4748
*/
4849
public final class Whip {
4950

51+
/** An endpoint under load answers 503, with Retry-After (RFC 9725, 4.5). */
52+
private static final Set<Integer> RETRIED = Set.of(503);
53+
54+
5055
private Whip() {
5156
}
5257

@@ -181,7 +186,7 @@ public CompletableFuture<Session> publish(WebRtc rtc) {
181186
peer.addTrack(track);
182187
}
183188

184-
return HttpSession.start(rtc, peer, endpoint, token, limit, Session::new);
189+
return HttpSession.start(rtc, peer, endpoint, token, limit, RETRIED, Session::new);
185190
}
186191
catch (RuntimeException | Error e) {
187192
// Until the session has it, no one else would close the peer.

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

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,9 @@
3232
import java.net.http.HttpClient;
3333
import java.nio.charset.StandardCharsets;
3434
import java.time.Duration;
35+
import java.time.Instant;
36+
import java.time.ZoneOffset;
37+
import java.time.format.DateTimeFormatter;
3538
import java.util.Arrays;
3639
import java.util.Base64;
3740
import java.util.Collections;
@@ -218,6 +221,24 @@ void tunnelRefusesBasicByDefault() throws Exception {
218221
}
219222
}
220223

224+
@Test
225+
void retryAfterRead() {
226+
long now = 1_000_000_000_000L;
227+
String inFive = DateTimeFormatter.RFC_1123_DATE_TIME.format(
228+
Instant.ofEpochMilli(now + 5000).atZone(ZoneOffset.UTC));
229+
String past = DateTimeFormatter.RFC_1123_DATE_TIME.format(
230+
Instant.ofEpochMilli(now - 5000).atZone(ZoneOffset.UTC));
231+
232+
assertEquals(3000, HttpCall.retryDelayMillis("3", now));
233+
assertEquals(0, HttpCall.retryDelayMillis(" 0 ", now));
234+
assertEquals(5000, HttpCall.retryDelayMillis(inFive, now));
235+
assertEquals(0, HttpCall.retryDelayMillis(past, now));
236+
assertEquals(Long.MAX_VALUE, HttpCall.retryDelayMillis("99999999999999999999", now));
237+
assertEquals(-1, HttpCall.retryDelayMillis("soon", now));
238+
assertEquals(-1, HttpCall.retryDelayMillis("", now));
239+
assertEquals(-1, HttpCall.retryDelayMillis(null, now));
240+
}
241+
221242
private static HttpCall post(HttpClient client, URI uri) {
222243
return new HttpCall(client, uri, "POST", null, TIMEOUT);
223244
}

0 commit comments

Comments
 (0)