From 0e9bb26bf1b03bcf03515091b2d18d9cbf8cb3d4 Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Sun, 8 Nov 2026 00:19:51 +0100 Subject: [PATCH] feat: add configurable ICE recovery for client peers and HTTP sessions --- docs/guide/client-api.md | 73 ++++- .../webrtc/examples/ClientApiExample.java | 4 + .../onvoid/webrtc/examples/WhepExample.java | 4 + .../dev/onvoid/webrtc/client/HttpIce.java | 12 +- .../dev/onvoid/webrtc/client/HttpSession.java | 10 +- .../dev/onvoid/webrtc/client/IceRecovery.java | 181 +++++++++++ .../dev/onvoid/webrtc/client/PeerImpl.java | 85 +++++- .../dev/onvoid/webrtc/client/PeerOptions.java | 22 +- .../onvoid/webrtc/client/RecoveryEvent.java | 52 ++++ .../onvoid/webrtc/client/RecoveryPolicy.java | 132 ++++++++ .../java/dev/onvoid/webrtc/client/Whep.java | 13 +- .../java/dev/onvoid/webrtc/client/Whip.java | 13 +- .../webrtc/client/HttpSessionTests.java | 26 ++ .../webrtc/client/IceRecoveryTests.java | 281 ++++++++++++++++++ .../webrtc/client/PeerRecoveryTests.java | 136 +++++++++ 15 files changed, 1034 insertions(+), 10 deletions(-) create mode 100644 webrtc/src/main/java/dev/onvoid/webrtc/client/IceRecovery.java create mode 100644 webrtc/src/main/java/dev/onvoid/webrtc/client/RecoveryEvent.java create mode 100644 webrtc/src/main/java/dev/onvoid/webrtc/client/RecoveryPolicy.java create mode 100644 webrtc/src/test/java/dev/onvoid/webrtc/client/IceRecoveryTests.java create mode 100644 webrtc/src/test/java/dev/onvoid/webrtc/client/PeerRecoveryTests.java diff --git a/docs/guide/client-api.md b/docs/guide/client-api.md index 3172a174b..18116a2f5 100644 --- a/docs/guide/client-api.md +++ b/docs/guide/client-api.md @@ -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 @@ -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>`: + +```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. diff --git a/webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/ClientApiExample.java b/webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/ClientApiExample.java index 46662f3d9..b315cdef3 100644 --- a/webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/ClientApiExample.java +++ b/webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/ClientApiExample.java @@ -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; @@ -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() diff --git a/webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/WhepExample.java b/webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/WhepExample.java index 0f1e50430..d43feebd0 100644 --- a/webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/WhepExample.java +++ b/webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/WhepExample.java @@ -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; @@ -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); diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpIce.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpIce.java index 54412814a..7fbb58f01 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpIce.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpIce.java @@ -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; @@ -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) { diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpSession.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpSession.java index 9e5096bcf..67a1d8b70 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpSession.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpSession.java @@ -181,9 +181,10 @@ public CompletableFuture 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 @@ -225,10 +226,11 @@ public void close() { */ static CompletableFuture start(WebRtc rtc, PeerImpl peer, URI endpoint, String authorization, Duration timeout, CompletableFuture prepared, Gathering gathering, - Protocol protocol, Factory factory) { + Protocol protocol, RecoveryPolicy recovery, Factory factory) { CompletableFuture abandoned = new CompletableFuture<>(); AtomicReference> extensions = new AtomicReference<>(Map.of()); HttpIce ice = new HttpIce(rtc, rtc.httpClient(authorization != null), peer, authorization, timeout); + ice.recovery(recovery); CompletableFuture 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, diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/IceRecovery.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/IceRecovery.java new file mode 100644 index 000000000..e0b69ee3a --- /dev/null +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/IceRecovery.java @@ -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> servers(int attempt); + void useServers(List servers); + void event(RecoveryEvent event); + } + + private final RecoveryPolicy policy; + private final Executor control; + private final ScheduledExecutorService timer; + private final BooleanSupplier closing; + private final Supplier> 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> 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. + } + } +} diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java index a6c3d841b..8b0a1657e 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java @@ -34,6 +34,8 @@ import dev.onvoid.webrtc.PeerConnectionObserver; import dev.onvoid.webrtc.RTCDataChannel; +import dev.onvoid.webrtc.RTCConfiguration; +import dev.onvoid.webrtc.RTCIceServer; import dev.onvoid.webrtc.RTCEncodedFrameTransformer; import dev.onvoid.webrtc.RTCIceCandidate; import dev.onvoid.webrtc.RTCIceGatheringState; @@ -102,6 +104,8 @@ final class PeerImpl implements Peer { private final PeerOptions options; + private IceRecovery recovery; + /** The stream the tracks added without stream ids share. */ final String defaultStreamId = UUID.randomUUID().toString(); @@ -241,6 +245,12 @@ void open() { } signaling.attach(); + if (options.recovery != null) { + startRecovery(options.recovery, () -> { + connection.restartIce(); + return CompletableFuture.completedFuture(null); + }); + } } @Override @@ -409,6 +419,77 @@ public Subscription onStats(Duration interval, Consumer handler) { return statistics.subscribe(interval, handler); } + /** Installs the same controller with the transport-specific restart operation. */ + void startRecovery(RecoveryPolicy policy, Supplier> restart) { + control.execute(() -> { + if (isClosing()) return; + if (recovery != null) recovery.close(); + recovery = new IceRecovery(policy, control, rtc.timer, this::isClosing, restart, new IceRecovery.Host() { + @Override + public CompletableFuture> servers(int attempt) { + return recoveryServers(policy, attempt); + } + + @Override + public void useServers(List servers) { + RTCConfiguration config = connection.getConfiguration(); + config.iceServers = servers; + connection.setConfiguration(config); + } + + @Override + public void event(RecoveryEvent event) { + events.execute(() -> call(policy.listener, event)); + } + }); + recovery.stateChanged(state); + }); + } + + private CompletableFuture> recoveryServers(RecoveryPolicy policy, int attempt) { + if (policy.iceServers == null) { + return CompletableFuture.completedFuture(null); + } + + CompletableFuture> result = new CompletableFuture<>(); + events.execute(() -> { + if (isClosing()) { + result.completeExceptionally(closedError()); + return; + } + try { + requireNonNull(policy.iceServers.apply(attempt), "ICE server stage").whenComplete((servers, error) -> { + if (error != null) { + result.completeExceptionally(error); + return; + } + try { + result.complete(copyIceServers(servers)); + } + catch (Throwable e) { + result.completeExceptionally(e); + } + }); + } + catch (Throwable e) { + result.completeExceptionally(e); + } + }, () -> result.completeExceptionally(closedError())); + return result; + } + + private static List copyIceServers(List servers) { + List copy = new ArrayList<>(); + for (RTCIceServer server : requireNonNull(servers, "ICE servers")) { + RTCIceServer item = new RTCIceServer(); + for (String url : server.urls) item.urls.add(requireNonNull(url, "ICE server URL")); + item.username = server.username; + item.password = server.password; + copy.add(item); + } + return copy; + } + @Override public void restartIce() { control.execute(() -> { @@ -691,13 +772,14 @@ void sendLocalDescription() { // What WebRTC reports, on the control executor. - private void connectionChanged(RTCPeerConnectionState nativeState) { + void connectionChanged(RTCPeerConnectionState nativeState) { if (closed) { return; } PeerState newState = PeerState.of(nativeState); state = newState; + if (recovery != null) recovery.stateChanged(newState); events.execute(() -> deliverState(newState), () -> settleConnected(newState)); } @@ -721,6 +803,7 @@ private void teardown() { teardownStarted = true; closing.set(true); closed = true; + if (recovery != null) recovery.close(); PeerClosedException error = closedError(); diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerOptions.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerOptions.java index 62546de04..949fbb0b9 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerOptions.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerOptions.java @@ -47,6 +47,8 @@ public final class PeerOptions { final String name; + final RecoveryPolicy recovery; + final List iceServers; final boolean relayOnly; @@ -74,6 +76,7 @@ public final class PeerOptions { private PeerOptions(Builder builder) { this.name = builder.name; + this.recovery = builder.recovery; this.iceServers = Collections.unmodifiableList(new ArrayList<>(builder.iceServers)); this.relayOnly = builder.relayOnly; this.signaling = builder.signaling; @@ -134,6 +137,8 @@ public static final class Builder { private String name; + private RecoveryPolicy recovery; + private boolean relayOnly; private Signaling signaling; @@ -158,6 +163,17 @@ public static final class Builder { private Builder() { } + /** + * Enables ICE recovery for automatic negotiation. Disabled by default. + * Signaling recovery and creating a replacement session remain application + * responsibilities; no peer, track or channel is replaced by this policy. + * For manual peers use the WHIP/WHEP builder's recovery option instead. + */ + public Builder recovery(RecoveryPolicy policy) { + recovery = requireNonNull(policy, "policy"); + return this; + } + /** * @param name the name in thread names and messages. * @@ -377,9 +393,13 @@ public Builder configure(Consumer customizer) { * @return the options. * * @throws IllegalStateException if the peer negotiates automatically - * and has no signaling. + * and has no signaling, or recovery is + * configured for manual negotiation. */ public PeerOptions build() { + if (recovery != null && negotiation != Negotiation.AUTOMATIC) { + throw new IllegalStateException("Peer recovery requires automatic negotiation"); + } if (negotiation == Negotiation.AUTOMATIC && signaling == null) { throw new IllegalStateException("A peer that negotiates automatically needs a Signaling. " + "Set one, or use Negotiation.MANUAL to drive the exchange through Peer.negotiator()"); diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/RecoveryEvent.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/RecoveryEvent.java new file mode 100644 index 000000000..6869fe43f --- /dev/null +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/RecoveryEvent.java @@ -0,0 +1,52 @@ +/* + * 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; + +/** A notification of ICE recovery on the existing peer, delivered on its event executor. */ +public final class RecoveryEvent { + + public enum State { + /** Waiting for a brief interruption to pass. */ + WAITING, + /** Refreshing credentials and starting the numbered attempt. */ + ATTEMPTING, + /** An attempt failed; another is scheduled after the backoff. */ + RETRYING, + /** Connectivity returned. */ + RECOVERED, + /** The budget was exhausted. The peer remains open for application action. */ + EXHAUSTED + } + + private final State state; + private final int attempt; + private final Throwable cause; + + RecoveryEvent(State state, int attempt, Throwable cause) { + this.state = state; + this.attempt = attempt; + this.cause = cause; + } + + public State state() { return state; } + + /** @return the number of attempts started in this outage, zero during the grace period. */ + public int attempt() { return attempt; } + + /** @return the failure of the last attempt, or null. */ + public Throwable cause() { return cause; } +} diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/RecoveryPolicy.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/RecoveryPolicy.java new file mode 100644 index 000000000..62e947013 --- /dev/null +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/RecoveryPolicy.java @@ -0,0 +1,132 @@ +/* + * 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 static java.util.Objects.requireNonNull; + +import java.time.Duration; +import java.util.List; +import java.util.concurrent.CompletionStage; +import java.util.function.Consumer; +import java.util.function.Function; + +import dev.onvoid.webrtc.RTCIceServer; +import dev.onvoid.webrtc.internal.Timeouts; + +/** + * Opt-in ICE recovery on the same peer. It never reconnects signaling or creates + * a new session, remote tracks or data channels. Signaling must be usable for + * an ICE restart to succeed. A return to CONNECTED resets the attempt budget. + */ +public final class RecoveryPolicy { + + final Duration grace; + final Duration initialBackoff; + final Duration maxBackoff; + final Duration attemptTimeout; + final int maxAttempts; + final Function>> iceServers; + final Consumer listener; + + private RecoveryPolicy(Builder b) { + grace = b.grace; + initialBackoff = b.initialBackoff; + maxBackoff = b.maxBackoff; + attemptTimeout = b.attemptTimeout; + maxAttempts = b.maxAttempts; + iceServers = b.iceServers; + listener = b.listener; + } + + public static Builder builder() { return new Builder(); } + + Duration backoff(int attempt) { + long delay = Timeouts.toMillis(initialBackoff); + long cap = Timeouts.toMillis(maxBackoff); + for (int i = 1; i < attempt && delay < cap; i++) { + delay = delay > cap / 2 ? cap : delay * 2; + } + return Duration.ofMillis(Math.min(delay, cap)); + } + + public static final class Builder { + private Duration grace = Duration.ofSeconds(2); + private Duration initialBackoff = Duration.ofSeconds(1); + private Duration maxBackoff = Duration.ofSeconds(30); + private Duration attemptTimeout = Duration.ofSeconds(15); + private int maxAttempts = 3; + private Function>> iceServers; + private Consumer listener = event -> { }; + + private Builder() { } + + /** Wait after DISCONNECTED; FAILED starts immediately. Default: two seconds. */ + public Builder grace(Duration value) { + grace = Timeouts.requireNonNegative(value, "grace"); + return this; + } + + /** Double the delay after each unsuccessful attempt, up to maximum. */ + public Builder backoff(Duration initial, Duration maximum) { + Timeouts.requirePositive(initial, "initial backoff"); + Timeouts.requirePositive(maximum, "maximum backoff"); + if (initial.compareTo(maximum) > 0) { + throw new IllegalArgumentException("Initial backoff exceeds maximum"); + } + initialBackoff = initial; + maxBackoff = maximum; + return this; + } + + /** Default: three attempts per outage; at least one. */ + public Builder maxAttempts(int value) { + if (value < 1) throw new IllegalArgumentException("At least one attempt is required"); + maxAttempts = value; + return this; + } + + /** + * Default: 15 seconds, including credentials and waiting for CONNECTED. + * An HTTP restart already in flight must finish or reach its own operation + * timeout before the next attempt starts; exchanges never overlap. + */ + public Builder attemptTimeout(Duration value) { + attemptTimeout = Timeouts.requirePositive(value, "attempt timeout"); + return this; + } + + /** + * Before each attempt, asynchronously supplies the complete replacement + * list of ICE servers, including fresh TURN credentials. Called on the + * peer's event executor with the one-based attempt number; return promptly. + * A failed or null result fails the attempt. Late results after timeout, + * recovery or close are ignored. The provider owns cancellation of its I/O. + */ + public Builder iceServers(Function>> provider) { + iceServers = requireNonNull(provider, "provider"); + return this; + } + + /** Receives progress and exhaustion on the peer's event executor. */ + public Builder onEvent(Consumer handler) { + listener = requireNonNull(handler, "handler"); + return this; + } + + public RecoveryPolicy build() { return new RecoveryPolicy(this); } + } +} diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/Whep.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/Whep.java index 690db9227..2a23b9c08 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/Whep.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/Whep.java @@ -137,6 +137,8 @@ public static final class Builder { private Gathering gathering = Gathering.TRICKLE; + private RecoveryPolicy recovery; + private Duration timeout = Duration.ofSeconds(15); @@ -267,6 +269,15 @@ public Builder gathering(Gathering gathering) { return this; } + /** + * Overrides the built-in ICE restart rule with a configurable policy. + * Recovery uses PATCH on this session; it never creates a new session. + */ + public Builder recovery(RecoveryPolicy policy) { + this.recovery = requireNonNull(policy, "policy"); + return this; + } + /** * @param timeout how long the session may take to be connected, and its * deletion to be answered; 15 seconds by default. @@ -343,7 +354,7 @@ public CompletableFuture play(WebRtc rtc) { try { return HttpSession.start(rtc, peer, endpoint, credentials, limit, peer.manual.preferCodecs(names), gathering, - PROTOCOL, Session::new); + PROTOCOL, recovery, Session::new); } catch (RuntimeException | Error e) { // Until the session has it, no one else would close the peer. diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/Whip.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/Whip.java index c95bced27..55233c635 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/Whip.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/Whip.java @@ -143,6 +143,8 @@ public static final class Builder { private Gathering gathering = Gathering.TRICKLE; + private RecoveryPolicy recovery; + private Duration timeout = Duration.ofSeconds(15); @@ -321,6 +323,15 @@ public Builder gathering(Gathering gathering) { return this; } + /** + * Overrides the built-in ICE restart rule with a configurable policy. + * Recovery uses PATCH on this session; it never creates a new session. + */ + public Builder recovery(RecoveryPolicy policy) { + this.recovery = requireNonNull(policy, "policy"); + return this; + } + /** * @param timeout how long the session may take to be connected, and its * deletion to be answered; 15 seconds by default. @@ -422,7 +433,7 @@ public CompletableFuture publish(WebRtc rtc) { CompletableFuture prepared = CompletableFuture.allOf(video, peer.manual.preferCodecs(names)); - return HttpSession.start(rtc, peer, endpoint, credentials, limit, prepared, gathering, PROTOCOL, + return HttpSession.start(rtc, peer, endpoint, credentials, limit, prepared, gathering, PROTOCOL, recovery, Session::new); } catch (RuntimeException | Error e) { diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpSessionTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpSessionTests.java index 8c7f0259a..e99774d43 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpSessionTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpSessionTests.java @@ -1031,6 +1031,32 @@ void refusedIceRestartKeepsSession() throws Exception { } } + @Test + void recoveryPolicyRetriesHttpFailures() throws Exception { + ManualTimer timer = new ManualTimer(); + WebRtc client = clientRuntime(builder -> builder.timer(timer)); + CompletableFuture retry = new CompletableFuture<>(); + CompletableFuture exhausted = new CompletableFuture<>(); + RecoveryPolicy policy = RecoveryPolicy.builder().maxAttempts(2).onEvent(event -> { + if (event.state() == RecoveryEvent.State.RETRYING) retry.complete(event); + if (event.state() == RecoveryEvent.State.EXHAUSTED) exhausted.complete(event); + }).build(); + try (TestHttpEndpoint endpoint = restartingEndpoint(new ArrayList<>())) { + endpoint.iceRestartStatus = 500; + Whep.Session session = await(Whep.from(endpoint.uri()).timeout(SESSION_TIMEOUT).recovery(policy).play(client)); + PeerImpl peer = (PeerImpl) session.peer(); + peer.control.execute(() -> peer.connectionChanged(dev.onvoid.webrtc.RTCPeerConnectionState.FAILED)); + assertEquals(1, await(retry).attempt()); + await(peer.withNative(c -> null)); // Retry has been scheduled on control. + assertEquals(1, timer.fire(Duration.ofSeconds(1))); + assertEquals(2, await(exhausted).attempt()); + assertEquals(2, endpoint.requests.stream().filter(r -> "*".equals(r.ifMatch)).count()); + assertEquals(PeerState.FAILED, peer.state()); + await(session.closeAsync()); + } + finally { client.close(); } + } + @Test void failedConnectionRestartsIce() throws Exception { List fragments = new CopyOnWriteArrayList<>(); diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/IceRecoveryTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/IceRecoveryTests.java new file mode 100644 index 000000000..415fb9b98 --- /dev/null +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/IceRecoveryTests.java @@ -0,0 +1,281 @@ +/* + * 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 static org.junit.jupiter.api.Assertions.*; +import static dev.onvoid.webrtc.client.RecoveryEvent.State.*; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; + +import dev.onvoid.webrtc.RTCIceServer; + +@Execution(ExecutionMode.SAME_THREAD) +class IceRecoveryTests { + private static final Duration GRACE = Duration.ofSeconds(2); + private static final Duration TIMEOUT = Duration.ofSeconds(15); + private final ManualExecutor control = new ManualExecutor(); + private final ManualTimer timer = new ManualTimer(); + private final AtomicBoolean closing = new AtomicBoolean(); + private final List events = new ArrayList<>(); + private final List> restarts = new ArrayList<>(); + private CompletableFuture> credentials = CompletableFuture.completedFuture(null); + private int usedServers; + + private IceRecovery recovery(RecoveryPolicy policy) { + return new IceRecovery(policy, control, timer, closing::get, () -> { + CompletableFuture result = new CompletableFuture<>(); + restarts.add(result); + return result; + }, new IceRecovery.Host() { + public CompletableFuture> servers(int attempt) { return credentials; } + public void useServers(List servers) { usedServers++; } + public void event(RecoveryEvent event) { events.add(event); } + }); + } + + private IceRecovery recovery() { return recovery(RecoveryPolicy.builder().build()); } + private void fire(Duration delay) { assertEquals(1, timer.fire(delay)); control.runAll(); } + private RecoveryEvent last() { return events.get(events.size() - 1); } + + @Test + void briefOutageRecovers() { + IceRecovery r = recovery(); + r.stateChanged(PeerState.DISCONNECTED); + assertEquals(WAITING, last().state()); + r.stateChanged(PeerState.CONNECTED); + assertEquals(RECOVERED, last().state()); + assertEquals(0, last().attempt()); + assertEquals(0, timer.fire(GRACE)); + assertTrue(restarts.isEmpty()); + } + + @Test + void graceStartsRestart() { + IceRecovery r = recovery(); + r.stateChanged(PeerState.DISCONNECTED); + r.stateChanged(PeerState.DISCONNECTED); + fire(GRACE); + assertEquals(1, restarts.size()); + assertEquals(ATTEMPTING, last().state()); + } + + @Test + void errorsDuringRestartDoNotOverlap() { + IceRecovery r = recovery(); + r.stateChanged(PeerState.FAILED); + control.runAll(); + r.stateChanged(PeerState.DISCONNECTED); + r.stateChanged(PeerState.FAILED); + assertEquals(1, restarts.size()); + restarts.get(0).completeExceptionally(new WebRtcException("Network unavailable")); + control.runAll(); + assertEquals(RETRYING, last().state()); + fire(Duration.ofSeconds(1)); + assertEquals(2, restarts.size()); + } + + @Test + void backoffEndsAtBudget() { + IceRecovery r = recovery(); + r.stateChanged(PeerState.FAILED); + control.runAll(); + for (int i = 0; i < 3; i++) { + restarts.get(i).completeExceptionally(new WebRtcException("Offline")); + control.runAll(); + if (i < 2) fire(Duration.ofSeconds(1L << i)); + } + assertEquals(EXHAUSTED, last().state()); + assertEquals(3, last().attempt()); + assertNotNull(last().cause()); + r.stateChanged(PeerState.FAILED); + r.stateChanged(PeerState.DISCONNECTED); + assertEquals(3, restarts.size()); + assertEquals(0, timer.scheduled(TIMEOUT)); + } + + @Test + void signalingSuccessStillNeedsConnectivity() { + IceRecovery r = recovery(); + r.stateChanged(PeerState.FAILED); + control.runAll(); + restarts.get(0).complete(null); + control.runAll(); + assertEquals(ATTEMPTING, last().state()); + fire(TIMEOUT); + assertEquals(RETRYING, last().state()); + fire(Duration.ofSeconds(1)); + assertEquals(2, restarts.size()); + } + + @Test + void timeoutWaitsForExchange() { + IceRecovery r = recovery(); + r.stateChanged(PeerState.FAILED); + control.runAll(); + fire(TIMEOUT); + assertEquals(0, timer.fire(Duration.ofSeconds(1))); + restarts.get(0).completeExceptionally(new WebRtcException("HTTP failed")); + control.runAll(); + fire(Duration.ofSeconds(1)); + assertEquals(2, restarts.size()); + } + + @Test + void closeCancelsRetry() { + IceRecovery r = recovery(); + r.stateChanged(PeerState.FAILED); + control.runAll(); + restarts.get(0).completeExceptionally(new WebRtcException("Offline")); + control.runAll(); + assertEquals(RETRYING, last().state()); + r.close(); + assertEquals(0, timer.fire(Duration.ofSeconds(1))); + control.runAll(); + assertEquals(1, restarts.size()); + } + + @Test + void closeWinsOverQueuedRetry() { + IceRecovery r = recovery(); + r.stateChanged(PeerState.FAILED); + control.runAll(); + restarts.get(0).completeExceptionally(new WebRtcException("Offline")); + control.runAll(); + assertEquals(1, timer.fire(Duration.ofSeconds(1))); + closing.set(true); // close() has been called, teardown is still queued. + control.runAll(); + assertEquals(1, restarts.size()); + } + + @Test + void lateCredentialsAreIgnored() { + credentials = new CompletableFuture<>(); + IceRecovery r = recovery(); + r.stateChanged(PeerState.FAILED); + fire(TIMEOUT); + credentials.complete(Collections.emptyList()); + control.runAll(); + assertEquals(0, usedServers); + assertTrue(restarts.isEmpty()); + credentials = CompletableFuture.completedFuture(Collections.emptyList()); + fire(Duration.ofSeconds(1)); + assertEquals(1, usedServers); + assertEquals(1, restarts.size()); + } + + @Test + void closeDuringCredentials() { + credentials = new CompletableFuture<>(); + IceRecovery r = recovery(); + r.stateChanged(PeerState.FAILED); + r.close(); + credentials.complete(Collections.emptyList()); + control.runAll(); + assertEquals(0, usedServers); + assertTrue(restarts.isEmpty()); + } + + @Test + void recoveryResetsBudget() { + IceRecovery r = recovery(RecoveryPolicy.builder().maxAttempts(1).build()); + r.stateChanged(PeerState.FAILED); + control.runAll(); + restarts.get(0).completeExceptionally(new WebRtcException("Offline")); + control.runAll(); + assertEquals(EXHAUSTED, last().state()); + r.stateChanged(PeerState.CONNECTED); + r.stateChanged(PeerState.FAILED); + control.runAll(); + assertEquals(2, restarts.size()); + assertEquals(1, last().attempt()); + } + + @Test + void recoveredExchangeCannotAffectNewOutage() { + IceRecovery r = recovery(); + r.stateChanged(PeerState.FAILED); + control.runAll(); + r.stateChanged(PeerState.CONNECTED); + r.stateChanged(PeerState.FAILED); + assertEquals(1, restarts.size()); + restarts.get(0).completeExceptionally(new WebRtcException("Old failure")); + control.runAll(); + assertEquals(2, restarts.size()); + assertEquals(ATTEMPTING, last().state()); + assertEquals(1, last().attempt()); + } + + @Test + void failedSkipsGrace() { + IceRecovery r = recovery(); + r.stateChanged(PeerState.DISCONNECTED); + r.stateChanged(PeerState.FAILED); + control.runAll(); + assertEquals(1, restarts.size()); + assertEquals(0, timer.fire(GRACE)); + } + + @Test + void oldExchangePreservesNewGrace() { + IceRecovery r = recovery(); + r.stateChanged(PeerState.FAILED); + control.runAll(); + r.stateChanged(PeerState.CONNECTED); + r.stateChanged(PeerState.DISCONNECTED); + restarts.get(0).complete(null); + control.runAll(); + assertEquals(1, restarts.size()); + fire(GRACE); + assertEquals(2, restarts.size()); + } + + @Test + void failedCredentialsUseBudget() { + credentials = new CompletableFuture<>(); + IceRecovery r = recovery(RecoveryPolicy.builder().maxAttempts(1).build()); + r.stateChanged(PeerState.FAILED); + credentials.completeExceptionally(new WebRtcException("Credential service unavailable")); + control.runAll(); + assertEquals(EXHAUSTED, last().state()); + assertEquals(1, last().attempt()); + assertTrue(restarts.isEmpty()); + } + + @Test + void policyValidatesAndCapsBackoff() { + assertThrows(IllegalArgumentException.class, () -> RecoveryPolicy.builder().maxAttempts(0)); + assertThrows(IllegalArgumentException.class, () -> RecoveryPolicy.builder().grace(Duration.ofSeconds(-1))); + assertThrows(IllegalArgumentException.class, () -> RecoveryPolicy.builder().attemptTimeout(Duration.ZERO)); + assertThrows(IllegalArgumentException.class, () -> RecoveryPolicy.builder().backoff(GRACE, Duration.ofSeconds(1))); + RecoveryPolicy p = RecoveryPolicy.builder().backoff(Duration.ofSeconds(1), Duration.ofSeconds(3)).build(); + assertEquals(Duration.ofSeconds(3), p.backoff(Integer.MAX_VALUE)); + RecoveryPolicy huge = RecoveryPolicy.builder().backoff(Duration.ofSeconds(Long.MAX_VALUE), + Duration.ofSeconds(Long.MAX_VALUE)).build(); + assertEquals(Duration.ofMillis(Long.MAX_VALUE), huge.backoff(2)); + assertThrows(IllegalStateException.class, () -> PeerOptions.builder().negotiation(Negotiation.MANUAL) + .recovery(p).build()); + } +} diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/PeerRecoveryTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/PeerRecoveryTests.java new file mode 100644 index 000000000..632d82565 --- /dev/null +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/PeerRecoveryTests.java @@ -0,0 +1,136 @@ +/* + * 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 static org.junit.jupiter.api.Assertions.*; + +import java.time.Duration; +import java.util.Collections; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import org.junit.jupiter.api.Test; + +import dev.onvoid.webrtc.RTCIceServer; +import dev.onvoid.webrtc.RTCPeerConnectionState; + +class PeerRecoveryTests extends ClientTestBase { + + @Test + void restartKeepsDataChannel() throws Exception { + CompletableFuture recovered = new CompletableFuture<>(); + RecoveryPolicy policy = RecoveryPolicy.builder().onEvent(event -> { + if (event.state() == RecoveryEvent.State.RECOVERED) recovered.complete(event); + }).build(); + AtomicReference calleeRef = new AtomicReference<>(); + CompletableFuture answeredRestart = new CompletableFuture<>(); + AtomicInteger answers = new AtomicInteger(); + PeerImpl caller = (PeerImpl) rtc.createPeer(PeerOptions.builder().recovery(policy) + .signaling(signal -> calleeRef.get().signal(signal)).build()); + Peer callee = rtc.createPeer(PeerOptions.builder().polite(true).signaling(signal -> { + caller.signal(signal); + if (signal.type() == SignalMessage.Type.ANSWER && answers.incrementAndGet() == 2) { + answeredRestart.complete(null); + } + }).build()); + calleeRef.set(callee); + CompletableFuture remote = new CompletableFuture<>(); + callee.onChannel(remote::complete); + DataChannel channel = caller.createChannel("survives-recovery"); + await(channel.whenOpen()); + DataChannel original = await(remote); + CompletableFuture message = new CompletableFuture<>(); + original.onMessage(value -> message.complete(value.text())); + String before = await(caller.withNative(c -> HttpIce.Fragment.of(c.getLocalDescription().sdp).ufrag)); + caller.control.execute(() -> caller.connectionChanged(RTCPeerConnectionState.FAILED)); + await(answeredRestart); + // The native connection stayed healthy in this test. Simulate the matching + // CONNECTED notification after the real restart's answer has been applied. + await(caller.withNative(c -> c.getSignalingState())); + caller.control.execute(() -> caller.connectionChanged(RTCPeerConnectionState.CONNECTED)); + assertEquals(1, await(recovered).attempt()); + assertNotEquals(before, await(caller.withNative(c -> HttpIce.Fragment.of(c.getLocalDescription().sdp).ufrag))); + await(channel.send("after-recovery")); + assertEquals("after-recovery", await(message)); + assertEquals(ChannelState.OPEN, original.state()); + } + + @Test + void refreshesServersOnEventExecutor() throws Exception { + CompletableFuture exhausted = new CompletableFuture<>(); + CompletableFuture requested = new CompletableFuture<>(); + CompletableFuture> credentials = new CompletableFuture<>(); + AtomicInteger calls = new AtomicInteger(); + ManualTimer timer = new ManualTimer(); + WebRtc client = WebRtc.builder().audio(AudioMode.HEADLESS).timer(timer).errorHandler(errors::add).build(); + try { + RecoveryPolicy policy = RecoveryPolicy.builder().maxAttempts(1) + .iceServers(attempt -> { + assertTrue(SerialExecutor.onEventThread()); + assertEquals(1, attempt); + calls.incrementAndGet(); + requested.complete(null); + return credentials; + }).onEvent(event -> { + assertTrue(SerialExecutor.onEventThread()); + if (event.state() == RecoveryEvent.State.EXHAUSTED) exhausted.complete(event); + }).attemptTimeout(Duration.ofSeconds(15)).build(); + PeerImpl peer = (PeerImpl) client.createPeer(PeerOptions.builder().signaling(message -> { }) + .recovery(policy).build()); + peer.control.execute(() -> peer.connectionChanged(RTCPeerConnectionState.FAILED)); + await(requested); + RTCIceServer turn = new RTCIceServer(); + turn.urls.add("turn:127.0.0.1:3478"); + turn.username = "refreshed"; + turn.password = "secret"; + // Complete on events, behind the provider; its callback posts to control. + CompletableFuture refreshed = new CompletableFuture<>(); + peer.events.execute(() -> { + credentials.complete(Collections.singletonList(turn)); + peer.control.execute(() -> refreshed.complete(null)); + }); + await(refreshed); + assertEquals("refreshed", await(peer.withNative(c -> c.getConfiguration().iceServers.get(0).username))); + assertEquals(1, timer.fire(Duration.ofSeconds(15))); + assertEquals(1, await(exhausted).attempt()); + assertEquals(1, calls.get()); + await(peer.closeAsync()); + } + finally { client.close(); } + } + + @Test + void closeIgnoresPendingCredentials() throws Exception { + CompletableFuture> credentials = new CompletableFuture<>(); + CompletableFuture requested = new CompletableFuture<>(); + RecoveryPolicy policy = RecoveryPolicy.builder().iceServers(attempt -> { + requested.complete(null); + return credentials; + }).build(); + PeerImpl peer = (PeerImpl) rtc.createPeer(PeerOptions.builder().signaling(message -> { }) + .recovery(policy).build()); + peer.control.execute(() -> peer.connectionChanged(RTCPeerConnectionState.FAILED)); + await(requested); + await(peer.closeAsync()); + credentials.complete(Collections.emptyList()); + CompletableFuture drained = new CompletableFuture<>(); + peer.control.execute(() -> drained.complete(null)); + await(drained); + assertEquals(PeerState.CLOSED, peer.state()); + } +}