Cotton code
457 lines · 22.2 KB · SwiftRaw
// The call engine against a scripted core: every effect the core can answer// reaches its port, once and in order, and what the ports report goes back to// the core as the right method.import CottonKitimport Foundationimport Testing@testable import CottonCalls// The core's answers written as JSON is written: true, false and numbers bare.extension JSONValue: @retroactive ExpressibleByBooleanLiteral, @retroactive ExpressibleByIntegerLiteral {    public init(booleanLiteral value: Bool) { self = .bool(value) }    public init(integerLiteral value: Int) { self = .number(Double(value)) }}private let uuid = "01234567-89AB-CDEF-0123-456789ABCDEF"private let room = "0123456789abcdef0123456789abcdef"/// A core that answers each method from a script, and records every ask.final class ScriptedCalls: CallsCore, @unchecked Sendable {    private let lock = NSLock()    private var answers: [String: [JSONValue]] = [:]    private var asked: [(String, JSONValue)] = []    func answer(_ method: String, call: JSONValue = .object(["phase": "live"]), effects: [JSONValue] = []) {        lock.withLock { answers[method, default: []].append(.object(["call": call, "effects": .array(effects)])) }    }    /// An answer of the method's own shape (`calls.openLink`).    func reply(_ method: String, _ json: JSONValue) {        lock.withLock { answers[method, default: []].append(json) }    }    func refuse(_ method: String, code: String = "no_number") {        lock.withLock { answers[method, default: []].append(.string("refuse:\(code)")) }    }    var methods: [String] { lock.withLock { asked.map(\.0) } }    func request(_ method: String) -> JSONValue? { lock.withLock { asked.last { $0.0 == method }?.1 } }    func ask(_ method: String, _ request: JSONValue) async throws -> JSONValue {        let next: JSONValue? = lock.withLock {            asked.append((method, request))            guard var queue = answers[method], !queue.isEmpty else { return nil }            let one = queue.removeFirst()            answers[method] = queue            return one        }        if case .string(let said)? = next, said.hasPrefix("refuse:") {            throw CottonCallError(code: String(said.dropFirst("refuse:".count)), message: "This person has no phone number to call.")        }        return next ?? .object(["call": .object(["phase": "idle"]), "effects": .array([])])    }}@MainActorfinal class FakeSystem: SystemCallPort, RingReporter {    var said: [String] = []    var endedReasons: [Int?] = []    func startOutgoing(uuid: UUID, handle: String, name: String?, video: Bool) { said.append("outgoing \(handle) \(name ?? "-") \(video)") }    func outgoingConnecting(uuid: UUID) { said.append("connecting") }    func outgoingConnected(uuid: UUID) { said.append("connected") }    func reportIncoming(uuid: UUID, title: String, handle: String?, video: Bool) { said.append("incoming \(title)\(handle.map { " \($0)" } ?? "")") }    func update(uuid: UUID, handle: String, name: String?, video: Bool) { said.append("update \(handle) \(name ?? "-")") }    func ended(uuid: UUID, reason: Int?) {        said.append("ended")        endedReasons.append(reason)    }    var rings: [(UUID, Bool)] = []    func reportRing(uuid: UUID, video: Bool, completion: @escaping @Sendable () -> Void) {        rings.append((uuid, video))        completion()    }}@MainActorfinal class FakeSocket: CallSocketPort {    var opened: [(URL, String)] = []    var sent: [JSONValue] = []    var closes = 0    var received: (@MainActor (JSONValue) -> Void)?    var closed: (@MainActor () -> Void)?    func open(url: URL, credential: String, received: @escaping @MainActor (JSONValue) -> Void, closed: @escaping @MainActor () -> Void) {        opened.append((url, credential))        self.received = received        self.closed = closed    }    func send(_ frame: JSONValue) { sent.append(frame) }    func close() { closes += 1 }}@MainActorfinal class FakePeer: CallPeerPort {    var said: [String] = []    var events: CallPeerEvents?    func create(offerer: Bool, iceServers: [CallIceServer], video: Bool, events: CallPeerEvents) {        said.append("create \(offerer) \(iceServers.first?.urls.first ?? "-") \(video)")        self.events = events    }    func applyRemote(kind: CallSignalKind, sdp: String) { said.append("remote \(kind.rawValue) \(sdp)") }    func addCandidate(_ candidate: String, mid: String?, mline: Int?) { said.append("candidate \(candidate) \(mid ?? "-") \(mline ?? -1)") }    func restartIce() { said.append("restart") }    func close() { said.append("close") }    func setSending(audio: Bool, video: Bool) { said.append("sending \(audio) \(video)") }    func startCamera() { said.append("camera on") }    func stopCamera() { said.append("camera off") }    func switchToSfu(iceServers: [CallIceServer], video: Bool, events: CallPeerEvents) {        said.append("sfu \(iceServers.first?.urls.first ?? "-") \(video)")        self.events = events    }    func pushTracks(audio: Bool, video: Bool) { said.append("push \(audio) \(video)") }    func applySfu(op: String, sdp: String, tracks: [CallSfuTrack]) {        let whose = tracks.map { "\($0.mid ?? "-")=\($0.member ?? "-")" }.joined(separator: ",")        said.append("sfu \(op) \(sdp) \(whose.isEmpty ? "-" : whose)")    }    func closeTracks(member: String) { said.append("close tracks \(member)") }}@MainActorfinal class FakeAudio: CallAudioPort {    var said: [String] = []    func configure(video: Bool) { said.append("configure \(video)") }    func stop() { said.append("stop") }    func activated() { said.append("activated") }    func deactivated() { said.append("deactivated") }    func setSpeaker(_ on: Bool) { said.append("speaker \(on)") }}@MainActorfinal class FakeTone: CallTonePort {    var said: [String] = []    func play(_ tone: String) { said.append("play \(tone)") }    func stop() { said.append("stop") }}/// A clock that fires only when told to.@MainActorfinal class FakeClock: CallClockPort {    var waits: [Int] = []    private var pending: [@MainActor () -> Void] = []    func after(milliseconds: Int, _ fire: @escaping @MainActor () -> Void) {        waits.append(milliseconds)        pending.append(fire)    }    func cancelAll() { pending.removeAll() }    func fireAll() {        let due = pending        pending.removeAll()        due.forEach { $0() }    }}@MainActorstruct Rig {    let core = ScriptedCalls()    let system = FakeSystem()    let socket = FakeSocket()    let peer = FakePeer()    let audio = FakeAudio()    let tone = FakeTone()    let clock = FakeClock()    let center: CallCenter    init() {        let core = self.core        center = CallCenter(            ports: .init(system: system, socket: socket, peer: peer, audio: audio, tone: tone, clock: clock),            core: { core }        )    }}private func effect(_ does: String, _ fields: [String: JSONValue] = [:]) -> JSONValue {    .object(fields.merging(["do": .string(does)]) { a, _ in a })}@MainActor@Suite struct CallCenterTests {    // RULE: every one-to-one effect in the core's table reaches its port, once, in the order answered.    @Test func everyEffectReachesItsPortOnce() async {        let rig = Rig()        let all: [JSONValue] = [            effect("system_call_outgoing", ["uuid": .string(uuid), "handle": "+15550100001", "name": "An Invented Friend", "video": .bool(true)]),            effect("start_audio", ["video": .bool(true)]),            effect("start_camera"),            effect("timer", ["after_ms": 60000]),            effect("open_socket", ["path": "/v1/calls/socket", "url": "wss://cottondb.example.test/v1/calls/socket", "credential": "ccr_room_secret", "after_ms": 0]),            effect("create_peer", ["offerer": true, "ice_servers": .array([.object(["urls": "turn:turn.example.test", "username": "u", "credential": "c"])])]),            effect("play_tone", ["tone": "ringback"]),            effect("system_call_connecting", ["uuid": .string(uuid)]),            effect("stop_tone"),            effect("send", ["frame": .object(["t": "ping"])]),            effect("apply_remote", ["kind": "answer", "sdp": "v=0 answer"]),            effect("add_candidate", ["candidate": "candidate:1", "mid": "0", "mline": 0]),            effect("system_call_connected", ["uuid": .string(uuid), "outgoing": true]),            effect("set_sending", ["audio": false, "video": .bool(true)]),            effect("restart_ice"),            effect("system_call_update", ["uuid": .string(uuid), "handle": "+15550100001", "name": "An Invented Friend", "video": .bool(true)]),            effect("system_call_incoming", ["uuid": .string(uuid), "title": "Cotton", "video": false]),            effect("stop_camera"),            effect("close_peer"),            effect("close_socket"),            effect("stop_audio"),            effect("system_call_ended", ["uuid": .string(uuid), "cause": "remote", "ios": 2, "android": 3]),        ]        rig.core.answer("calls.start", call: .object(["phase": "ringing_out", "video": true, "uuid": .string(uuid)]), effects: all)        rig.center.start(person: "p-friend", video: true)        await rig.center.settle()        #expect(rig.center.performed == all.map { $0["do"]!.string! })        #expect(rig.system.said == [            "outgoing +15550100001 An Invented Friend true", "connecting", "connected",            "update +15550100001 An Invented Friend", "incoming Cotton", "ended",        ])        #expect(rig.system.endedReasons == [2])        #expect(rig.audio.said == ["configure true", "stop"])        #expect(rig.peer.said == [            "camera on", "create true turn:turn.example.test true", "remote answer v=0 answer",            "candidate candidate:1 0 0", "sending false true", "restart", "camera off", "close",        ])        #expect(rig.tone.said == ["play ringback", "stop"])        #expect(rig.socket.opened.map(\.0.absoluteString) == ["wss://cottondb.example.test/v1/calls/socket"])        #expect(rig.socket.opened.map(\.1) == ["ccr_room_secret"])        #expect(rig.socket.sent == [.object(["t": "ping"])])        #expect(rig.socket.closes == 1)        #expect(rig.clock.waits == [60000])        #expect(rig.center.call.phase == .ringingOut)        #expect(rig.core.request("calls.start") == .object(["person": "p-friend", "video": .bool(true)]))    }    // RULE: a timer hands calls.tick back when it falls due, and not before.    @Test func aTimerTicks() async {        let rig = Rig()        rig.core.answer("calls.start", effects: [effect("timer", ["after_ms": 45000])])        rig.center.start(number: "+15550100001", video: false)        await rig.center.settle()        #expect(!rig.core.methods.contains("calls.tick"))        rig.clock.fireAll()        await rig.center.settle()        #expect(rig.core.methods == ["calls.start", "calls.tick"])    }    // RULE: the socket's frames go to calls.signal { in } as they came; a close nobody asked for is calls.socketClosed; a socket opened after after_ms waits on the clock.    @Test func theSocketTalksToTheCore() async {        let rig = Rig()        rig.core.answer("calls.incoming", effects: [            effect("open_socket", ["url": "wss://cottondb.example.test/v1/calls/socket", "credential": "ccr_x", "after_ms": 1000]),        ])        rig.center.incoming(room: room, video: false)        await rig.center.settle()        #expect(rig.socket.opened.isEmpty)        #expect(rig.clock.waits == [1000])        rig.clock.fireAll()        #expect(rig.socket.opened.count == 1)        rig.socket.received?(.object(["t": "state", "state": "connecting"]))        await rig.center.settle()        #expect(rig.core.request("calls.signal") == .object(["in": .object(["t": "state", "state": "connecting"])]))        rig.socket.closed?()        await rig.center.settle()        #expect(rig.core.methods.last == "calls.socketClosed")        // A frame from the socket since closed is dropped.        rig.socket.received?(.object(["t": "state", "state": "live"]))        await rig.center.settle()        #expect(rig.core.methods.filter { $0 == "calls.signal" }.count == 1)    }    // RULE: what the peer makes goes back as calls.signal { out }, its ICE state as calls.media.    @Test func thePeerTalksToTheCore() async {        let rig = Rig()        rig.core.answer("calls.answer", effects: [effect("create_peer", ["offerer": false, "ice_servers": .array([])])])        rig.center.answer()        await rig.center.settle()        rig.peer.events?.signal(.answer, "v=0 mine", nil, nil, nil)        rig.peer.events?.signal(.ice, nil, "candidate:2", "0", 0)        rig.peer.events?.media(.connected)        await rig.center.settle()        #expect(rig.core.methods == ["calls.answer", "calls.signal", "calls.signal", "calls.media"])        #expect(rig.core.request("calls.media") == .object(["state": "connected"]))        #expect(rig.core.request("calls.signal") == .object(["out": .object(["kind": "ice", "candidate": "candidate:2", "mid": "0", "mline": 0])]))    }    // RULE: a group call's effects are performed on the peer, in order, and never end the call (chat/CONTRACT.md    // "Group calls", "The media").    @Test func aGroupCallsEffectsReachThePeerAndEndNothing() async {        let rig = Rig()        let servers: JSONValue = .array([.object(["urls": .array([.string("stun:sfu")])])])        let tracks: JSONValue = .array([.object(["mid": "3", "member": "m1", "name": "audio-1"]), .object(["mid": "4", "member": "m1", "name": "video-2"])])        rig.core.answer("chat.call", call: .object(["phase": "connecting", "video": true, "mode": "sfu"]), effects: [            effect("switch_to_sfu", ["ice_servers": servers]), effect("push_tracks", ["audio": true, "video": true]),            effect("apply_remote_sdp", ["op": "answer", "sdp": "v=0 sfu"]), effect("pull_tracks", ["member": "m1", "names": .array([])]),            effect("apply_remote_sdp", ["op": "offer", "sdp": "v=0 theirs", "tracks": tracks]), effect("show_roster"),            effect("close_tracks", ["member": "m1"]),        ])        rig.center.place("chat.call", .object(["thread": "g1"]))        await rig.center.settle()        await rig.center.settle()        #expect(rig.core.methods == ["chat.call"])        #expect(rig.peer.said == ["sfu stun:sfu true", "push true true", "sfu answer v=0 sfu -", "sfu offer v=0 theirs 3=m1,4=m1", "close tracks m1"])        #expect(rig.center.performed.contains("pull_tracks"))        #expect(rig.center.rosterMoved == 1)    }    // RULE: what the SFU's connection makes goes back as `calls.signal { out: { sfu } }`, and this phone's voice as    // `calls.speaking`.    @Test func theSfusOpsAndSpeakingGoBackToTheCore() async {        let rig = Rig()        rig.core.answer("chat.call", effects: [effect("switch_to_sfu", ["ice_servers": .array([])])])        rig.center.place("chat.call", .object(["thread": "g1"]))        await rig.center.settle()        rig.peer.events?.sfu("push", "v=0 mine", [CallSfuTrack(mid: "0", member: nil, name: "audio-0", kind: "audio")], nil)        rig.peer.events?.sfu("close", nil, nil, ["3", "4"])        rig.peer.events?.speaking(true)        await rig.center.settle()        #expect(rig.core.methods == ["chat.call", "calls.signal", "calls.signal", "calls.speaking"])        #expect(rig.core.request("calls.speaking") == .object(["on": true]))        #expect(rig.core.request("calls.signal") == .object(["out": .object(["sfu": "close", "mids": .array(["3", "4"])])]))    }    // RULE: an app that draws Take notes' mark says so (`can`) on a call's start, ring, join and chat.call; one that    // says nothing is never counted as able to (chat/CONTRACT.md "Take notes").    @Test func whatTheScreenCanShowIsSaidOnEveryCall() async {        let rig = Rig()        rig.center.start(person: "p-friend", video: false)        await rig.center.settle()        #expect(rig.core.request("calls.start")?["can"] == nil)        rig.center.can = ["notes"]        rig.center.start(person: "p-friend", video: false)        rig.center.place("chat.call", .object(["thread": "g1", "join": true]))        rig.core.reply("calls.incoming", .object(["call": .object(["phase": "ringing_in"]), "effects": .array([]), "join": .string(room)]))        rig.center.incoming(room: room, video: false)        await rig.center.settle()        await rig.center.settle()        let notes: JSONValue = .array(["notes"])        #expect(rig.core.request("calls.start")?["can"] == notes)        #expect(rig.core.request("chat.call")?["can"] == notes)        #expect(rig.core.request("calls.incoming")?["can"] == notes)        #expect(rig.core.request("calls.join") == .object(["room": .string(room), "can": notes]))    }    // RULE: a placed call's whole answer is read once its effects are performed (`flush: true` on a group's).    @Test func aPlacedCallsAnswerIsReadAfterItsEffects() async {        let rig = Rig()        rig.core.reply("chat.call", .object(["call": .object(["phase": "dialling"]), "effects": .array([effect("start_audio")]), "flush": true]))        var flushed = false        rig.center.place("chat.call", .object(["thread": "g1"]), answered: { answer in            flushed = answer["flush"]?.bool == true && rig.center.performed == ["start_audio"]        })        await rig.center.settle()        #expect(flushed)    }    // RULE: the room's roster ends nothing: the core says show_roster on a call of two as well.    @Test func aRosterOnACallOfTwoEndsNothing() async {        let rig = Rig()        rig.core.answer("calls.start", effects: [effect("show_roster"), effect("show_roster")])        rig.center.start(person: "p-friend", video: false)        await rig.center.settle()        await rig.center.settle()        #expect(rig.core.methods == ["calls.start"])    }    // RULE: a refused start keeps the core's own words for the screen.    @Test func aRefusalIsTheCoresWords() async {        let rig = Rig()        rig.core.refuse("calls.start")        rig.center.start(person: "p-nobody", video: false)        await rig.center.settle()        #expect(rig.center.refusal == "This person has no phone number to call.")    }    // RULE: mute and camera ask calls.mute with both flags; the loudspeaker is this phone's route alone.    @Test func controlsAskTheCore() async {        let rig = Rig()        rig.core.answer("calls.answer", call: .object(["phase": "live", "own": .object(["audio": true, "video": .bool(true)])]))        rig.center.answer()        await rig.center.settle()        rig.center.toggleMute()        await rig.center.settle()        #expect(rig.core.request("calls.mute") == .object(["audio": false, "video": .bool(true)]))        rig.center.toggleSpeaker()        #expect(rig.audio.said == ["speaker true"])        #expect(!rig.core.methods.contains("calls.speaker"))    }    // RULE: the system screen's end declines a ring and ends anything else.    @Test func theSystemsEndDeclinesARing() async {        let rig = Rig()        rig.core.answer("calls.incoming", call: .object(["phase": "ringing_in"]))        rig.center.incoming(room: room, video: false)        await rig.center.settle()        rig.center.systemEnded()        await rig.center.settle()        #expect(rig.core.methods.last == "calls.decline")    }    // RULE: the VoIP token goes to the object as hex, under this app's topic.    @Test func thePushTokenIsHex() async {        let rig = Rig()        rig.center.pushToken(Data([0xAB, 0x01, 0xFF]), topic: "com.cottondb.calling.dev", sandbox: false)        await rig.center.settle()        #expect(rig.core.request("calls.pushToken") == .object([            "platform": "ios", "token": "ab01ff", "topic": "com.cottondb.calling.dev", "sandbox": false,        ]))    }    // RULE (CALLS FIX 2): Comms's token says what it speaks, so a phone rung by push alone is rung the new way;    // Cotton Calling's (above) says nothing and is rung as before.    @Test func commsTokenSaysWhatItSpeaks() async {        let rig = Rig()        rig.center.pushToken(Data([0xAB]), topic: "com.cottondb.messages.dev", sandbox: true)        await rig.center.settle()        #expect(rig.core.request("calls.pushToken")?["can"] == .array([.string("ring_ack")]))    }    // RULE: a token refused not_connected (PushKit answers before the object's door opens) is sent again on the clock until the object takes it, then no more.    // RULE (CALLS FIX 3): a push's ack that fails (an older Worker's 404, no network) is never shown, never holds up    // the ring, and is tried again quietly on the clock, a few times.    @Test func aFailedAckIsQuietAndTriedAgain() async {        let rig = Rig()        rig.core.refuse("calls.ack", code: "not_found")        rig.center.ack(room: "0123456789abcdef0123456789abcdef")        await rig.center.settle()        #expect(rig.center.refusal == nil, "never shown on the call screen")        #expect(rig.clock.waits == [CallCenter.ackRetry])        rig.clock.fireAll()        await rig.center.settle()        #expect(rig.core.methods == ["calls.ack", "calls.ack"])        #expect(rig.center.refusal == nil)    }    @Test func aTokenWaitsForTheObject() async {        let rig = Rig()        rig.core.refuse("calls.pushToken", code: "not_connected")        rig.center.pushToken(Data([0x01]), topic: "com.cottondb.calling.dev", sandbox: false)        await rig.center.settle()        #expect(rig.clock.waits == [10_000])        rig.clock.fireAll()        await rig.center.settle()        #expect(rig.core.methods == ["calls.pushToken", "calls.pushToken"])        rig.center.refresh()        await rig.center.settle()        #expect(rig.core.methods.filter { $0 == "calls.pushToken" }.count == 2, "taken: never sent again")    }    // RULE: a cottoncalling link is read by the core, and a call to its person starts.    @Test func aLinkPlacesACall() async {        let rig = Rig()        rig.core.reply("calls.openLink", .object(["people": .array(["p-friend"]), "video": .bool(true)]))        rig.center.open(link: URL(string: "cottoncallingdev://call?person=p-friend&video=1")!)        await rig.center.settle()        #expect(rig.core.methods == ["calls.openLink", "calls.start"])        #expect(rig.core.request("calls.openLink") == .object(["url": "cottoncallingdev://call?person=p-friend&video=1"]))        #expect(rig.core.request("calls.start") == .object(["person": "p-friend", "video": .bool(true)]))    }}