// 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.importCottonKitimportFoundation@MainActorpublicfinalclassWebSocketCallSocket: CallSocketPort {privatelet session: URLSessionprivatevar task: URLSessionWebSocketTask?privatevar log: @Sendable (String) -> Void/// Sends handed to a task and not yet done, by task.privatevar unsent: [ObjectIdentifier: Int] = [:]/// Tasks closed while a send was still on its way: cancelled once it has gone.privatevar closing: Set<ObjectIdentifier> = []/// The longest a closed socket waits for its last send.staticlet lastSendWait: Duration = .seconds(2)publicinit(session: URLSession = .shared, log: @escaping @Sendable (String) -> Void = { _ in }) {self.session = sessionself.log = log }publicfuncopen(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.publicfunc send(_ frame: JSONValue) {guardlet 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)) { [weakself, log] error iniflet error { log("calls socket: a send failed: \(error.localizedDescription)") }Task { @MainActor inself?.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`.publicfunc close() {guardlet task else { return }self.task = nillet id = ObjectIdentifier(task)guard (unsent[id] ?? 0) > 0else { task.cancel(with: .normalClosure, reason: nil)return } closing.insert(id)Task { @MainActor [weakself] intry? awaitTask.sleep(for: Self.lastSendWait)guardletself, self.closing.remove(id) != nilelse { return }self.unsent[id] = nil task.cancel(with: .normalClosure, reason: nil) } }privatefunc sent(_ task: URLSessionWebSocketTask) {let id = ObjectIdentifier(task)let left = (unsent[id] ?? 1) - 1 unsent[id] = left > 0 ? left : nilif left <= 0, closing.remove(id) != nil { task.cancel(with: .normalClosure, reason: nil) } }privatefunc listen(_ task: URLSessionWebSocketTask, received: @escaping @MainActor (JSONValue) -> Void, closed: @escaping @MainActor () -> Void) { task.receive { [weakself] result inTask { @MainActor inguardletself, 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 }iflet 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() } } } }}