SPB Git

Repository Public

FakeWebSocket.swift 15.3 KB 379 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/ClaudeRemoteTestSupport/Transport/FakeWebSocket.swift10// Module           : ClaudeRemoteTestSupport11// 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 ClaudeRemoteAPI89import Foundation9091/// In-memory WebSocket: the test plays the server.92public final class FakeWebSocket: WebSocketConnection, @unchecked Sendable {93    private let lock = NSLock()94    private var inbox: [Result<WebSocketMessage, WebSocketClosed>] = []95    private var waiter: CheckedContinuation<WebSocketMessage, Error>?96    private var closed: WebSocketClosed?97    private var _sent: [WebSocketMessage] = []98    private var _clientClose: (code: Int, reason: String?)?99    private var sentWaiters: [(predicate: @Sendable ([WebSocketMessage]) -> Bool, continuation: CheckedContinuation<Bool, Never>)] = []100    public let request: URLRequest101    /// Called for every client message (e.g. to answer pings).102    public var onClientMessage: (@Sendable (WebSocketMessage, FakeWebSocket) -> Void)? {103        get { lock.withLock { _onClientMessage } }104        set { lock.withLock { _onClientMessage = newValue } }105    }106    private var _onClientMessage: (@Sendable (WebSocketMessage, FakeWebSocket) -> Void)?107108    public init(request: URLRequest) { self.request = request }109110    // MARK: Server side (driven by the test)111112    public func serverSend(_ message: WebSocketMessage) {113        let c: CheckedContinuation<WebSocketMessage, Error>? = lock.withLock {114            if let w = waiter { waiter = nil; return w }115            inbox.append(.success(message))116            return nil117        }118        c?.resume(returning: message)119    }120121    public func serverSend(text: String) { serverSend(.text(text)) }122    public func serverSend(bytes: String) { serverSend(.data(Data(bytes.utf8))) }123124    /// Closes from the server side; pending and later `receive()` calls throw `WebSocketClosed`.125    public func serverClose(code: Int, reason: String? = nil) {126        let error = WebSocketClosed(code: code, reason: reason)127        let c: CheckedContinuation<WebSocketMessage, Error>? = lock.withLock {128            if closed == nil { closed = error }129            if let w = waiter { waiter = nil; return w }130            return nil131        }132        c?.resume(throwing: error)133    }134135    /// Everything the client sent, in order.136    public var sent: [WebSocketMessage] { lock.withLock { _sent } }137    public var sentTexts: [String] { sent.compactMap { if case .text(let t) = $0 { t } else { nil } } }138    public var sentData: Data { sent.reduce(into: Data()) { if case .data(let d) = $1 { $0.append(d) } } }139    /// Close requested by the client, if any.140    public var clientClose: (code: Int, reason: String?)? { lock.withLock { _clientClose } }141    public var isClosed: Bool { lock.withLock { closed != nil } }142143    /// Waits until the sent messages satisfy `predicate` (or the timeout elapses).144    @discardableResult145    public func waitForSent(timeout: TimeInterval = 2, _ predicate: @escaping @Sendable ([WebSocketMessage]) -> Bool) async -> Bool {146        let deadline = Date().addingTimeInterval(timeout)147        while Date() < deadline {148            if predicate(sent) { return true }149            try? await Task.sleep(for: .milliseconds(5))150        }151        return predicate(sent)152    }153154    // MARK: WebSocketConnection (client side)155156    public func send(_ message: WebSocketMessage) async throws {157        let handler: (@Sendable (WebSocketMessage, FakeWebSocket) -> Void)? = try lock.withLock {158            if let closed { throw closed }159            _sent.append(message)160            return _onClientMessage161        }162        handler?(message, self)163    }164165    public func receive() async throws -> WebSocketMessage {166        try await withTaskCancellationHandler {167            try await withCheckedThrowingContinuation { (c: CheckedContinuation<WebSocketMessage, Error>) in168                let immediate: Result<WebSocketMessage, Error>? = lock.withLock {169                    if !inbox.isEmpty {170                        switch inbox.removeFirst() {171                        case .success(let m): return .success(m)172                        case .failure(let e): return .failure(e)173                        }174                    }175                    if let closed { return .failure(closed) }176                    waiter = c177                    return nil178                }179                if let immediate { c.resume(with: immediate) }180            }181        } onCancel: {182            let c: CheckedContinuation<WebSocketMessage, Error>? = lock.withLock {183                let w = waiter184                waiter = nil185                return w186            }187            c?.resume(throwing: CancellationError())188        }189    }190191    public func close(code: Int, reason: String?) {192        let c: CheckedContinuation<WebSocketMessage, Error>? = lock.withLock {193            if _clientClose == nil { _clientClose = (code, reason) }194            if closed == nil { closed = WebSocketClosed(code: code, reason: reason) }195            let w = waiter196            waiter = nil197            return w198        }199        c?.resume(throwing: WebSocketClosed(code: code, reason: reason))200    }201}202203/// Scripted transport: each `connect` consumes the next plan (default: accept).204public final class FakeWebSocketTransport: WebSocketTransport, @unchecked Sendable {205    public enum Plan: Sendable {206        case accept207        /// The upgrade is answered with a plain HTTP status.208        case refuse(status: Int)209        case unreachable210    }211212    private let lock = NSLock()213    private var plans: [Plan] = []214    private var _requests: [URLRequest] = []215    private var _connections: [FakeWebSocket] = []216    /// Applied to every accepted socket before it is returned (install auto-responders here).217    public var onAccept: (@Sendable (FakeWebSocket) -> Void)? {218        get { lock.withLock { _onAccept } }219        set { lock.withLock { _onAccept = newValue } }220    }221    private var _onAccept: (@Sendable (FakeWebSocket) -> Void)?222223    public init() {}224225    public func enqueue(_ plan: Plan...) { lock.withLock { plans.append(contentsOf: plan) } }226    /// Every upgrade request received (accepted or not).227    public var requests: [URLRequest] { lock.withLock { _requests } }228    /// Accepted sockets, in order.229    public var connections: [FakeWebSocket] { lock.withLock { _connections } }230    public var last: FakeWebSocket? { connections.last }231232    public func connect(_ request: URLRequest) async throws -> any WebSocketConnection {233        let (plan, accept): (Plan, (@Sendable (FakeWebSocket) -> Void)?) = lock.withLock {234            _requests.append(request)235            return (plans.isEmpty ? .accept : plans.removeFirst(), _onAccept)236        }237        switch plan {238        case .refuse(let status): throw WebSocketConnectError.upgradeRefused(status: status)239        case .unreachable: throw WebSocketConnectError.unreachable("unreachable (test)")240        case .accept:241            let socket = FakeWebSocket(request: request)242            accept?(socket)243            lock.withLock { _connections.append(socket) }244            return socket245        }246    }247248    /// Waits until `count` sockets were accepted; returns the last one.249    public func waitForConnection(count: Int = 1, timeout: TimeInterval = 2) async -> FakeWebSocket? {250        let deadline = Date().addingTimeInterval(timeout)251        while Date() < deadline {252            let c = connections253            if c.count >= count { return c[count - 1] }254            try? await Task.sleep(for: .milliseconds(5))255        }256        let c = connections257        return c.count >= count ? c[count - 1] : nil258    }259260    /// Waits until `count` upgrade requests were received (accepted or refused).261    @discardableResult262    public func waitForRequests(count: Int, timeout: TimeInterval = 2) async -> Bool {263        let deadline = Date().addingTimeInterval(timeout)264        while Date() < deadline {265            if requests.count >= count { return true }266            try? await Task.sleep(for: .milliseconds(5))267        }268        return requests.count >= count269    }270}271272/// A `Sleeper` whose time only moves when the test says so.273public final class ManualSleeper: Sleeper, @unchecked Sendable {274    private struct Pending {275        var deadline: TimeInterval276        var continuation: CheckedContinuation<Void, Error>277        var id: Int278    }279280    private let lock = NSLock()281    private var time: TimeInterval = 1000282    private var pending: [Pending] = []283    private var nextID = 0284    private var _requested: [TimeInterval] = []285286    public init() {}287288    /// Every duration passed to `sleep`, in order.289    public var requested: [TimeInterval] { lock.withLock { _requested } }290    /// Number of sleeps currently suspended.291    public var pendingCount: Int { lock.withLock { pending.count } }292293    public func now() -> TimeInterval { lock.withLock { time } }294295    public func sleep(seconds: TimeInterval) async throws {296        let id: Int = lock.withLock {297            nextID += 1298            return nextID299        }300        try await withTaskCancellationHandler {301            try await withCheckedThrowingContinuation { (c: CheckedContinuation<Void, Error>) in302                let fireNow: Bool = lock.withLock {303                    _requested.append(seconds)304                    if Task.isCancelled { return true }305                    pending.append(Pending(deadline: time + seconds, continuation: c, id: id))306                    return false307                }308                if fireNow { c.resume(throwing: CancellationError()) }309            }310        } onCancel: {311            let c: CheckedContinuation<Void, Error>? = lock.withLock {312                guard let i = pending.firstIndex(where: { $0.id == id }) else { return nil }313                return pending.remove(at: i).continuation314            }315            c?.resume(throwing: CancellationError())316        }317    }318319    /// Moves time forward and resumes every sleep whose deadline passed.320    public func advance(by seconds: TimeInterval) {321        let due: [CheckedContinuation<Void, Error>] = lock.withLock {322            time += seconds323            let ready = pending.filter { $0.deadline <= time }324            pending.removeAll { $0.deadline <= time }325            return ready.sorted { $0.deadline < $1.deadline }.map(\.continuation)326        }327        due.forEach { $0.resume() }328    }329330    /// Waits (real time) until `count` sleeps are suspended.331    @discardableResult332    public func waitForPending(count: Int = 1, timeout: TimeInterval = 2) async -> Bool {333        let deadline = Date().addingTimeInterval(timeout)334        while Date() < deadline {335            if pendingCount >= count { return true }336            try? await Task.sleep(for: .milliseconds(5))337        }338        return pendingCount >= count339    }340341    /// Waits (real time) until `count` sleeps were requested in total.342    @discardableResult343    public func waitForRequested(count: Int, timeout: TimeInterval = 2) async -> Bool {344        let deadline = Date().addingTimeInterval(timeout)345        while Date() < deadline {346            if requested.count >= count { return true }347            try? await Task.sleep(for: .milliseconds(5))348        }349        return requested.count >= count350    }351}352353/// Network monitor driven by the test.354public final class FakeNetworkMonitor: NetworkPathMonitoring, @unchecked Sendable {355    private let lock = NSLock()356    private var online: Bool357    private var observers: [UUID: AsyncStream<Bool>.Continuation] = [:]358359    public init(isOnline: Bool = true) { online = isOnline }360361    public var isOnline: Bool { lock.withLock { online } }362363    public func changes() -> AsyncStream<Bool> {364        let id = UUID()365        let (stream, continuation) = AsyncStream<Bool>.makeStream()366        lock.withLock { observers[id] = continuation }367        return stream368    }369370    public func set(online value: Bool) {371        let targets: [AsyncStream<Bool>.Continuation] = lock.withLock {372            guard value != online else { return [] }373            online = value374            return Array(observers.values)375        }376        targets.forEach { $0.yield(value) }377    }378}379
Files main
Menu

Theme