From 9aaea48e1143e63586aa4fea83e150a4eef9a889 Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Sun, 1 Nov 2026 11:14:55 +0100 Subject: [PATCH] refactor: split operation chain and perfect negotiation out of PeerImpl --- .../webrtc/client/NegotiationSteps.java | 295 +++++++++ .../onvoid/webrtc/client/OperationChain.java | 321 ++++++++++ .../dev/onvoid/webrtc/client/PeerImpl.java | 575 +++--------------- .../webrtc/client/PerfectNegotiation.java | 201 ++++++ .../webrtc/client/OperationChainTests.java | 265 ++++++++ 5 files changed, 1158 insertions(+), 499 deletions(-) create mode 100644 webrtc/src/main/java/dev/onvoid/webrtc/client/NegotiationSteps.java create mode 100644 webrtc/src/main/java/dev/onvoid/webrtc/client/OperationChain.java create mode 100644 webrtc/src/main/java/dev/onvoid/webrtc/client/PerfectNegotiation.java create mode 100644 webrtc/src/test/java/dev/onvoid/webrtc/client/OperationChainTests.java diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/NegotiationSteps.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/NegotiationSteps.java new file mode 100644 index 000000000..4df2817b3 --- /dev/null +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/NegotiationSteps.java @@ -0,0 +1,295 @@ +/* + * 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.ArrayList; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.function.BooleanSupplier; +import java.util.function.Supplier; + +import dev.onvoid.webrtc.AddIceCandidateObserver; +import dev.onvoid.webrtc.CreateSessionDescriptionObserver; +import dev.onvoid.webrtc.RTCAnswerOptions; +import dev.onvoid.webrtc.RTCIceCandidate; +import dev.onvoid.webrtc.RTCIceGatheringState; +import dev.onvoid.webrtc.RTCOfferOptions; +import dev.onvoid.webrtc.RTCPeerConnection; +import dev.onvoid.webrtc.RTCSdpType; +import dev.onvoid.webrtc.RTCSessionDescription; +import dev.onvoid.webrtc.RTCSignalingState; +import dev.onvoid.webrtc.SetSessionDescriptionObserver; +import dev.onvoid.webrtc.internal.Timeouts; + +/** + * The calls into the connection that negotiation is made of, each as a step + * of the running operation of the {@link OperationChain}, so that its timeout + * fails them. WebRTC answers them on its own threads; the answers are posted + * to the control executor, where everything here is confined to. + */ +final class NegotiationSteps { + + private final SerialExecutor control; + + private final ScheduledExecutorService timer; + + private final OperationChain chain; + + private final Supplier connection; + + private final Duration gatheringTimeout; + + private final BooleanSupplier ignoringOffer; + + /** The remote candidates that came before a remote description. */ + private final List heldCandidates = new ArrayList<>(); + + private final List> gatheringWaiters = new ArrayList<>(); + + + /** + * @param control the control executor of the peer. + * @param timer schedules the end of waiting for gathering. + * @param chain the operations chain the steps belong to. + * @param connection the connection, once there is one. + * @param gatheringTimeout how long to wait for gathering to complete. + * @param ignoringOffer whether the peer ignored a remote offer, whose + * candidates then fail to be added, harmlessly. + */ + NegotiationSteps(SerialExecutor control, ScheduledExecutorService timer, OperationChain chain, + Supplier connection, Duration gatheringTimeout, BooleanSupplier ignoringOffer) { + this.control = control; + this.timer = timer; + this.chain = chain; + this.connection = connection; + this.gatheringTimeout = gatheringTimeout; + this.ignoringOffer = ignoringOffer; + } + + /** + * Applies the description WebRTC finds for the signaling state, an offer + * or an answer. + */ + CompletableFuture setLocal() { + CompletableFuture future = chain.step(); + connection.get().setLocalDescription(descriptionObserver(future, "Applying the local description failed")); + return future; + } + + CompletableFuture setLocal(RTCSessionDescription description) { + CompletableFuture future = chain.step(); + connection.get().setLocalDescription(description, + descriptionObserver(future, "Applying the local description failed")); + return future; + } + + CompletableFuture setRemote(RTCSessionDescription description) { + CompletableFuture future = chain.step(); + connection.get().setRemoteDescription(description, descriptionObserver(future, + "Applying the remote " + description.sdpType.name().toLowerCase() + " failed")); + return future; + } + + CompletableFuture createOffer() { + CompletableFuture future = chain.step(); + connection.get().createOffer(new RTCOfferOptions(), createObserver(future, "Creating the offer failed")); + return future; + } + + CompletableFuture createAnswer() { + CompletableFuture future = chain.step(); + connection.get().createAnswer(new RTCAnswerOptions(), createObserver(future, "Creating the answer failed")); + return future; + } + + /** + * Takes back what is pending of an offer/answer exchange, whichever side + * made the offer, so that signaling is stable again. + */ + CompletableFuture rollback() { + RTCSignalingState state = connection.get().getSignalingState(); + + if (state == RTCSignalingState.STABLE) { + return CompletableFuture.completedFuture(null); + } + + RTCSessionDescription description = new RTCSessionDescription(RTCSdpType.ROLLBACK, ""); + + return state == RTCSignalingState.HAVE_REMOTE_OFFER || state == RTCSignalingState.HAVE_LOCAL_PR_ANSWER + ? setRemote(description) + : setLocal(description); + } + + /** + * Adds a remote candidate, or holds it while there is no remote + * description to add it to. + */ + CompletableFuture addRemoteCandidate(RTCIceCandidate candidate) { + CompletableFuture future = chain.step(); + + if (connection.get().getRemoteDescription() == null) { + heldCandidates.add(new HeldCandidate(candidate, future)); + } + else { + addCandidate(candidate, future); + } + + return future; + } + + /** + * Adds the remote candidates held so far, once there is a remote + * description. + */ + void releaseHeldCandidates() { + List held = new ArrayList<>(heldCandidates); + heldCandidates.clear(); + + for (HeldCandidate candidate : held) { + addCandidate(candidate.candidate, candidate.future); + } + } + + /** + * Waits until gathering is complete, or the gathering timeout passed. + */ + CompletableFuture waitForGathering() { + if (connection.get().getIceGatheringState() == RTCIceGatheringState.COMPLETE) { + return CompletableFuture.completedFuture(null); + } + + CompletableFuture future = chain.step(); + gatheringWaiters.add(future); + + // A STUN or TURN server that cannot be reached holds up the end of + // gathering for long; the description then goes with what there is. + try { + timer.schedule(() -> control.execute(() -> { + if (gatheringWaiters.remove(future)) { + future.complete(null); + } + }), Timeouts.toMillis(gatheringTimeout), TimeUnit.MILLISECONDS); + } + catch (RejectedExecutionException e) { + // The runtime is closing and has no timer left to wait with. + gatheringWaiters.remove(future); + future.complete(null); + } + + return future; + } + + /** + * Ends the waiting for gathering, which WebRTC reports complete. + */ + void gatheringComplete() { + List> waiters = new ArrayList<>(gatheringWaiters); + gatheringWaiters.clear(); + + waiters.forEach(waiter -> waiter.complete(null)); + } + + /** + * Fails the waiting for gathering and the candidates held, once the peer + * is closing. + */ + void close(PeerClosedException error) { + for (CompletableFuture waiter : gatheringWaiters) { + waiter.completeExceptionally(error); + } + gatheringWaiters.clear(); + + for (HeldCandidate candidate : heldCandidates) { + candidate.future.completeExceptionally(error); + } + heldCandidates.clear(); + } + + private void addCandidate(RTCIceCandidate candidate, CompletableFuture future) { + connection.get().addIceCandidate(candidate, new AddIceCandidateObserver() { + + @Override + public void onSuccess() { + control.execute(() -> future.complete(null)); + } + + @Override + public void onFailure(String error) { + control.execute(() -> { + if (ignoringOffer.getAsBoolean()) { + // A candidate of an offer this peer ignored. + future.complete(null); + } + else { + future.completeExceptionally(new NegotiationException("Adding a remote candidate failed: " + + error)); + } + }); + } + }); + } + + private SetSessionDescriptionObserver descriptionObserver(CompletableFuture future, String message) { + return new SetSessionDescriptionObserver() { + + @Override + public void onSuccess() { + control.execute(() -> future.complete(null)); + } + + @Override + public void onFailure(String error) { + control.execute(() -> future.completeExceptionally(new NegotiationException(message + ": " + error))); + } + }; + } + + private CreateSessionDescriptionObserver createObserver( + CompletableFuture future, String message) { + return new CreateSessionDescriptionObserver() { + + @Override + public void onSuccess(RTCSessionDescription description) { + control.execute(() -> future.complete(description)); + } + + @Override + public void onFailure(String error) { + control.execute(() -> future.completeExceptionally(new NegotiationException(message + ": " + error))); + } + }; + } + + + + private static final class HeldCandidate { + + final RTCIceCandidate candidate; + + final CompletableFuture future; + + + HeldCandidate(RTCIceCandidate candidate, CompletableFuture future) { + this.candidate = candidate; + this.future = future; + } + } +} diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/OperationChain.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/OperationChain.java new file mode 100644 index 000000000..fc5c723a8 --- /dev/null +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/OperationChain.java @@ -0,0 +1,321 @@ +/* + * 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.ArrayDeque; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.function.BiConsumer; +import java.util.function.Supplier; + +import dev.onvoid.webrtc.internal.Timeouts; + +/** + * The operations chain of a peer: runs each operation once the one before + * finished, as the standard does with the changes it chains. + *

+ * Everything here is confined to the control executor of the peer: an + * operation is started there, and its result completes there. An operation + * that WebRTC does not finish within the operation timeout fails with a + * {@link TimeoutException}; the chain then has the host bring signaling back + * to stable before the next operation starts, and gives the peer up when + * that fails too, or does not finish within another timeout. + */ +final class OperationChain { + + /** + * What the chain needs of the peer it orders the operations of. Called + * on the control executor. + */ + interface Host { + + /** + * @return whether the peer is closed, so that no operation may run. + */ + boolean isClosed(); + + /** + * @return the error that operations fail with once the peer closed. + */ + PeerClosedException closedError(); + + /** + * Brings signaling back to stable after an operation timed out, + * through steps of that operation. + * + * @return a future that completes on the control executor. + */ + CompletableFuture rollback(); + + /** + * Gives the peer up, once its signaling cannot be brought back to + * stable, and closes it. + */ + void abandon(); + } + + private final SerialExecutor control; + + private final ScheduledExecutorService timer; + + private final Duration timeout; + + private final String owner; + + private final Host host; + + private final ArrayDeque queued = new ArrayDeque<>(); + + private boolean running; + + private CompletableFuture runningOperation; + + /** The unfinished steps of the running operation. */ + private Operation activeOperation; + + + /** + * @param control the control executor of the peer. + * @param timer schedules the operation timeouts. + * @param timeout how long WebRTC may take for an operation. + * @param owner names the peer in errors. + * @param host the peer. + */ + OperationChain(SerialExecutor control, ScheduledExecutorService timer, Duration timeout, String owner, + Host host) { + this.control = control; + this.timer = timer; + this.timeout = timeout; + this.owner = owner; + this.host = host; + } + + /** + * Runs an operation once the ones queued before it finished. It fails + * with a {@link PeerClosedException} when the peer closed first, and with + * a {@link TimeoutException} when WebRTC never finishes it. + * + * @return a future that completes on the control executor. + */ + CompletableFuture enqueue(Supplier> operation) { + return enqueue(operation, (value, error) -> { }); + } + + /** + * Runs an operation as {@link #enqueue(Supplier)} does. + * + * @param finished runs once the operation finished and signaling is back + * to stable, before the next operation starts; what it + * throws fails the result. + */ + CompletableFuture enqueue(Supplier> operation, BiConsumer finished) { + CompletableFuture result = new CompletableFuture<>(); + + queued.add(() -> start(operation, finished, result)); + + runNext(); + + return result; + } + + /** + * Creates the future of a step of the running operation, such as a + * description WebRTC is applying, which the operation's timeout fails + * so that the stages depending on it cannot act on a late result. + * + * @return a future the caller completes on the control executor. + */ + CompletableFuture step() { + CompletableFuture future = new CompletableFuture<>(); + Operation scope = activeOperation; + + if (scope != null) { + scope.steps.add(future); + future.whenComplete((value, error) -> scope.steps.remove(future)); + } + + return future; + } + + /** + * Fails the running operation and its unfinished steps, once the peer is + * closing. Those queued behind it fail as they start. + */ + void close(PeerClosedException error) { + if (activeOperation != null) { + for (CompletableFuture step : new ArrayList<>(activeOperation.steps)) { + step.completeExceptionally(error); + } + } + if (runningOperation != null) { + runningOperation.completeExceptionally(error); + } + } + + private void start(Supplier> operation, BiConsumer finished, + CompletableFuture result) { + Operation scope = new Operation(); + activeOperation = scope; + CompletableFuture current; + + if (host.isClosed()) { + current = CompletableFuture.failedFuture(host.closedError()); + } + else { + try { + current = operation.get(); + } + catch (Throwable e) { + current = CompletableFuture.failedFuture(e); + } + } + + runningOperation = current; + + // One that is done already, as on a closed peer, needs no timeout. + ScheduledFuture timeout = current.isDone() ? null : timeOut(current, scope); + + current.whenComplete((value, error) -> control.execute(() -> { + if (timeout != null) { + timeout.cancel(false); + } + + CompletableFuture stable = scope.expired && !host.isClosed() + ? host.rollback() + : CompletableFuture.completedFuture(null); + + stable.whenComplete((ignored, cleanupError) -> control.execute( + () -> finish(scope, value, cleanupError == null ? error : cleanupError, cleanupError != null, + finished, result))); + })); + } + + private void finish(Operation scope, T value, Throwable error, boolean unrecoverable, + BiConsumer finished, CompletableFuture result) { + if (unrecoverable && !host.isClosed()) { + // A peer whose signaling cannot be restored must not run another + // negotiation against the abandoned description. + host.abandon(); + } + if (scope.cleanupTimeout != null) { + scope.cleanupTimeout.cancel(false); + } + + activeOperation = null; + runningOperation = null; + running = false; + + Throwable failure = error; + + try { + finished.accept(value, failure); + } + catch (Throwable e) { + failure = e; + } + + PeerImpl.complete(result, value, failure); + + runNext(); + } + + /** + * Fails a running operation once the operation timeout has passed. + * + * @return the timeout, or null once the runtime has stopped its timer. + */ + private ScheduledFuture timeOut(CompletableFuture operation, Operation scope) { + try { + return timer.schedule(() -> control.execute(() -> expire(operation, scope)), + Timeouts.toMillis(timeout), TimeUnit.MILLISECONDS); + } + catch (RejectedExecutionException e) { + // The runtime is closing: control tasks queued before still run, + // and it fails the futures they leave open. + return null; + } + } + + private void expire(CompletableFuture operation, Operation scope) { + if (operation.isDone()) { + return; + } + + scope.expired = true; + + // Recovery calls are native operations too. If they stop answering, + // close the peer instead of leaving its queue open. + try { + scope.cleanupTimeout = timer.schedule(() -> control.execute(() -> { + if (activeOperation == scope && !host.isClosed()) { + host.abandon(); + } + }), Timeouts.toMillis(timeout), TimeUnit.MILLISECONDS); + } + catch (RejectedExecutionException e) { + // Runtime shutdown closes the peer and its unfinished steps. + } + + TimeoutException error = new TimeoutException("WebRTC did not finish an operation of " + + owner + " within " + timeout); + + // Fail the awaited steps, so dependent stages cannot apply a late + // answer. Their error paths finish before the queue moves. + List> steps = new ArrayList<>(scope.steps); + + for (CompletableFuture step : steps) { + step.completeExceptionally(error); + } + if (steps.isEmpty()) { + operation.completeExceptionally(error); + } + } + + private void runNext() { + if (running) { + return; + } + + Runnable next = queued.poll(); + + if (next != null) { + running = true; + next.run(); + } + } + + + + /** The unfinished steps of an operation, and whether it timed out. */ + private static final class Operation { + + final Set> steps = new HashSet<>(); + + boolean expired; + + ScheduledFuture cleanupTimeout; + } +} 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 df16b7a72..12ff6a0f7 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java @@ -19,7 +19,6 @@ import static java.util.Objects.requireNonNull; import java.time.Duration; -import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -38,10 +37,8 @@ import java.util.concurrent.CompletionException; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ExecutionException; -import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BiConsumer; @@ -50,17 +47,13 @@ import java.util.function.Supplier; import java.util.function.UnaryOperator; -import dev.onvoid.webrtc.AddIceCandidateObserver; -import dev.onvoid.webrtc.CreateSessionDescriptionObserver; import dev.onvoid.webrtc.PeerConnectionObserver; -import dev.onvoid.webrtc.RTCAnswerOptions; import dev.onvoid.webrtc.RTCConfiguration; import dev.onvoid.webrtc.RTCDataChannel; import dev.onvoid.webrtc.RTCEncodedFrameTransformer; import dev.onvoid.webrtc.RTCIceCandidate; import dev.onvoid.webrtc.RTCIceGatheringState; import dev.onvoid.webrtc.RTCIceServer; -import dev.onvoid.webrtc.RTCOfferOptions; import dev.onvoid.webrtc.RTCPeerConnection; import dev.onvoid.webrtc.RTCPeerConnectionState; import dev.onvoid.webrtc.RTCRtpCapabilities; @@ -73,9 +66,7 @@ import dev.onvoid.webrtc.RTCSdpType; import dev.onvoid.webrtc.RTCSessionDescription; import dev.onvoid.webrtc.RTCSignalingState; -import dev.onvoid.webrtc.SetSessionDescriptionObserver; import dev.onvoid.webrtc.client.internal.EncodedFrames; -import dev.onvoid.webrtc.internal.Timeouts; import dev.onvoid.webrtc.media.MediaStream; import dev.onvoid.webrtc.media.MediaStreamTrack; import dev.onvoid.webrtc.media.MediaType; @@ -92,8 +83,11 @@ * told so far. Neither ever waits for the other, and nothing on a WebRTC * thread waits for either, so no handler can deadlock the connection. *

- * Changes that the standard runs on its operations chain go through {@link - * #enqueue}, which starts one only once the one before finished. + * Changes that the standard runs on its operations chain go through the + * {@link OperationChain}, which starts one only once the one before finished, + * made of the {@link NegotiationSteps}. The automatic negotiation is the + * {@link PerfectNegotiation}; all three are confined to the control executor + * as well. */ final class PeerImpl implements Peer { @@ -103,9 +97,6 @@ final class PeerImpl implements Peer { EncodedFrames.register(new EncodedFramesAccess()); } - /** How long an impolite peer waits for an answer after it ignored an offer. */ - private static final long COLLISION_TIMEOUT_MS = 5000; - /** * The codecs that go along with those a session names: retransmission, * redundancy, FEC, comfort noise and DTMF, which serve the media codecs. @@ -144,28 +135,13 @@ final class PeerImpl implements Peer { private boolean closed; - private final ArrayDeque operations = new ArrayDeque<>(); - - private boolean operationRunning; - - private CompletableFuture runningOperation; - - /** The unfinished steps of the current operation, owned by control. */ - private Operation activeOperation; - private boolean teardownStarted; - private boolean negotiationQueued; - - private boolean ignoreOffer; - - private int remoteAnswers; + private final OperationChain chain; - private ScheduledFuture collisionCheck; + private final NegotiationSteps steps; - private final List heldCandidates = new ArrayList<>(); - - private final List> gatheringWaiters = new ArrayList<>(); + private final PerfectNegotiation automatic; private final Map remoteTrackById = new HashMap<>(); @@ -227,6 +203,10 @@ final class PeerImpl implements Peer { this.trackHandlers = new Handlers<>(rtc::reportError); this.channelHandlers = new Handlers<>(rtc::reportError); this.errorHandlers = new Handlers<>(rtc::reportError); + this.chain = new OperationChain(control, rtc.timer, rtc.operationTimeout, name, new ChainHost()); + this.steps = new NegotiationSteps(control, rtc.timer, chain, () -> connection, options.gatheringTimeout, + this::ignoresOffer); + this.automatic = new PerfectNegotiation(this, options, chain, steps); rtc.track(connected, events); rtc.track(closedFuture, events); @@ -318,7 +298,7 @@ public PeerState state() { public void signal(SignalMessage message) { requireNonNull(message, "message"); - control.execute(() -> handleSignal(message)); + control.execute(() -> automatic.signal(message)); } @Override @@ -498,7 +478,7 @@ public Negotiator negotiator() { * @return a future with the offer, which {@link #applyLocal} applies. */ CompletableFuture offer() { - return negotiator.run(this::createOffer); + return negotiator.run(steps::createOffer); } /** @@ -506,7 +486,7 @@ CompletableFuture offer() { * candidates for it. */ CompletableFuture applyLocal(RTCSessionDescription description) { - return negotiator.run(() -> setLocal(description)); + return negotiator.run(() -> steps.setLocal(description)); } /** @@ -737,16 +717,16 @@ CompletableFuture restartIce( // Keep the server's offerer role (including its DTLS role and // media sections). Create an offer only to obtain fresh local // ICE credentials; do not apply it or change signaling roles. - return createOffer().thenCompose(offer -> onControl(exchange.apply(offer)) - .thenCompose(change -> setRemote(new RTCSessionDescription( + return steps.createOffer().thenCompose(offer -> onControl(exchange.apply(offer)) + .thenCompose(change -> steps.setRemote(new RTCSessionDescription( RTCSdpType.OFFER, change.apply(remote.sdp)))) .thenCompose(ignored -> { // Reapplying the server's offer can create transceivers // for media the original answer rejected. stopTransceivers(midsNotReceived(remote.sdp)); - return createAnswer(); + return steps.createAnswer(); }) - .thenCompose(answer -> setLocal(new RTCSessionDescription(RTCSdpType.ANSWER, + .thenCompose(answer -> steps.setLocal(new RTCSessionDescription(RTCSdpType.ANSWER, HttpIce.Fragment.of(offer.sdp).applyCredentialsTo(answer.sdp))))) .handle((applied, error) -> { if (error == null) { @@ -756,19 +736,19 @@ CompletableFuture restartIce( if (closed || connection.getSignalingState() != RTCSignalingState.HAVE_REMOTE_OFFER) { return failed; } - return setRemote(new RTCSessionDescription(RTCSdpType.ROLLBACK, "")) + return steps.setRemote(new RTCSessionDescription(RTCSdpType.ROLLBACK, "")) .handle((ignored, rollbackError) -> null) .thenCompose(ignored -> failed); }).thenCompose(result -> result); } - return createOffer() - .thenCompose(offer -> setLocal(offer).thenApply(ignored -> offer)) + return steps.createOffer() + .thenCompose(offer -> steps.setLocal(offer).thenApply(ignored -> offer)) .thenCompose(offer -> onControl(exchange.apply(offer))) .thenCompose(change -> { RTCSessionDescription answer = connection.getRemoteDescription(); - return setRemote(new RTCSessionDescription(RTCSdpType.ANSWER, change.apply(answer.sdp))); + return steps.setRemote(new RTCSessionDescription(RTCSdpType.ANSWER, change.apply(answer.sdp))); }) .handle((applied, error) -> { if (error == null) { @@ -782,7 +762,7 @@ CompletableFuture restartIce( } // Back to the ICE session before, which the server keeps. - return setLocal(new RTCSessionDescription(RTCSdpType.ROLLBACK, "")) + return steps.setLocal(new RTCSessionDescription(RTCSdpType.ROLLBACK, "")) .handle((ignored, rollbackError) -> null) .thenCompose(ignored -> failed); }) @@ -795,7 +775,7 @@ CompletableFuture restartIce( * executor, or fails once the peer is closed. */ private CompletableFuture onControl(CompletableFuture future) { - CompletableFuture result = operationStep(); + CompletableFuture result = chain.step(); future.whenComplete((value, error) -> control.execute(() -> complete(result, value, error), () -> result.completeExceptionally(closedError()))); @@ -839,18 +819,18 @@ CompletableFuture answerInstead(RTCSessionDescription off // An offer created but not applied yet needs no taking back. CompletableFuture stable = connection.getSignalingState() == RTCSignalingState.STABLE ? CompletableFuture.completedFuture(null) - : setLocal(new RTCSessionDescription(RTCSdpType.ROLLBACK, "")); + : steps.setLocal(new RTCSessionDescription(RTCSdpType.ROLLBACK, "")); return stable - .thenCompose(ignored -> setRemote(offer)) + .thenCompose(ignored -> steps.setRemote(offer)) .thenCompose(ignored -> { stopTransceivers(rejected); // The offer made transceivers of its own. applyCodecs(); - releaseHeldCandidates(); - return createAnswer(); + steps.releaseHeldCandidates(); + return steps.createAnswer(); }) - .thenCompose(this::setLocal) + .thenCompose(steps::setLocal) .thenCompose(ignored -> negotiator.gathered(gathering)); }); } @@ -1009,7 +989,7 @@ public CompletableFuture withNative(Function action CompletableFuture result = new CompletableFuture<>(); - control.execute(() -> enqueue(() -> CompletableFuture.completedFuture(action.apply(connection))) + control.execute(() -> chain.enqueue(() -> CompletableFuture.completedFuture(action.apply(connection))) .whenComplete((value, error) -> complete(result, value, error))); return toPublic(result); @@ -1218,6 +1198,10 @@ boolean isClosed() { return closed; } + private boolean ignoresOffer() { + return automatic.ignoresOffer(); + } + static Throwable unwrap(Throwable error) { while ((error instanceof CompletionException || error instanceof ExecutionException) && error.getCause() != null) { @@ -1258,307 +1242,19 @@ private LocalTrackImpl checkTrack(LocalTrack track) { return (LocalTrackImpl) track; } - // Operations, on the control executor. - /** - * Runs an operation once the ones queued before it finished. It fails - * with a {@link PeerClosedException} when the peer closed first, and with - * a {@link TimeoutException} when WebRTC never finishes it. - * - * @return a future that completes on the control executor. + * @return the connection, or null before it is created. Only on the + * control executor. */ - private CompletableFuture enqueue(Supplier> operation) { - return enqueue(operation, (value, error) -> { }); - } - - private CompletableFuture enqueue(Supplier> operation, - BiConsumer finished) { - CompletableFuture result = new CompletableFuture<>(); - - operations.add(() -> { - Operation scope = new Operation(); - activeOperation = scope; - CompletableFuture running; - - if (closed) { - running = new CompletableFuture<>(); - running.completeExceptionally(closedError()); - } - else { - try { - running = operation.get(); - } - catch (Throwable e) { - running = new CompletableFuture<>(); - running.completeExceptionally(e); - } - } - - CompletableFuture current = running; - runningOperation = current; - - // One that is done already, as on a closed peer, needs no timeout. - ScheduledFuture timeout = current.isDone() ? null : timeOut(current, scope); - - current.whenComplete((value, error) -> control.execute(() -> { - if (timeout != null) { - timeout.cancel(false); - } - - CompletableFuture stable = scope.expired && !closed ? rollback() : - CompletableFuture.completedFuture(null); - stable.whenComplete((ignored, cleanupError) -> control.execute(() -> { - Throwable failure = cleanupError == null ? error : cleanupError; - if (cleanupError != null && !closed) { - // A peer whose signaling cannot be restored must not run - // another negotiation against the abandoned description. - teardown(); - } - if (scope.cleanupTimeout != null) { - scope.cleanupTimeout.cancel(false); - } - activeOperation = null; - runningOperation = null; - operationRunning = false; - try { - finished.accept(value, failure); - } - catch (Throwable e) { - failure = e; - } - complete(result, value, failure); - runNextOperation(); - })); - })); - }); - - runNextOperation(); - - return result; + RTCPeerConnection connection() { + return connection; } /** - * Fails a running operation once the operation timeout has passed. - * - * @return the timeout, or null once the runtime has stopped its timer. - */ - private ScheduledFuture timeOut(CompletableFuture operation, Operation scope) { - try { - return rtc.timer.schedule(() -> control.execute(() -> { - if (operation.isDone()) { - return; - } - scope.expired = true; - // Recovery calls are native operations too. If they stop - // answering, close the peer instead of leaving its queue open. - try { - scope.cleanupTimeout = rtc.timer.schedule(() -> control.execute(() -> { - if (activeOperation == scope && !closed) { - teardown(); - } - }), Timeouts.toMillis(rtc.operationTimeout), TimeUnit.MILLISECONDS); - } - catch (RejectedExecutionException e) { - // Runtime shutdown closes the peer and its unfinished steps. - } - TimeoutException error = new TimeoutException("WebRTC did not finish an operation of " - + name + " within " + rtc.operationTimeout); - // Fail the awaited steps, so dependent stages cannot apply a - // late answer. Their error paths finish before the queue moves. - List> steps = new ArrayList<>(scope.steps); - for (CompletableFuture step : steps) { - step.completeExceptionally(error); - } - if (steps.isEmpty()) { - operation.completeExceptionally(error); - } - }), - Timeouts.toMillis(rtc.operationTimeout), TimeUnit.MILLISECONDS); - } - catch (RejectedExecutionException e) { - // The runtime is closing: control tasks queued before still run, - // and it fails the futures they leave open. - return null; - } - } - - private CompletableFuture rollback() { - RTCSignalingState state = connection.getSignalingState(); - if (state == RTCSignalingState.STABLE) { - return CompletableFuture.completedFuture(null); - } - RTCSessionDescription description = new RTCSessionDescription(RTCSdpType.ROLLBACK, ""); - return state == RTCSignalingState.HAVE_REMOTE_OFFER || state == RTCSignalingState.HAVE_LOCAL_PR_ANSWER - ? setRemote(description) : setLocal(description); - } - - private CompletableFuture operationStep() { - CompletableFuture future = new CompletableFuture<>(); - Operation scope = activeOperation; - if (scope != null) { - scope.steps.add(future); - future.whenComplete((value, error) -> scope.steps.remove(future)); - } - return future; - } - - private static final class Operation { - final Set> steps = new HashSet<>(); - boolean expired; - ScheduledFuture cleanupTimeout; - } - - private void runNextOperation() { - if (operationRunning) { - return; - } - - Runnable next = operations.poll(); - - if (next != null) { - operationRunning = true; - next.run(); - } - } - - private CompletableFuture setLocal() { - CompletableFuture future = operationStep(); - connection.setLocalDescription(descriptionObserver(future, "Applying the local description failed")); - return future; - } - - private CompletableFuture setLocal(RTCSessionDescription description) { - CompletableFuture future = operationStep(); - connection.setLocalDescription(description, descriptionObserver(future, "Applying the local description failed")); - return future; - } - - private CompletableFuture setRemote(RTCSessionDescription description) { - CompletableFuture future = operationStep(); - connection.setRemoteDescription(description, descriptionObserver(future, - "Applying the remote " + description.sdpType.name().toLowerCase() + " failed")); - return future; - } - - private CompletableFuture createOffer() { - CompletableFuture future = operationStep(); - connection.createOffer(new RTCOfferOptions(), createObserver(future, "Creating the offer failed")); - return future; - } - - private CompletableFuture createAnswer() { - CompletableFuture future = operationStep(); - connection.createAnswer(new RTCAnswerOptions(), createObserver(future, "Creating the answer failed")); - return future; - } - - private SetSessionDescriptionObserver descriptionObserver(CompletableFuture future, String message) { - return new SetSessionDescriptionObserver() { - - @Override - public void onSuccess() { - control.execute(() -> future.complete(null)); - } - - @Override - public void onFailure(String error) { - control.execute(() -> future.completeExceptionally(new NegotiationException(message + ": " + error))); - } - }; - } - - private CreateSessionDescriptionObserver createObserver( - CompletableFuture future, String message) { - return new CreateSessionDescriptionObserver() { - - @Override - public void onSuccess(RTCSessionDescription description) { - control.execute(() -> future.complete(description)); - } - - @Override - public void onFailure(String error) { - control.execute(() -> future.completeExceptionally(new NegotiationException(message + ": " + error))); - } - }; - } - - /** - * Adds a remote candidate, or holds it while there is no remote - * description to add it to. + * Sends the local description through the signaling. On the control + * executor. */ - private CompletableFuture addRemoteCandidate(RTCIceCandidate candidate) { - CompletableFuture future = operationStep(); - - if (connection.getRemoteDescription() == null) { - heldCandidates.add(new HeldCandidate(candidate, future)); - } - else { - addCandidate(candidate, future); - } - - return future; - } - - private void addCandidate(RTCIceCandidate candidate, CompletableFuture future) { - connection.addIceCandidate(candidate, new AddIceCandidateObserver() { - - @Override - public void onSuccess() { - control.execute(() -> future.complete(null)); - } - - @Override - public void onFailure(String error) { - control.execute(() -> { - if (ignoreOffer) { - // A candidate of an offer this peer ignored. - future.complete(null); - } - else { - future.completeExceptionally(new NegotiationException("Adding a remote candidate failed: " + error)); - } - }); - } - }); - } - - private void releaseHeldCandidates() { - List held = new ArrayList<>(heldCandidates); - heldCandidates.clear(); - - for (HeldCandidate candidate : held) { - addCandidate(candidate.candidate, candidate.future); - } - } - - private CompletableFuture waitForGathering() { - if (connection.getIceGatheringState() == RTCIceGatheringState.COMPLETE) { - return CompletableFuture.completedFuture(null); - } - - CompletableFuture future = operationStep(); - gatheringWaiters.add(future); - - // A STUN or TURN server that cannot be reached holds up the end of - // gathering for long; the description then goes with what there is. - try { - rtc.timer.schedule(() -> control.execute(() -> { - if (gatheringWaiters.remove(future)) { - future.complete(null); - } - }), Timeouts.toMillis(options.gatheringTimeout), TimeUnit.MILLISECONDS); - } - catch (RejectedExecutionException e) { - // The runtime is closing and has no timer left to wait with. - gatheringWaiters.remove(future); - future.complete(null); - } - - return future; - } - - private void sendLocalDescription() { + void sendLocalDescription() { send(SignalMessage.of(connection.getLocalDescription())); } @@ -1577,116 +1273,6 @@ private void send(SignalMessage message) { }); } - private void reportFailure(Object value, Throwable error) { - if (error != null && !(unwrap(error) instanceof PeerClosedException)) { - deliverError(asWebRtcException(error, "Negotiation of " + name + " failed")); - } - } - - // Automatic negotiation: perfect negotiation, on the control executor. - - private void onNegotiationNeeded() { - if (closed || options.negotiation != Negotiation.AUTOMATIC || negotiationQueued) { - return; - } - - negotiationQueued = true; - - enqueue(() -> { - negotiationQueued = false; - - if (connection.getSignalingState() != RTCSignalingState.STABLE) { - // WebRTC asks again once the exchange under way is done. - return CompletableFuture.completedFuture(null); - } - - return setLocal().thenRun(this::sendLocalDescription); - }).whenComplete(this::reportFailure); - } - - private void handleSignal(SignalMessage message) { - if (closed) { - return; - } - - switch (message.type()) { - case OFFER: - case ANSWER: - if (options.negotiation == Negotiation.MANUAL) { - deliverError(new NegotiationException("The peer " + name + " negotiates by hand. " - + "Apply descriptions through Peer.negotiator(), not Peer.signal()")); - return; - } - - enqueue(() -> applyRemoteDescription(message.description())) - .whenComplete(this::reportFailure); - break; - - case CANDIDATE: - enqueue(() -> ignoreOffer - ? CompletableFuture.completedFuture(null) - : addRemoteCandidate(message.candidate())) - .whenComplete(this::reportFailure); - break; - - default: - // WebRTC needs no end of candidates. - break; - } - } - - private CompletableFuture applyRemoteDescription(RTCSessionDescription description) { - boolean offer = description.sdpType == RTCSdpType.OFFER; - boolean collision = offer && connection.getSignalingState() != RTCSignalingState.STABLE; - - ignoreOffer = !options.polite && collision; - - if (ignoreOffer) { - // The polite peer gives way and answers this peer's offer instead. - watchCollision(); - return CompletableFuture.completedFuture(null); - } - - // A polite peer's own pending offer is rolled back implicitly. - return setRemote(description).thenCompose(ignored -> { - releaseHeldCandidates(); - - if (!offer) { - remoteAnswers++; - return CompletableFuture.completedFuture(null); - } - - return setLocal().thenRun(this::sendLocalDescription); - }); - } - - /** - * Tells the application when the remote peer never answered the offer this - * peer kept, which happens when both peers are impolite. - */ - private void watchCollision() { - if (collisionCheck != null) { - return; - } - - int answers = remoteAnswers; - - try { - collisionCheck = rtc.timer.schedule(() -> control.execute(() -> { - collisionCheck = null; - - if (!closed && remoteAnswers == answers - && connection.getSignalingState() == RTCSignalingState.HAVE_LOCAL_OFFER) { - deliverError(new NegotiationException("Both peers sent an offer at once, and both are impolite, " - + "so neither gives way. Build exactly one of them with PeerOptions.Builder.polite(true)")); - } - }), COLLISION_TIMEOUT_MS, TimeUnit.MILLISECONDS); - } - catch (RejectedExecutionException e) { - // The runtime is closing, and the peer with it. - } - } - // What WebRTC reports, on the control executor. private void connectionChanged(RTCPeerConnectionState nativeState) { @@ -1702,10 +1288,7 @@ private void connectionChanged(RTCPeerConnectionState nativeState) { private void gatheringChanged(RTCIceGatheringState gatheringState) { if (gatheringState == RTCIceGatheringState.COMPLETE) { - List> waiters = new ArrayList<>(gatheringWaiters); - gatheringWaiters.clear(); - - waiters.forEach(waiter -> waiter.complete(null)); + steps.gatheringComplete(); Runnable listener = gatheredListener; @@ -1823,28 +1406,9 @@ private void teardown() { PeerClosedException error = closedError(); - if (activeOperation != null) { - for (CompletableFuture step : new ArrayList<>(activeOperation.steps)) { - step.completeExceptionally(error); - } - } - if (runningOperation != null) { - runningOperation.completeExceptionally(error); - } - if (collisionCheck != null) { - collisionCheck.cancel(false); - collisionCheck = null; - } - - for (CompletableFuture waiter : gatheringWaiters) { - waiter.completeExceptionally(error); - } - gatheringWaiters.clear(); - - for (HeldCandidate candidate : heldCandidates) { - candidate.future.completeExceptionally(error); - } - heldCandidates.clear(); + chain.close(error); + automatic.close(); + steps.close(error); for (DataChannelImpl channel : new ArrayList<>(channels)) { channel.closeFromPeer(error); @@ -1972,7 +1536,7 @@ public void onIceGatheringChange(RTCIceGatheringState state) { @Override public void onRenegotiationNeeded() { - control.execute(PeerImpl.this::onNegotiationNeeded); + control.execute(automatic::negotiationNeeded); } @Override @@ -2014,8 +1578,8 @@ public CompletableFuture createOffer() { public CompletableFuture createOffer(Gathering gathering) { requireNonNull(gathering, "gathering"); - return run(() -> PeerImpl.this.createOffer() - .thenCompose(PeerImpl.this::setLocal) + return run(() -> steps.createOffer() + .thenCompose(steps::setLocal) .thenCompose(ignored -> gathered(gathering))); } @@ -2033,12 +1597,12 @@ public CompletableFuture answer(RTCSessionDescription off throw new IllegalArgumentException("Expected an offer, got " + offer.sdpType); } - return run(() -> setRemote(offer) + return run(() -> steps.setRemote(offer) .thenCompose(ignored -> { - releaseHeldCandidates(); - return PeerImpl.this.createAnswer(); + steps.releaseHeldCandidates(); + return steps.createAnswer(); }) - .thenCompose(PeerImpl.this::setLocal) + .thenCompose(steps::setLocal) .thenCompose(ignored -> gathered(gathering))); } @@ -2050,19 +1614,19 @@ public CompletableFuture applyAnswer(RTCSessionDescription answer) { throw new IllegalArgumentException("Expected an answer, got " + answer.sdpType); } - return run(() -> setRemote(answer).thenRun(PeerImpl.this::releaseHeldCandidates)); + return run(() -> steps.setRemote(answer).thenRun(steps::releaseHeldCandidates)); } @Override public CompletableFuture addCandidate(RTCIceCandidate candidate) { requireNonNull(candidate, "candidate"); - return run(() -> addRemoteCandidate(candidate)); + return run(() -> steps.addRemoteCandidate(candidate)); } private CompletableFuture gathered(Gathering gathering) { CompletableFuture ready = gathering == Gathering.COMPLETE - ? waitForGathering() + ? steps.waitForGathering() : CompletableFuture.completedFuture(null); return ready.thenApply(ignored -> connection.getLocalDescription()); @@ -2076,7 +1640,7 @@ private CompletableFuture run(Supplier> operation, BiConsumer finished) { CompletableFuture result = new CompletableFuture<>(); - control.execute(() -> enqueue(operation, finished) + control.execute(() -> chain.enqueue(operation, finished) .whenComplete((value, error) -> complete(result, value, error))); return toPublic(result); @@ -2085,16 +1649,29 @@ private CompletableFuture run(Supplier> operation, - private static final class HeldCandidate { + /** + * What the operations chain needs of this peer, on the control executor. + */ + private final class ChainHost implements OperationChain.Host { - final RTCIceCandidate candidate; + @Override + public boolean isClosed() { + return closed; + } - final CompletableFuture future; + @Override + public PeerClosedException closedError() { + return PeerImpl.this.closedError(); + } + @Override + public CompletableFuture rollback() { + return steps.rollback(); + } - HeldCandidate(RTCIceCandidate candidate, CompletableFuture future) { - this.candidate = candidate; - this.future = future; + @Override + public void abandon() { + teardown(); } } } diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/PerfectNegotiation.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/PerfectNegotiation.java new file mode 100644 index 000000000..c740cc57c --- /dev/null +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/PerfectNegotiation.java @@ -0,0 +1,201 @@ +/* + * 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.util.concurrent.CompletableFuture; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; + +import dev.onvoid.webrtc.RTCSdpType; +import dev.onvoid.webrtc.RTCSessionDescription; +import dev.onvoid.webrtc.RTCSignalingState; + +/** + * The automatic negotiation of a peer, perfect negotiation as the standard + * describes it: the peer offers whenever WebRTC asks for a negotiation, and + * answers the offers that come through its {@link Signaling}. When both + * peers offer at once, the polite one gives way and the impolite one ignores + * the other's offer. + *

+ * Every exchange runs as an operation of the peer's {@link OperationChain}, + * and everything here is confined to the control executor. + */ +final class PerfectNegotiation { + + /** How long an impolite peer waits for an answer after it ignored an offer. */ + static final long COLLISION_TIMEOUT_MS = 5000; + + private final PeerImpl peer; + + private final PeerOptions options; + + private final OperationChain chain; + + private final NegotiationSteps steps; + + private boolean negotiationQueued; + + private boolean ignoreOffer; + + private int remoteAnswers; + + private ScheduledFuture collisionCheck; + + + PerfectNegotiation(PeerImpl peer, PeerOptions options, OperationChain chain, NegotiationSteps steps) { + this.peer = peer; + this.options = options; + this.chain = chain; + this.steps = steps; + } + + /** + * @return whether the last remote offer was ignored, as an impolite peer + * does with one that collides with its own. + */ + boolean ignoresOffer() { + return ignoreOffer; + } + + /** + * Offers, once the exchange under way is done, when WebRTC asks for a + * negotiation. Several requests before the offer starts make one offer. + */ + void negotiationNeeded() { + if (peer.isClosed() || options.negotiation != Negotiation.AUTOMATIC || negotiationQueued) { + return; + } + + negotiationQueued = true; + + chain.enqueue(() -> { + negotiationQueued = false; + + if (peer.connection().getSignalingState() != RTCSignalingState.STABLE) { + // WebRTC asks again once the exchange under way is done. + return CompletableFuture.completedFuture(null); + } + + return steps.setLocal().thenRun(peer::sendLocalDescription); + }).whenComplete(this::reportFailure); + } + + /** + * Applies what the remote peer signaled. + */ + void signal(SignalMessage message) { + if (peer.isClosed()) { + return; + } + + switch (message.type()) { + case OFFER: + case ANSWER: + if (options.negotiation == Negotiation.MANUAL) { + peer.deliverError(new NegotiationException("The peer " + peer.name + " negotiates by hand. " + + "Apply descriptions through Peer.negotiator(), not Peer.signal()")); + return; + } + + chain.enqueue(() -> applyRemoteDescription(message.description())) + .whenComplete(this::reportFailure); + break; + + case CANDIDATE: + chain.enqueue(() -> ignoreOffer + ? CompletableFuture.completedFuture(null) + : steps.addRemoteCandidate(message.candidate())) + .whenComplete(this::reportFailure); + break; + + default: + // WebRTC needs no end of candidates. + break; + } + } + + /** + * Stops watching for a collision neither peer gives way in, once the peer + * is closing. + */ + void close() { + if (collisionCheck != null) { + collisionCheck.cancel(false); + collisionCheck = null; + } + } + + private CompletableFuture applyRemoteDescription(RTCSessionDescription description) { + boolean offer = description.sdpType == RTCSdpType.OFFER; + boolean collision = offer && peer.connection().getSignalingState() != RTCSignalingState.STABLE; + + ignoreOffer = !options.polite && collision; + + if (ignoreOffer) { + // The polite peer gives way and answers this peer's offer instead. + watchCollision(); + return CompletableFuture.completedFuture(null); + } + + // A polite peer's own pending offer is rolled back implicitly. + return steps.setRemote(description).thenCompose(ignored -> { + steps.releaseHeldCandidates(); + + if (!offer) { + remoteAnswers++; + return CompletableFuture.completedFuture(null); + } + + return steps.setLocal().thenRun(peer::sendLocalDescription); + }); + } + + /** + * Tells the application when the remote peer never answered the offer this + * peer kept, which happens when both peers are impolite. + */ + private void watchCollision() { + if (collisionCheck != null) { + return; + } + + int answers = remoteAnswers; + + try { + collisionCheck = peer.rtc.timer.schedule(() -> peer.control.execute(() -> { + collisionCheck = null; + + if (!peer.isClosed() && remoteAnswers == answers + && peer.connection().getSignalingState() == RTCSignalingState.HAVE_LOCAL_OFFER) { + peer.deliverError(new NegotiationException("Both peers sent an offer at once, and both are " + + "impolite, so neither gives way. Build exactly one of them with " + + "PeerOptions.Builder.polite(true)")); + } + }), COLLISION_TIMEOUT_MS, TimeUnit.MILLISECONDS); + } + catch (RejectedExecutionException e) { + // The runtime is closing, and the peer with it. + } + } + + private void reportFailure(Object value, Throwable error) { + if (error != null && !(PeerImpl.unwrap(error) instanceof PeerClosedException)) { + peer.deliverError(PeerImpl.asWebRtcException(error, "Negotiation of " + peer.name + " failed")); + } + } +} diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/OperationChainTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/OperationChainTests.java new file mode 100644 index 000000000..1c4bf657a --- /dev/null +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/OperationChainTests.java @@ -0,0 +1,265 @@ +/* + * 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.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +/** + * Drives an {@link OperationChain} on a control executor over a {@link + * ManualExecutor}, with a {@link ManualTimer}, so that each test decides when + * an operation times out. Needs no native code. + */ +class OperationChainTests { + + private static final Duration TIMEOUT = Duration.ofSeconds(30); + + private final List errors = new ArrayList<>(); + + private final ManualExecutor pool = new ManualExecutor(); + + private final ManualTimer timer = new ManualTimer(); + + private final SerialExecutor control = new SerialExecutor(pool, errors::add, false, null); + + private final TestHost host = new TestHost(); + + private final OperationChain chain = new OperationChain(control, timer, TIMEOUT, "the peer", host); + + private final List started = new ArrayList<>(); + + + @AfterEach + void noErrors() { + assertTrue(errors.isEmpty(), () -> "Errors: " + errors); + } + + @Test + void runsOneAtATime() throws Exception { + CompletableFuture pending = new CompletableFuture<>(); + CompletableFuture first = enqueue("first", () -> pending); + CompletableFuture second = enqueue("second", () -> CompletableFuture.completedFuture("done")); + + assertEquals(List.of("first"), started); + + run(() -> pending.complete("value")); + + assertEquals(List.of("first", "second"), started); + assertEquals("value", first.get()); + assertEquals("done", second.get()); + } + + @Test + void finishedRunsBeforeNext() throws Exception { + AtomicReference seen = new AtomicReference<>(); + CompletableFuture first = onControl(() -> chain.enqueue( + () -> CompletableFuture.completedFuture("value"), (value, error) -> { + seen.set(value); + throw new IllegalStateException("Cleanup failed"); + })); + CompletableFuture second = enqueue("second", () -> { + assertEquals("value", seen.get()); + return CompletableFuture.completedFuture("done"); + }); + + assertInstanceOf(IllegalStateException.class, failure(first)); + assertEquals("done", second.get()); + } + + @Test + void throwingOperationFails() throws Exception { + CompletableFuture first = enqueue("first", () -> { + throw new IllegalArgumentException("Refused"); + }); + CompletableFuture second = enqueue("second", () -> CompletableFuture.completedFuture("done")); + + assertInstanceOf(IllegalArgumentException.class, failure(first)); + assertEquals("done", second.get()); + } + + @Test + void timeoutRollsBackFirst() throws Exception { + AtomicReference> step = new AtomicReference<>(); + CompletableFuture late = enqueue("late", () -> { + step.set(chain.step()); + return step.get().thenApply(answer -> answer); + }); + CompletableFuture next = enqueue("next", () -> CompletableFuture.completedFuture("done")); + CompletableFuture rollback = new CompletableFuture<>(); + host.rollback = () -> rollback; + + assertEquals(1, timer.fire(TIMEOUT)); + pool.runAll(); + + // The step fails, so that an answer arriving late is not acted on. + assertInstanceOf(TimeoutException.class, failure(step.get())); + assertEquals(1, host.rollbacks); + // The next one waits for signaling to be stable again. + assertEquals(List.of("late"), started); + assertFalse(late.isDone()); + + run(() -> rollback.complete(null)); + + assertInstanceOf(TimeoutException.class, failure(late)); + assertEquals(List.of("late", "next"), started); + assertEquals("done", next.get()); + assertEquals(0, host.abandoned); + assertEquals(0, timer.scheduled(TIMEOUT)); + } + + @Test + void failedRollbackAbandons() { + CompletableFuture late = enqueue("late", CompletableFuture::new); + NegotiationException refused = new NegotiationException("Rollback refused"); + host.rollback = () -> CompletableFuture.failedFuture(refused); + + assertEquals(1, timer.fire(TIMEOUT)); + pool.runAll(); + + assertSame(refused, failure(late)); + assertEquals(1, host.abandoned); + } + + @Test + void stuckRollbackAbandons() { + CompletableFuture late = enqueue("late", CompletableFuture::new); + CompletableFuture next = enqueue("next", () -> CompletableFuture.completedFuture("done")); + // A step of the operation, as the native rollback is. + host.rollback = chain::step; + + assertEquals(1, timer.fire(TIMEOUT)); + pool.runAll(); + assertFalse(late.isDone()); + + // The rollback does not finish within another timeout either. + assertEquals(1, timer.fire(TIMEOUT)); + pool.runAll(); + + assertEquals(1, host.abandoned); + assertInstanceOf(PeerClosedException.class, failure(late)); + // The next one starts on a closed peer, and fails without running. + assertInstanceOf(PeerClosedException.class, failure(next)); + assertEquals(List.of("late"), started); + } + + @Test + void closeFailsRunningAndQueued() { + AtomicReference> step = new AtomicReference<>(); + CompletableFuture running = enqueue("running", () -> { + step.set(chain.step()); + return step.get(); + }); + CompletableFuture queued = enqueue("queued", () -> CompletableFuture.completedFuture("done")); + + run(host::abandon); + + assertInstanceOf(PeerClosedException.class, failure(step.get())); + assertInstanceOf(PeerClosedException.class, failure(running)); + assertInstanceOf(PeerClosedException.class, failure(queued)); + assertEquals(List.of("running"), started); + // Neither the closed operations nor the next ones roll back. + assertEquals(0, host.rollbacks); + assertEquals(0, timer.scheduled(TIMEOUT)); + } + + /** + * Enqueues an operation on the control executor, and runs the control + * tasks that follow from it. + */ + private CompletableFuture enqueue(String name, Supplier> operation) { + return onControl(() -> chain.enqueue(() -> { + started.add(name); + return operation.get(); + })); + } + + private T onControl(Supplier task) { + AtomicReference result = new AtomicReference<>(); + + control.execute(() -> result.set(task.get())); + pool.runAll(); + + return result.get(); + } + + private void run(Runnable task) { + control.execute(task); + pool.runAll(); + } + + private static Throwable failure(CompletableFuture future) { + assertTrue(future.isDone(), "Not done"); + + return assertThrows(ExecutionException.class, future::get).getCause(); + } + + + + /** The peer the chain runs the operations of, as its teardown does. */ + private final class TestHost implements OperationChain.Host { + + Supplier> rollback = () -> CompletableFuture.completedFuture(null); + + int rollbacks; + + int abandoned; + + boolean closed; + + + @Override + public boolean isClosed() { + return closed; + } + + @Override + public PeerClosedException closedError() { + return new PeerClosedException("The peer is closed"); + } + + @Override + public CompletableFuture rollback() { + rollbacks++; + + return rollback.get(); + } + + @Override + public void abandon() { + abandoned++; + closed = true; + + chain.close(closedError()); + } + } +}