|
| 1 | +/* |
| 2 | + * Copyright 2026 Alex Andres |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package dev.onvoid.webrtc.client; |
| 18 | + |
| 19 | +import java.time.Duration; |
| 20 | +import java.util.List; |
| 21 | +import java.util.concurrent.CompletableFuture; |
| 22 | +import java.util.concurrent.Executor; |
| 23 | +import java.util.concurrent.ScheduledExecutorService; |
| 24 | +import java.util.concurrent.ScheduledFuture; |
| 25 | +import java.util.concurrent.TimeUnit; |
| 26 | +import java.util.function.BooleanSupplier; |
| 27 | +import java.util.function.Supplier; |
| 28 | + |
| 29 | +import dev.onvoid.webrtc.RTCIceServer; |
| 30 | +import dev.onvoid.webrtc.internal.Timeouts; |
| 31 | + |
| 32 | +/** All state belongs to control. Application code is dispatched by the host. */ |
| 33 | +final class IceRecovery { |
| 34 | + interface Host { |
| 35 | + CompletableFuture<List<RTCIceServer>> servers(int attempt); |
| 36 | + void useServers(List<RTCIceServer> servers); |
| 37 | + void event(RecoveryEvent event); |
| 38 | + } |
| 39 | + |
| 40 | + private final RecoveryPolicy policy; |
| 41 | + private final Executor control; |
| 42 | + private final ScheduledExecutorService timer; |
| 43 | + private final BooleanSupplier closing; |
| 44 | + private final Supplier<CompletableFuture<Void>> restart; |
| 45 | + private final Host host; |
| 46 | + private ScheduledFuture<?> wait; |
| 47 | + private long generation; |
| 48 | + private int attempts; |
| 49 | + private boolean outage; |
| 50 | + private boolean exhausted; |
| 51 | + private boolean closed; |
| 52 | + private boolean exchanging; |
| 53 | + private boolean deferredAttempt; |
| 54 | + private boolean gracePeriod; |
| 55 | + private Throwable timedOut; |
| 56 | + |
| 57 | + IceRecovery(RecoveryPolicy policy, Executor control, ScheduledExecutorService timer, |
| 58 | + BooleanSupplier closing, Supplier<CompletableFuture<Void>> restart, Host host) { |
| 59 | + this.policy = policy; |
| 60 | + this.control = control; |
| 61 | + this.timer = timer; |
| 62 | + this.closing = closing; |
| 63 | + this.restart = restart; |
| 64 | + this.host = host; |
| 65 | + } |
| 66 | + |
| 67 | + void stateChanged(PeerState state) { |
| 68 | + if (closed || closing.getAsBoolean()) return; |
| 69 | + if (state == PeerState.CLOSED) { close(); return; } |
| 70 | + if (state == PeerState.CONNECTED) { |
| 71 | + if (outage) emit(RecoveryEvent.State.RECOVERED, null); |
| 72 | + outage = false; |
| 73 | + exhausted = false; |
| 74 | + attempts = 0; |
| 75 | + invalidate(); |
| 76 | + return; |
| 77 | + } |
| 78 | + if (state != PeerState.DISCONNECTED && state != PeerState.FAILED) return; |
| 79 | + if (outage || exhausted) { |
| 80 | + if (state == PeerState.FAILED && gracePeriod && !exhausted) { |
| 81 | + invalidate(); |
| 82 | + attempt(); |
| 83 | + } |
| 84 | + return; |
| 85 | + } |
| 86 | + outage = true; |
| 87 | + if (state == PeerState.DISCONNECTED) { |
| 88 | + gracePeriod = true; |
| 89 | + emit(RecoveryEvent.State.WAITING, null); |
| 90 | + schedule(policy.grace, this::attempt); |
| 91 | + } |
| 92 | + else attempt(); |
| 93 | + } |
| 94 | + |
| 95 | + void close() { |
| 96 | + closed = true; |
| 97 | + invalidate(); |
| 98 | + } |
| 99 | + |
| 100 | + private void invalidate() { |
| 101 | + generation++; |
| 102 | + deferredAttempt = false; |
| 103 | + gracePeriod = false; |
| 104 | + if (wait != null) wait.cancel(false); |
| 105 | + wait = null; |
| 106 | + timedOut = null; |
| 107 | + } |
| 108 | + |
| 109 | + private boolean current(long token) { |
| 110 | + return token == generation && outage && !closed && !closing.getAsBoolean(); |
| 111 | + } |
| 112 | + |
| 113 | + private void attempt() { |
| 114 | + if (closed || closing.getAsBoolean() || !outage || exhausted) return; |
| 115 | + // A connection can recover and fail again while an HTTP exchange ends. |
| 116 | + if (exchanging) { deferredAttempt = true; return; } |
| 117 | + gracePeriod = false; |
| 118 | + attempts++; |
| 119 | + long token = ++generation; |
| 120 | + emit(RecoveryEvent.State.ATTEMPTING, null); |
| 121 | + schedule(policy.attemptTimeout, () -> { |
| 122 | + Throwable error = new WebRtcException("ICE recovery attempt timed out"); |
| 123 | + if (exchanging) timedOut = error; |
| 124 | + else failed(token, error); |
| 125 | + }); |
| 126 | + try { |
| 127 | + host.servers(attempts).whenComplete((servers, error) -> control.execute(() -> { |
| 128 | + if (!current(token)) return; |
| 129 | + if (error != null) { failed(token, error); return; } |
| 130 | + try { |
| 131 | + if (servers != null) host.useServers(servers); |
| 132 | + exchanging = true; |
| 133 | + restart.get().whenComplete((ignored, failure) -> control.execute(() -> { |
| 134 | + exchanging = false; |
| 135 | + if (!current(token)) { |
| 136 | + if (deferredAttempt && outage && !exhausted && !closed && !closing.getAsBoolean()) { |
| 137 | + deferredAttempt = false; |
| 138 | + attempt(); |
| 139 | + } |
| 140 | + return; |
| 141 | + } |
| 142 | + if (failure != null || timedOut != null) failed(token, failure != null ? failure : timedOut); |
| 143 | + // Successful signaling is not successful connectivity: keep the deadline. |
| 144 | + })); |
| 145 | + } |
| 146 | + catch (Throwable failure) { exchanging = false; failed(token, failure); } |
| 147 | + })); |
| 148 | + } |
| 149 | + catch (Throwable error) { failed(token, error); } |
| 150 | + } |
| 151 | + |
| 152 | + private void failed(long token, Throwable error) { |
| 153 | + if (!current(token)) return; |
| 154 | + invalidate(); |
| 155 | + error = PeerImpl.unwrap(error); |
| 156 | + if (attempts >= policy.maxAttempts) { |
| 157 | + exhausted = true; |
| 158 | + emit(RecoveryEvent.State.EXHAUSTED, error); |
| 159 | + } |
| 160 | + else { |
| 161 | + emit(RecoveryEvent.State.RETRYING, error); |
| 162 | + schedule(policy.backoff(attempts), this::attempt); |
| 163 | + } |
| 164 | + } |
| 165 | + |
| 166 | + private void emit(RecoveryEvent.State state, Throwable cause) { |
| 167 | + host.event(new RecoveryEvent(state, attempts, cause)); |
| 168 | + } |
| 169 | + |
| 170 | + private void schedule(Duration delay, Runnable task) { |
| 171 | + long token = generation; |
| 172 | + try { |
| 173 | + wait = timer.schedule(() -> control.execute(() -> { |
| 174 | + if (current(token)) { wait = null; task.run(); } |
| 175 | + }), Timeouts.toMillis(delay), TimeUnit.MILLISECONDS); |
| 176 | + } |
| 177 | + catch (java.util.concurrent.RejectedExecutionException error) { |
| 178 | + close(); // The runtime is stopping its timer. |
| 179 | + } |
| 180 | + } |
| 181 | +} |
0 commit comments