Skip to content

Commit 31438ec

Browse files
committed
fix: discard expired negotiations and serialize ICE restart cleanup
1 parent f175af9 commit 31438ec

3 files changed

Lines changed: 343 additions & 26 deletions

File tree

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

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -175,7 +175,7 @@ CompletableFuture<Void> restart() {
175175
}
176176
}
177177

178-
Fragment[] before = new Fragment[1];
178+
Restart restart = new Restart();
179179

180180
return peer.restartIce(offer -> {
181181
HttpCall request;
@@ -186,26 +186,31 @@ CompletableFuture<Void> restart() {
186186
return CompletableFuture.failedFuture(new PeerClosedException("The session is closed"));
187187
}
188188

189-
before[0] = local;
189+
restart.before = local;
190190
local = fragment;
191191
restarting = true;
192192
pending.clear();
193193
gathered = false;
194194

195195
request = new HttpCall(client, session, "PATCH", authorization, timeout).header("If-Match", "*");
196+
restart.request = request;
196197
restartRequest = request;
197198
}
198199

199200
return request.send(FRAGMENT_TYPE, fragment.text.getBytes(StandardCharsets.UTF_8), MAX_FRAGMENT,
200-
head -> { }).handle((response, error) -> answered(request, response, error));
201-
}).whenComplete((restarted, error) -> {
201+
head -> { }).handle((response, error) -> sdp -> answered(request, response, error).apply(sdp));
202+
}, (restarted, error) -> {
202203
synchronized (this) {
204+
if (restart.request == null || restartRequest != restart.request) {
205+
return;
206+
}
203207
restarting = false;
204208
restartRequest = null;
209+
restart.request.abort();
205210

206-
if (error != null && before[0] != null) {
211+
if (error != null && restart.before != null) {
207212
// Taken back: the candidates of the new offer go nowhere.
208-
local = before[0];
213+
local = restart.before;
209214
pending.clear();
210215
gathered = false;
211216
}
@@ -215,6 +220,11 @@ CompletableFuture<Void> restart() {
215220
});
216221
}
217222

223+
private static final class Restart {
224+
Fragment before;
225+
HttpCall request;
226+
}
227+
218228
/**
219229
* Stops sending: cuts off the requests under way, and makes no more.
220230
*/

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

Lines changed: 125 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@
4444
import java.util.concurrent.TimeoutException;
4545
import java.util.concurrent.atomic.AtomicBoolean;
4646
import java.util.concurrent.atomic.AtomicReference;
47+
import java.util.function.BiConsumer;
4748
import java.util.function.Consumer;
4849
import java.util.function.Function;
4950
import java.util.function.Supplier;
@@ -149,6 +150,11 @@ final class PeerImpl implements Peer {
149150

150151
private CompletableFuture<?> runningOperation;
151152

153+
/** The unfinished steps of the current operation, owned by control. */
154+
private Operation activeOperation;
155+
156+
private boolean teardownStarted;
157+
152158
private boolean negotiationQueued;
153159

154160
private boolean ignoreOffer;
@@ -710,6 +716,12 @@ void onLocalCandidates(Consumer<RTCIceCandidate> candidates, Runnable gathered)
710716
*/
711717
CompletableFuture<Void> restartIce(
712718
Function<RTCSessionDescription, CompletableFuture<UnaryOperator<String>>> exchange) {
719+
return restartIce(exchange, (value, error) -> { });
720+
}
721+
722+
CompletableFuture<Void> restartIce(
723+
Function<RTCSessionDescription, CompletableFuture<UnaryOperator<String>>> exchange,
724+
BiConsumer<Void, Throwable> finished) {
713725
return negotiator.run(() -> {
714726
RTCSessionDescription remote = connection.getRemoteDescription();
715727

@@ -775,15 +787,15 @@ CompletableFuture<Void> restartIce(
775787
.thenCompose(ignored -> failed);
776788
})
777789
.thenCompose(result -> result);
778-
});
790+
}, finished);
779791
}
780792

