// The call engine: every `calls.*` answer's effects performed, in order, on // the ports, and what happened handed back as the next method. // // It decides nothing. A tap asks the core (`calls.start`, `calls.end`, …), a // VoIP push asks it (`calls.incoming`, `calls.stop`), the socket's frames, the // peer's descriptions and ICE state and every timer ask it; each answer is // `{ call, effects }`, drawn and performed here. The asks run one at a time, // in the order they happened, so an answer's effects are all performed before // the next event reaches the core. import CottonKit import Foundation import Observation @MainActor @Observable public final class CallCenter { /// The ports, made once by whoever builds the center. public struct Ports { public var system: any SystemCallPort public var socket: any CallSocketPort public var peer: any CallPeerPort public var audio: any CallAudioPort public var tone: any CallTonePort public var clock: any CallClockPort public init(system: any SystemCallPort, socket: any CallSocketPort, peer: any CallPeerPort, audio: any CallAudioPort, tone: any CallTonePort, clock: any CallClockPort) { self.system = system self.socket = socket self.peer = peer self.audio = audio self.tone = tone self.clock = clock } } /// The call as the core last answered it. public private(set) var call: CallState = .idle /// The loudspeaker: a route of this phone's, never the core's. public private(set) var speaker = false /// The core's words for a refused ask (`calls.start` refused `no_number`), /// to be said once and taken. public var refusal: String? /// Every effect performed, by name, in order: what a walk and the tests read. public private(set) var performed: [String] = [] /// Moves whenever a group call's roster does (who is in, talking, muted, taking notes): the screen asks again. public private(set) var rosterMoved = 0 /// What this app's call screen can show, said on a call's start, ring, join and enter (`can`): Comms draws Take /// notes' mark (`["notes"]`), so the room counts it among the phones that show it (chat/CONTRACT.md "Take notes"). @ObservationIgnored public var can: [String] = [] /// `request` with `can`, where this app says it can show something. private func saying(_ request: JSONValue) -> JSONValue { guard !can.isEmpty, case .object(var fields) = request else { return request } fields["can"] = .array(can.map(JSONValue.string)) return .object(fields) } @ObservationIgnored private let ports: Ports @ObservationIgnored private let core: @Sendable () async -> (any CallsCore)? /// The asks, chained: each waits for the one before it. @ObservationIgnored private var chain: Task? /// The socket's generation: a frame or a close from a socket since closed is dropped. @ObservationIgnored private var socketGeneration = 0 @ObservationIgnored private var log: @Sendable (String) -> Void public init(ports: Ports, core: @escaping @Sendable () async -> (any CallsCore)?, log: @escaping @Sendable (String) -> Void = { _ in }) { self.ports = ports self.core = core self.log = log } // MARK: What a person does /// Call a person in this copy (`calls.start { person, video }`). A /// refusal's words (`no_number`, `in_a_call`) go to `refused` as well as /// `refusal`. public func start(person: String, video: Bool, refused: (@MainActor (String) -> Void)? = nil) { ask("calls.start", saying(.object(["person": .string(person), "video": .bool(video)])), refused: refused) } /// Call a number as typed (`calls.start { number, video }`). public func start(number: String, video: Bool) { ask("calls.start", saying(.object(["number": .string(number), "video": .bool(video)]))) } /// Any method that answers as `calls.start` does (`chat.call`): the call /// it answers is taken and its effects performed, in turn with the rest. /// /// `answered` reads the whole answer once its effects are performed: `chat.call` on a group says `flush: true`, /// so the group's sealed `call` word goes out by the next `chat.flush`. public func place(_ method: String, _ request: JSONValue, refused: (@MainActor (String) -> Void)? = nil, answered: (@MainActor (JSONValue) -> Void)? = nil) { let request = saying(request) enqueue(refused: refused) { [weak self] core in guard let self else { return } let answer = try await core.ask(method, request) self.take(answer) answered?(answer) } } /// Take notes on this call, or stop (`calls.notes { on }`): the room tells everyone, and the mark follows. public func notes(on: Bool) { ask("calls.notes", .object(["on": .bool(on)])) } /// A read the engine performs nothing for (`chat.callScreen`), outside the /// chain of asks: nil when there is no core or it refuses. public func read(_ method: String, _ request: JSONValue) async -> JSONValue? { guard let core = await core() else { return nil } return try? await core.ask(method, request) } public func answer() { ask("calls.answer", .object([:])) } public func decline() { ask("calls.decline", .object([:])) } /// Hang up, or cancel a call still ringing out. public func end() { ask("calls.end", .object([:])) } /// Mute or unmute the microphone. public func toggleMute() { mute(audio: !call.sendingAudio) } /// The microphone as CallKit's own mute says it. public func mute(audio: Bool) { ask("calls.mute", .object(["audio": .bool(audio), "video": .bool(call.sendingVideo)])) } /// Turn this phone's camera on or off. public func toggleVideo() { ask("calls.mute", .object(["audio": .bool(call.sendingAudio), "video": .bool(!call.sendingVideo)])) } public func toggleSpeaker() { speaker.toggle() ports.audio.setSpeaker(speaker) } /// A `cottoncalling://call?…` link another app opened: the core reads it, /// and a call to its one person starts. public func open(link: URL) { enqueue { [weak self] core in guard let self else { return } let read = try await core.ask("calls.openLink", .object(["url": .string(link.absoluteString)])) guard let person = read["people"]?.strings?.first else { return } let video = read["video"]?.bool ?? false try await self.run(core, "calls.start", self.saying(.object(["person": .string(person), "video": .bool(video)]))) } } // MARK: What the system says /// A VoIP push rang this phone. The push handler has ALREADY reported the /// call to CallKit (`VoIPPushes`): iOS ends an app that does not report a /// call for every VoIP push before its handler returns. /// /// `ring` is the push's sealed box naming the caller, opened by the core /// with this phone's chat key (`privateKey`) without the network, so /// `system_call_incoming` names them at once. `later` asks the core to /// answer before the join; when its answer names the room to `join`, /// `calls.join` is asked next, in turn, its effects performed the same way. /// `pushed`: a VoIP push, already reported to CallKit, so a ring for a call that ended here is ended at once. /// `at`: when the ring began, as the object kept it: a phone rung late starts the call there. public func incoming(room: String, video: Bool, ring: String? = nil, privateKey: String? = nil, pushed: Bool = false, at: Int64? = nil) { var request: [String: JSONValue] = ["room": .string(room), "video": .bool(video), "later": .bool(true)] if pushed { request["pushed"] = .bool(true) } if let at { request["at"] = .number(Double(at)) } if let ring, let privateKey { request["ring"] = .string(ring) request["privateKey"] = .string(privateKey) } let rung = saying(.object(request)) let joining = { (room: String) in self.saying(.object(["room": .string(room)])) } enqueue { [weak self] core in guard let self else { return } let answer = try await core.ask("calls.incoming", rung) self.take(answer) guard let join = answer["join"]?.string else { return } try await self.run(core, "calls.join", joining(join)) } } /// A stop push: the ring here is over (answered elsewhere, cancelled). /// A ring stopped. `ring` (with this phone's chat key) names who called on a missed call's stop, so a phone that /// never heard the ring writes its Missed row all the same (`calls.stop`, CALLS FIX 1). /// `times`: when it rang and ended, for that row; `pushed`: a VoIP push, already reported to CallKit (and ended /// at once when this phone holds no such call); over the socket nothing was reported, and nothing rings. public func stop(room: String, reason: String, ring: String? = nil, privateKey: String? = nil, times: CallTimes? = nil, pushed: Bool = false) { var request: [String: JSONValue] = ["room": .string(room), "reason": .string(reason)] if let ring, let privateKey { request["ring"] = .string(ring) request["privateKey"] = .string(privateKey) } if let times { request["at"] = .number(Double(times.at)) request["ended"] = .number(Double(times.ended)) } if pushed { request["pushed"] = .bool(true) } ask("calls.stop", .object(request)) } /// A ring or a stop came by VoIP push: the object is told this phone has it (`calls.ack`), as a socket's frame is /// acked, so it pushes no more and keeps no missed call for it (CALLS FIX 2). Apart from the asks' chain, so it never /// holds up the ring; a failure (an older Worker's 404, no network) is never shown, only logged, and tried again /// quietly, every `ackRetry` ms, at most `ackTries` times (CALLS FIX 3). public func ack(room: String, tries: Int = 0) { let before = acks let core = self.core let log = self.log acks = Task { @MainActor [weak self] in await before?.value guard let core = await core() else { return } do { _ = try await core.ask("calls.ack", .object(["room": .string(room)])) } catch { log("calls: an ack was not taken (\(error)); tried again later") guard let self, tries + 1 < Self.ackTries else { return } self.ports.clock.after(milliseconds: Self.ackRetry) { [weak self] in self?.ack(room: room, tries: tries + 1) } } } } static let ackTries = 5 static let ackRetry = 15_000 /// The acks, chained apart from the asks. @ObservationIgnored private var acks: Task? /// The person ended the call on the system's call screen. public func systemEnded() { if call.phase == .ringingIn { decline() } else { end() } } /// CallKit activated or deactivated the audio session. public func audioActivated() { ports.audio.activated() } public func audioDeactivated() { ports.audio.deactivated() } /// VoIP push token, as PushKit hands it. PushKit hands it at launch, /// often before this phone has connected to its object, which the core /// refuses `not_connected`: the token is kept and sent again until the /// object takes it (every `pushRetry` ms, at most `pushRetries` times), and /// again at each `refresh` (a return to the app). public func pushToken(_ token: Data, topic: String, sandbox: Bool) { let hex = token.map { String(format: "%02x", $0) }.joined() var token: [String: JSONValue] = ["platform": .string("ios"), "token": .string(hex), "topic": .string(topic), "sandbox": .bool(sandbox)] // Comms speaks the new way (it acks each ring and takes a missed call kept for it); Cotton Calling says nothing. if topic.hasPrefix("com.cottondb.messages") { token["can"] = .array(CallRingFrame.can.map { .string($0) }) } pending = .object(token) pushTries = 0 sendToken() } static let pushRetry = 10_000 static let pushRetries = 30 @ObservationIgnored private var pending: JSONValue? @ObservationIgnored private var pushTries = 0 private func sendToken() { guard let token = pending else { return } let log = self.log enqueue { [weak self] core in do { _ = try await core.ask("calls.pushToken", token) if self?.pending == token { self?.pending = nil } } catch let refusal as CottonCallError where refusal.code == "not_connected" { guard let self, self.pending == token, self.pushTries < Self.pushRetries else { return } self.pushTries += 1 log("calls: the push token waits for the object (\(self.pushTries))") self.ports.clock.after(milliseconds: Self.pushRetry) { [weak self] in self?.sendToken() } } } } /// The call as the core holds it now (a launch, a return to the app). public func refresh() { sendToken() enqueue { [weak self] core in let held = try await core.ask("calls.state", .object([:])) self?.call = CallState(json: held["call"] ?? .object([:])) } } // MARK: The asks, one at a time private func ask(_ method: String, _ request: JSONValue, refused: (@MainActor (String) -> Void)? = nil) { enqueue(refused: refused) { [weak self] core in try await self?.run(core, method, request) } } private func enqueue(refused: (@MainActor (String) -> Void)? = nil, _ work: @escaping @MainActor (any CallsCore) async throws -> Void) { let before = chain let core = self.core let log = self.log chain = Task { @MainActor [weak self] in await before?.value guard let core = await core() else { log("calls: no core to ask") return } do { try await work(core) } catch let refusal as CottonCallError { log("calls: refused \(refusal.code)") self?.refusal = refusal.message refused?(refusal.message) } catch { log("calls: \(error)") } } } /// A line in the calls log from the shell around the center (a Join tapped, a gate that held it). public func write(_ line: String) { log(line) } /// Wait for every ask made so far: the tests' and a walk's. public func settle() async { await chain?.value await acks?.value } private func run(_ core: any CallsCore, _ method: String, _ request: JSONValue) async throws { take(try await core.ask(method, request)) } /// One answer: its call drawn, its effects performed. private func take(_ json: JSONValue) { let answer = CallAnswer(json: json) call = answer.call // What a walk needs to follow a call: its phase and the effects' names, never an SDP or a credential. if !answer.effects.isEmpty || json["call"]?["phase"] != nil { let names = answer.effects.map(Self.name(of:)).filter { $0 != "send" && $0 != "add_candidate" } log("calls: \(json["call"]?["phase"]?.string ?? "-") \(json["call"]?["mode"]?.string ?? "")\(json["call"]?["reason"]?.string.map { " (\($0))" } ?? "") ← \(names.joined(separator: ","))") } perform(answer.effects) } // MARK: The effects /// Each effect on its port, in the order the core said them. func perform(_ effects: [CallEffect]) { for effect in effects { performed.append(Self.name(of: effect)) switch effect { case .systemCallOutgoing(let uuid, let handle, let name, let video): guard let uuid = UUID(uuidString: uuid) else { continue } ports.system.startOutgoing(uuid: uuid, handle: handle, name: name, video: video) case .systemCallConnecting(let uuid): UUID(uuidString: uuid).map(ports.system.outgoingConnecting) case .systemCallConnected(let uuid, let outgoing): // An incoming call is connected by its answer action, already fulfilled. if outgoing { UUID(uuidString: uuid).map(ports.system.outgoingConnected) } case .systemCallIncoming(let uuid, let title, let handle, let video): guard let uuid = UUID(uuidString: uuid) else { continue } ports.system.reportIncoming(uuid: uuid, title: title, handle: handle, video: video) case .systemCallUpdate(let uuid, let handle, let name, let video): guard let uuid = UUID(uuidString: uuid) else { continue } ports.system.update(uuid: uuid, handle: handle, name: name, video: video) case .systemCallEnded(let uuid, _, let ios): guard let uuid = UUID(uuidString: uuid) else { continue } ports.system.ended(uuid: uuid, reason: ios) case .startAudio(let video): ports.audio.configure(video: video) case .stopAudio: ports.audio.stop() speaker = false case .startCamera: ports.peer.startCamera() case .stopCamera: ports.peer.stopCamera() case .playTone(let tone): ports.tone.play(tone) case .stopTone: ports.tone.stop() case .openSocket(let url, let credential, let afterMs): openSocket(url: url, credential: credential, afterMs: afterMs) case .send(let frame): ports.socket.send(frame) case .closeSocket: socketGeneration += 1 ports.socket.close() case .createPeer(let offerer, let servers): ports.peer.create(offerer: offerer, iceServers: servers, video: call.video, events: peerEvents()) case .applyRemote(let kind, let sdp): ports.peer.applyRemote(kind: kind, sdp: sdp) case .addCandidate(let candidate, let mid, let mline): ports.peer.addCandidate(candidate, mid: mid, mline: mline) case .restartIce: ports.peer.restartIce() case .closePeer: ports.peer.close() case .setSending(let audio, let video): ports.peer.setSending(audio: audio, video: video) case .timer(let afterMs): ports.clock.after(milliseconds: afterMs) { [weak self] in self?.ask("calls.tick", .object([:])) } case .switchToSfu(let servers): ports.peer.switchToSfu(iceServers: servers, video: call.video, events: peerEvents()) case .pushTracks(let audio, let video): ports.peer.pushTracks(audio: audio, video: video) case .pullTracks: // The core asked the room for them already; they are claimed as their offer arrives. break case .closeTracks(let member): ports.peer.closeTracks(member: member) case .applySfu(let op, let sdp, let tracks): ports.peer.applySfu(op: op, sdp: sdp, tracks: tracks) case .showRoster: // Who is in, talking, muted, taking notes: the screen asks `chat.callScreen` again. rosterMoved += 1 case .unknown(let does): log("calls: an effect this build does not know: \(does)") } } } private func openSocket(url: URL, credential: String, afterMs: Int) { socketGeneration += 1 let generation = socketGeneration let open = { [weak self] in guard let self, self.socketGeneration == generation else { return } self.ports.socket.open(url: url, credential: credential, received: { [weak self] frame in guard let self, self.socketGeneration == generation else { return } self.ask("calls.signal", .object(["in": frame])) }, closed: { [weak self] in guard let self, self.socketGeneration == generation else { return } self.socketGeneration += 1 self.ask("calls.socketClosed", .object([:])) }) } if afterMs > 0 { ports.clock.after(milliseconds: afterMs) { open() } } else { open() } } private func peerEvents() -> CallPeerEvents { CallPeerEvents( signal: { [weak self] kind, sdp, candidate, mid, mline in var out: [String: JSONValue] = ["kind": .string(kind.rawValue)] if let sdp { out["sdp"] = .string(sdp) } if let candidate { out["candidate"] = .string(candidate) } if let mid { out["mid"] = .string(mid) } if let mline { out["mline"] = .number(Double(mline)) } self?.ask("calls.signal", .object(["out": .object(out)])) }, media: { [weak self] state in self?.ask("calls.media", .object(["state": .string(state.rawValue)])) }, sfu: { [weak self] op, sdp, tracks, mids in var out: [String: JSONValue] = ["sfu": .string(op)] if let sdp { out["sdp"] = .string(sdp) } if let tracks { out["tracks"] = .array(tracks.map(\.json)) } if let mids { out["mids"] = .array(mids.map(JSONValue.string)) } self?.ask("calls.signal", .object(["out": .object(out)])) }, speaking: { [weak self] on in self?.ask("calls.speaking", .object(["on": .bool(on)])) } ) } static func name(of effect: CallEffect) -> String { switch effect { case .systemCallOutgoing: "system_call_outgoing" case .systemCallConnecting: "system_call_connecting" case .systemCallConnected: "system_call_connected" case .systemCallIncoming: "system_call_incoming" case .systemCallUpdate: "system_call_update" case .systemCallEnded: "system_call_ended" case .startAudio: "start_audio" case .stopAudio: "stop_audio" case .startCamera: "start_camera" case .stopCamera: "stop_camera" case .playTone: "play_tone" case .stopTone: "stop_tone" case .openSocket: "open_socket" case .send: "send" case .closeSocket: "close_socket" case .createPeer: "create_peer" case .applyRemote: "apply_remote" case .addCandidate: "add_candidate" case .restartIce: "restart_ice" case .closePeer: "close_peer" case .setSending: "set_sending" case .timer: "timer" case .switchToSfu: "switch_to_sfu" case .pushTracks: "push_tracks" case .pullTracks: "pull_tracks" case .closeTracks: "close_tracks" case .applySfu: "apply_remote_sdp" case .showRoster: "show_roster" case .unknown(let does): does } } }