SPB Git

Repository Public

EventStream.swift 12.4 KB 313 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/ClaudeRemoteCore/EventStream.swift10// Module           : ClaudeRemoteCore11// 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 ClaudeRemoteModels90import Foundation91import Observation9293/// The single shared connection to WS `/api/v1/events`.94///95/// - Reconnects with exponential backoff + jitter (`ReconnectPolicy.events`); a network path96///   change or `wake()` retries at once.97/// - `pause()` / `resume()` are the background / foreground hooks (the socket is closed while98///   paused; iOS would suspend it anyway).99/// - After every RE-connection `onResync` handlers run: events may have been missed, so stores100///   refetch their lists. There is no polling while the stream is healthy.101/// - `auth.expired`, a 401 upgrade or a 4401 close end the stream with `.unauthorized` and call102///   `onUnauthorized`.103@MainActor104@Observable105public final class EventStream {106    public private(set) var state: ConnectionState = .idle107    /// Round-trip time of the last probe (`GET /health`) or of the WebSocket handshake.108    public private(set) var latencyMs: Int?109    public private(set) var lastEventAt: Date?110    /// Server clock offset learned from `hello` (server − local), for relative times.111    public private(set) var serverTimeOffset: TimeInterval = 0112    public private(set) var reconnectCount = 0113114    @ObservationIgnored private let client: APIClient115    @ObservationIgnored private let policy: ReconnectPolicy116    @ObservationIgnored private let sleeper: any Sleeper117    @ObservationIgnored private let network: any NetworkPathMonitoring118    @ObservationIgnored private let latencyProbeInterval: TimeInterval?119    @ObservationIgnored private var handlers: [@MainActor (ServerEvent) -> Void] = []120    @ObservationIgnored private var resyncHandlers: [@MainActor () async -> Void] = []121    /// Called once when the server ends the session.122    @ObservationIgnored public var onUnauthorized: (@MainActor () async -> Void)?123124    @ObservationIgnored private var loop: Task<Void, Never>?125    @ObservationIgnored private var networkTask: Task<Void, Never>?126    @ObservationIgnored private var probeTask: Task<Void, Never>?127    @ObservationIgnored private var sleepTask: Task<Void, Never>?128    @ObservationIgnored private var gate: CheckedContinuation<Void, Never>?129    @ObservationIgnored private var socket: (any WebSocketConnection)?130    @ObservationIgnored private var wanted = false131    @ObservationIgnored private var paused = false132    @ObservationIgnored private var everConnected = false133134    public init(client: APIClient, policy: ReconnectPolicy = .events, sleeper: any Sleeper = SystemSleeper(),135                network: any NetworkPathMonitoring = SystemNetworkMonitor(), latencyProbeInterval: TimeInterval? = 30) {136        self.client = client137        self.policy = policy138        self.sleeper = sleeper139        self.network = network140        self.latencyProbeInterval = latencyProbeInterval141    }142143    /// Registers a consumer of server events (stores do this once).144    public func onEvent(_ handler: @escaping @MainActor (ServerEvent) -> Void) { handlers.append(handler) }145146    /// Registers a refetch to run after each re-connection.147    public func onResync(_ handler: @escaping @MainActor () async -> Void) { resyncHandlers.append(handler) }148149    /// Starts (or restarts) the stream. Idempotent while running.150    public func start() {151        wanted = true152        paused = false153        guard loop == nil else { return }154        everConnected = false155        state = .connecting156        loop = Task { [weak self] in await self?.run() }157        if networkTask == nil {158            let changes = network.changes()159            networkTask = Task { [weak self] in160                for await online in changes {161                    guard let self else { return }162                    if online { self.wake() } else if self.loop != nil, self.state != .unauthorized { self.dropForOffline() }163                }164            }165        }166    }167168    /// Stops for good (sign-out).169    public func stop() {170        wanted = false171        teardown()172        networkTask?.cancel()173        networkTask = nil174        state = .idle175        latencyMs = nil176    }177178    /// Background hook: closes the socket and stops retrying.179    public func pause() {180        guard wanted, !paused else { return }181        paused = true182        teardown()183        if state != .unauthorized { state = .idle }184    }185186    /// Foreground hook: reconnects at once and resyncs the stores.187    public func resume() {188        guard wanted, paused else { wake(); return }189        paused = false190        let reconnecting = everConnected191        start()192        everConnected = reconnecting193    }194195    /// Retry now (app became active, network came back, user tapped "retry").196    public func wake() {197        sleepTask?.cancel()198        gate?.resume()199        gate = nil200    }201202    private func teardown() {203        loop?.cancel()204        loop = nil205        probeTask?.cancel()206        probeTask = nil207        sleepTask?.cancel()208        sleepTask = nil209        gate?.resume()210        gate = nil211        socket?.close(code: 1000, reason: nil)212        socket = nil213    }214215    private func dropForOffline() {216        socket?.close(code: 1000, reason: nil)217        if state != .unauthorized { state = .offline }218    }219220    private func run() async {221        var attempt = 0222        while !Task.isCancelled {223            if !network.isOnline {224                state = .offline225                await withCheckedContinuation { (c: CheckedContinuation<Void, Never>) in226                    if Task.isCancelled { c.resume() } else { gate = c }227                }228                continue229            }230            if attempt > 0 { state = .reconnecting(attempt: attempt, nextRetry: nil) }231            do {232                let started = sleeper.now()233                let socket = try await client.openEventStream()234                if Task.isCancelled { socket.close(code: 1000, reason: nil); return }235                self.socket = socket236                latencyMs = max(0, Int((sleeper.now() - started) * 1000))237                state = .online238                attempt = 0239                if everConnected {240                    reconnectCount += 1241                    for handler in resyncHandlers { await handler() }242                }243                everConnected = true244                startProbe()245                while true {246                    let message = try await socket.receive()247                    guard case .text(let text) = message, let event = ServerEvent(text: text) else { continue }248                    lastEventAt = Date()249                    if case .hello(let serverTime) = event { serverTimeOffset = serverTime.timeIntervalSinceNow }250                    if case .authExpired = event {251                        await endUnauthorized()252                        return253                    }254                    for handler in handlers { handler(event) }255                }256            } catch let closed as WebSocketClosed where closed.code == WSCloseCode.unauthorized.rawValue {257                await endUnauthorized()258                return259            } catch let error as APIError where error.status == 401 {260                await endUnauthorized()261                return262            } catch is CancellationError {263                return264            } catch {265                // fall through to the retry below266            }267            if Task.isCancelled { return } // a newer loop may already own `socket`268            socket = nil269            probeTask?.cancel()270            probeTask = nil271            latencyMs = nil272            if !network.isOnline { continue }273            let delay = policy.delay(attempt: attempt)274            attempt += 1275            state = .reconnecting(attempt: attempt, nextRetry: Date().addingTimeInterval(delay))276            let sleeper = self.sleeper277            let sleep = Task { _ = try? await sleeper.sleep(seconds: delay) }278            sleepTask = sleep279            await sleep.value280            sleepTask = nil281        }282    }283284    private func endUnauthorized() async {285        socket?.close(code: 1000, reason: nil)286        socket = nil287        probeTask?.cancel()288        probeTask = nil289        loop = nil290        wanted = false291        state = .unauthorized292        latencyMs = nil293        await onUnauthorized?()294    }295296    private func startProbe() {297        probeTask?.cancel()298        guard let interval = latencyProbeInterval else { return }299        let sleeper = self.sleeper300        let client = self.client301        probeTask = Task { [weak self] in302            while !Task.isCancelled {303                guard (try? await sleeper.sleep(seconds: interval)) != nil else { return }304                let started = sleeper.now()305                guard (try? await client.health()) != nil else { continue }306                let ms = max(0, Int((sleeper.now() - started) * 1000))307                guard let self, !Task.isCancelled, self.state == .online else { return }308                self.latencyMs = ms309            }310        }311    }312}313
Files main
Menu

Theme