781793
/**
782794
* @return a future that completes as the given one, but on the control
783795
* executor, or fails once the peer is closed.
784796
*/
785797
private <T> CompletableFuture<T> onControl(CompletableFuture<T> future) {
786-
CompletableFuture<T> result = new CompletableFuture<>();
798+
CompletableFuture<T> result = operationStep();
787799

788800
future.whenComplete((value, error) -> control.execute(() -> complete(result, value, error),
789801
() -> result.completeExceptionally(closedError())));
@@ -1256,9 +1268,16 @@ private LocalTrackImpl checkTrack(LocalTrack track) {
12561268
* @return a future that completes on the control executor.
12571269
*/
12581270
private <T> CompletableFuture<T> enqueue(Supplier<CompletableFuture<T>> operation) {
1271+
return enqueue(operation, (value, error) -> { });
1272+
}
1273+
1274+
private <T> CompletableFuture<T> enqueue(Supplier<CompletableFuture<T>> operation,
1275+
BiConsumer<T, Throwable> finished) {
12591276
CompletableFuture<T> result = new CompletableFuture<>();
12601277

12611278
operations.add(() -> {
1279+
Operation scope = new Operation();
1280+
activeOperation = scope;
12621281
CompletableFuture<T> running;
12631282

12641283
if (closed) {
@@ -1279,18 +1298,37 @@ private <T> CompletableFuture<T> enqueue(Supplier<CompletableFuture<T>> operatio
12791298
runningOperation = current;
12801299

12811300
// One that is done already, as on a closed peer, needs no timeout.
1282-
ScheduledFuture<?> timeout = current.isDone() ? null : timeOut(current);
1301+
ScheduledFuture<?> timeout = current.isDone() ? null : timeOut(current, scope);
12831302

12841303
current.whenComplete((value, error) -> control.execute(() -> {
12851304
if (timeout != null) {
12861305
timeout.cancel(false);
12871306
}
12881307

1289-
runningOperation = null;
1290-
operationRunning = false;
1291-
1292-
complete(result, value, error);
1293-
runNextOperation();
1308+
CompletableFuture<Void> stable = scope.expired && !closed ? rollback() :
1309+
CompletableFuture.completedFuture(null);
1310+
stable.whenComplete((ignored, cleanupError) -> control.execute(() -> {
1311+
Throwable failure = cleanupError == null ? error : cleanupError;
1312+
if (cleanupError != null && !closed) {
1313+
// A peer whose signaling cannot be restored must not run
1314+
// another negotiation against the abandoned description.
1315+
teardown();
1316+
}
1317+
if (scope.cleanupTimeout != null) {
1318+
scope.cleanupTimeout.cancel(false);
1319+
}
1320+
activeOperation = null;
1321+
runningOperation = null;
1322+
operationRunning = false;
1323+
try {
1324+
finished.accept(value, failure);
1325+
}
1326+
catch (Throwable e) {
1327+
failure = e;
1328+
}
1329+
complete(result, value, failure);
1330+
runNextOperation();
1331+
}));
12941332
}));
12951333
});
12961334

@@ -1304,11 +1342,37 @@ private <T> CompletableFuture<T> enqueue(Supplier<CompletableFuture<T>> operatio
13041342
*
13051343
* @return the timeout, or null once the runtime has stopped its timer.
13061344
*/
1307-
private ScheduledFuture<?> timeOut(CompletableFuture<?> operation) {
1345+
private ScheduledFuture<?> timeOut(CompletableFuture<?> operation, Operation scope) {
13081346
try {
1309-
return rtc.timer.schedule(() -> control.execute(() ->
1310-
operation.completeExceptionally(new TimeoutException("WebRTC did not finish an operation of "
1311-
+ name + " within " + rtc.operationTimeout))),
1347+
return rtc.timer.schedule(() -> control.execute(() -> {
1348+
if (operation.isDone()) {
1349+
return;
1350+
}
1351+
scope.expired = true;
1352+
// Recovery calls are native operations too. If they stop
1353+
// answering, close the peer instead of leaving its queue open.
1354+
try {
1355+
scope.cleanupTimeout = rtc.timer.schedule(() -> control.execute(() -> {
1356+
if (activeOperation == scope && !closed) {
1357+
teardown();
1358+
}
1359+
}), Timeouts.toMillis(rtc.operationTimeout), TimeUnit.MILLISECONDS);
1360+
}
1361+
catch (RejectedExecutionException e) {
1362+
// Runtime shutdown closes the peer and its unfinished steps.
1363+
}
1364+
TimeoutException error = new TimeoutException("WebRTC did not finish an operation of "
1365+
+ name + " within " + rtc.operationTimeout);
1366+
// Fail the awaited steps, so dependent stages cannot apply a
1367+
// late answer. Their error paths finish before the queue moves.
1368+
List<CompletableFuture<?>> steps = new ArrayList<>(scope.steps);
1369+
for (CompletableFuture<?> step : steps) {
1370+
step.completeExceptionally(error);
1371+
}
1372+
if (steps.isEmpty()) {
1373+
operation.completeExceptionally(error);
1374+
}
1375+
}),
13121376
Timeouts.toMillis(rtc.operationTimeout), TimeUnit.MILLISECONDS);
13131377
}
13141378
catch (RejectedExecutionException e) {
@@ -1318,6 +1382,32 @@ private ScheduledFuture<?> timeOut(CompletableFuture<?> operation) {
13181382
}
13191383
}
13201384

1385+
private CompletableFuture<Void> rollback() {
1386+
RTCSignalingState state = connection.getSignalingState();
1387+
if (state == RTCSignalingState.STABLE) {
1388+
return CompletableFuture.completedFuture(null);
1389+
}
1390+
RTCSessionDescription description = new RTCSessionDescription(RTCSdpType.ROLLBACK, "");
1391+
return state == RTCSignalingState.HAVE_REMOTE_OFFER || state == RTCSignalingState.HAVE_LOCAL_PR_ANSWER
1392+
? setRemote(description) : setLocal(description);
1393+
}
1394+
1395+
private <T> CompletableFuture<T> operationStep() {
1396+
CompletableFuture<T> future = new CompletableFuture<>();
1397+
Operation scope = activeOperation;
1398+
if (scope != null) {
1399+
scope.steps.add(future);
1400+
future.whenComplete((value, error) -> scope.steps.remove(future));
1401+
}
1402+
return future;
1403+
}
1404+
1405+
private static final class Operation {
1406+
final Set<CompletableFuture<?>> steps = new HashSet<>();
1407+
boolean expired;
1408+
ScheduledFuture<?> cleanupTimeout;
1409+
}
1410+
13211411
private void runNextOperation() {
13221412
if (operationRunning) {
13231413
return;
@@ -1332,32 +1422,32 @@ private void runNextOperation() {
13321422
}
13331423

13341424
private CompletableFuture<Void> setLocal() {
1335-
CompletableFuture<Void> future = new CompletableFuture<>();
1425+
CompletableFuture<Void> future = operationStep();
13361426
connection.setLocalDescription(descriptionObserver(future, "Applying the local description failed"));
13371427
return future;
13381428
}
13391429

13401430
private CompletableFuture<Void> setLocal(RTCSessionDescription description) {
1341-
CompletableFuture<Void> future = new CompletableFuture<>();
1431+
CompletableFuture<Void> future = operationStep();
13421432
connection.setLocalDescription(description, descriptionObserver(future, "Applying the local description failed"));
13431433
return future;
13441434
}
13451435

13461436
private CompletableFuture<Void> setRemote(RTCSessionDescription description) {
1347-
CompletableFuture<Void> future = new CompletableFuture<>();
1437+
CompletableFuture<Void> future = operationStep();
13481438
connection.setRemoteDescription(description, descriptionObserver(future,
13491439
"Applying the remote " + description.sdpType.name().toLowerCase() + " failed"));
13501440
return future;
13511441
}
13521442

13531443
private CompletableFuture<RTCSessionDescription> createOffer() {
1354-
CompletableFuture<RTCSessionDescription> future = new CompletableFuture<>();
1444+
CompletableFuture<RTCSessionDescription> future = operationStep();
13551445
connection.createOffer(new RTCOfferOptions(), createObserver(future, "Creating the offer failed"));
13561446
return future;
13571447
}
13581448

13591449
private CompletableFuture<RTCSessionDescription> createAnswer() {
1360-
CompletableFuture<RTCSessionDescription> future = new CompletableFuture<>();
1450+
CompletableFuture<RTCSessionDescription> future = operationStep();
13611451
connection.createAnswer(new RTCAnswerOptions(), createObserver(future, "Creating the answer failed"));
13621452
return future;
13631453
}
@@ -1398,7 +1488,7 @@ public void onFailure(String error) {
13981488
* description to add it to.
13991489
*/
14001490
private CompletableFuture<Void> addRemoteCandidate(RTCIceCandidate candidate) {
1401-
CompletableFuture<Void> future = new CompletableFuture<>();
1491+
CompletableFuture<Void> future = operationStep();
14021492

14031493
if (connection.getRemoteDescription() == null) {
14041494
heldCandidates.add(new HeldCandidate(candidate, future));
@@ -1447,7 +1537,7 @@ private CompletableFuture<Void> waitForGathering() {
14471537
return CompletableFuture.completedFuture(null);
14481538
}
14491539

1450-
CompletableFuture<Void> future = new CompletableFuture<>();
1540+
CompletableFuture<Void> future = operationStep();
14511541
gatheringWaiters.add(future);
14521542

14531543
// A STUN or TURN server that cannot be reached holds up the end of
@@ -1724,10 +1814,20 @@ void channelClosed(DataChannelImpl channel) {
17241814
}
17251815

17261816
private void teardown() {
1817+
if (teardownStarted) {
1818+
return;
1819+
}
1820+
teardownStarted = true;
1821+
closing.set(true);
17271822
closed = true;
17281823

17291824
PeerClosedException error = closedError();
17301825

1826+
if (activeOperation != null) {
1827+
for (CompletableFuture<?> step : new ArrayList<>(activeOperation.steps)) {
1828+
step.completeExceptionally(error);
1829+
}
1830+
}
17311831
if (runningOperation != null) {
17321832
runningOperation.completeExceptionally(error);
17331833
}
@@ -1969,9 +2069,14 @@ private CompletableFuture<RTCSessionDescription> gathered(Gathering gathering) {
19692069
}
19702070

19712071
private <T> CompletableFuture<T> run(Supplier<CompletableFuture<T>> operation) {
2072+
return run(operation, (value, error) -> { });
2073+
}
2074+
2075+
private <T> CompletableFuture<T> run(Supplier<CompletableFuture<T>> operation,
2076+
BiConsumer<T, Throwable> finished) {
19722077
CompletableFuture<T> result = new CompletableFuture<>();
19732078

1974-
control.execute(() -> enqueue(operation)
2079+
control.execute(() -> enqueue(operation, finished)
19752080
.whenComplete((value, error) -> complete(result, value, error)));
19762081

19772082
return toPublic(result);

0 commit comments

Comments
 (0)