Cotton code
105 lines · 4.9 KB · SwiftRaw
// The room's socket: `URLSessionWebSocketTask`, the room credential in the// `Authorization: Bearer ccr_…` header and never in the URL// (`apps/business/src/open.ts`). Each text frame is handed to the core as it// came (`calls.signal { in }`); frames the core hands before the socket is// open wait, in order, and go once it is.import CottonKitimport Foundation@MainActorpublic final class WebSocketCallSocket: CallSocketPort {    private let session: URLSession    private var task: URLSessionWebSocketTask?    private var log: @Sendable (String) -> Void    /// Sends handed to a task and not yet done, by task.    private var unsent: [ObjectIdentifier: Int] = [:]    /// Tasks closed while a send was still on its way: cancelled once it has gone.    private var closing: Set<ObjectIdentifier> = []    /// The longest a closed socket waits for its last send.    static let lastSendWait: Duration = .seconds(2)    public init(session: URLSession = .shared, log: @escaping @Sendable (String) -> Void = { _ in }) {        self.session = session        self.log = log    }    public func open(url: URL, credential: String, received: @escaping @MainActor (JSONValue) -> Void, closed: @escaping @MainActor () -> Void) {        close()        var request = URLRequest(url: url)        request.setValue("Bearer \(credential)", forHTTPHeaderField: "Authorization")        let task = session.webSocketTask(with: request)        self.task = task        task.resume()        listen(task, received: received, closed: closed)    }    /// `URLSessionWebSocketTask` queues a send made before the handshake and    /// sends it once open, in order, which is the core's rule for frames.    public func send(_ frame: JSONValue) {        guard let task, let data = try? JSONEncoder().encode(frame) else { return }        let text = String(decoding: data, as: UTF8.self)        unsent[ObjectIdentifier(task), default: 0] += 1        task.send(.string(text)) { [weak self, log] error in            if let error { log("calls socket: a send failed: \(error.localizedDescription)") }            Task { @MainActor in self?.sent(task) }        }    }    /// A leave or end handed just before the close goes first: cancelling at once dropped it (a socket still opening    /// had not sent it), and the room then held this phone's place for 30 s (CALLS WALK 1, group run 1). The task is    /// cancelled once its last send has gone, or after `lastSendWait`.    public func close() {        guard let task else { return }        self.task = nil        let id = ObjectIdentifier(task)        guard (unsent[id] ?? 0) > 0 else {            task.cancel(with: .normalClosure, reason: nil)            return        }        closing.insert(id)        Task { @MainActor [weak self] in            try? await Task.sleep(for: Self.lastSendWait)            guard let self, self.closing.remove(id) != nil else { return }            self.unsent[id] = nil            task.cancel(with: .normalClosure, reason: nil)        }    }    private func sent(_ task: URLSessionWebSocketTask) {        let id = ObjectIdentifier(task)        let left = (unsent[id] ?? 1) - 1        unsent[id] = left > 0 ? left : nil        if left <= 0, closing.remove(id) != nil { task.cancel(with: .normalClosure, reason: nil) }    }    private func listen(_ task: URLSessionWebSocketTask, received: @escaping @MainActor (JSONValue) -> Void, closed: @escaping @MainActor () -> Void) {        task.receive { [weak self] result in            Task { @MainActor in                guard let self, self.task === task else { return }                switch result {                case .success(let message):                    let data: Data? = switch message {                    case .string(let text): Data(text.utf8)                    case .data(let data): data                    @unknown default: nil                    }                    if let data, let frame = try? JSONDecoder().decode(JSONValue.self, from: data) {                        // The room's refusals say what failed (an SFU step: its op and Cloudflare's words, no one's data).                        if frame["t"]?.string == "error" {                            self.log("calls room: error \(frame["code"]?.string ?? "-") \(frame["op"]?.string ?? "") \(frame["detail"]?.string ?? "")")                        }                        received(frame)                    }                    self.listen(task, received: received, closed: closed)                case .failure(let error):                    // A refused upgrade says why only in its status (the room: 401 invalid_credential, 410 no_call).                    let status = (task.response as? HTTPURLResponse).map { " (HTTP \($0.statusCode))" } ?? ""                    self.log("calls socket: closed: \(error.localizedDescription)\(status)")                    self.task = nil                    closed()                }            }        }    }}