SPB Git

Repository Public

WebSocket.swift 10.9 KB 275 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Claude Remote / Codex Remote9// File             : Packages/ClaudeRemoteKit/Sources/ClaudeRemoteAPI/WebSocket.swift10// Module           : ClaudeRemoteAPI11// Repository       : https://git.spboucher.ai/claude-remote-apple12// Project Website  : https://claude.spboucher.ai13// Created          : 2026-11-2914// Last Modified    : 2026-11-2915//16// =============================================================================17// AUTHOR & PROFESSIONAL AFFILIATION18// =============================================================================19//20// Author           : Simon-Pierre Boucher21// Position         : Professor of Finance22// Institution      : Université du Québec en Outaouais (UQO)23// Department       : Département des sciences administratives24// Organization     : SP Boucher25//26// Website          : https://spboucher.ai27// Git              : https://git.spboucher.ai28//29// =============================================================================30// OFFICIAL CONTACT DIRECTORY31// =============================================================================32//33// General          : info@spboucher.ai34// Professional     : contact@spboucher.ai35// Direct           : simon@spboucher.ai36// Research         : research@spboucher.ai37// Development      : dev@spboucher.ai38// Support          : support@spboucher.ai39// Security/Admin   : admin@spboucher.ai40// Notifications    : notifications@spboucher.ai41//42// Preferred Contact: support@spboucher.ai43//44// =============================================================================45// COPYRIGHT & INTELLECTUAL PROPERTY46// =============================================================================47//48// Copyright (c) 202649// Simon-Pierre Boucher50//51// All rights reserved where applicable.52//53// This file is governed by the applicable project license,54// copyright notices, institutional agreements and relevant law.55//56// Unless expressly authorized by the applicable license or57// rights holder, copying, redistribution, sublicensing,58// publication and commercial exploitation are not permitted.59//60// Existing third-party rights and notices remain unaffected.61//62// =============================================================================63// CONFIDENTIALITY & SECURITY64// =============================================================================65//66// Classification   : Public67// Distribution     : Public repository; use is governed by the project license68// Security Contact : admin@spboucher.ai69//70// Access to this source does not independently grant permission71// to redistribute or disclose confidential materials.72//73// Do not embed credentials, private keys, access tokens,74// certificates or confidential personal information.75//76// =============================================================================77// LICENSE & MAINTENANCE78// =============================================================================79//80// License          : None specified (no license file in this repository)81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import Foundation8990public enum WebSocketMessage: Hashable, Sendable {91    case data(Data)92    case text(String)93}9495/// Thrown by `WebSocketConnection.receive()` once the socket is closed.96public struct WebSocketClosed: Error, Hashable, Sendable {97    /// WebSocket close code (1000 normal, 1006 abnormal / connection lost, 44xx application codes).98    public var code: Int99    public var reason: String?100    public init(code: Int, reason: String? = nil) {101        self.code = code102        self.reason = reason103    }104    public static let abnormal = WebSocketClosed(code: 1006)105}106107/// Thrown by `WebSocketTransport.connect` when the socket never opened.108public enum WebSocketConnectError: Error, Hashable, Sendable {109    /// The server answered the upgrade with a plain HTTP status (401, 403, 404, 410, 503…).110    case upgradeRefused(status: Int)111    /// No answer (offline, DNS, TLS, timeout).112    case unreachable(String)113}114115/// One open WebSocket. `receive()` is called by a single consumer loop.116public protocol WebSocketConnection: Sendable {117    func send(_ message: WebSocketMessage) async throws118    func receive() async throws -> WebSocketMessage119    func close(code: Int, reason: String?)120}121122public protocol WebSocketTransport: Sendable {123    /// Performs the upgrade and returns once the socket is open.124    func connect(_ request: URLRequest) async throws -> any WebSocketConnection125}126127/// `URLSessionWebSocketTask`-based transport (system TLS validation, no pinning bypass).128public final class URLSessionWebSocketTransport: NSObject, WebSocketTransport, URLSessionWebSocketDelegate {129    private struct Entry {130        var open: CheckedContinuation<Void, Error>?131        var closeCode: Int?132        var closeReason: String?133    }134135    private let lock = NSLock()136    nonisolated(unsafe) private var entries: [Int: Entry] = [:]137    nonisolated(unsafe) private var session: URLSession!138    /// Largest accepted message. The server replays up to 2 MiB of history on attach.139    private let maximumMessageSize: Int140141    public init(configuration: URLSessionConfiguration = .crAPI, maximumMessageSize: Int = 16 * 1024 * 1024) {142        self.maximumMessageSize = maximumMessageSize143        super.init()144        session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)145    }146147    deinit { session.invalidateAndCancel() }148149    public func connect(_ request: URLRequest) async throws -> any WebSocketConnection {150        let task = session.webSocketTask(with: request)151        task.maximumMessageSize = maximumMessageSize152        let id = task.taskIdentifier153        try await withTaskCancellationHandler {154            try await withCheckedThrowingContinuation { (c: CheckedContinuation<Void, Error>) in155                lock.withLock { entries[id] = Entry(open: c) }156                task.resume()157            }158        } onCancel: {159            task.cancel()160        }161        return Connection(task: task, owner: self)162    }163164    fileprivate func closeInfo(_ id: Int) -> (code: Int?, reason: String?) {165        lock.withLock { (entries[id]?.closeCode, entries[id]?.closeReason) }166    }167168    fileprivate func forget(_ id: Int) {169        lock.withLock { _ = entries.removeValue(forKey: id) }170    }171172    public func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didOpenWithProtocol protocol: String?) {173        let c = lock.withLock { () -> CheckedContinuation<Void, Error>? in174            let c = entries[webSocketTask.taskIdentifier]?.open175            entries[webSocketTask.taskIdentifier]?.open = nil176            return c177        }178        c?.resume()179    }180181    public func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didCloseWith closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) {182        lock.withLock {183            entries[webSocketTask.taskIdentifier]?.closeCode = closeCode.rawValue184            entries[webSocketTask.taskIdentifier]?.closeReason = reason.flatMap { String(data: $0, encoding: .utf8) }185        }186    }187188    public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {189        let c = lock.withLock { () -> CheckedContinuation<Void, Error>? in190            let c = entries[task.taskIdentifier]?.open191            entries[task.taskIdentifier]?.open = nil192            return c193        }194        guard let c else { return }195        // Never opened: a refused upgrade is a plain HTTP answer.196        if let http = task.response as? HTTPURLResponse, http.statusCode != 101 {197            c.resume(throwing: WebSocketConnectError.upgradeRefused(status: http.statusCode))198        } else if let error, (error as? URLError)?.code == .cancelled {199            c.resume(throwing: CancellationError())200        } else {201            c.resume(throwing: WebSocketConnectError.unreachable(error?.localizedDescription ?? "connection failed"))202        }203        forget(task.taskIdentifier)204    }205206    private final class Connection: WebSocketConnection {207        let task: URLSessionWebSocketTask208        let owner: URLSessionWebSocketTransport209210        init(task: URLSessionWebSocketTask, owner: URLSessionWebSocketTransport) {211            self.task = task212            self.owner = owner213        }214215        deinit {216            task.cancel(with: .goingAway, reason: nil)217            owner.forget(task.taskIdentifier)218        }219220        func send(_ message: WebSocketMessage) async throws {221            do {222                switch message {223                case .data(let d): try await task.send(.data(d))224                case .text(let s): try await task.send(.string(s))225                }226            } catch {227                throw closed()228            }229        }230231        func receive() async throws -> WebSocketMessage {232            do {233                switch try await task.receive() {234                case .data(let d): return .data(d)235                case .string(let s): return .text(s)236                @unknown default: return .data(Data())237                }238            } catch {239                if Task.isCancelled { throw CancellationError() }240                throw closed()241            }242        }243244        private func closed() -> WebSocketClosed {245            let info = owner.closeInfo(task.taskIdentifier)246            if let code = info.code { return WebSocketClosed(code: code, reason: info.reason) }247            let raw = task.closeCode.rawValue248            return raw > 0 ? WebSocketClosed(code: raw, reason: nil) : .abnormal249        }250251        func close(code: Int, reason: String?) {252            task.cancel(with: URLSessionWebSocketTask.CloseCode(rawValue: code) ?? .normalClosure, reason: reason?.data(using: .utf8))253        }254    }255}256257extension URLSessionConfiguration {258    /// Configuration of every connection to an instance: no cookies, no cache, no credential259    /// storage (the bearer lives in the Keychain), system TLS validation.260    public static var crAPI: URLSessionConfiguration {261        let c = URLSessionConfiguration.ephemeral262        c.httpCookieAcceptPolicy = .never263        c.httpShouldSetCookies = false264        c.httpCookieStorage = nil265        c.urlCache = nil266        c.urlCredentialStorage = nil267        c.requestCachePolicy = .reloadIgnoringLocalCacheData268        c.timeoutIntervalForRequest = 30269        c.timeoutIntervalForResource = 15 * 60270        c.waitsForConnectivity = false271        c.tlsMinimumSupportedProtocolVersion = .TLSv12272        return c273    }274}275
Files main
Menu

Theme