Skip to content

Commit 0e9bb26

Browse files
committed
feat: add configurable ICE recovery for client peers and HTTP sessions
1 parent 7ba398d commit 0e9bb26

15 files changed

Lines changed: 1034 additions & 10 deletions

File tree

‎docs/guide/client-api.md‎

Lines changed: 72 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -201,7 +201,7 @@ When two impolite peers collide, neither gives way. An impolite peer that waited
201201
| `CONNECTING` | ICE and DTLS are establishing the connection. |
202202
| `CONNECTED` | Media and data can flow. |
203203
| `DISCONNECTED` | Connectivity was lost. It may come back by itself. |
204-
| `FAILED` | The connection failed. `peer.restartIce()` tries to recover it. |
204+
| `FAILED` | The connection failed. `peer.restartIce()` or the configured recovery policy tries to recover it. |
205205
| `CLOSED` | The peer was closed. This state is final. |
206206

207207
```java
@@ -213,6 +213,77 @@ peer.whenClosed().thenRun(() -> System.out.println("Closed"));
213213

214214
`onStateChange` calls a new handler with the current state first, so a handler added late still learns where the peer stands. `whenConnected()` fails if the connection fails or closes first.
215215

216+
### Automatic ICE Recovery
217+
218+
Automatic peers can opt into a `RecoveryPolicy`. Without one, the application still
219+
calls `peer.restartIce()` itself. The policy waits through short disconnections,
220+
restarts ICE on the same peer, and bounds retries with exponential backoff:
221+
222+
```java
223+
RecoveryPolicy recovery = RecoveryPolicy.builder()
224+
.grace(Duration.ofSeconds(2))
225+
.maxAttempts(3)
226+
.backoff(Duration.ofSeconds(1), Duration.ofSeconds(30))
227+
.attemptTimeout(Duration.ofSeconds(15))
228+
.onEvent(event -> System.out.println(event.state() + " attempt " + event.attempt()))
229+
.build();
230+
231+
Peer peer = rtc.createPeer(PeerOptions.builder()
232+
.signaling(signaling)
233+
.recovery(recovery)
234+
.build());
235+
```
236+
237+
`DISCONNECTED` starts the grace period; `FAILED` skips it. Repeated failure
238+
notifications during an attempt do not start parallel restarts. Events are
239+
`WAITING`, `ATTEMPTING`, `RETRYING`, `RECOVERED` and `EXHAUSTED`, delivered on the
240+
peer's event executor. `attempt()` counts attempts in the current outage, starting
241+
at one; a recovery during the grace period reports zero. `cause()` gives the last
242+
failure on retry or exhaustion. Successful signaling alone does not count as
243+
recovery: the peer must report `CONNECTED`. That resets the budget, including
244+
after exhaustion. Exhaustion leaves the peer open and creates no further automatic
245+
attempts until it connects again. `whenConnected()` keeps its existing first-connection
246+
semantics; observe `RECOVERED` for later recovery.
247+
248+
Before an attempt, `iceServers(attempt -> completionStage)` can obtain fresh TURN
249+
credentials asynchronously. It runs on the event executor and must return promptly;
250+
the resulting list replaces **all** ICE servers, so include STUN servers that should
251+
remain available. The library copies the supplied servers; failed, null or invalid
252+
results fail the attempt. For example, with an application's asynchronous credential
253+
service returning `CompletionStage<List<RTCIceServer>>`:
254+
255+
```java
256+
RecoveryPolicy recovery = RecoveryPolicy.builder()
257+
.iceServers(attempt -> credentials.fetchIceServers())
258+
.onEvent(event -> {
259+
if (event.state() == RecoveryEvent.State.EXHAUSTED) {
260+
showReconnectAction(event.cause());
261+
}
262+
})
263+
.build();
264+
```
265+
266+
The attempt deadline covers credentials, signaling and waiting for connectivity.
267+
An HTTP restart already in flight finishes or reaches its own operation timeout
268+
before another starts. Late credentials and completions after recovery or `close()`
269+
are ignored; the credential service owns cancellation of its requests. Closing the
270+
peer or runtime cancels scheduled retries, including one whose timer has fired but
271+
whose control task has not run yet. Event notifications already queued may still arrive.
272+
273+
ICE recovery requires working signaling. Reconnecting a WebSocket or refreshing
274+
HTTP authorization is the application's separate responsibility. A policy does not
275+
create a replacement peer or session. If the application chooses that fallback, it
276+
must close the old session, attach handlers to the new peer, republish local tracks,
277+
and handle new remote tracks and data channels explicitly; their old handles are
278+
not transferred.
279+
280+
`Whip.to(endpoint).recovery(recovery)` and `Whep.from(endpoint).recovery(recovery)`
281+
use the same policy with the session's ICE `PATCH` exchange. This replaces their
282+
built-in restart rule for that session. Keep using `session.restartIce()` for a
283+
manual HTTP restart; `session.peer().restartIce()` does not perform the HTTP
284+
exchange. For a manually negotiated peer outside WHIP/WHEP, the application owns
285+
recovery and its protocol-specific offer/answer exchange.
286+
216287
## Threads
217288

218289
Every method of the client API may be called from any thread, including from inside a handler. Methods that change a peer return at once and take effect in the order they were called.

‎webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/ClientApiExample.java‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
import dev.onvoid.webrtc.client.PcmFormat;
3333
import dev.onvoid.webrtc.client.Peer;
3434
import dev.onvoid.webrtc.client.PeerOptions;
35+
import dev.onvoid.webrtc.client.RecoveryPolicy;
3536
import dev.onvoid.webrtc.client.SignalMessage;
3637
import dev.onvoid.webrtc.client.VideoStats;
3738
import dev.onvoid.webrtc.client.WebRtc;
@@ -84,6 +85,9 @@ public static void main(String[] args) throws Exception {
8485
// A real application sends it through its WebSocket instead.
8586
Peer caller = rtc.createPeer(PeerOptions.builder()
8687
.name("caller")
88+
.recovery(RecoveryPolicy.builder()
89+
.onEvent(event -> System.out.println("Caller recovery: " + event.state()))
90+
.build())
8791
.signaling(message -> transmit("caller", calleeRef.get(), message.toJson()))
8892
.build());
8993
Peer callee = rtc.createPeer(PeerOptions.builder()

‎webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/WhepExample.java‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
import java.util.concurrent.atomic.AtomicLong;
2323

2424
import dev.onvoid.webrtc.client.Peer;
25+
import dev.onvoid.webrtc.client.RecoveryPolicy;
2526
import dev.onvoid.webrtc.client.WebRtc;
2627
import dev.onvoid.webrtc.client.Whep;
2728

@@ -66,6 +67,9 @@ public static void main(String[] args) throws Exception {
6667
// Authenticated TURN is configured with .turnServer(url, username, password).
6768
Whep.Session session = Whep.from(endpoint)
6869
.iceServer("stun:stun.l.google.com:19302")
70+
.recovery(RecoveryPolicy.builder()
71+
.onEvent(event -> System.out.println("ICE recovery: " + event.state()))
72+
.build())
6973
.play(rtc)
7074
.get(15, TimeUnit.SECONDS);
7175

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

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,10 @@ final class HttpIce {
112112

113113
private boolean closed;
114114

115+
private RecoveryPolicy recoveryPolicy;
116+
117+
void recovery(RecoveryPolicy policy) { recoveryPolicy = policy; }
118+
115119

116120
HttpIce(WebRtc rtc, HttpClient client, PeerImpl peer, String authorization, Duration timeout) {
117121
this.rtc = rtc;
@@ -147,7 +151,13 @@ synchronized void attach(URI session, String etag, String offer) {
147151
* disconnected for {@link #DISCONNECTED_GRACE}.
148152
*/
149153
void watch() {
150-
Subscription subscription = peer.onStateChange(this::stateChanged);
154+
if (recoveryPolicy != null) {
155+
peer.startRecovery(recoveryPolicy, this::restart);
156+
}
157+
Subscription subscription = peer.onStateChange(state -> {
158+
if (recoveryPolicy == null) stateChanged(state);
159+
else if (state == PeerState.CLOSED) close();
160+
});
151161

152162
synchronized (this) {
153163
if (closed) {

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

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -181,9 +181,10 @@ public CompletableFuture<Void> closeAsync() {
181181
/**
182182
* Restarts ICE, as after the network changed: the peer gathers new
183183
* candidates, and only the ICE information goes to the session, by PATCH,
184-
* as WHIP and WHEP do; the media go on as negotiated. The session restarts
185-
* ICE by itself too, when the connection fails or stays disconnected for
186-
* two seconds, up to three times in a row without success.
184+
* as WHIP and WHEP do; the media go on as negotiated. By default, the session
185+
* restarts ICE by itself too, when the connection fails or stays disconnected
186+
* for two seconds, up to three times in a row without success. The session
187+
* builder's recovery option replaces that rule with a {@link RecoveryPolicy}.
187188
*
188189
* @return a future that completes once the new ICE information of both
189190
* sides is applied, or fails, among others when the session takes no ICE
@@ -225,10 +226,11 @@ public void close() {
225226
*/
226227
static <S extends HttpSession> CompletableFuture<S> start(WebRtc rtc, PeerImpl peer, URI endpoint,
227228
String authorization, Duration timeout, CompletableFuture<?> prepared, Gathering gathering,
228-
Protocol protocol, Factory<S> factory) {
229+
Protocol protocol, RecoveryPolicy recovery, Factory<S> factory) {
229230
CompletableFuture<Void> abandoned = new CompletableFuture<>();
230231
AtomicReference<Map<String, URI>> extensions = new AtomicReference<>(Map.of());
231232
HttpIce ice = new HttpIce(rtc, rtc.httpClient(authorization != null), peer, authorization, timeout);
233+
ice.recovery(recovery);
232234
CompletableFuture<S> session = peer.toPublic(negotiate(rtc, peer, endpoint, authorization, timeout, prepared,
233235
gathering, protocol, ice, extensions, abandoned)
234236
.thenApply(resource -> factory.create(rtc, peer, resource, extensions.get(), authorization, timeout,
Lines changed: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,181 @@
1+
/*
2+
* Copyright 2026 Alex Andres
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package dev.onvoid.webrtc.client;
18+
19+
import java.time.Duration;
20+
import java.util.List;
21+
import java.util.concurrent.CompletableFuture;
22+
import java.util.concurrent.Executor;
23+
import java.util.concurrent.ScheduledExecutorService;
24+
import java.util.concurrent.ScheduledFuture;
25+
import java.util.concurrent.TimeUnit;
26+
import java.util.function.BooleanSupplier;
27+
import java.util.function.Supplier;
28+
29+
import dev.onvoid.webrtc.RTCIceServer;
30+
import dev.onvoid.webrtc.internal.Timeouts;
31+
32+
/** All state belongs to control. Application code is dispatched by the host. */
33+
final class IceRecovery {
34+
interface Host {
35+
CompletableFuture<List<RTCIceServer>> servers(int attempt);
36+
void useServers(List<RTCIceServer> servers);
37+
void event(RecoveryEvent event);
38+
}
39+
40+
private final RecoveryPolicy policy;
41+
private final Executor control;
42+
private final ScheduledExecutorService timer;
43+
private final BooleanSupplier closing;
44+
private final Supplier<CompletableFuture<Void>> restart;
45+
private final Host host;
46+
private ScheduledFuture<?> wait;
47+
private long generation;
48+
private int attempts;
49+
private boolean outage;
50+
private boolean exhausted;
51+
private boolean closed;
52+
private boolean exchanging;
53+
private boolean deferredAttempt;
54+
private boolean gracePeriod;
55+
private Throwable timedOut;
56+
57+
IceRecovery(RecoveryPolicy policy, Executor control, ScheduledExecutorService timer,
58+
BooleanSupplier closing, Supplier<CompletableFuture<Void>> restart, Host host) {
59+
this.policy = policy;
60+
this.control = control;
61+
this.timer = timer;
62+
this.closing = closing;
63+
this.restart = restart;
64+
this.host = host;
65+
}
66+
67+
void stateChanged(PeerState state) {
68+
if (closed || closing.getAsBoolean()) return;
69+
if (state == PeerState.CLOSED) { close(); return; }
70+
if (state == PeerState.CONNECTED) {
71+
if (outage) emit(RecoveryEvent.State.RECOVERED, null);
72+
outage = false;
73+
exhausted = false;
74+
attempts = 0;
75+
invalidate();
76+
return;
77+
}
78+
if (state != PeerState.DISCONNECTED && state != PeerState.FAILED) return;
79+
if (outage || exhausted) {
80+
if (state == PeerState.FAILED && gracePeriod && !exhausted) {
81+
invalidate();
82+
attempt();
83+
}
84+
return;
85+
}
86+
outage = true;
87+
if (state == PeerState.DISCONNECTED) {
88+
gracePeriod = true;
89+
emit(RecoveryEvent.State.WAITING, null);
90+
schedule(policy.grace, this::attempt);
91+
}
92+
else attempt();
93+
}
94+
95+
void close() {
96+
closed = true;
97+
invalidate();
98+
}
99+
100+
private void invalidate() {
101+
generation++;
102+
deferredAttempt = false;
103+
gracePeriod = false;
104+
if (wait != null) wait.cancel(false);
105+
wait = null;
106+
timedOut = null;
107+
}
108+
109+
private boolean current(long token) {
110+
return token == generation && outage && !closed && !closing.getAsBoolean();
111+
}
112+
113+
private void attempt() {
114+
if (closed || closing.getAsBoolean() || !outage || exhausted) return;
115+
// A connection can recover and fail again while an HTTP exchange ends.
116+
if (exchanging) { deferredAttempt = true; return; }
117+
gracePeriod = false;
118+
attempts++;
119+
long token = ++generation;
120+
emit(RecoveryEvent.State.ATTEMPTING, null);
121+
schedule(policy.attemptTimeout, () -> {
122+
Throwable error = new WebRtcException("ICE recovery attempt timed out");
123+
if (exchanging) timedOut = error;
124+
else failed(token, error);
125+
});
126+
try {
127+
host.servers(attempts).whenComplete((servers, error) -> control.execute(() -> {
128+
if (!current(token)) return;
129+
if (error != null) { failed(token, error); return; }
130+
try {
131+
if (servers != null) host.useServers(servers);
132+
exchanging = true;
133+
restart.get().whenComplete((ignored, failure) -> control.execute(() -> {
134+
exchanging = false;
135+
if (!current(token)) {
136+
if (deferredAttempt && outage && !exhausted && !closed && !closing.getAsBoolean()) {
137+
deferredAttempt = false;
138+
attempt();
139+
}
140+
return;
141+
}
142+
if (failure != null || timedOut != null) failed(token, failure != null ? failure : timedOut);
143+
// Successful signaling is not successful connectivity: keep the deadline.
144+
}));
145+
}
146+
catch (Throwable failure) { exchanging = false; failed(token, failure); }
147+
}));
148+
}
149+
catch (Throwable error) { failed(token, error); }
150+
}
151+
152+
private void failed(long token, Throwable error) {
153+
if (!current(token)) return;
154+
invalidate();
155+
error = PeerImpl.unwrap(error);
156+
if (attempts >= policy.maxAttempts) {
157+
exhausted = true;
158+
emit(RecoveryEvent.State.EXHAUSTED, error);
159+
}
160+
else {
161+
emit(RecoveryEvent.State.RETRYING, error);
162+
schedule(policy.backoff(attempts), this::attempt);
163+
}
164+
}
165+
166+
private void emit(RecoveryEvent.State state, Throwable cause) {
167+
host.event(new RecoveryEvent(state, attempts, cause));
168+
}
169+
170+
private void schedule(Duration delay, Runnable task) {
171+
long token = generation;
172+
try {
173+
wait = timer.schedule(() -> control.execute(() -> {
174+
if (current(token)) { wait = null; task.run(); }
175+
}), Timeouts.toMillis(delay), TimeUnit.MILLISECONDS);
176+
}
177+
catch (java.util.concurrent.RejectedExecutionException error) {
178+
close(); // The runtime is stopping its timer.
179+
}
180+
}
181+
}

0 commit comments

Comments
 (0)