Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Core/Sync/SyncClient.swift3// Description: Long-lived sync stream (`GET /api/events?after=`) with reconnection and backoff, and the pull variant (`GET /api/sync`).4import Foundation56public enum SyncUpdate: Sendable, Equatable {7 /// The stream is open; `head` is the server's latest sequence number.8 case connected(head: Int)9 /// Changes to apply (already reduced). `head` carries the sequence to resume from.10 case invalidate(SyncInvalidation)11 /// The stream dropped; a reconnection is scheduled.12 case disconnected13 /// The session no longer exists on the server.14 case sessionEnded15}1617public final class SyncClient: Sendable {18 public struct Timing: Sendable {19 public var reconnectBase: Duration = .seconds(1)20 public var reconnectCap: Duration = .seconds(30)21 public var silenceTimeout: Duration = .seconds(70) // the server sends a heartbeat comment well below this22 public var onlinePoll: Duration = .seconds(2)23 public init() {}24 }25 private let api: APIClient26 private let timing: Timing27 private let isOnline: @Sendable () -> Bool28 private let sleep: @Sendable (Duration) async throws -> Void2930 public init(api: APIClient, timing: Timing = Timing(), isOnline: @escaping @Sendable () -> Bool = { true },31 sleep: @escaping @Sendable (Duration) async throws -> Void = { try await Task.sleep(for: $0) }) {32 self.api = api; self.timing = timing; self.isOnline = isOnline; self.sleep = sleep33 }3435 /// `GET /api/sync?after=` — used when the app becomes active, and as a catch-up before the stream opens.36 public func pull(after: Int) async throws -> SyncFeed { try await api.decode(SyncFeed.self, .get, "/api/sync", query: ["after": String(max(after, 0))]) }3738 /// Follows the feed from `after` until the consuming task is cancelled. Reconnects with exponential backoff and39 /// resumes from the last sequence number it delivered, so no change is skipped and none is applied twice.40 public func events(after start: Int) -> AsyncStream<SyncUpdate> {41 let (stream, continuation) = AsyncStream<SyncUpdate>.makeStream(bufferingPolicy: .unbounded)42 let task = Task { [self] in43 var last = max(start, 0); var tries = 044 while !Task.isCancelled {45 do {46 let opening = try await api.openStream(.get, "/api/events", query: ["after": String(last)], timeout: timing.silenceTimeout.seconds)47 guard case .events(_, let bytes) = opening else { throw APIError(.decoding, message: "Flux de synchronisation inattendu.") }48 tries = 049 var parser = SSEParser()50 for try await chunk in bytes {51 var batch = SyncInvalidation(); batch.head = last52 for sse in parser.feed(chunk) {53 switch SyncEvent(sse) {54 case .hello(let head, _):55 continuation.yield(.connected(head: head))56 // a head below what this client has seen means the feed was reset on the server57 if head < last { batch.markEverything(head: head); last = head }58 case .change(let c): if c.seq > last { batch.apply(c); last = c.seq }59 case .resync(let head): batch.markEverything(head: head); last = max(head, 0)60 case .unknown: break61 }62 }63 if !batch.isEmpty { batch.head = last; continuation.yield(.invalidate(batch)) }64 }65 } catch let e as APIError {66 if e.kind == .locked { continuation.yield(.sessionEnded); break }67 if e.kind == .cancelled { break }68 } catch { if Task.isCancelled { break } }69 if Task.isCancelled { break }70 continuation.yield(.disconnected)71 tries += 172 let backoff = min(timing.reconnectBase * (1 << min(tries - 1, 5)), timing.reconnectCap)73 try? await sleep(backoff + .milliseconds(Int.random(in: 0...300)))74 while !isOnline() && !Task.isCancelled { try? await sleep(timing.onlinePoll) }75 }76 continuation.finish()77 }78 continuation.onTermination = { @Sendable _ in task.cancel() }79 return stream80 }81}8283extension Duration {84 var seconds: TimeInterval { let c = components; return TimeInterval(c.seconds) + TimeInterval(c.attoseconds) / 1e18 }85}8687public extension APIClient {88 /// Server draft with its clock (`updatedAt` when the server sends it), to arbitrate with a draft kept locally.89 func draftRecord(scope: String) async throws -> (text: String, updatedAt: Date?)? {90 let j = try await json(.get, "/api/drafts", query: ["scope": scope])91 guard let d = j["draft"], !d.isNull else { return nil }92 let at = (d["updatedAt"] ?? d["updated_at"])?.stringValue.flatMap(ServerDate.parse)93 return (d["text"]?.stringValue ?? "", at)94 }95}96