Cotton code
602 lines · 26.9 KB · SwiftRaw
// Cotton to Cotton messages on this phone: what the shell keeps and carries// round the core's `chat.*` methods, which make every decision.//// The shell keeps three things the core cannot:// - the CHAT KEY, minted by `chat.key` and kept in the app group's Keychain//   (`ChatKeychain`), handed to every call that seals or opens;// - the SOCKET, open while the app is in front: each frame goes to//   `chat.incoming`, a ping every 30 s, a reconnect with backoff;// - the CLOCKS: `chat.flush` at the outbox's `nextAt`, the other person's//   typing drawn for 6 s, and this person's own typing said at most every 4 s//   and taken back after 5 s without a key;// - the NETWORK: when the phone's path comes back (unsatisfied, then//   satisfied for a second, so a flapping path asks once) while the app is in//   front, it connects at once rather than when the socket's backoff runs out,//   and what was written offline goes (`chat.flush { online: true }`), not when//   the outbox's backoff (up to five minutes) runs out. Every connect that the//   object answered flushes so, as Android's does; none while the path is down.//// Registration (`chat.register`) waits for the object: a launch often asks// before `personal.connect` has opened its door, which the core refuses// `not_connected`, so it is asked again every 10 s, 30 times, and at once when// the door opens or the app comes back. A new alert token registers again.// Sign-out asks the object, through the core, to forget this phone's chat// device before the credential goes, then forgets the key and the names here.// The socket opens with a ticket the core asks the object for: the device's// credential never leaves Rust.import CottonKitimport CottonMailboximport CottonUIimport Foundationimport Observation@MainActor@Observablepublic final class ChatCenter: CottonChatting {    public struct Ports {        public var socket: any ChatSocketPort        public var clock: any ChatClock        public var secrets: any ChatSecrets        /// Where the names the extension titles alerts with are kept (`ChatNames`).        public var names: UserDefaults?        /// Where opened pictures are written.        public var pictures: URL        /// The phone's network path; nil reads as always online.        public var path: (any ChatPathPort)?        public init(socket: any ChatSocketPort, clock: any ChatClock, secrets: any ChatSecrets, names: UserDefaults?, pictures: URL,                    path: (any ChatPathPort)? = nil) {            self.socket = socket            self.clock = clock            self.secrets = secrets            self.names = names            self.pictures = pictures            self.path = path        }    }    static let registerRetry: Int64 = 10_000    static let registerRetries = 30    static let ping: Int64 = 30_000    static let theirTyping: Int64 = 6_000    static let typingAgain: Int64 = 4_000    static let typingIdle: Int64 = 5_000    static let backoffFirst: Int64 = 1_000    static let backoffMax: Int64 = 60_000    /// How long a path that came back must stay up before it counts.    static let backOnlineSettle: Int64 = 1_000    /// The other person typing, by thread, until when.    public private(set) var typingUntil: [String: Int64] = [:]    public private(set) var readReceipts = false    public private(set) var sendsTyping = false    /// Whether this app's chats signal at all (`chat.settings`' `offered`,    /// the kit's `signals`): where they do not, no read receipt and no    /// typing is sent or drawn, and no switch is offered.    public private(set) var signals = false    /// Whether this phone's chat key is published to its object.    public private(set) var registered = false    @ObservationIgnored private let ports: Ports    @ObservationIgnored private let core: @Sendable () async -> (any ChatCore)?    @ObservationIgnored private let topic: String?    @ObservationIgnored private let log: @Sendable (String) -> Void    @ObservationIgnored private var chain: Task<Void, Never>?    @ObservationIgnored private var foreground = false    @ObservationIgnored private var token: String?    @ObservationIgnored private var registeredToken: String?    @ObservationIgnored private var registerTries = 0    @ObservationIgnored private var registerTimer: (any ChatTimer)?    @ObservationIgnored private var socketOpen = false    @ObservationIgnored private var backoff: Int64 = ChatCenter.backoffFirst    @ObservationIgnored private var reconnectTimer: (any ChatTimer)?    @ObservationIgnored private var pingTimer: (any ChatTimer)?    @ObservationIgnored private var flushTimer: (any ChatTimer)?    @ObservationIgnored private var typingTimers: [String: any ChatTimer] = [:]    @ObservationIgnored private var saidTypingAt: [String: Int64] = [:]    @ObservationIgnored private var idleTimers: [String: any ChatTimer] = [:]    @ObservationIgnored private var visible: String?    /// The phone's network as last reported; nil before the first report.    @ObservationIgnored private var online: Bool?    @ObservationIgnored private var backOnlineTimer: (any ChatTimer)?    /// `topic` is this app's bundle id, which its alert token is filed under.    public init(ports: Ports, topic: String?, core: @escaping @Sendable () async -> (any ChatCore)?, log: @escaping @Sendable (String) -> Void = { _ in }) {        self.ports = ports        self.topic = topic        self.core = core        self.log = log        ports.path?.watch { [weak self] satisfied in self?.pathChanged(satisfied) }    }    // MARK: The app's life    /// The app came to the front (or launched there): register if owed, open    /// the socket, take what waits and send what is queued.    public func foregrounded() {        foreground = true        connect()    }    /// The app went to the back: the socket closes and the clocks stop; a    /// message arriving now is the push's.    public func backgrounded() {        foreground = false        if let visible { stopTyping(thread: visible) }        closeSocket()        reconnectTimer?.cancel()        flushTimer?.cancel()        backOnlineTimer?.cancel()    }    /// The phone's network path changed. Back (it was down, and is up still    /// after `backOnlineSettle`) with the app in front: connect now, which    /// sends what waited. Down: nothing is asked.    func pathChanged(_ satisfied: Bool) {        let was = online        online = satisfied        guard satisfied else {            backOnlineTimer?.cancel()            backOnlineTimer = nil            return        }        // The first report, or still up: nothing came back.        guard was == false else { return }        backOnlineTimer?.cancel()        backOnlineTimer = ports.clock.after(milliseconds: Self.backOnlineSettle) { [weak self] in            guard let self else { return }            self.backOnlineTimer = nil            guard self.online == true, self.foreground else { return }            self.log("chat: the network is back")            self.backoff = Self.backoffFirst            self.reconnectTimer?.cancel()            self.connect()        }    }    /// APNs handed this phone an alert token (lowercase hex).    public func alertToken(_ hex: String) {        guard hex != token else { return }        token = hex        registerTries = 0        connect()    }    /// The object's door opened (a sign-in, a connect).    public func doorOpened() {        registerTries = 0        connect()    }    /// The person is signing out, the door still open: the object forgets    /// this phone's chat device (its key, its token and what waits for it),    /// asked by the core on its door (`chat.forget`). Awaited, so it goes    /// before the credential does; a refusal leaves the object's own sign-out    /// to forget it.    public func forgetDevice() async {        guard let core = await core() else { return }        do {            _ = try await core.ask("chat.forget", .object([:]))        } catch {            log("chat: the object was not told to forget this phone: \((error as? CottonCallError)?.code ?? "refused")")        }    }    /// The person signed out: the key and the names go from here.    public func signedOut() {        closeSocket()        reconnectTimer?.cancel()        flushTimer?.cancel()        registerTimer?.cancel()        backOnlineTimer?.cancel()        ports.secrets.forget()        ChatNames.forget(in: ports.names)        ChatThreads.forget(in: ports.names)        registered = false        registeredToken = nil        typingUntil = [:]    }    // MARK: Connecting    private func connect() {        enqueue { [weak self] core in            guard let self else { return }            let key = try await self.key(core)            if !self.registered || self.registeredToken != self.token {                guard try await self.register(core, key: key) else { return }            }            if self.foreground, !self.socketOpen {                // A ticket the object minted for one socket, asked by the core on its door: no credential of this app's.                let socket = try await core.ask("chat.socket", .object([:]))                if let url = socket["url"]?.string, let ticket = socket["ticket"]?.string, let address = URL(string: url) {                    self.openSocket(address, ticket: ticket)                }            }            try await self.take(core, key: key, items: nil)            // The object just answered: what waited out a try that got no answer goes now.            try await self.flush(core, key: key, online: self.online != false)            // What was sent while the socket was down: the inbox is asked again (`SendCenter`).            NotificationCenter.default.post(name: .cottonSendArrived, object: nil)        }    }    /// This phone's chat key, minted the first time.    private func key(_ core: any ChatCore) async throws -> String {        if let held = ports.secrets.key() { return held }        let minted = try await core.ask("chat.key", .object([:]))        guard let key = minted["privateKey"]?.string else { throw CottonCallError(code: "no_key", message: ShellLines.line("chat", "refused.no_key")) }        try ports.secrets.saveKey(key)        log("chat: a key was minted")        return key    }    /// The key published (and the token filed); false while the object waits.    private func register(_ core: any ChatCore, key: String) async throws -> Bool {        var request: [String: JSONValue] = ["privateKey": .string(key)]        let token = self.token        if let token, let topic {            request["platform"] = .string("ios")            request["token"] = .string(token)            request["topic"] = .string(topic)            // `aps-environment` is production on every build (`Cotton.entitlements`).            request["sandbox"] = .bool(false)        }        do {            _ = try await core.ask("chat.register", .object(request))            registered = true            registeredToken = token            registerTimer?.cancel()            log("chat: registered\(token == nil ? "" : " with a token")")            return true        } catch let refusal as CottonCallError where refusal.code == "not_connected" {            guard registerTries < Self.registerRetries else { return false }            registerTries += 1            registerTimer?.cancel()            registerTimer = ports.clock.after(milliseconds: Self.registerRetry) { [weak self] in self?.connect() }            return false        }    }    // MARK: The socket    private func openSocket(_ url: URL, ticket: String) {        socketOpen = true        ports.socket.open(url: url, ticket: ticket, received: { [weak self] frame in            self?.frame(frame)        }, closed: { [weak self] in            self?.socketClosed()        })        // What this build speaks, said first: the object rings it the new way (an ack per ring, a late ring, a missed        // call kept for it); a build that says nothing is rung as before (CALLS FIX 2).        ports.socket.send(.object(["t": .string("hello"), "can": .array(CallRingFrame.can.map { .string($0) })]))        armPing()    }    private func closeSocket() {        socketOpen = false        pingTimer?.cancel()        ports.socket.close()    }    private func armPing() {        pingTimer?.cancel()        pingTimer = ports.clock.after(milliseconds: Self.ping) { [weak self] in            guard let self, self.socketOpen else { return }            self.ports.socket.send(.object(["t": .string("ping")]))            self.armPing()        }    }    func frame(_ frame: JSONValue) {        // Anything heard means the socket is up: the next drop starts its wait afresh.        backoff = Self.backoffFirst        // A send arrived for this person: the inbox lands it on its thread (`SendCenter`).        if frame["t"]?.string == "send" { return NotificationCenter.default.post(name: .cottonSendArrived, object: nil) }        // A call's ring or its stop: the Worker rings a phone with this socket open here and NOT by push, so a phone        // with Comms open rings only if this is taken (the calls engine takes it as a push; Android: ChatFrames.ring).        if let ring = CallRingFrame(frame: frame) {            // Acked at once: a frame the socket took is not proof this phone rang, so the Worker pushes as well unless            // the ack comes (CALLS FIX 1); a stop is acked so its missed call is not kept for this phone.            ports.socket.send(.object(["t": .string("ring_ack"), "room": .string(ring.room)]))            return NotificationCenter.default.post(name: CallRingFrame.arrived, object: ring)        }        // Someone this person waited for can be written to now: the outbox's pass sends what waited (chat-people).        if frame["t"]?.string == "reach" {            enqueue { [weak self] core in                guard let self, let key = self.ports.secrets.key() else { return }                try await self.flush(core, key: key)            }            return        }        guard frame["t"]?.string == "envelope", let item = frame["item"] else { return }        enqueue { [weak self] core in            guard let self, let key = self.ports.secrets.key() else { return }            try await self.take(core, key: key, items: [item])        }    }    private func socketClosed() {        socketOpen = false        pingTimer?.cancel()        guard foreground else { return }        let wait = backoff        backoff = min(backoff * 2, Self.backoffMax)        reconnectTimer?.cancel()        reconnectTimer = ports.clock.after(milliseconds: wait) { [weak self] in            // With the path down the path's return connects (`pathChanged`).            guard let self, self.foreground, self.online != false else { return }            self.connect()        }    }    // MARK: What arrives    /// `chat.incoming` over the socket's items, or the inbox when nil; what it    /// answers moves the typing clocks, the names and the read receipt.    private func take(_ core: any ChatCore, key: String, items: [JSONValue]?) async throws {        var request: [String: JSONValue] = ["privateKey": .string(key)]        if let items { request["items"] = .array(items) }        let answer = try await core.ask("chat.incoming", .object(request))        for typing in answer["typing"]?.array ?? [] {            guard let thread = typing["thread"]?.string else { continue }            theyTyped(thread: thread, on: typing["on"]?.bool == true)        }        var names: [String: String] = [:]        var threads: [String: String] = [:]        var landedHere = false        for landed in answer["landed"]?.array ?? [] {            if let peer = landed["peer"]?.string, let name = landed["name"]?.string { names[peer] = name }            // The thread the core lands this number in, for the extension's            // alerts and a notification's tap (`ChatThreads`). Every message            // lands in its number's thread in this build (groups land later).            if let peer = landed["peer"]?.string, let thread = landed["thread"]?.string { threads[peer] = thread }            if let thread = landed["thread"]?.string {                // A message from them ends their typing.                if landed["out"]?.bool != true { theyTyped(thread: thread, on: false) }                if thread == visible { landedHere = true }                // Cotton Chat's list and thread draw again only what changed.                NotificationCenter.default.post(name: .cottonChatLanded, object: nil, userInfo: ["thread": thread])            }        }        if !names.isEmpty { ChatNames.remember(names, in: ports.names) }        if !threads.isEmpty { ChatThreads.remember(threads, in: ports.names) }        // Chats read on another of the person's phones: read here too, so        // their notifications go (`ChatNotifier` asks `chat.notices`).        for readThere in answer["read"]?.array ?? [] {            if let thread = readThere.string { NotificationCenter.default.post(name: .cottonChatRead, object: nil, userInfo: ["thread": thread]) }        }        if landedHere, let visible { try await read(core, key: key, thread: visible) }    }    private func theyTyped(thread: String, on: Bool) {        typingTimers[thread]?.cancel()        guard on else {            typingTimers[thread] = nil            typingUntil[thread] = nil            return        }        typingUntil[thread] = ports.clock.now() + Self.theirTyping        typingTimers[thread] = ports.clock.after(milliseconds: Self.theirTyping) { [weak self] in            self?.typingTimers[thread] = nil            self?.typingUntil[thread] = nil        }    }    private func read(_ core: any ChatCore, key: String, thread: String) async throws {        _ = try await core.ask("chat.receipt", .object(["thread": .string(thread), "privateKey": .string(key)]))    }    // MARK: The outbox    private func flush(_ core: any ChatCore, key: String, online: Bool = false) async throws {        var request: [String: JSONValue] = ["privateKey": .string(key)]        if online { request["online"] = .bool(true) }        let answer = try await core.ask("chat.flush", .object(request))        schedule(nextAt: answer["nextAt"])    }    /// The outbox's next attempt, on the clock: `nextAt` is when (ms), null when nothing waits.    private func schedule(nextAt: JSONValue?) {        flushTimer?.cancel()        flushTimer = nil        guard let at = nextAt?.double else { return }        let wait = max(0, Int64(at) - ports.clock.now())        flushTimer = ports.clock.after(milliseconds: wait) { [weak self] in            // With the path down the path's return flushes (`pathChanged`).            guard self?.online != false else { return }            self?.enqueue { [weak self] core in                guard let self, let key = self.ports.secrets.key() else { return }                try await self.flush(core, key: key)            }        }    }    // MARK: What the person does    /// What `chat.act` queued goes now rather than at the outbox's next tick.    public func flush() async {        enqueue { [weak self] core in            guard let self, let key = self.ports.secrets.key() else { return }            try await self.flush(core, key: key)        }    }    public func send(thread: String, body: String?, replyTo: String?, pictures: [ChatPicture]) async throws {        stopTyping(thread: thread)        var request: [String: JSONValue] = ["thread": .string(thread)]        if let body { request["body"] = .string(body) }        if let replyTo { request["replyTo"] = .string(replyTo) }        if !pictures.isEmpty {            request["pictures"] = .array(pictures.map { picture in                var one: [String: JSONValue] = ["path": .string(picture.path), "mime": .string(picture.mime)]                if let width = picture.width { one["width"] = .number(Double(width)) }                if let height = picture.height { one["height"] = .number(Double(height)) }                return .object(one)            })        }        let answer = try await keyed("chat.send", request)        schedule(nextAt: answer["nextAt"])    }    public func retry(message: String) async throws {        let answer = try await keyed("chat.retry", ["message": .string(message)])        schedule(nextAt: answer["nextAt"])    }    /// A key pressed: typing is said once, again every 4 s while it goes on,    /// and taken back 5 s after the last key.    public func typed(thread: String) {        let now = ports.clock.now()        if now - (saidTypingAt[thread] ?? .min / 2) >= Self.typingAgain {            saidTypingAt[thread] = now            sayTyping(thread: thread, on: true)        }        idleTimers[thread]?.cancel()        idleTimers[thread] = ports.clock.after(milliseconds: Self.typingIdle) { [weak self] in self?.stopTyping(thread: thread) }    }    private func stopTyping(thread: String) {        idleTimers[thread]?.cancel()        idleTimers[thread] = nil        guard saidTypingAt.removeValue(forKey: thread) != nil else { return }        sayTyping(thread: thread, on: false)    }    private func sayTyping(thread: String, on: Bool) {        // An app whose chats do not signal says nothing; the core would refuse it too.        guard signals else { return }        enqueue { [weak self] core in            guard let key = try await self?.key(core) else { return }            _ = try await core.ask("chat.typing", .object(["thread": .string(thread), "on": .bool(on), "privateKey": .string(key)]))        }    }    public func showing(thread: String?) {        if let visible, visible != thread { stopTyping(thread: visible) }        visible = thread        guard let thread else { return }        enqueue { [weak self] core in            guard let self else { return }            try await self.read(core, key: try await self.key(core), thread: thread)        }    }    public func isTyping(thread: String) -> Bool {        (typingUntil[thread] ?? 0) > ports.clock.now()    }    public func decide(thread: String, _ decision: ChatDecision) async throws {        _ = try await ask("chat.\(decision.rawValue)", .object(["thread": .string(thread)]))        // Accepted while it shows: what the request brought is read now, and        // the sender told (a request's messages stay unread until then).        if decision == .accept, thread == visible { _ = try? await keyed("chat.receipt", ["thread": .string(thread)]) }    }    public func start(number: String?, person: String?) async throws -> String {        var request: [String: JSONValue] = [:]        if let number { request["number"] = .string(number) }        if let person { request["person"] = .string(person) }        let answer = try await ask("chat.start", .object(request))        guard let thread = answer["thread"]?.string else { throw CottonCallError(code: "not_found", message: ShellLines.line("chat", "refused.not_found")) }        if let number = answer["number"]?.string, let name = answer["name"]?.string { ChatNames.remember([number: name], in: ports.names) }        if let number = answer["number"]?.string { ChatThreads.remember([number: thread], in: ports.names) }        return thread    }    // MARK: What the notifications ask (`ChatNotifier`)    /// What waits in the inbox, landed now (a background push, a response    /// to a notification), every ask before it answered first.    public func landWaiting() async {        enqueue { [weak self] core in            guard let self else { return }            try await self.take(core, key: try await self.key(core), items: nil)        }        await settled()    }    /// What `chat.act` queued, sent now and awaited (a Reply or a Mark as    /// read from a notification, which iOS gives only a moment).    public func flushNow() async {        await flush()        await settled()    }    /// Any of the core's `chat.*` methods, with this phone's chat key when    /// it seals or opens (`keyed`).    public func call(_ method: String, _ request: [String: JSONValue] = [:], keyed: Bool = false) async throws -> JSONValue {        if keyed { return try await self.keyed(method, request) }        return try await ask(method, .object(request))    }    public func picture(message: String, index: Int) async throws -> URL {        let answer = try await ask("chat.picture", .object([            "message": .string(message), "index": .number(Double(index)), "dir": .string(ports.pictures.path),        ]))        guard let path = answer["path"]?.string else { throw CottonCallError(code: "unreadable", message: ShellLines.line("chat", "refused.not_found")) }        return URL(fileURLWithPath: path)    }    /// The two switches as the core keeps them.    public func loadSettings() async {        guard let answer = try? await ask("chat.settings", .object([:])) else { return }        apply(settings: answer)    }    public func set(readReceipts: Bool?, typing: Bool?) async throws {        var request: [String: JSONValue] = [:]        if let readReceipts { request["readReceipts"] = .bool(readReceipts) }        if let typing { request["typing"] = .bool(typing) }        apply(settings: try await ask("chat.settings", .object(request)))    }    private func apply(settings: JSONValue) {        if let on = settings["readReceipts"]?.bool { readReceipts = on }        if let on = settings["typing"]?.bool { sendsTyping = on }        signals = settings["offered"]?.bool ?? false    }    // MARK: The asks    /// A call that seals or opens: the key goes with it.    public func keyed(_ method: String, _ request: [String: JSONValue]) async throws -> JSONValue {        guard let core = await core() else { throw CottonCallError(code: "not_signed_in", message: ShellLines.line("chat", "refused.not_signed_in")) }        let key = try await self.key(core)        var request = request        request["privateKey"] = .string(key)        return try await core.ask(method, .object(request))    }    private func ask(_ method: String, _ request: JSONValue) async throws -> JSONValue {        guard let core = await core() else { throw CottonCallError(code: "not_signed_in", message: ShellLines.line("chat", "refused.not_signed_in")) }        return try await core.ask(method, request)    }    /// The engine's own asks, one at a time and in order; a refusal is logged.    private func enqueue(_ work: @escaping @MainActor (any ChatCore) async throws -> Void) {        let before = chain        let core = self.core        let log = self.log        chain = Task { @MainActor in            await before?.value            guard let core = await core() else { return }            do {                try await work(core)            } catch let refusal as CottonCallError {                log("chat: refused \(refusal.code)")            } catch {                log("chat: \(error)")            }        }    }    /// Everything asked so far has been answered (a test's wait).    func settled() async {        while let chain {            await chain.value            if chain == self.chain { return }        }    }}