454 lines · 21.7 KB · SwiftRaw
// The chat engine against a scripted core, a fake socket and a hand-wound// clock: the key is minted once and kept, registration waits for the object// and carries the alert token, frames go to the core, the outbox is flushed// when the core says, typing is said and taken back on its clocks, and// sign-out forgets everything this phone kept.import CottonKitimport CottonMailboximport CottonUIimport Foundationimport Testing@testable import CottonChat/// A core that answers each method from a script, and records every ask.final class ScriptedChat: ChatCore, @unchecked Sendable { private let lock = NSLock() private var answers: [String: [JSONValue]] = [:] private var asked: [(String, JSONValue)] = [] func reply(_ method: String, _ json: JSONValue) { lock.withLock { answers[method, default: []].append(json) } } func refuse(_ method: String, code: String) { lock.withLock { answers[method, default: []].append(.string("refuse:\(code)")) } } var methods: [String] { lock.withLock { asked.map(\.0) } } func requests(_ method: String) -> [JSONValue] { lock.withLock { asked.filter { $0.0 == method }.map(\.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: "refused") } if let next { return next } switch method { case "chat.key": return .object(["privateKey": .string("PRIVATE"), "publicKey": .string("PUBLIC")]) case "chat.socket": return .object(["url": .string("wss://object.example.test/v1/chat/socket"), "ticket": .string("cts_test")]) case "chat.flush": return .object(["sent": .array([]), "waiting": .number(0), "nextAt": .null]) case "chat.incoming": return .object(["landed": .array([]), "typing": .array([]), "receipts": .array([]), "requests": .array([])]) case "chat.settings": return .object(["readReceipts": .bool(true), "typing": .bool(true)]) default: return .object(["ok": .bool(true)]) } }}@MainActorfinal class FakeSocket: ChatSocketPort { var opened: [(URL, String)] = [] var sent: [JSONValue] = [] var closes = 0 var received: (@MainActor (JSONValue) -> Void)? var closed: (@MainActor () -> Void)? func open(url: URL, ticket: String, received: @escaping @MainActor (JSONValue) -> Void, closed: @escaping @MainActor () -> Void) { opened.append((url, ticket)) self.received = received self.closed = closed } func send(_ frame: JSONValue) { sent.append(frame) } func close() { closes += 1 }}@MainActorfinal class FakeClock: ChatClock { final class Timer: ChatTimer { let at: Int64 let fire: @MainActor () -> Void var cancelled = false init(at: Int64, fire: @escaping @MainActor () -> Void) { self.at = at self.fire = fire } func cancel() { cancelled = true } } var time: Int64 = 1_000_000 var timers: [Timer] = [] func now() -> Int64 { time } func after(milliseconds: Int64, _ fire: @escaping @MainActor () -> Void) -> any ChatTimer { let timer = Timer(at: time + milliseconds, fire: fire) timers.append(timer) return timer } /// Wind the clock on, firing each timer due on the way, in order. func advance(_ ms: Int64) { let until = time + ms while let next = timers.filter({ !$0.cancelled && $0.at <= until }).min(by: { $0.at < $1.at }) { next.cancelled = true time = max(time, next.at) next.fire() } time = until } var pending: [Int64] { timers.filter { !$0.cancelled }.map { $0.at - time }.sorted() }}/// A network path wound by hand: `report` is what the system would say.@MainActorfinal class FakePath: ChatPathPort { var changed: (@MainActor @Sendable (Bool) -> Void)? func watch(_ changed: @escaping @MainActor @Sendable (Bool) -> Void) { self.changed = changed } func report(_ satisfied: Bool) { changed?(satisfied) }}@MainActorprivate func engine(_ core: ScriptedChat, secrets: MemoryChatSecrets = MemoryChatSecrets(), names: UserDefaults? = nil, path: FakePath? = nil) -> (ChatCenter, FakeSocket, FakeClock) { let socket = FakeSocket() let clock = FakeClock() let center = ChatCenter( ports: .init(socket: socket, clock: clock, secrets: secrets, names: names, pictures: FileManager.default.temporaryDirectory, path: path), topic: "com.cottondb.messages.dev", core: { core }) return (center, socket, clock)}@MainActor@Suite struct ChatCenterTests { // RULE: the chat key is minted once and kept in the Keychain; registration publishes it and the socket opens with the ticket chat.socket hands, never a credential. @Test func aKeyIsMintedOnceAndTheSocketOpens() async throws { let core = ScriptedChat() let secrets = MemoryChatSecrets() let (center, socket, _) = engine(core, secrets: secrets) center.foregrounded() await center.settled() #expect(secrets.key() == "PRIVATE") #expect(core.methods == ["chat.key", "chat.register", "chat.socket", "chat.incoming", "chat.flush"]) #expect(core.requests("chat.register").first?["privateKey"]?.string == "PRIVATE") #expect(socket.opened.map(\.1) == ["cts_test"]) #expect(center.registered) center.backgrounded() center.foregrounded() await center.settled() #expect(core.methods.filter { $0 == "chat.key" }.count == 1, "the key is kept, never minted again") #expect(core.methods.filter { $0 == "chat.register" }.count == 1, "registered once while nothing changed") #expect(socket.opened.count == 2) } // RULE: the network back (down, then up for a second) with the app in front connects at once and flushes once with online: true; a flap within the second asks once; nothing is asked while it is down or the app is behind. @Test func theNetworkBackSendsWhatWaitedOnce() async throws { let core = ScriptedChat() let path = FakePath() let (center, socket, clock) = engine(core, path: path) path.report(true) center.foregrounded() await center.settled() #expect(core.requests("chat.flush").map { $0["online"]?.bool } == [true], "a connect the object answered flushes online, as Android's does") // Offline: the socket drops and its reconnect waits out a backoff that nothing asks before. path.report(false) socket.closed?() let before = core.methods.count clock.advance(500) await center.settled() #expect(core.methods.count == before, "nothing is asked while the path is down") // Back, then a flap within the second, then up. path.report(true) clock.advance(400) path.report(false) clock.advance(100) path.report(true) clock.advance(400) await center.settled() #expect(core.requests("chat.flush").count == 1, "not yet: the path has not stood a second") clock.advance(600) await center.settled() let flushes = core.requests("chat.flush") #expect(flushes.count == 2, "the flap asked once") #expect(flushes.last?["online"]?.bool == true) #expect(flushes.last?["privateKey"]?.string == "PRIVATE") #expect(socket.opened.count == 2, "the socket opens at once, not when its backoff runs out") clock.advance(10_000) await center.settled() #expect(core.requests("chat.flush").count == 2) // Up again with no down between: nothing came back. path.report(true) clock.advance(2_000) await center.settled() #expect(core.requests("chat.flush").count == 2) // Down and back with the app behind: nothing; coming to the front then flushes online. center.backgrounded() path.report(false) path.report(true) clock.advance(2_000) await center.settled() #expect(core.requests("chat.flush").count == 2, "behind, the network's return asks nothing") center.foregrounded() await center.settled() #expect(core.requests("chat.flush").count == 3) #expect(core.requests("chat.flush").last?["online"]?.bool == true) } // RULE: a connect while the path is down never flushes online. @Test func aConnectWhileOfflineIsNotOnline() async throws { let core = ScriptedChat() let path = FakePath() let (center, _, _) = engine(core, path: path) path.report(false) center.foregrounded() await center.settled() #expect(core.requests("chat.flush").allSatisfy { $0["online"] == nil }) } // RULE: registration waits for the object (not_connected) on a 10 s clock, and an alert token registers again with its topic. @Test func registrationWaitsForTheObjectAndCarriesTheToken() async throws { let core = ScriptedChat() core.refuse("chat.register", code: "not_connected") let (center, socket, clock) = engine(core) center.foregrounded() await center.settled() #expect(!center.registered) #expect(socket.opened.isEmpty) #expect(clock.pending == [10_000]) clock.advance(10_000) await center.settled() #expect(center.registered) #expect(socket.opened.count == 1) center.alertToken("abcd") await center.settled() let last = try #require(core.requests("chat.register").last) #expect(last["token"]?.string == "abcd") #expect(last["topic"]?.string == "com.cottondb.messages.dev") #expect(last["platform"]?.string == "ios") #expect(last["sandbox"]?.bool == false) } // RULE (CALLS FIX 1): a ring frame, or its stop, is acked over the socket at once and handed to the calls engine. @Test func aRingFrameIsAckedAtOnce() async throws { let core = ScriptedChat() let (center, socket, _) = engine(core) center.foregrounded() await center.settled() let room = "0123456789abcdef0123456789abcdef" final class Posted: @unchecked Sendable { var rings: [CallRingFrame] = [] } let posted = Posted() let watch = NotificationCenter.default.addObserver(forName: CallRingFrame.arrived, object: nil, queue: nil) { note in if let ring = note.object as? CallRingFrame { posted.rings.append(ring) } } defer { NotificationCenter.default.removeObserver(watch) } socket.received?(.object(["t": .string("ring"), "kind": .string("ring"), "room": .string(room), "video": .string("0")])) socket.received?(.object(["t": .string("ring"), "kind": .string("stop"), "room": .string(room), "stop": .string("missed"), "box": .string("sealed")])) socket.received?(.object(["t": .string("ring"), "kind": .string("missed"), "room": .string(room), "stop": .string("missed"), "box": .string("sealed"), "at": .string("1790000000000"), "ended": .string("1790000045000")])) let acks = socket.sent.filter { $0["t"]?.string == "ring_ack" } #expect(acks == Array(repeating: .object(["t": .string("ring_ack"), "room": .string(room)]), count: 3)) #expect(posted.rings == [ .ring(room: room, video: false, box: nil), .stop(room: room, reason: "missed", box: "sealed"), .missed(room: room, reason: "missed", box: "sealed", times: CallTimes(at: 1_790_000_000_000, ended: 1_790_000_045_000)), ]) } // RULE (CALLS FIX 2): the socket's first frame says what this build speaks, so the object rings it the new way; a // build that says nothing is rung as before. @Test func theSocketSaysHelloFirst() async throws { let core = ScriptedChat() let (center, socket, _) = engine(core) center.foregrounded() await center.settled() #expect(socket.sent.first == .object(["t": .string("hello"), "can": .array([.string("ring_ack")])])) } // RULE: each envelope frame goes to chat.incoming with its item and the key; typing they send is drawn for 6 s. @Test func framesLandAndTypingIsDrawn() async throws { let core = ScriptedChat() let (center, socket, clock) = engine(core) center.foregrounded() await center.settled() core.reply("chat.incoming", .object(["landed": .array([]), "typing": .array([.object(["thread": .string("t1"), "on": .bool(true)])])])) socket.received?(.object(["t": .string("envelope"), "item": .object(["id": .string("x"), "kind": .string("typing")])])) await center.settled() let asked = try #require(core.requests("chat.incoming").last) #expect(asked["items"]?.array?.first?["id"]?.string == "x") #expect(asked["privateKey"]?.string == "PRIVATE") #expect(center.isTyping(thread: "t1")) clock.advance(6_000) #expect(!center.isTyping(thread: "t1")) } // RULE: a dropped socket comes back with a doubling wait while the app is in front, and not at all behind. @Test func aDroppedSocketReconnectsWithBackoff() async throws { let core = ScriptedChat() let (center, socket, clock) = engine(core) center.foregrounded() await center.settled() socket.closed?() #expect(clock.pending.contains(1_000)) clock.advance(1_000) await center.settled() #expect(socket.opened.count == 2) socket.closed?() #expect(clock.pending.contains(2_000)) center.backgrounded() clock.advance(2_000) await center.settled() #expect(socket.opened.count == 2) } // RULE: the outbox is flushed at the core's nextAt, and a send schedules its own. @Test func theOutboxIsFlushedWhenTheCoreSays() async throws { let core = ScriptedChat() let (center, _, clock) = engine(core) core.reply("chat.flush", .object(["nextAt": .number(Double(clock.time + 4_000))])) center.foregrounded() await center.settled() #expect(clock.pending.contains(4_000)) clock.advance(4_000) await center.settled() #expect(core.methods.filter { $0 == "chat.flush" }.count == 2) core.reply("chat.send", .object(["message": .string("m"), "state": .string("queued"), "nextAt": .number(Double(clock.time + 2_000))])) try await center.send(thread: "t1", body: "hi", replyTo: "m0", pictures: [ChatPicture(path: "/tmp/p.jpg", mime: "image/jpeg", width: 4, height: 3)]) let sent = try #require(core.requests("chat.send").last) #expect(sent["body"]?.string == "hi") #expect(sent["replyTo"]?.string == "m0") #expect(sent["pictures"]?.array?.first?["mime"]?.string == "image/jpeg") #expect(sent["privateKey"]?.string == "PRIVATE") #expect(clock.pending.contains(2_000)) try await center.retry(message: "m") #expect(core.requests("chat.retry").last?["message"]?.string == "m") } // RULE: typing is said once, again after 4 s of keys, and taken back 5 s after the last; a send takes it back at once. @Test func typingIsSaidAndTakenBack() async throws { let core = ScriptedChat() let (center, _, clock) = engine(core) // An app whose kit says its chats signal (`chat.settings`' `offered`). core.reply("chat.settings", .object(["readReceipts": .bool(true), "typing": .bool(true), "offered": .bool(true)])) await center.loadSettings() #expect(center.signals) center.typed(thread: "t1") center.typed(thread: "t1") await center.settled() #expect(core.requests("chat.typing").map { $0["on"]?.bool } == [true]) clock.advance(4_000) center.typed(thread: "t1") await center.settled() #expect(core.requests("chat.typing").map { $0["on"]?.bool } == [true, true]) clock.advance(5_000) await center.settled() #expect(core.requests("chat.typing").map { $0["on"]?.bool } == [true, true, false]) center.typed(thread: "t1") try await center.send(thread: "t1", body: "hi", replyTo: nil, pictures: []) await center.settled() #expect(core.requests("chat.typing").map { $0["on"]?.bool } == [true, true, false, true, false]) } // RULE (owner, 15 Nov 2026): Messages sends no typing: where the core does not offer the signals (the kit's switch is off), a key pressed asks the core nothing, and no switch is offered. @Test func typingIsNotSaidWhereChatsDoNotSignal() async throws { let core = ScriptedChat() let (center, _, clock) = engine(core) core.reply("chat.settings", .object(["readReceipts": .bool(true), "typing": .bool(true), "offered": .bool(false)])) await center.loadSettings() #expect(!center.signals) center.typed(thread: "t1") clock.advance(5_000) await center.settled() #expect(core.requests("chat.typing").isEmpty) } // RULE: a conversation on screen is read; a message landing in it while it shows is read at once. @Test func aChatOnScreenIsRead() async throws { let core = ScriptedChat() let (center, socket, _) = engine(core) center.foregrounded() await center.settled() center.showing(thread: "t1") await center.settled() #expect(core.requests("chat.receipt").map { $0["thread"]?.string } == ["t1"]) core.reply("chat.incoming", .object(["landed": .array([.object(["thread": .string("t1"), "out": .bool(false), "peer": .string("+15550100001"), "name": .string("Asha Example")])])])) socket.received?(.object(["t": .string("envelope"), "item": .object(["id": .string("y")])])) await center.settled() #expect(core.requests("chat.receipt").count == 2) center.showing(thread: nil) core.reply("chat.incoming", .object(["landed": .array([.object(["thread": .string("t1"), "out": .bool(false)])])])) socket.received?(.object(["t": .string("envelope"), "item": .object(["id": .string("z")])])) await center.settled() #expect(core.requests("chat.receipt").count == 2) } // RULE: a phone signing out asks the core to have the object forget its chat device while the door is open; signed out, the key and the names go here. @Test func signOutForgetsEverything() async throws { let core = ScriptedChat() let secrets = MemoryChatSecrets() let suite = "cotton.chat.tests.\(UUID().uuidString)" let names = try #require(UserDefaults(suiteName: suite)) defer { names.removePersistentDomain(forName: suite) } let (center, socket, _) = engine(core, secrets: secrets, names: names) center.foregrounded() await center.settled() ChatNames.remember(["+15550100001": "Asha Example"], in: names) await center.forgetDevice() #expect(core.requests("chat.forget").count == 1) center.signedOut() #expect(secrets.key() == nil) #expect(ChatNames.read(from: names).isEmpty) #expect(ChatThreads.read(from: names).isEmpty) #expect(socket.closes >= 1) #expect(!center.registered) } // RULE: what lands says its number's thread for the extension and a notification's tap; a chat read on another of the person's phones is said here. @Test func landingKeepsTheThreadAndSaysTheReads() async throws { let core = ScriptedChat() let suite = "cotton.chat.tests.\(UUID().uuidString)" let names = try #require(UserDefaults(suiteName: suite)) defer { names.removePersistentDomain(forName: suite) } let (center, _, _) = engine(core, names: names) core.reply("chat.incoming", .object([ "landed": .array([.object(["thread": .string("t1"), "peer": .string("+15550100001"), "name": .string("Asha Example"), "out": .bool(false)])]), "read": .array([.string("t2")]), ])) let reads = Heard() let token = NotificationCenter.default.addObserver(forName: .cottonChatRead, object: nil, queue: nil) { note in if let thread = note.userInfo?["thread"] as? String { reads.add(thread) } } defer { NotificationCenter.default.removeObserver(token) } await center.landWaiting() #expect(ChatThreads.read(from: names) == ["+15550100001": "t1"]) #expect(reads.all == ["t2"]) #expect(core.methods.suffix(1) == ["chat.incoming"]) } // RULE: a notification's Reply or Mark as read is flushed now and awaited, and the core's methods go with the key only when asked. @Test func notificationsAskThroughTheEngine() async throws { let core = ScriptedChat() let (center, _, _) = engine(core) _ = try await center.call("chat.notices") #expect(core.requests("chat.notices").first == .object([:])) _ = try await center.call("chat.keep", ["unmetered": .bool(true)]) #expect(core.requests("chat.keep").first == .object(["unmetered": .bool(true)])) _ = try await center.call("chat.receipt", ["thread": .string("t1")], keyed: true) #expect(core.requests("chat.receipt").first?["privateKey"]?.string == "PRIVATE") await center.flushNow() #expect(core.requests("chat.flush").last?["privateKey"]?.string == "PRIVATE", "flushed before flushNow returned") }}/// What a notification observer heard, in order.final class Heard: @unchecked Sendable { private let lock = NSLock() private var heard: [String] = [] func add(_ one: String) { lock.withLock { heard.append(one) } } var all: [String] { lock.withLock { heard } }}