Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sync/SyncEngine.swift3// Description: The sync loop of a signed-in device: replays the journal of local operations, pulls the server's changes into the mirror, runs the transfer queue, reacts to network changes and wake-ups, and rests (no timer faster than its poll interval) when nothing happens.4import Foundation5import SPDriveCore67public enum SyncPhase: Sendable, Equatable { case idle, syncing, offline, paused, needsLogin, error(String) }8public struct SyncStatus: Sendable, Equatable {9 public var phase = SyncPhase.idle10 public var lastSync: Date?11 public var pendingOperations = 012 public var openConflicts = 013 public var transfers = TransferQueue.Summary()14 public var lastError: String?15 /// How server changes reach this device right now: pushed stream, polling fallback, or nothing (paused, stopped).16 public var events = EventListener.Channel.off17 public init() {}18}1920public actor SyncEngine {21 public nonisolated let api: APIClient22 public nonisolated let store: MetadataStore23 public nonisolated let journal: OperationJournal24 public nonisolated let transfers: TransferQueue25 public nonisolated let detector: ChangeDetector26 public nonisolated let conflicts: ConflictResolver27 private let network: NetworkMonitor28 private var loop: Task<Void, Never>?29 private var netWatch: Task<Void, Never>?30 private var transferWatch: Task<Void, Never>?31 private var waiter: CheckedContinuation<Void, Never>?32 private var poked = false33 private var paused = false34 private var status = SyncStatus()35 private var listeners: [UUID: AsyncStream<SyncStatus>.Continuation] = [:]36 private var onRemoteChanges: (@Sendable ([DetectedChange]) async -> Void)?37 /// Seconds between two looks at the server when nothing happens; shortens after activity.38 public static let pollRange: ClosedRange<Double> = 10...12039 private var interval = SyncEngine.pollRange.lowerBound40 private var eventSource: RemoteEventSource?41 private var onNotify: (@Sendable (String) async -> Void)?42 private func notified(_ kind: String) async { await onNotify?(kind) }43 private var listener: EventListener?44 private var channelWatch: Task<Void, Never>?45 private let eventPollInterval: Double4647 /// - Parameters:48 /// - power: battery and Low Power Mode, read by the transfer queue (nil = ignore power).49 /// - eventPollInterval: seconds between two looks at the head revision while no event stream is live (contract: 30 s).50 public init(api: APIClient, store: MetadataStore, network: NetworkMonitor, workDirectory: URL, deviceName: String, power: PowerSource? = nil, eventPollInterval: Double = 30) {51 self.api = api; self.store = store; self.network = network; self.eventPollInterval = eventPollInterval52 journal = OperationJournal(api: api, store: store)53 transfers = TransferQueue(api: api, store: store, workDirectory: workDirectory, deviceName: deviceName, network: network, power: power)54 detector = ChangeDetector(api: api, store: store)55 conflicts = ConflictResolver(api: api, store: store)56 }57 /// Called after remote changes were written to the mirror (the app signals the File Provider and refreshes its views).58 public func setRemoteChangeHandler(_ h: @escaping @Sendable ([DetectedChange]) async -> Void) { onRemoteChanges = h }5960 /// Plugs in the pushed event stream (SSE in 2.0). Without one, or while it is down, the engine polls.61 public func setEventSource(_ source: RemoteEventSource?) async {62 eventSource = source63 if listener != nil { await stopListening(); await startListening() }64 }65 /// Called for each `notify` event of the stream (a notification was created for the account).66 public func setNotifyHandler(_ h: (@Sendable (String) async -> Void)?) { onNotify = h }67 private func startListening() async {68 guard listener == nil else { return }69 let api = self.api70 let l = EventListener(source: eventSource, pollInterval: eventPollInterval, head: { try await api.syncCursor().head },71 onNotify: { [weak self] kind in await self?.notified(kind) }, onChange: { [weak self] _ in await self?.poke() })72 listener = l73 channelWatch = Task { [weak self] in for await c in await l.channels() { await self?.channelChanged(c) } }74 await l.start()75 }76 private func stopListening() async {77 channelWatch?.cancel(); channelWatch = nil78 await listener?.stop(); listener = nil79 await channelChanged(.off)80 }81 private func channelChanged(_ c: EventListener.Channel) async {82 guard status.events != c else { return }83 status.events = c84 for l in listeners.values { l.yield(status) }85 }8687 // MARK: Status88 public func statusStream() -> AsyncStream<SyncStatus> {89 AsyncStream { c in90 let id = UUID(); listeners[id] = c; c.yield(status)91 c.onTermination = { [weak self] _ in Task { await self?.drop(id) } }92 }93 }94 private func drop(_ id: UUID) { listeners[id] = nil }95 public func currentStatus() -> SyncStatus { status }96 private func publish(_ phase: SyncPhase? = nil, error: String?? = nil) async {97 var s = status98 if let phase { s.phase = phase }99 if let error { s.lastError = error }100 s.lastSync = store.lastSync101 s.pendingOperations = (try? journal.pendingCount()) ?? 0102 s.openConflicts = (try? conflicts.openCount()) ?? 0103 s.transfers = await transfers.summary()104 s.events = status.events // may have changed while this method was suspended105 guard s != status else { return }106 status = s107 for l in listeners.values { l.yield(s) }108 }109110 // MARK: Lifecycle111 public func start() async {112 guard loop == nil else { return }113 await transfers.start()114 netWatch = Task { [weak self, network] in115 for await s in network.changes() { if s.online { await self?.networkReturned() } else { await self?.publish(.offline) } }116 }117 transferWatch = Task { [weak self, transfers] in for await _ in await transfers.events() { await self?.publish() } }118 loop = Task { [weak self] in await self?.runLoop() }119 if !paused { await startListening() }120 }121 public func stop() async {122 loop?.cancel(); netWatch?.cancel(); transferWatch?.cancel(); loop = nil; netWatch = nil; transferWatch = nil123 await transfers.stop(); await stopListening(); wake()124 }125 /// Pauses syncing: transfers stop and keep their progress, the journal keeps recording, nothing is sent or pulled.126 public func pause() async { paused = true; await transfers.pauseAll(); await stopListening(); await publish(.paused) }127 public func resume() async { paused = false; await transfers.resumeAll(); if loop != nil { await startListening() }; poke() }128 public var isPaused: Bool { paused }129 /// Asks for a sync pass now (something was just decided locally, the machine woke up, the person asked).130 public func poke() { interval = SyncEngine.pollRange.lowerBound; poked = true; wake() }131 private func networkReturned() async { await transfers.kick(); poke() }132 private func wake() { waiter?.resume(); waiter = nil }133 private func rest(_ seconds: Double) async {134 if poked { poked = false; return }135 let sleeper = Task { [weak self] in try? await Task.sleep(nanoseconds: UInt64(seconds * 1e9)); await self?.wake() }136 await withCheckedContinuation { (c: CheckedContinuation<Void, Never>) in waiter = c }137 sleeper.cancel(); poked = false138 }139140 /// One pass: journal first (what was decided here goes out before judging what came in), then the server's changes.141 @discardableResult public func syncOnce() async throws -> [DetectedChange] {142 let r = await journal.run()143 if r.blocked { _ = try await api.syncCursor() } // surfaces the real reason (offline, signed out) as an error144 let changes = try await detector.pull()145 if r.done > 0 || !changes.isEmpty { await onRemoteChanges?(changes) }146 return changes147 }148 private func runLoop() async {149 while !Task.isCancelled {150 if paused { await publish(.paused); await rest(3600); continue }151 if !network.status.online { await publish(.offline); await rest(300); continue }152 await publish(.syncing)153 do {154 let pendingBefore = (try? journal.pendingCount()) ?? 0155 let changes = try await syncOnce()156 await publish(.idle, error: .some(nil))157 // stay attentive while things move, drift toward a slow poll when they do not158 interval = (!changes.isEmpty || pendingBefore > 0) ? SyncEngine.pollRange.lowerBound : min(SyncEngine.pollRange.upperBound, interval * 1.5)159 } catch {160 let e = DriveError.wrap(error)161 if e == .unauthenticated { await publish(.needsLogin, error: e.errorDescription); await rest(3600); continue }162 if e == .cancelled { break }163 if e.isTransient { await publish(.offline, error: e.errorDescription) } else { await publish(.error(e.errorDescription ?? e.code), error: e.errorDescription) }164 interval = min(SyncEngine.pollRange.upperBound, max(15, interval * 2))165 }166 await rest(interval)167 }168 }169}170