Cotton code
183 lines · 8.3 KB · SwiftRaw
// COTTON SLOW (the coordinator, 26 Nov: on build 23 the owner could stream nothing for 20 minutes while the live server// answered in 2 to 10 s, and the player showed a spinner with no words). The player now says plainly, after a few// seconds with no picture or a stall, "Cotton is slow right now · trying again" (cards `film.slow`), and keeps trying:// the core asked again while it does not answer or cannot reach the film, the relay's address again when the film// fails, each wait a little longer up to 10 s, until it plays or he closes the player.import Networkimport SwiftUI@MainActor @Observablefinal class FilmSlow {    private(set) var shown = false    /// Says it once, and to VoiceOver as it appears.    func on() {        guard !shown else { return }        shown = true        UIAccessibility.post(notification: .announcement, argument: Self.line)    }    func off() { shown = false }    static var line: String { ShellLines.line("cards", "film.slow") }    /// No picture, or a stall, for this long: say so.    static let after: Duration = .seconds(4)    /// The wait before the next try: 2, 3, 5, 8, then 10 s.    nonisolated static func wait(_ tries: Int) -> Duration {        let steps = [2, 3, 5, 8, 10]        return .seconds(steps[min(max(tries, 1), steps.count) - 1])    }    /// A call that did not get Cotton's answer (no answer, timed out, unreachable): asked again, unless this phone has    /// no network at all, which the film's own words say.    static func again(_ error: Error) -> Bool {        guard FilmNetwork.reachable else { return false }        guard let refused = error as? CottonCallError else { return true }        return ["offline", "unreachable", "timeout", "network", "unavailable", "busy"].contains(refused.code)    }    /// The core answered but could not reach the film (its stream address not minted: Cotton slow or not answering):    /// asked again. "No network" with a network is Cotton not answering, asked again for as long as it takes; a plain    /// refusal is asked again for half a minute (Cotton's 5xx), then said, since it may be the film's own.    static func again(_ answer: PlayerAnswer, since began: ContinuousClock.Instant) -> Bool {        guard let film = answer.playing, film.kind == "film", film.stream == nil, film.bundle == nil,              let refusal = answer.refusal, FilmNetwork.reachable else { return false }        if refusal == answer.words.offline { return true }        if refusal == answer.words.refused { return ContinuousClock.now - began < .seconds(30) }        return false    }}/// The words over the picture, under the spinner while it waits.struct FilmSlowNote: View {    let slow: FilmSlow    var body: some View {        ZStack {            if slow.shown {                Text(FilmSlow.line)                    .font(.subheadline.weight(.semibold))                    .foregroundStyle(.white)                    .multilineTextAlignment(.center)                    .padding(.horizontal, 16)                    .padding(.vertical, 10)                    .background(.black.opacity(0.6), in: Capsule())                    .padding(.horizontal, 24)                    .offset(y: 72)                    .accessibilityIdentifier("film-slow")                    .transition(.opacity)            }        }        .frame(maxWidth: .infinity, maxHeight: .infinity)        .animation(.easeInOut(duration: 0.25), value: slow.shown)    }}extension FilmNetwork {    /// The phone has a network at all (Wi-Fi, wire or mobile data).    static var reachable: Bool { currentStatus == .satisfied }}#if COTTON_DEV/// A slow Cotton on a simulator, for walking what the player says (Dev builds only; never the Mac's own network):/// - `-film-throttle-ms <ms>`: each ask of the relay waits this long before it goes;/// - `-film-throttle-kbps <kbit/s>`: the relay's bytes come no faster;/// - `-film-fail-core <n>`: the first n Play asks get no answer from the core, as when Cotton does not answer;/// - `-film-slow-core-ms <ms>`: every Play ask waits this long first, as a server answering in 2 to 10 s.final class FilmThrottle: @unchecked Sendable {    static let shared: FilmThrottle? = {        let defaults = UserDefaults.standard        let delay = defaults.integer(forKey: "film-throttle-ms")        let kbps = defaults.integer(forKey: "film-throttle-kbps")        guard delay > 0 || kbps > 0 else { return nil }        return FilmThrottle(delayMs: delay, bytesPerSecond: kbps * 1000 / 8)    }()    @MainActor private static var failsLeft = UserDefaults.standard.integer(forKey: "film-fail-core")    /// Before a Play ask: the slow server's wait, and the asks that get no answer.    @MainActor static func coreAsk() async throws {        let slow = UserDefaults.standard.integer(forKey: "film-slow-core-ms")        if slow > 0 { try await Task.sleep(for: .milliseconds(slow)) }        if failsLeft > 0 {            failsLeft -= 1            PlayClock.note("throttle: a Play ask got no answer")            throw CottonCallError(code: "offline", message: "")        }    }    /// The relay's address through the throttle.    static func route(_ url: URL) -> URL {        guard let throttle = shared, url.host() == "127.0.0.1", let port = url.port, let mine = throttle.port() else { return url }        throttle.queue.sync { throttle.target = UInt16(port) }        var parts = URLComponents(url: url, resolvingAgainstBaseURL: false)        parts?.port = Int(mine)        return parts?.url ?? url    }    private let delayMs: Int    private let bytesPerSecond: Int    private let queue = DispatchQueue(label: "film-throttle")    private let listener: NWListener?    private let ready = DispatchSemaphore(value: 0)    private var target: UInt16 = 0    private init(delayMs: Int, bytesPerSecond: Int) {        self.delayMs = delayMs        self.bytesPerSecond = bytesPerSecond        let parameters = NWParameters.tcp        parameters.requiredLocalEndpoint = NWEndpoint.hostPort(host: "127.0.0.1", port: .any)        listener = try? NWListener(using: parameters)        listener?.stateUpdateHandler = { [ready] state in if case .ready = state { ready.signal(); ready.signal() } }        listener?.newConnectionHandler = { [weak self] inbound in self?.accept(inbound) }        listener?.start(queue: queue)    }    private var isReady = false    /// The listener's own port, once it is listening (asked before, it says 0).    private func port() -> UInt16? {        if !queue.sync(execute: { isReady }) {            _ = ready.wait(timeout: .now() + 2)            queue.sync { isReady = true }        }        return listener?.port.map(\.rawValue).flatMap { $0 == 0 ? nil : $0 }    }    private func accept(_ inbound: NWConnection) {        guard let port = NWEndpoint.Port(rawValue: target) else { return inbound.cancel() }        let outbound = NWConnection(host: "127.0.0.1", port: port, using: .tcp)        inbound.start(queue: queue)        outbound.start(queue: queue)        pipe(from: inbound, to: outbound, asks: true)        pipe(from: outbound, to: inbound, asks: false)    }    /// Asks go after the delay; answers at the bandwidth.    private func pipe(from: NWConnection, to: NWConnection, asks: Bool) {        let chunk = asks || bytesPerSecond == 0 ? 65_536 : max(1_024, bytesPerSecond / 10)        from.receive(minimumIncompleteLength: 1, maximumLength: chunk) { [weak self] data, _, done, error in            guard let self else { return }            if let data, !data.isEmpty {                let before = asks ? Double(self.delayMs) / 1000 : 0                let after = !asks && self.bytesPerSecond > 0 ? Double(data.count) / Double(self.bytesPerSecond) : 0                self.queue.asyncAfter(deadline: .now() + before) {                    to.send(content: data, completion: .contentProcessed { _ in                        self.queue.asyncAfter(deadline: .now() + after) { self.pipe(from: from, to: to, asks: asks) }                    })                }            } else if error != nil {                from.cancel()                to.cancel()            } else if done {                to.send(content: nil, contentContext: .finalMessage, isComplete: true, completion: .idempotent)            } else {                self.pipe(from: from, to: to, asks: asks)            }        }    }}#endif