// 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.importCottonKitimportFoundationimportObservation@MainActor@ObservablepublicfinalclassCallCenter {/// The ports, made once by whoever builds the center.publicstructPorts {publicvar system: any SystemCallPortpublicvar socket: any CallSocketPortpublicvar peer: any CallPeerPortpublicvar audio: any CallAudioPortpublicvar tone: any CallTonePortpublicvar clock: any CallClockPortpublicinit(system: any SystemCallPort, socket: any CallSocketPort, peer: any CallPeerPort, audio: any CallAudioPort, tone: any CallTonePort, clock: any CallClockPort) {self.system = systemself.socket = socketself.peer = peerself.audio = audioself.tone = toneself.clock = clock } }/// The call as the core last answered it.publicprivate(set) var call: CallState = .idle/// The loudspeaker: a route of this phone's, never the core's.publicprivate(set) var speaker = false/// The core's words for a refused ask (`calls.start` refused `no_number`),/// to be said once and taken.publicvar refusal: String?/// Every effect performed, by name, in order: what a walk and the tests read.publicprivate(set) var performed: [String] = []/// Moves whenever a group call's roster does (who is in, talking, muted, taking notes): the screen asks again.publicprivate(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 publicvar can: [String] = []/// `request` with `can`, where this app says it can show something.privatefunc 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 privatelet ports: Ports @ObservationIgnored privatelet core: @Sendable () async -> (any CallsCore)?/// The asks, chained: each waits for the one before it. @ObservationIgnored privatevar chain: Task<Void, Never>?/// The socket's generation: a frame or a close from a socket since closed is dropped. @ObservationIgnored privatevar socketGeneration = 0 @ObservationIgnored privatevar log: @Sendable (String) -> Voidpublicinit(ports: Ports, core: @escaping @Sendable () async -> (any CallsCore)?, log: @escaping @Sendable (String) -> Void = { _ in }) {self.ports = portsself.core = coreself.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`.publicfunc 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 }`).publicfunc 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`.publicfunc place(_ method: String, _ request: JSONValue, refused: (@MainActor (String) -> Void)? = nil, answered: (@MainActor (JSONValue) -> Void)? = nil) {let request = saying(request) enqueue(refused: refused) { [weakself] core inguardletselfelse { return }let answer = tryawait 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.publicfunc 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.publicfunc read(_ method: String, _ request: JSONValue) async -> JSONValue? {guardlet core = await core() else { returnnil }returntry? await core.ask(method, request) }publicfunc answer() { ask("calls.answer", .object([:])) }publicfunc decline() { ask("calls.decline", .object([:])) }/// Hang up, or cancel a call still ringing out.publicfunc end() { ask("calls.end", .object([:])) }/// Mute or unmute the microphone.publicfunc toggleMute() { mute(audio: !call.sendingAudio) }/// The microphone as CallKit's own mute says it.publicfunc mute(audio: Bool) { ask("calls.mute", .object(["audio": .bool(audio), "video": .bool(call.sendingVideo)])) }/// Turn this phone's camera on or off.publicfunc toggleVideo() { ask("calls.mute", .object(["audio": .bool(call.sendingAudio), "video": .bool(!call.sendingVideo)])) }publicfunc 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.publicfuncopen(link: URL) { enqueue { [weakself] core inguardletselfelse { return }let read = tryawait core.ask("calls.openLink", .object(["url": .string(link.absoluteString)]))guardlet person = read["people"]?.strings?.first else { return }let video = read["video"]?.bool ?? falsetryawaitself.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.publicfunc 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) }iflet at { request["at"] = .number(Double(at)) }iflet ring, let privateKey { request["ring"] = .string(ring) request["privateKey"] = .string(privateKey) }let rung = saying(.object(request))let joining = { (room: String) inself.saying(.object(["room": .string(room)])) } enqueue { [weakself] core inguardletselfelse { return }let answer = tryawait core.ask("calls.incoming", rung)self.take(answer)guardlet join = answer["join"]?.string else { return }tryawaitself.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.publicfunc 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)]iflet ring, let privateKey { request["ring"] = .string(ring) request["privateKey"] = .string(privateKey) }iflet 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).publicfunc ack(room: String, tries: Int = 0) {let before = ackslet core = self.corelet log = self.log acks = Task { @MainActor [weakself] inawait before?.valueguardlet core = await core() else { return }do { _ = tryawait core.ask("calls.ack", .object(["room": .string(room)])) } catch { log("calls: an ack was not taken (\(error)); tried again later")guardletself, tries + 1 < Self.ackTries else { return }self.ports.clock.after(milliseconds: Self.ackRetry) { [weakself] inself?.ack(room: room, tries: tries + 1) } } } }staticlet ackTries = 5staticlet ackRetry = 15_000/// The acks, chained apart from the asks. @ObservationIgnored privatevar acks: Task<Void, Never>?/// The person ended the call on the system's call screen.publicfunc systemEnded() {if call.phase == .ringingIn { decline() } else { end() } }/// CallKit activated or deactivated the audio session.publicfunc audioActivated() { ports.audio.activated() }publicfunc 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).publicfunc 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() }staticlet pushRetry = 10_000staticlet pushRetries = 30 @ObservationIgnored privatevar pending: JSONValue? @ObservationIgnored privatevar pushTries = 0privatefunc sendToken() {guardlet token = pending else { return }let log = self.log enqueue { [weakself] core indo { _ = tryawait core.ask("calls.pushToken", token)ifself?.pending == token { self?.pending = nil } } catchlet refusal asCottonCallErrorwhere refusal.code == "not_connected" {guardletself, 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) { [weakself] inself?.sendToken() } } } }/// The call as the core holds it now (a launch, a return to the app).publicfunc refresh() { sendToken() enqueue { [weakself] core inlet held = tryawait core.ask("calls.state", .object([:]))self?.call = CallState(json: held["call"] ?? .object([:])) } }// MARK: The asks, one at a timeprivatefunc ask(_ method: String, _ request: JSONValue, refused: (@MainActor (String) -> Void)? = nil) { enqueue(refused: refused) { [weakself] core intryawaitself?.run(core, method, request) } }privatefunc enqueue(refused: (@MainActor (String) -> Void)? = nil, _ work: @escaping @MainActor (any CallsCore) asyncthrows -> Void) {let before = chainlet core = self.corelet log = self.log chain = Task { @MainActor [weakself] inawait before?.valueguardlet core = await core() else { log("calls: no core to ask")return }do {tryawait work(core) } catchlet refusal asCottonCallError { 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).publicfunc write(_ line: String) { log(line) }/// Wait for every ask made so far: the tests' and a walk's.publicfunc settle() async {await chain?.valueawait acks?.value }privatefunc run(_ core: any CallsCore, _ method: String, _ request: JSONValue) asyncthrows { take(tryawait core.ask(method, request)) }/// One answer: its call drawn, its effects performed.privatefunc 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):guardlet 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):guardlet 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):guardlet uuid = UUID(uuidString: uuid) else { continue } ports.system.update(uuid: uuid, handle: handle, name: name, video: video)case .systemCallEnded(let uuid, _, let ios):guardlet 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 = falsecase .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) { [weakself] inself?.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.breakcase .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 += 1case .unknown(let does): log("calls: an effect this build does not know: \(does)") } } }privatefunc openSocket(url: URL, credential: String, afterMs: Int) { socketGeneration += 1let generation = socketGenerationletopen = { [weakself] inguardletself, self.socketGeneration == generation else { return }self.ports.socket.open(url: url, credential: credential, received: { [weakself] frame inguardletself, self.socketGeneration == generation else { return }self.ask("calls.signal", .object(["in": frame])) }, closed: { [weakself] inguardletself, self.socketGeneration == generation else { return }self.socketGeneration += 1self.ask("calls.socketClosed", .object([:])) }) }if afterMs > 0 { ports.clock.after(milliseconds: afterMs) { open() } } else {open() } }privatefunc peerEvents() -> CallPeerEvents {CallPeerEvents( signal: { [weakself] kind, sdp, candidate, mid, mline invar out: [String: JSONValue] = ["kind": .string(kind.rawValue)]iflet sdp { out["sdp"] = .string(sdp) }iflet candidate { out["candidate"] = .string(candidate) }iflet mid { out["mid"] = .string(mid) }iflet mline { out["mline"] = .number(Double(mline)) }self?.ask("calls.signal", .object(["out": .object(out)])) }, media: { [weakself] state inself?.ask("calls.media", .object(["state": .string(state.rawValue)])) }, sfu: { [weakself] op, sdp, tracks, mids invar out: [String: JSONValue] = ["sfu": .string(op)]iflet sdp { out["sdp"] = .string(sdp) }iflet tracks { out["tracks"] = .array(tracks.map(\.json)) }iflet mids { out["mids"] = .array(mids.map(JSONValue.string)) }self?.ask("calls.signal", .object(["out": .object(out)])) }, speaking: { [weakself] on inself?.ask("calls.speaking", .object(["on": .bool(on)])) } ) }staticfunc 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 } }}