// 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.importNetworkimportSwiftUI@MainActor @ObservablefinalclassFilmSlow {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 }staticvar line: String { ShellLines.line("cards", "film.slow") }/// No picture, or a stall, for this long: say so.staticlet after: Duration = .seconds(4)/// The wait before the next try: 2, 3, 5, 8, then 10 s. nonisolated staticfunc 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.staticfunc again(_ error: Error) -> Bool {guardFilmNetwork.reachable else { returnfalse }guardlet refused = error as? CottonCallErrorelse { returntrue }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.staticfunc again(_ answer: PlayerAnswer, since began: ContinuousClock.Instant) -> Bool {guardlet film = answer.playing, film.kind == "film", film.stream == nil, film.bundle == nil,let refusal = answer.refusal, FilmNetwork.reachable else { returnfalse }if refusal == answer.words.offline { returntrue }if refusal == answer.words.refused { returnContinuousClock.now - began < .seconds(30) }returnfalse }}/// The words over the picture, under the spinner while it waits.structFilmSlowNote: View {let slow: FilmSlowvar body: someView { 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) }}extensionFilmNetwork {/// The phone has a network at all (Wi-Fi, wire or mobile data).staticvar 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.finalclassFilmThrottle: @unchecked Sendable {staticlet shared: FilmThrottle? = {let defaults = UserDefaults.standardlet delay = defaults.integer(forKey: "film-throttle-ms")let kbps = defaults.integer(forKey: "film-throttle-kbps")guard delay > 0 || kbps > 0else { returnnil }returnFilmThrottle(delayMs: delay, bytesPerSecond: kbps * 1000 / 8) }() @MainActor privatestaticvar 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 staticfunc coreAsk() asyncthrows {let slow = UserDefaults.standard.integer(forKey: "film-slow-core-ms")if slow > 0 { tryawaitTask.sleep(for: .milliseconds(slow)) }if failsLeft > 0 { failsLeft -= 1PlayClock.note("throttle: a Play ask got no answer")throwCottonCallError(code: "offline", message: "") } }/// The relay's address through the throttle.staticfunc route(_ url: URL) -> URL {guardlet 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 }privatelet delayMs: Intprivatelet bytesPerSecond: Intprivatelet queue = DispatchQueue(label: "film-throttle")privatelet listener: NWListener?privatelet ready = DispatchSemaphore(value: 0)privatevar target: UInt16 = 0privateinit(delayMs: Int, bytesPerSecond: Int) {self.delayMs = delayMsself.bytesPerSecond = bytesPerSecondlet parameters = NWParameters.tcp parameters.requiredLocalEndpoint = NWEndpoint.hostPort(host: "127.0.0.1", port: .any) listener = try? NWListener(using: parameters) listener?.stateUpdateHandler = { [ready] state inifcase .ready = state { ready.signal(); ready.signal() } } listener?.newConnectionHandler = { [weakself] inbound inself?.accept(inbound) } listener?.start(queue: queue) }privatevar isReady = false/// The listener's own port, once it is listening (asked before, it says 0).privatefunc 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 } }privatefunc accept(_ inbound: NWConnection) {guardlet 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.privatefunc 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) { [weakself] data, _, done, error inguardletselfelse { return }iflet data, !data.isEmpty {let before = asks ? Double(self.delayMs) / 1000 : 0let after = !asks && self.bytesPerSecond > 0 ? Double(data.count) / Double(self.bytesPerSecond) : 0self.queue.asyncAfter(deadline: .now() + before) { to.send(content: data, completion: .contentProcessed { _ inself.queue.asyncAfter(deadline: .now() + after) { self.pipe(from: from, to: to, asks: asks) } }) } } elseif error != nil { from.cancel() to.cancel() } elseif done { to.send(content: nil, contentContext: .finalMessage, isComplete: true, completion: .idempotent) } else {self.pipe(from: from, to: to, asks: asks) } } }}#endif