Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 72 additions & 1 deletion docs/guide/client-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ When two impolite peers collide, neither gives way. An impolite peer that waited
| `CONNECTING` | ICE and DTLS are establishing the connection. |
| `CONNECTED` | Media and data can flow. |
| `DISCONNECTED` | Connectivity was lost. It may come back by itself. |
| `FAILED` | The connection failed. `peer.restartIce()` tries to recover it. |
| `FAILED` | The connection failed. `peer.restartIce()` or the configured recovery policy tries to recover it. |
| `CLOSED` | The peer was closed. This state is final. |

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

`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.

### Automatic ICE Recovery

Automatic peers can opt into a `RecoveryPolicy`. Without one, the application still
calls `peer.restartIce()` itself. The policy waits through short disconnections,
restarts ICE on the same peer, and bounds retries with exponential backoff:

```java
RecoveryPolicy recovery = RecoveryPolicy.builder()
.grace(Duration.ofSeconds(2))
.maxAttempts(3)
.backoff(Duration.ofSeconds(1), Duration.ofSeconds(30))
.attemptTimeout(Duration.ofSeconds(15))
.onEvent(event -> System.out.println(event.state() + " attempt " + event.attempt()))
.build();

Peer peer = rtc.createPeer(PeerOptions.builder()
.signaling(signaling)
.recovery(recovery)
.build());
```

`DISCONNECTED` starts the grace period; `FAILED` skips it. Repeated failure
notifications during an attempt do not start parallel restarts. Events are
`WAITING`, `ATTEMPTING`, `RETRYING`, `RECOVERED` and `EXHAUSTED`, delivered on the
peer's event executor. `attempt()` counts attempts in the current outage, starting
at one; a recovery during the grace period reports zero. `cause()` gives the last
failure on retry or exhaustion. Successful signaling alone does not count as
recovery: the peer must report `CONNECTED`. That resets the budget, including
after exhaustion. Exhaustion leaves the peer open and creates no further automatic
attempts until it connects again. `whenConnected()` keeps its existing first-connection
semantics; observe `RECOVERED` for later recovery.

Before an attempt, `iceServers(attempt -> completionStage)` can obtain fresh TURN
credentials asynchronously. It runs on the event executor and must return promptly;
the resulting list replaces **all** ICE servers, so include STUN servers that should
remain available. The library copies the supplied servers; failed, null or invalid
results fail the attempt. For example, with an application's asynchronous credential
service returning `CompletionStage<List<RTCIceServer>>`:

```java
RecoveryPolicy recovery = RecoveryPolicy.builder()
.iceServers(attempt -> credentials.fetchIceServers())
.onEvent(event -> {
if (event.state() == RecoveryEvent.State.EXHAUSTED) {
showReconnectAction(event.cause());
}
})
.build();
```

The attempt deadline covers credentials, signaling and waiting for connectivity.
An HTTP restart already in flight finishes or reaches its own operation timeout
before another starts. Late credentials and completions after recovery or `close()`
are ignored; the credential service owns cancellation of its requests. Closing the
peer or runtime cancels scheduled retries, including one whose timer has fired but
whose control task has not run yet. Event notifications already queued may still arrive.

ICE recovery requires working signaling. Reconnecting a WebSocket or refreshing
HTTP authorization is the application's separate responsibility. A policy does not
create a replacement peer or session. If the application chooses that fallback, it
must close the old session, attach handlers to the new peer, republish local tracks,
and handle new remote tracks and data channels explicitly; their old handles are
not transferred.

`Whip.to(endpoint).recovery(recovery)` and `Whep.from(endpoint).recovery(recovery)`
use the same policy with the session's ICE `PATCH` exchange. This replaces their
built-in restart rule for that session. Keep using `session.restartIce()` for a
manual HTTP restart; `session.peer().restartIce()` does not perform the HTTP
exchange. For a manually negotiated peer outside WHIP/WHEP, the application owns
recovery and its protocol-specific offer/answer exchange.

## Threads

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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import dev.onvoid.webrtc.client.PcmFormat;
import dev.onvoid.webrtc.client.Peer;
import dev.onvoid.webrtc.client.PeerOptions;
import dev.onvoid.webrtc.client.RecoveryPolicy;
import dev.onvoid.webrtc.client.SignalMessage;
import dev.onvoid.webrtc.client.VideoStats;
import dev.onvoid.webrtc.client.WebRtc;
Expand Down Expand Up @@ -84,6 +85,9 @@ public static void main(String[] args) throws Exception {
// A real application sends it through its WebSocket instead.
Peer caller = rtc.createPeer(PeerOptions.builder()
.name("caller")
.recovery(RecoveryPolicy.builder()
.onEvent(event -> System.out.println("Caller recovery: " + event.state()))
.build())
.signaling(message -> transmit("caller", calleeRef.get(), message.toJson()))
.build());
Peer callee = rtc.createPeer(PeerOptions.builder()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import java.util.concurrent.atomic.AtomicLong;

import dev.onvoid.webrtc.client.Peer;
import dev.onvoid.webrtc.client.RecoveryPolicy;
import dev.onvoid.webrtc.client.WebRtc;
import dev.onvoid.webrtc.client.Whep;

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

Expand Down
12 changes: 11 additions & 1 deletion webrtc/src/main/java/dev/onvoid/webrtc/client/HttpIce.java
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,10 @@ final class HttpIce {

private boolean closed;

private RecoveryPolicy recoveryPolicy;

void recovery(RecoveryPolicy policy) { recoveryPolicy = policy; }


HttpIce(WebRtc rtc, HttpClient client, PeerImpl peer, String authorization, Duration timeout) {
this.rtc = rtc;
Expand Down Expand Up @@ -147,7 +151,13 @@ synchronized void attach(URI session, String etag, String offer) {
* disconnected for {@link #DISCONNECTED_GRACE}.
*/
void watch() {
Subscription subscription = peer.onStateChange(this::stateChanged);
if (recoveryPolicy != null) {
peer.startRecovery(recoveryPolicy, this::restart);
}
Subscription subscription = peer.onStateChange(state -> {
if (recoveryPolicy == null) stateChanged(state);
else if (state == PeerState.CLOSED) close();
});

synchronized (this) {
if (closed) {
Expand Down
10 changes: 6 additions & 4 deletions webrtc/src/main/java/dev/onvoid/webrtc/client/HttpSession.java
Original file line number Diff line number Diff line change
Expand Up @@ -181,9 +181,10 @@ public CompletableFuture<Void> closeAsync() {
/**
* Restarts ICE, as after the network changed: the peer gathers new
* candidates, and only the ICE information goes to the session, by PATCH,
* as WHIP and WHEP do; the media go on as negotiated. The session restarts
* ICE by itself too, when the connection fails or stays disconnected for
* two seconds, up to three times in a row without success.
* as WHIP and WHEP do; the media go on as negotiated. By default, the session
* restarts ICE by itself too, when the connection fails or stays disconnected
* for two seconds, up to three times in a row without success. The session
* builder's recovery option replaces that rule with a {@link RecoveryPolicy}.
*
* @return a future that completes once the new ICE information of both
* sides is applied, or fails, among others when the session takes no ICE
Expand Down Expand Up @@ -225,10 +226,11 @@ public void close() {
*/
static <S extends HttpSession> CompletableFuture<S> start(WebRtc rtc, PeerImpl peer, URI endpoint,
String authorization, Duration timeout, CompletableFuture<?> prepared, Gathering gathering,
Protocol protocol, Factory<S> factory) {
Protocol protocol, RecoveryPolicy recovery, Factory<S> factory) {
CompletableFuture<Void> abandoned = new CompletableFuture<>();
AtomicReference<Map<String, URI>> extensions = new AtomicReference<>(Map.of());
HttpIce ice = new HttpIce(rtc, rtc.httpClient(authorization != null), peer, authorization, timeout);
ice.recovery(recovery);
CompletableFuture<S> session = peer.toPublic(negotiate(rtc, peer, endpoint, authorization, timeout, prepared,
gathering, protocol, ice, extensions, abandoned)
.thenApply(resource -> factory.create(rtc, peer, resource, extensions.get(), authorization, timeout,
Expand Down
181 changes: 181 additions & 0 deletions webrtc/src/main/java/dev/onvoid/webrtc/client/IceRecovery.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
/*
* Copyright 2026 Alex Andres
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package dev.onvoid.webrtc.client;

import java.time.Duration;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.BooleanSupplier;
import java.util.function.Supplier;

import dev.onvoid.webrtc.RTCIceServer;
import dev.onvoid.webrtc.internal.Timeouts;

/** All state belongs to control. Application code is dispatched by the host. */
final class IceRecovery {
interface Host {
CompletableFuture<List<RTCIceServer>> servers(int attempt);
void useServers(List<RTCIceServer> servers);
void event(RecoveryEvent event);
}

private final RecoveryPolicy policy;
private final Executor control;
private final ScheduledExecutorService timer;
private final BooleanSupplier closing;
private final Supplier<CompletableFuture<Void>> restart;
private final Host host;
private ScheduledFuture<?> wait;
private long generation;
private int attempts;
private boolean outage;
private boolean exhausted;
private boolean closed;
private boolean exchanging;
private boolean deferredAttempt;
private boolean gracePeriod;
private Throwable timedOut;

IceRecovery(RecoveryPolicy policy, Executor control, ScheduledExecutorService timer,
BooleanSupplier closing, Supplier<CompletableFuture<Void>> restart, Host host) {
this.policy = policy;
this.control = control;
this.timer = timer;
this.closing = closing;
this.restart = restart;
this.host = host;
}

void stateChanged(PeerState state) {
if (closed || closing.getAsBoolean()) return;
if (state == PeerState.CLOSED) { close(); return; }
if (state == PeerState.CONNECTED) {
if (outage) emit(RecoveryEvent.State.RECOVERED, null);
outage = false;
exhausted = false;
attempts = 0;
invalidate();
return;
}
if (state != PeerState.DISCONNECTED && state != PeerState.FAILED) return;
if (outage || exhausted) {
if (state == PeerState.FAILED && gracePeriod && !exhausted) {
invalidate();
attempt();
}
return;
}
outage = true;
if (state == PeerState.DISCONNECTED) {
gracePeriod = true;
emit(RecoveryEvent.State.WAITING, null);
schedule(policy.grace, this::attempt);
}
else attempt();
}

void close() {
closed = true;
invalidate();
}

private void invalidate() {
generation++;
deferredAttempt = false;
gracePeriod = false;
if (wait != null) wait.cancel(false);
wait = null;
timedOut = null;
}

private boolean current(long token) {
return token == generation && outage && !closed && !closing.getAsBoolean();
}

private void attempt() {
if (closed || closing.getAsBoolean() || !outage || exhausted) return;
// A connection can recover and fail again while an HTTP exchange ends.
if (exchanging) { deferredAttempt = true; return; }
gracePeriod = false;
attempts++;
long token = ++generation;
emit(RecoveryEvent.State.ATTEMPTING, null);
schedule(policy.attemptTimeout, () -> {
Throwable error = new WebRtcException("ICE recovery attempt timed out");
if (exchanging) timedOut = error;
else failed(token, error);
});
try {
host.servers(attempts).whenComplete((servers, error) -> control.execute(() -> {
if (!current(token)) return;
if (error != null) { failed(token, error); return; }
try {
if (servers != null) host.useServers(servers);
exchanging = true;
restart.get().whenComplete((ignored, failure) -> control.execute(() -> {
exchanging = false;
if (!current(token)) {
if (deferredAttempt && outage && !exhausted && !closed && !closing.getAsBoolean()) {
deferredAttempt = false;
attempt();
}
return;
}
if (failure != null || timedOut != null) failed(token, failure != null ? failure : timedOut);
// Successful signaling is not successful connectivity: keep the deadline.
}));
}
catch (Throwable failure) { exchanging = false; failed(token, failure); }
}));
}
catch (Throwable error) { failed(token, error); }
}

private void failed(long token, Throwable error) {
if (!current(token)) return;
invalidate();
error = PeerImpl.unwrap(error);
if (attempts >= policy.maxAttempts) {
exhausted = true;
emit(RecoveryEvent.State.EXHAUSTED, error);
}
else {
emit(RecoveryEvent.State.RETRYING, error);
schedule(policy.backoff(attempts), this::attempt);
}
}

private void emit(RecoveryEvent.State state, Throwable cause) {
host.event(new RecoveryEvent(state, attempts, cause));
}

private void schedule(Duration delay, Runnable task) {
long token = generation;
try {
wait = timer.schedule(() -> control.execute(() -> {
if (current(token)) { wait = null; task.run(); }
}), Timeouts.toMillis(delay), TimeUnit.MILLISECONDS);
}
catch (java.util.concurrent.RejectedExecutionException error) {
close(); // The runtime is stopping its timer.
}
}
}
Loading
Loading