SPB Git

Repository Public

RemoteEvents.swift 5.4 KB 113 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sync/RemoteEvents.swift3// Description: Listening for "something changed on the server": an event stream behind a protocol (Server-Sent Events in SP Drive 2.0), with the polling fallback that keeps working whenever the stream is absent or down. Events are a hint, never the source of truth: a change only tells the engine to pull the change feed.4import Foundation5import SPDriveCore67/// What the server pushes (contract §3). `hello` once per connection, `change` when the owner's head revision moved.8public enum RemoteEvent: Sendable, Equatable {9    case hello(head: Int64)10    case change(head: Int64)11    case notify(kind: String)12}1314/// A source of pushed events. `connect()` opens one connection; the stream ends (or throws) when the connection drops.15/// SP Drive 2.0 plugs its SSE client (`GET /sync/events`) in here; nothing else in the engine knows about the transport.16public protocol RemoteEventSource: Sendable {17    func connect() -> AsyncThrowingStream<RemoteEvent, Error>18}1920/// Keeps the engine informed of server changes: follows the event stream when there is one, reconnects with exponential21/// back-off and jitter (1 s → 60 s), and polls the head revision (every 30 s by default) for as long as the stream is not live.22public actor EventListener {23    public enum Channel: String, Sendable, Equatable { case off, polling, stream }24    private let source: RemoteEventSource?25    private let head: @Sendable () async throws -> Int6426    private let onChange: @Sendable (Int64) async -> Void27    private let onNotify: (@Sendable (String) async -> Void)?28    private let pollInterval: Double29    private let retry: RetryPolicy30    private var streamTask: Task<Void, Never>?31    private var pollTask: Task<Void, Never>?32    private var lastHead: Int64?33    public private(set) var channel = Channel.off34    public private(set) var reconnects = 035    public private(set) var polls = 036    private var channelListeners: [UUID: AsyncStream<Channel>.Continuation] = [:]3738    /// - Parameters:39    ///   - source: the pushed stream, or nil to poll only.40    ///   - head: reads the owner's head revision (one small request).41    ///   - onChange: called when the head revision is seen to move (from either channel).42    public init(source: RemoteEventSource?, pollInterval: Double = 30, retry: RetryPolicy = .reconnect, head: @escaping @Sendable () async throws -> Int64,43                onNotify: (@Sendable (String) async -> Void)? = nil, onChange: @escaping @Sendable (Int64) async -> Void) {44        self.source = source; self.pollInterval = pollInterval; self.retry = retry; self.head = head; self.onNotify = onNotify; self.onChange = onChange45    }46    public func channels() -> AsyncStream<Channel> {47        AsyncStream { c in48            let id = UUID(); channelListeners[id] = c; c.yield(channel)49            c.onTermination = { [weak self] _ in Task { await self?.dropListener(id) } }50        }51    }52    private func dropListener(_ id: UUID) { channelListeners[id] = nil }53    private func set(_ c: Channel) { guard c != channel else { return }; channel = c; for l in channelListeners.values { l.yield(c) } }5455    public func start() {56        guard streamTask == nil, pollTask == nil else { return }57        if source != nil { streamTask = Task { [weak self] in await self?.follow() } }58        startPolling()59    }60    public func stop() {61        streamTask?.cancel(); pollTask?.cancel(); streamTask = nil; pollTask = nil62        set(.off)63    }64    /// The head the engine already has (after its own pull), so that the next poll does not report it as news.65    public func noteHead(_ h: Int64) { lastHead = h }6667    private func saw(_ h: Int64) async {68        guard h != lastHead else { return }69        lastHead = h70        await onChange(h)71    }72    private func startPolling() {73        guard pollTask == nil else { return }74        if channel != .stream { set(.polling) }75        pollTask = Task { [weak self, pollInterval] in76            while !Task.isCancelled {77                try? await Task.sleep(nanoseconds: UInt64(pollInterval * 1e9))78                if Task.isCancelled { break }79                await self?.pollOnce()80            }81        }82    }83    private func stopPolling() { pollTask?.cancel(); pollTask = nil }84    private func pollOnce() async {85        guard channel != .stream else { return }86        polls += 187        if let h = try? await head() { await saw(h) }88    }89    private func streamIsLive() { set(.stream); stopPolling() }90    private func streamDropped() { reconnects += 1; if channel == .stream { set(.polling) }; startPolling() }9192    private func follow() async {93        guard let source else { return }94        var failures = 095        while !Task.isCancelled {96            do {97                for try await event in source.connect() {98                    if Task.isCancelled { return }99                    switch event {100                    case .hello(let h): failures = 0; streamIsLive(); await saw(h)101                    case .change(let h): await saw(h)102                    case .notify(let kind): await onNotify?(kind)103                    }104                }105            } catch {}106            if Task.isCancelled { return }107            // the connection ended: poll while waiting, then try again a little later each time108            streamDropped(); failures += 1109            try? await Task.sleep(nanoseconds: UInt64(retry.delay(attempt: failures) * 1e9))110        }111    }112}113
Files main
Menu

Theme