// What the chat engine reaches: the core's `chat.*` methods, the object's // socket, a clock, the phone's network path, and the Keychain items // (`CottonMailbox/ChatKeychain`). // Each is a port so the engine runs against fakes in `CottonChatTests`. import CottonKit import Foundation import Network /// The core's `chat.*` methods, as the engine asks them. public protocol ChatCore: Sendable { func ask(_ method: String, _ request: JSONValue) async throws -> JSONValue } /// The live core. public struct CoreChat: ChatCore { private let core: any CottonCalling public init(core: any CottonCalling) { self.core = core } public func ask(_ method: String, _ request: JSONValue) async throws -> JSONValue { try await core.call(method, request, as: JSONValue.self) } } /// The object's chat socket (`GET /v1/chat/socket`). @MainActor public protocol ChatSocketPort: AnyObject { func open(url: URL, ticket: String, received: @escaping @MainActor (JSONValue) -> Void, closed: @escaping @MainActor () -> Void) func send(_ frame: JSONValue) func close() } /// A timer the clock handed out. @MainActor public protocol ChatTimer: AnyObject { func cancel() } /// Time, as the engine needs it: now, and later. @MainActor public protocol ChatClock: AnyObject { /// Milliseconds since 1970, the core's `nextAt` clock. func now() -> Int64 func after(milliseconds: Int64, _ fire: @escaping @MainActor () -> Void) -> any ChatTimer } /// `DispatchQueue.main`'s clock. @MainActor public final class MainChatClock: ChatClock { public init() {} public func now() -> Int64 { Int64(Date().timeIntervalSince1970 * 1000) } public func after(milliseconds: Int64, _ fire: @escaping @MainActor () -> Void) -> any ChatTimer { let timer = MainTimer() let item = DispatchWorkItem { MainActor.assumeIsolated { fire() } } timer.item = item DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(Int(max(0, min(milliseconds, Int64(Int32.max))))), execute: item) return timer } private final class MainTimer: ChatTimer { var item: DispatchWorkItem? func cancel() { item?.cancel() } } } /// Whether the phone has a network: each path the system reports, satisfied /// or not, told on the main actor from the moment `watch` is called. @MainActor public protocol ChatPathPort: AnyObject { func watch(_ changed: @escaping @MainActor @Sendable (Bool) -> Void) } /// `NWPathMonitor`'s path, on the main queue. @MainActor public final class NetworkChatPath: ChatPathPort { private let monitor = NWPathMonitor() public init() {} public func watch(_ changed: @escaping @MainActor @Sendable (Bool) -> Void) { monitor.pathUpdateHandler = { path in let satisfied = path.status == .satisfied MainActor.assumeIsolated { changed(satisfied) } } monitor.start(queue: .main) } }