import Foundation /// A connection that stops working is mended without anyone asking (spec /// §15.28, 2026-10-21). /// /// Paul, on the Mac app and sharing his screen, saw "Reconnecting to Farshad /// (Mac)…" and "A participant's media could not connect" when Farshad moved /// from the browser to the Mac app, and it never came back until Farshad left /// and joined again. Up to 0.4.10 nothing in the apps ever restarted ICE on /// a connection that failed: the only restarts were §5.3's renewals, and the /// only rebuild a `pair` someone else asked for. The gate's reproduction /// (TestNativeMacIceRecovery) showed the pair staying down for as long as it /// watched, with libwebrtc never even calling it `failed`. /// /// Per remote peer, across that pair's connections (a rebuild is a new /// connection, and the same episode): /// /// - **In trouble**: ICE `failed`; `disconnected` for `disconnectedAfter` /// (5 s); never connected `connectAfter` (15 s) after the connection was /// made, or at once when a negotiation step on it threw. A connection /// that is up is never in trouble, whatever a step said on the way. /// - **Attempts**, `backoff` apart — 0, 2, 5, 10, 20 s, then every 30 s — /// for as long as the trouble lasts and the peer is in the call: an ICE /// restart, another, then the pair rebuilt from nothing (`reset`, which /// the hub answers with a new generation to both sides, §4.6), and round /// again. While the signalling stream is down nothing can be negotiated, /// so an attempt that falls due then waits for it to come back. /// - **Who acts.** The impolite side (§5.1, the higher peer id) leads, on /// the schedule. The polite side follows `followerDelay` (3 s) behind it, /// and only if the leader has not acted: no remote offer has arrived for a /// restart, no new connection for a rebuild, since the attempt fell due. /// So two new apps never both rebuild, and an app from before this, which /// never leads, is still mended from this side: it answers an ICE restart /// and rebuilds on `pair`, as every app has since 0.2. /// - **Recovered** is ICE connected or completed. A connection that goes /// wrong again within `flapWindow` (60 s) carries on where its schedule /// was, rather than starting at nought again: a link that comes and goes /// is not restarted every two seconds. /// - **What is said**: "Reconnecting to Farshad…" on their tile while it /// tries (ReconnectWatch, fed `trying`); the failure notice only once it /// has gone on `noticeAfter` (60 s), and gone again when it recovers. /// /// Pure: fed the facts as they are, with the time. The browser's /// `recoveryStep` is its twin. struct ConnectionRecovery: Equatable { static let disconnectedAfter = 5.0 static let connectAfter = 15.0 static let backoff: [Double] = [0, 2, 5, 10, 20] static let every = 30.0 static let followerDelay = 3.0 static let noticeAfter = 60.0 static let flapWindow = 60.0 enum ICE: Equatable { case new, checking, connected, completed, disconnected, failed, closed } enum Action: Equatable { case restart, rebuild } /// One connection as it is now. struct Look: Equatable { var ice: ICE /// When this connection was made: a rebuild makes a new one. var builtAt: Double /// The impolite side of the pair (§5.1), which leads. var leader: Bool /// The signalling stream is up, so a negotiation can go out. var signalling = true /// When a remote ICE restart (an offer with a new username fragment) /// was last applied on this connection. var remoteOfferAt: Double? /// A negotiation step on this connection threw. var errored = false } private(set) var troubleSince: Double? private var disconnectedSince: Double? /// Attempts made (or left to the leader) this episode, which says what /// the next one is and how long after the last it falls due. private(set) var attempts = 0 /// When the next attempt falls due on the leader's schedule, and when /// the one before it did (the episode's start, for the first). private var nextAt: Double? private var lastDue: Double? private var recoveredAt: Double? private var attemptsAtRecovery = 0 /// Every restart and rebuild this side has made, for the gate. private(set) var restarts = 0 private(set) var rebuilds = 0 init() {} /// Trying to mend it now: their tile says "Reconnecting to …". var trying: Bool { troubleSince != nil } /// Trying for `noticeAfter` and more: the failure notice. func failing(at now: Double) -> Bool { troubleSince.map { now - $0 >= Self.noticeAfter } ?? false } /// The wait before attempt `k` (counting from nought), after the last. static func gap(_ k: Int) -> Double { k < backoff.count ? backoff[k] : every } /// Two restarts, then a rebuild, and round again. static func kind(_ k: Int) -> Action { k % 3 == 2 ? .rebuild : .restart } /// One look; what to do now, if anything. mutating func observe(at now: Double, _ look: Look) -> Action? { if look.ice == .closed { return nil } // A connection that is up is well, whatever a negotiation step said on // the way: an error only hastens the verdict on one that is not. let healthy = look.ice == .connected || look.ice == .completed if healthy { disconnectedSince = nil if troubleSince != nil { troubleSince = nil nextAt = nil recoveredAt = now attemptsAtRecovery = attempts } return nil } disconnectedSince = look.ice == .disconnected ? (disconnectedSince ?? now) : nil if troubleSince == nil { let bad: Bool switch look.ice { case .failed: bad = true case .disconnected: bad = now - (disconnectedSince ?? now) >= Self.disconnectedAfter case .new, .checking: bad = now - look.builtAt >= Self.connectAfter case .connected, .completed, .closed: bad = false } guard bad || look.errored else { return nil } troubleSince = now attempts = recoveredAt.map { now - $0 < Self.flapWindow } == true ? attemptsAtRecovery : 0 nextAt = now + (attempts == 0 ? 0 : Self.gap(attempts)) lastDue = now } guard look.signalling, let due = nextAt else { return nil } let offset = look.leader ? 0 : Self.followerDelay guard now >= due + offset else { return nil } let kind = Self.kind(attempts) // The follower stands back when the leader has already acted: a remote // offer (the leader's restart), or a new connection (its rebuild), // since the follower's own last attempt fell due. Either side's // episode can start a beat before the other's, so it is that window // and not this attempt's instant that counts. var leaderActed = false if !look.leader { let since = lastDue ?? due switch kind { case .restart: leaderActed = (look.remoteOfferAt ?? -.infinity) > since case .rebuild: leaderActed = look.builtAt > since } } lastDue = due attempts += 1 nextAt = max(due, now - offset) + Self.gap(attempts) if leaderActed { return nil } switch kind { case .restart: restarts += 1 case .rebuild: rebuilds += 1 } return kind } } /// "Farshad is on an old version of Calls" (spec §15.28): what a tile says /// about the app at the other end, from the roster's `client`. enum ClientVersion { /// The oldest app that does not break a call for the people in it with /// it: protocol.MinNativeVersion, and the reason is written there. static let minimum = "0.4.2" static let nativeApps: Set = ["mac", "iphone", "ipad"] /// "mac 0.4.12" as its two halves; "native" as ("native", nil); nil for /// anything else, a browser's absent key included. static func parse(_ client: String?) -> (app: String, version: String?)? { guard let client else { return nil } if client == "native" { return ("native", nil) } let parts = client.split(separator: " ", omittingEmptySubsequences: false) guard parts.count == 2, nativeApps.contains(String(parts[0])), valid(String(parts[1])) else { return nil } return (String(parts[0]), String(parts[1])) } static func valid(_ version: String) -> Bool { let parts = version.split(separator: ".", omittingEmptySubsequences: false) return (1...4).contains(parts.count) && parts.allSatisfy { !$0.isEmpty && $0.count <= 4 && $0.allSatisfy { $0.isASCII && $0.isNumber } } } /// Numeric, part by part, a missing part counting as nought. static func compare(_ a: String, _ b: String) -> Int { let x = a.split(separator: ".").map { Int($0) ?? 0 } let y = b.split(separator: ".").map { Int($0) ?? 0 } for i in 0.. String? { guard let (app, version) = parse(client) else { return nil } if let version { return compare(version, minimum) < 0 ? VersionWords.old(name) : nil } return app == "native" && failing ? VersionWords.mayBeOld(name) : nil } } public enum VersionWords { public static func old(_ name: String) -> String { "\(name) is on an old version of Calls — ask them to update" } public static func mayBeOld(_ name: String) -> String { "\(name) may be on an old version of Calls — ask them to update" } }