| 1 | import Foundation |
| 2 | |
| 3 | /// A connection that stops working is mended without anyone asking (spec |
| 4 | /// §15.28, 2026-10-21). |
| 5 | /// |
| 6 | /// Paul, on the Mac app and sharing his screen, saw "Reconnecting to Farshad |
| 7 | /// (Mac)…" and "A participant's media could not connect" when Farshad moved |
| 8 | /// from the browser to the Mac app, and it never came back until Farshad left |
| 9 | /// and joined again. Up to 0.4.10 nothing in the apps ever restarted ICE on |
| 10 | /// a connection that failed: the only restarts were §5.3's renewals, and the |
| 11 | /// only rebuild a `pair` someone else asked for. The gate's reproduction |
| 12 | /// (TestNativeMacIceRecovery) showed the pair staying down for as long as it |
| 13 | /// watched, with libwebrtc never even calling it `failed`. |
| 14 | /// |
| 15 | /// Per remote peer, across that pair's connections (a rebuild is a new |
| 16 | /// connection, and the same episode): |
| 17 | /// |
| 18 | /// - **In trouble**: ICE `failed`; `disconnected` for `disconnectedAfter` |
| 19 | /// (5 s); never connected `connectAfter` (15 s) after the connection was |
| 20 | /// made, or at once when a negotiation step on it threw. A connection |
| 21 | /// that is up is never in trouble, whatever a step said on the way. |
| 22 | /// - **Attempts**, `backoff` apart — 0, 2, 5, 10, 20 s, then every 30 s — |
| 23 | /// for as long as the trouble lasts and the peer is in the call: an ICE |
| 24 | /// restart, another, then the pair rebuilt from nothing (`reset`, which |
| 25 | /// the hub answers with a new generation to both sides, §4.6), and round |
| 26 | /// again. While the signalling stream is down nothing can be negotiated, |
| 27 | /// so an attempt that falls due then waits for it to come back. |
| 28 | /// - **Who acts.** The impolite side (§5.1, the higher peer id) leads, on |
| 29 | /// the schedule. The polite side follows `followerDelay` (3 s) behind it, |
| 30 | /// and only if the leader has not acted: no remote offer has arrived for a |
| 31 | /// restart, no new connection for a rebuild, since the attempt fell due. |
| 32 | /// So two new apps never both rebuild, and an app from before this, which |
| 33 | /// never leads, is still mended from this side: it answers an ICE restart |
| 34 | /// and rebuilds on `pair`, as every app has since 0.2. |
| 35 | /// - **Recovered** is ICE connected or completed. A connection that goes |
| 36 | /// wrong again within `flapWindow` (60 s) carries on where its schedule |
| 37 | /// was, rather than starting at nought again: a link that comes and goes |
| 38 | /// is not restarted every two seconds. |
| 39 | /// - **What is said**: "Reconnecting to Farshad…" on their tile while it |
| 40 | /// tries (ReconnectWatch, fed `trying`); the failure notice only once it |
| 41 | /// has gone on `noticeAfter` (60 s), and gone again when it recovers. |
| 42 | /// |
| 43 | /// Pure: fed the facts as they are, with the time. The browser's |
| 44 | /// `recoveryStep` is its twin. |
| 45 | struct ConnectionRecovery: Equatable { |
| 46 | static let disconnectedAfter = 5.0 |
| 47 | static let connectAfter = 15.0 |
| 48 | static let backoff: [Double] = [0, 2, 5, 10, 20] |
| 49 | static let every = 30.0 |
| 50 | static let followerDelay = 3.0 |
| 51 | static let noticeAfter = 60.0 |
| 52 | static let flapWindow = 60.0 |
| 53 | |
| 54 | enum ICE: Equatable { case new, checking, connected, completed, disconnected, failed, closed } |
| 55 | enum Action: Equatable { case restart, rebuild } |
| 56 | |
| 57 | /// One connection as it is now. |
| 58 | struct Look: Equatable { |
| 59 | var ice: ICE |
| 60 | /// When this connection was made: a rebuild makes a new one. |
| 61 | var builtAt: Double |
| 62 | /// The impolite side of the pair (§5.1), which leads. |
| 63 | var leader: Bool |
| 64 | /// The signalling stream is up, so a negotiation can go out. |
| 65 | var signalling = true |
| 66 | /// When a remote ICE restart (an offer with a new username fragment) |
| 67 | /// was last applied on this connection. |
| 68 | var remoteOfferAt: Double? |
| 69 | /// A negotiation step on this connection threw. |
| 70 | var errored = false |
| 71 | } |
| 72 | |
| 73 | private(set) var troubleSince: Double? |
| 74 | private var disconnectedSince: Double? |
| 75 | /// Attempts made (or left to the leader) this episode, which says what |
| 76 | /// the next one is and how long after the last it falls due. |
| 77 | private(set) var attempts = 0 |
| 78 | /// When the next attempt falls due on the leader's schedule, and when |
| 79 | /// the one before it did (the episode's start, for the first). |
| 80 | private var nextAt: Double? |
| 81 | private var lastDue: Double? |
| 82 | private var recoveredAt: Double? |
| 83 | private var attemptsAtRecovery = 0 |
| 84 | /// Every restart and rebuild this side has made, for the gate. |
| 85 | private(set) var restarts = 0 |
| 86 | private(set) var rebuilds = 0 |
| 87 | |
| 88 | init() {} |
| 89 | |
| 90 | /// Trying to mend it now: their tile says "Reconnecting to …". |
| 91 | var trying: Bool { troubleSince != nil } |
| 92 | /// Trying for `noticeAfter` and more: the failure notice. |
| 93 | func failing(at now: Double) -> Bool { troubleSince.map { now - $0 >= Self.noticeAfter } ?? false } |
| 94 | |
| 95 | /// The wait before attempt `k` (counting from nought), after the last. |
| 96 | static func gap(_ k: Int) -> Double { k < backoff.count ? backoff[k] : every } |
| 97 | /// Two restarts, then a rebuild, and round again. |
| 98 | static func kind(_ k: Int) -> Action { k % 3 == 2 ? .rebuild : .restart } |
| 99 | |
| 100 | /// One look; what to do now, if anything. |
| 101 | mutating func observe(at now: Double, _ look: Look) -> Action? { |
| 102 | if look.ice == .closed { return nil } |
| 103 | // A connection that is up is well, whatever a negotiation step said on |
| 104 | // the way: an error only hastens the verdict on one that is not. |
| 105 | let healthy = look.ice == .connected || look.ice == .completed |
| 106 | if healthy { |
| 107 | disconnectedSince = nil |
| 108 | if troubleSince != nil { |
| 109 | troubleSince = nil |
| 110 | nextAt = nil |
| 111 | recoveredAt = now |
| 112 | attemptsAtRecovery = attempts |
| 113 | } |
| 114 | return nil |
| 115 | } |
| 116 | disconnectedSince = look.ice == .disconnected ? (disconnectedSince ?? now) : nil |
| 117 | if troubleSince == nil { |
| 118 | let bad: Bool |
| 119 | switch look.ice { |
| 120 | case .failed: bad = true |
| 121 | case .disconnected: bad = now - (disconnectedSince ?? now) >= Self.disconnectedAfter |
| 122 | case .new, .checking: bad = now - look.builtAt >= Self.connectAfter |
| 123 | case .connected, .completed, .closed: bad = false |
| 124 | } |
| 125 | guard bad || look.errored else { return nil } |
| 126 | troubleSince = now |
| 127 | attempts = recoveredAt.map { now - $0 < Self.flapWindow } == true ? attemptsAtRecovery : 0 |
| 128 | nextAt = now + (attempts == 0 ? 0 : Self.gap(attempts)) |
| 129 | lastDue = now |
| 130 | } |
| 131 | guard look.signalling, let due = nextAt else { return nil } |
| 132 | let offset = look.leader ? 0 : Self.followerDelay |
| 133 | guard now >= due + offset else { return nil } |
| 134 | let kind = Self.kind(attempts) |
| 135 | // The follower stands back when the leader has already acted: a remote |
| 136 | // offer (the leader's restart), or a new connection (its rebuild), |
| 137 | // since the follower's own last attempt fell due. Either side's |
| 138 | // episode can start a beat before the other's, so it is that window |
| 139 | // and not this attempt's instant that counts. |
| 140 | var leaderActed = false |
| 141 | if !look.leader { |
| 142 | let since = lastDue ?? due |
| 143 | switch kind { |
| 144 | case .restart: leaderActed = (look.remoteOfferAt ?? -.infinity) > since |
| 145 | case .rebuild: leaderActed = look.builtAt > since |
| 146 | } |
| 147 | } |
| 148 | lastDue = due |
| 149 | attempts += 1 |
| 150 | nextAt = max(due, now - offset) + Self.gap(attempts) |
| 151 | if leaderActed { return nil } |
| 152 | switch kind { |
| 153 | case .restart: restarts += 1 |
| 154 | case .rebuild: rebuilds += 1 |
| 155 | } |
| 156 | return kind |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | /// "Farshad is on an old version of Calls" (spec §15.28): what a tile says |
| 161 | /// about the app at the other end, from the roster's `client`. |
| 162 | enum ClientVersion { |
| 163 | /// The oldest app that does not break a call for the people in it with |
| 164 | /// it: protocol.MinNativeVersion, and the reason is written there. |
| 165 | static let minimum = "0.4.2" |
| 166 | static let nativeApps: Set<String> = ["mac", "iphone", "ipad"] |
| 167 | |
| 168 | /// "mac 0.4.12" as its two halves; "native" as ("native", nil); nil for |
| 169 | /// anything else, a browser's absent key included. |
| 170 | static func parse(_ client: String?) -> (app: String, version: String?)? { |
| 171 | guard let client else { return nil } |
| 172 | if client == "native" { return ("native", nil) } |
| 173 | let parts = client.split(separator: " ", omittingEmptySubsequences: false) |
| 174 | guard parts.count == 2, nativeApps.contains(String(parts[0])), valid(String(parts[1])) else { return nil } |
| 175 | return (String(parts[0]), String(parts[1])) |
| 176 | } |
| 177 | |
| 178 | static func valid(_ version: String) -> Bool { |
| 179 | let parts = version.split(separator: ".", omittingEmptySubsequences: false) |
| 180 | return (1...4).contains(parts.count) |
| 181 | && parts.allSatisfy { !$0.isEmpty && $0.count <= 4 && $0.allSatisfy { $0.isASCII && $0.isNumber } } |
| 182 | } |
| 183 | |
| 184 | /// Numeric, part by part, a missing part counting as nought. |
| 185 | static func compare(_ a: String, _ b: String) -> Int { |
| 186 | let x = a.split(separator: ".").map { Int($0) ?? 0 } |
| 187 | let y = b.split(separator: ".").map { Int($0) ?? 0 } |
| 188 | for i in 0..<max(x.count, y.count) { |
| 189 | let l = i < x.count ? x[i] : 0 |
| 190 | let r = i < y.count ? y[i] : 0 |
| 191 | if l != r { return l < r ? -1 : 1 } |
| 192 | } |
| 193 | return 0 |
| 194 | } |
| 195 | |
| 196 | /// The tile's words, or nil. An app that says it is older than |
| 197 | /// `minimum` is told so whatever the connection is doing. An app that |
| 198 | /// does not say at all ("native": every app from before this) is only |
| 199 | /// worth a sentence once the connection to it has been failing for |
| 200 | /// ConnectionRecovery's minute — and then it *may* be the reason, which |
| 201 | /// is all this side can know. A browser is never old: its page is the |
| 202 | /// server's own. |
| 203 | static func notice(name: String, client: String?, failing: Bool) -> String? { |
| 204 | guard let (app, version) = parse(client) else { return nil } |
| 205 | if let version { |
| 206 | return compare(version, minimum) < 0 ? VersionWords.old(name) : nil |
| 207 | } |
| 208 | return app == "native" && failing ? VersionWords.mayBeOld(name) : nil |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | public enum VersionWords { |
| 213 | public static func old(_ name: String) -> String { "\(name) is on an old version of Calls — ask them to update" } |
| 214 | public static func mayBeOld(_ name: String) -> String { |
| 215 | "\(name) may be on an old version of Calls — ask them to update" |
| 216 | } |
| 217 | } |
| 218 | |