Repository Public
1// SP Drive iOS2// File: Sync/ChangeListener.swift3// Description: Sync engine 2.0 — how the device learns that the Drive changed. A source of hints (the server's event stream in 2.0)4// sits behind a protocol; hints never carry data, they only say « look at the change feed now ». Without a source, or5// while the source is down, the listener polls. The source is reconnected with exponential backoff and jitter.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation1011/// What a source of events may say. A hint is never the truth: the change feed is.12public enum ChangeHint: Sendable, Equatable {13 /// The stream is open (`hello`).14 case connected(head: Int64?)15 /// The owner's head revision advanced.16 case changed(head: Int64?)17 /// A notification was created on the server.18 case notify(kind: String)19}2021/// A live source of hints (SSE `GET /sync/events` in 2.0). The stream ends or throws when the connection is lost.22public protocol ChangeEventSource: Sendable {23 func hints() -> AsyncThrowingStream<ChangeHint, Error>24}2526public actor ChangeListener {27 public struct Configuration: Sendable {28 /// Polling interval while no stream is up (contract: 30 s in the foreground).29 public var pollInterval: Duration30 /// Safety poll while the stream is up: events are a hint, a missed one must not leave the device behind for long.31 public var safetyInterval: Duration32 public var reconnectBase: TimeInterval33 public var reconnectCap: TimeInterval34 public init(pollInterval: Duration = .seconds(30), safetyInterval: Duration = .seconds(300), reconnectBase: TimeInterval = 1, reconnectCap: TimeInterval = 60) {35 self.pollInterval = pollInterval; self.safetyInterval = safetyInterval; self.reconnectBase = reconnectBase; self.reconnectCap = reconnectCap36 }37 }38 public enum Mode: Sendable, Equatable { case stopped, polling, streaming }3940 private let source: ChangeEventSource?41 private let configuration: Configuration42 /// Called for every reason to look at the change feed (hint or poll tick). Calls are not overlapped.43 private let onChange: @Sendable () async -> Void44 private let onNotify: @Sendable (String) async -> Void45 private var streamTask: Task<Void, Never>?46 private var pollTask: Task<Void, Never>?47 public private(set) var mode: Mode = .stopped48 /// Connection attempts made so far (tests, diagnostics).49 public private(set) var connectAttempts = 050 public private(set) var hintsReceived = 051 private var lastHead: Int64?5253 public init(source: ChangeEventSource?, configuration: Configuration = Configuration(), onNotify: @escaping @Sendable (String) async -> Void = { _ in }, onChange: @escaping @Sendable () async -> Void) {54 self.source = source55 self.configuration = configuration56 self.onChange = onChange57 self.onNotify = onNotify58 }5960 /// Starts listening (foreground). Safe to call again.61 public func start() {62 guard mode == .stopped else { return }63 mode = .polling64 startPolling()65 if let source { streamTask = Task { [weak self] in await self?.runStream(source) } }66 }6768 /// Stops everything (background, sign-out). iOS suspends the app anyway; BackgroundTasks take over.69 public func stop() {70 streamTask?.cancel(); streamTask = nil71 pollTask?.cancel(); pollTask = nil72 mode = .stopped73 }7475 private func startPolling() {76 pollTask?.cancel()77 pollTask = Task { [weak self] in78 while !Task.isCancelled {79 guard let self else { return }80 let interval = await self.mode == .streaming ? self.configuration.safetyInterval : self.configuration.pollInterval81 try? await Task.sleep(for: interval)82 if Task.isCancelled { return }83 await self.onChange()84 }85 }86 }8788 private func setMode(_ m: Mode) {89 guard mode != .stopped, mode != m else { return }90 mode = m91 startPolling() // the interval depends on the mode92 }9394 private func runStream(_ source: ChangeEventSource) async {95 var failures = 096 while !Task.isCancelled {97 connectAttempts += 198 do {99 for try await hint in source.hints() {100 hintsReceived += 1101 switch hint {102 case .connected(let head):103 failures = 0104 setMode(.streaming)105 // whatever happened while the stream was down is fetched now106 if head == nil || head != lastHead { lastHead = head; await onChange() }107 case .changed(let head):108 lastHead = head ?? lastHead109 await onChange()110 case .notify(let kind):111 await onNotify(kind)112 }113 }114 } catch {}115 if Task.isCancelled { return }116 setMode(.polling)117 let delay = Backoff.delay(attempt: failures, base: configuration.reconnectBase, cap: configuration.reconnectCap)118 failures += 1119 try? await Task.sleep(for: .seconds(delay))120 }121 }122}123