// 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.importCottonKitimportCottonMailboximportCottonUIimportFoundationimportObservation@MainActor@ObservablepublicfinalclassChatCenter: CottonChatting {publicstructPorts {publicvar socket: any ChatSocketPortpublicvar clock: any ChatClockpublicvar secrets: any ChatSecrets/// Where the names the extension titles alerts with are kept (`ChatNames`).publicvar names: UserDefaults?/// Where opened pictures are written.publicvar pictures: URL/// The phone's network path; nil reads as always online.publicvar path: (any ChatPathPort)?publicinit(socket: any ChatSocketPort, clock: any ChatClock, secrets: any ChatSecrets, names: UserDefaults?, pictures: URL, path: (any ChatPathPort)? = nil) {self.socket = socketself.clock = clockself.secrets = secretsself.names = namesself.pictures = picturesself.path = path } }staticlet registerRetry: Int64 = 10_000staticlet registerRetries = 30staticlet ping: Int64 = 30_000staticlet theirTyping: Int64 = 6_000staticlet typingAgain: Int64 = 4_000staticlet typingIdle: Int64 = 5_000staticlet backoffFirst: Int64 = 1_000staticlet backoffMax: Int64 = 60_000/// How long a path that came back must stay up before it counts.staticlet backOnlineSettle: Int64 = 1_000/// The other person typing, by thread, until when.publicprivate(set) var typingUntil: [String: Int64] = [:]publicprivate(set) var readReceipts = falsepublicprivate(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.publicprivate(set) var signals = false/// Whether this phone's chat key is published to its object.publicprivate(set) var registered = false @ObservationIgnored privatelet ports: Ports @ObservationIgnored privatelet core: @Sendable () async -> (any ChatCore)? @ObservationIgnored privatelet topic: String? @ObservationIgnored privatelet log: @Sendable (String) -> Void @ObservationIgnored privatevar chain: Task<Void, Never>? @ObservationIgnored privatevar foreground = false @ObservationIgnored privatevar token: String? @ObservationIgnored privatevar registeredToken: String? @ObservationIgnored privatevar registerTries = 0 @ObservationIgnored privatevar registerTimer: (any ChatTimer)? @ObservationIgnored privatevar socketOpen = false @ObservationIgnored privatevar backoff: Int64 = ChatCenter.backoffFirst @ObservationIgnored privatevar reconnectTimer: (any ChatTimer)? @ObservationIgnored privatevar pingTimer: (any ChatTimer)? @ObservationIgnored privatevar flushTimer: (any ChatTimer)? @ObservationIgnored privatevar typingTimers: [String: any ChatTimer] = [:] @ObservationIgnored privatevar saidTypingAt: [String: Int64] = [:] @ObservationIgnored privatevar idleTimers: [String: any ChatTimer] = [:] @ObservationIgnored privatevar visible: String?/// The phone's network as last reported; nil before the first report. @ObservationIgnored privatevar online: Bool? @ObservationIgnored privatevar backOnlineTimer: (any ChatTimer)?/// `topic` is this app's bundle id, which its alert token is filed under.publicinit(ports: Ports, topic: String?, core: @escaping @Sendable () async -> (any ChatCore)?, log: @escaping @Sendable (String) -> Void = { _ in }) {self.ports = portsself.topic = topicself.core = coreself.log = log ports.path?.watch { [weakself] satisfied inself?.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.publicfunc 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.publicfunc backgrounded() { foreground = falseiflet 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 = satisfiedguard satisfied else { backOnlineTimer?.cancel() backOnlineTimer = nilreturn }// The first report, or still up: nothing came back.guard was == falseelse { return } backOnlineTimer?.cancel() backOnlineTimer = ports.clock.after(milliseconds: Self.backOnlineSettle) { [weakself] inguardletselfelse { return }self.backOnlineTimer = nilguardself.online == true, self.foreground else { return }self.log("chat: the network is back")self.backoff = Self.backoffFirstself.reconnectTimer?.cancel()self.connect() } }/// APNs handed this phone an alert token (lowercase hex).publicfunc alertToken(_ hex: String) {guard hex != token else { return } token = hex registerTries = 0 connect() }/// The object's door opened (a sign-in, a connect).publicfunc 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.publicfunc forgetDevice() async {guardlet core = await core() else { return }do { _ = tryawait 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.publicfunc 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: Connectingprivatefunc connect() { enqueue { [weakself] core inguardletselfelse { return }let key = tryawaitself.key(core)if !self.registered || self.registeredToken != self.token {guardtryawaitself.register(core, key: key) else { return } }ifself.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 = tryawait core.ask("chat.socket", .object([:]))iflet url = socket["url"]?.string, let ticket = socket["ticket"]?.string, let address = URL(string: url) {self.openSocket(address, ticket: ticket) } }tryawaitself.take(core, key: key, items: nil)// The object just answered: what waited out a try that got no answer goes now.tryawaitself.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.privatefunc key(_ core: any ChatCore) asyncthrows -> String {iflet held = ports.secrets.key() { return held }let minted = tryawait core.ask("chat.key", .object([:]))guardlet key = minted["privateKey"]?.string else { throwCottonCallError(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.privatefunc register(_ core: any ChatCore, key: String) asyncthrows -> Bool {var request: [String: JSONValue] = ["privateKey": .string(key)]let token = self.tokeniflet 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 { _ = tryawait core.ask("chat.register", .object(request)) registered = true registeredToken = token registerTimer?.cancel() log("chat: registered\(token == nil ? "" : " with a token")")returntrue } catchlet refusal asCottonCallErrorwhere refusal.code == "not_connected" {guard registerTries < Self.registerRetries else { returnfalse } registerTries += 1 registerTimer?.cancel() registerTimer = ports.clock.after(milliseconds: Self.registerRetry) { [weakself] inself?.connect() }returnfalse } }// MARK: The socketprivatefunc openSocket(_ url: URL, ticket: String) { socketOpen = true ports.socket.open(url: url, ticket: ticket, received: { [weakself] frame inself?.frame(frame) }, closed: { [weakself] inself?.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() }privatefunc closeSocket() { socketOpen = false pingTimer?.cancel() ports.socket.close() }privatefunc armPing() { pingTimer?.cancel() pingTimer = ports.clock.after(milliseconds: Self.ping) { [weakself] inguardletself, 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" { returnNotificationCenter.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).iflet 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)]))returnNotificationCenter.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 { [weakself] core inguardletself, let key = self.ports.secrets.key() else { return }tryawaitself.flush(core, key: key) }return }guard frame["t"]?.string == "envelope", let item = frame["item"] else { return } enqueue { [weakself] core inguardletself, let key = self.ports.secrets.key() else { return }tryawaitself.take(core, key: key, items: [item]) } }privatefunc 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) { [weakself] in// With the path down the path's return connects (`pathChanged`).guardletself, self.foreground, self.online != falseelse { 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.privatefunc take(_ core: any ChatCore, key: String, items: [JSONValue]?) asyncthrows {var request: [String: JSONValue] = ["privateKey": .string(key)]iflet items { request["items"] = .array(items) }let answer = tryawait core.ask("chat.incoming", .object(request))for typing in answer["typing"]?.array ?? [] {guardlet thread = typing["thread"]?.string else { continue } theyTyped(thread: thread, on: typing["on"]?.bool == true) }var names: [String: String] = [:]var threads: [String: String] = [:]var landedHere = falsefor landed in answer["landed"]?.array ?? [] {iflet 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).iflet peer = landed["peer"]?.string, let thread = landed["thread"]?.string { threads[peer] = thread }iflet 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 ?? [] {iflet thread = readThere.string { NotificationCenter.default.post(name: .cottonChatRead, object: nil, userInfo: ["thread": thread]) } }if landedHere, let visible { tryawait read(core, key: key, thread: visible) } }privatefunc theyTyped(thread: String, on: Bool) { typingTimers[thread]?.cancel()guard on else { typingTimers[thread] = nil typingUntil[thread] = nilreturn } typingUntil[thread] = ports.clock.now() + Self.theirTyping typingTimers[thread] = ports.clock.after(milliseconds: Self.theirTyping) { [weakself] inself?.typingTimers[thread] = nilself?.typingUntil[thread] = nil } }privatefunc read(_ core: any ChatCore, key: String, thread: String) asyncthrows { _ = tryawait core.ask("chat.receipt", .object(["thread": .string(thread), "privateKey": .string(key)])) }// MARK: The outboxprivatefunc flush(_ core: any ChatCore, key: String, online: Bool = false) asyncthrows {var request: [String: JSONValue] = ["privateKey": .string(key)]if online { request["online"] = .bool(true) }let answer = tryawait 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.privatefunc schedule(nextAt: JSONValue?) { flushTimer?.cancel() flushTimer = nilguardlet at = nextAt?.double else { return }let wait = max(0, Int64(at) - ports.clock.now()) flushTimer = ports.clock.after(milliseconds: wait) { [weakself] in// With the path down the path's return flushes (`pathChanged`).guardself?.online != falseelse { return }self?.enqueue { [weakself] core inguardletself, let key = self.ports.secrets.key() else { return }tryawaitself.flush(core, key: key) } } }// MARK: What the person does/// What `chat.act` queued goes now rather than at the outbox's next tick.publicfunc flush() async { enqueue { [weakself] core inguardletself, let key = self.ports.secrets.key() else { return }tryawaitself.flush(core, key: key) } }publicfunc send(thread: String, body: String?, replyTo: String?, pictures: [ChatPicture]) asyncthrows { stopTyping(thread: thread)var request: [String: JSONValue] = ["thread": .string(thread)]iflet body { request["body"] = .string(body) }iflet replyTo { request["replyTo"] = .string(replyTo) }if !pictures.isEmpty { request["pictures"] = .array(pictures.map { picture invar one: [String: JSONValue] = ["path": .string(picture.path), "mime": .string(picture.mime)]iflet width = picture.width { one["width"] = .number(Double(width)) }iflet height = picture.height { one["height"] = .number(Double(height)) }return .object(one) }) }let answer = tryawait keyed("chat.send", request) schedule(nextAt: answer["nextAt"]) }publicfunc retry(message: String) asyncthrows {let answer = tryawait 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.publicfunc 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) { [weakself] inself?.stopTyping(thread: thread) } }privatefunc stopTyping(thread: String) { idleTimers[thread]?.cancel() idleTimers[thread] = nilguard saidTypingAt.removeValue(forKey: thread) != nilelse { return } sayTyping(thread: thread, on: false) }privatefunc 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 { [weakself] core inguardlet key = tryawaitself?.key(core) else { return } _ = tryawait core.ask("chat.typing", .object(["thread": .string(thread), "on": .bool(on), "privateKey": .string(key)])) } }publicfunc showing(thread: String?) {iflet visible, visible != thread { stopTyping(thread: visible) } visible = threadguardlet thread else { return } enqueue { [weakself] core inguardletselfelse { return }tryawaitself.read(core, key: tryawaitself.key(core), thread: thread) } }publicfunc isTyping(thread: String) -> Bool { (typingUntil[thread] ?? 0) > ports.clock.now() }publicfunc decide(thread: String, _ decision: ChatDecision) asyncthrows { _ = tryawait 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)]) } }publicfunc start(number: String?, person: String?) asyncthrows -> String {var request: [String: JSONValue] = [:]iflet number { request["number"] = .string(number) }iflet person { request["person"] = .string(person) }let answer = tryawait ask("chat.start", .object(request))guardlet thread = answer["thread"]?.string else { throwCottonCallError(code: "not_found", message: ShellLines.line("chat", "refused.not_found")) }iflet number = answer["number"]?.string, let name = answer["name"]?.string { ChatNames.remember([number: name], in: ports.names) }iflet 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.publicfunc landWaiting() async { enqueue { [weakself] core inguardletselfelse { return }tryawaitself.take(core, key: tryawaitself.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).publicfunc 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`).publicfunc call(_ method: String, _ request: [String: JSONValue] = [:], keyed: Bool = false) asyncthrows -> JSONValue {if keyed { returntryawaitself.keyed(method, request) }returntryawait ask(method, .object(request)) }publicfunc picture(message: String, index: Int) asyncthrows -> URL {let answer = tryawait ask("chat.picture", .object(["message": .string(message), "index": .number(Double(index)), "dir": .string(ports.pictures.path), ]))guardlet path = answer["path"]?.string else { throwCottonCallError(code: "unreadable", message: ShellLines.line("chat", "refused.not_found")) }return URL(fileURLWithPath: path) }/// The two switches as the core keeps them.publicfunc loadSettings() async {guardlet answer = try? await ask("chat.settings", .object([:])) else { return } apply(settings: answer) }publicfunc set(readReceipts: Bool?, typing: Bool?) asyncthrows {var request: [String: JSONValue] = [:]iflet readReceipts { request["readReceipts"] = .bool(readReceipts) }iflet typing { request["typing"] = .bool(typing) } apply(settings: tryawait ask("chat.settings", .object(request))) }privatefunc apply(settings: JSONValue) {iflet on = settings["readReceipts"]?.bool { readReceipts = on }iflet 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.publicfunc keyed(_ method: String, _ request: [String: JSONValue]) asyncthrows -> JSONValue {guardlet core = await core() else { throwCottonCallError(code: "not_signed_in", message: ShellLines.line("chat", "refused.not_signed_in")) }let key = tryawaitself.key(core)var request = request request["privateKey"] = .string(key)returntryawait core.ask(method, .object(request)) }privatefunc ask(_ method: String, _ request: JSONValue) asyncthrows -> JSONValue {guardlet core = await core() else { throwCottonCallError(code: "not_signed_in", message: ShellLines.line("chat", "refused.not_signed_in")) }returntryawait core.ask(method, request) }/// The engine's own asks, one at a time and in order; a refusal is logged.privatefunc enqueue(_ work: @escaping @MainActor (any ChatCore) asyncthrows -> Void) {let before = chainlet core = self.corelet log = self.log chain = Task { @MainActor inawait before?.valueguardlet core = await core() else { return }do {tryawait work(core) } catchlet refusal asCottonCallError { log("chat: refused \(refusal.code)") } catch { log("chat: \(error)") } } }/// Everything asked so far has been answered (a test's wait).func settled() async {whilelet chain {await chain.valueif chain == self.chain { return } } }}