SPB Git

Repository Public

SyncCenter.swift 12.3 KB 216 lines swift

1//2//  VQuant iOS3//  File: VQuant/Next/SyncCenter.swift4//  Description: One account, synced: owns the VQuantKit sync engine of the signed-in person (replica in the app-group5//               container, sealed with the cache key), the observable collections of every object kind, and the6//               one-time migration of the data VQuant 1.0 kept on the device.7//8//  Author: Simon-Pierre Boucher9//  Contact: contact@spboucher.ai10//1112import Foundation13import Observation14import VQuantKit1516@MainActor17@Observable18final class SyncCenter {19    private(set) var engine: VQSyncEngine20    private(set) var watchlists: VQSyncedCollection<VQWatchlist>21    private(set) var portfolios: VQSyncedCollection<VQPortfolio>22    private(set) var charts: VQSyncedCollection<VQChart>23    private(set) var projects: VQSyncedCollection<VQProject>24    private(set) var notes: VQSyncedCollection<VQNote>25    private(set) var workspaces: VQSyncedCollection<VQWorkspace>26    private(set) var reviews: VQSyncedCollection<VQReview>27    private(set) var preferences: VQSyncedCollection<VQPreference>28    private(set) var status: VQSyncStatusStore29    private(set) var person: String?30    /// True once a pull succeeded during this launch (the replica reflects the server, not only the device).31    private(set) var hasPulled = false32    /// What the one-time migration of 1.0 data did, for the settings screen.33    private(set) var migrationNotes: [String] = []3435    /// Called (main actor) when a server-side list changed: conversations, running analyses, quant jobs.36    var onHint: (@MainActor (VQSyncHint) -> Void)?37    /// Called after local or remote changes of objects (widgets, Spotlight).38    var onObjectsChanged: (@MainActor (Set<VQObjectKind>) -> Void)?3940    private let client: VQClient41    private let keys: CacheKeyProvider42    private let defaults: UserDefaults43    /// `ios-` in the app, `ios-test-` when a test token is injected: tests only ever write objects with that prefix.44    let objectPrefix: String45    private let isTest: Bool46    private var tasks: [Task<Void, Never>] = []4748    /// Where the replica directories live, and where 1.0 left its watchlist file (injectable for tests).49    private let root: URL50    private let legacyWatchlist: URL5152    init(client: VQClient, keys: CacheKeyProvider, defaults: UserDefaults, isTest: Bool, root: URL = SharedContainer.directory, legacyWatchlist: URL = SharedContainer.watchlistURL) {53        self.client = client; self.keys = keys; self.defaults = defaults; self.isTest = isTest54        self.root = root; self.legacyWatchlist = legacyWatchlist55        objectPrefix = isTest ? "ios-test-" : "ios-"56        let e = VQSyncEngine(client: client, storage: VQMemorySyncStorage())57        engine = e58        watchlists = VQSyncedCollection(engine: e); portfolios = VQSyncedCollection(engine: e); charts = VQSyncedCollection(engine: e)59        projects = VQSyncedCollection(engine: e); notes = VQSyncedCollection(engine: e); workspaces = VQSyncedCollection(engine: e)60        reviews = VQSyncedCollection(engine: e); preferences = VQSyncedCollection(engine: e)61        status = VQSyncStatusStore(engine: e)62    }6364    /// The convention of the three clients (web, Mac, iOS): lists merge element-wise, and other fields are65    /// last-writer-wins per field, so two devices changing different preferences — or a note's title and its body —66    /// do not undo each other.67    static var configuration: VQSyncEngine.Configuration {68        var c = VQSyncEngine.Configuration()69        c.granularity = .field70        return c71    }7273    var watchlistId: String { objectPrefix + "watchlist" }74    var testPortfolioId: String { "ios-test-portfolio" }75    /// The portfolio shown by default: the agent's (`main`), or the test portfolio in a test run.76    var defaultPortfolioId: String { isTest ? testPortfolioId : VQObjectID.mainPortfolio }77    /// One working chart per symbol, with the id the web client uses (`sym-<SYMBOL>`, other characters as `_<hex>`),78    /// so drawings made on the web open on the iPad and back.79    func chartId(_ symbol: String) -> String {80        let safe = symbol.uppercased().unicodeScalars.map { u -> String in81            (u.value >= 48 && u.value <= 57) || (u.value >= 65 && u.value <= 90) ? String(u) : "_" + String(u.value, radix: 16)82        }.joined()83        return String(((isTest ? "ios-test-sym-" : "sym-") + safe).prefix(64))84    }85    var preferenceId: String { isTest ? "ios-test-default" : VQObjectID.defaultPreference }86    func newId() -> String { isTest ? objectPrefix + String(VQObjectID.make().prefix(18)) : VQObjectID.make() }8788    static func directory(person: String, isTest: Bool, root: URL = SharedContainer.directory) -> URL {89        let safe = String(person.unicodeScalars.map { CharacterSet.alphanumerics.contains($0) ? Character($0) : "_" })90        return root.appendingPathComponent(isTest ? "sync-test" : "sync", isDirectory: true).appendingPathComponent(safe.isEmpty ? "_" : safe, isDirectory: true)91    }9293    /// Builds the engine of this person and starts it. Idempotent for the same person.94    func start(person id: String) {95        if person == id { Task { await engine.start() }; return }96        stopObserving()97        person = id; hasPulled = false98        let dir = Self.directory(person: id, isTest: isTest, root: root)99        let storage: any VQSyncStorage = (try? VQFileSyncStorage(directory: dir, cipher: AppSyncCipher(keys: keys))) ?? VQMemorySyncStorage()100        var values = URLResourceValues(); values.isExcludedFromBackup = true101        var d = dir; try? d.setResourceValues(values)102        let e = VQSyncEngine(client: client, storage: storage, configuration: Self.configuration)103        engine = e104        watchlists = VQSyncedCollection(engine: e); portfolios = VQSyncedCollection(engine: e); charts = VQSyncedCollection(engine: e)105        projects = VQSyncedCollection(engine: e); notes = VQSyncedCollection(engine: e); workspaces = VQSyncedCollection(engine: e)106        reviews = VQSyncedCollection(engine: e); preferences = VQSyncedCollection(engine: e)107        status = VQSyncStatusStore(engine: e)108        let (w, p, c, pr, n, ws, r, pf, st) = (watchlists, portfolios, charts, projects, notes, workspaces, reviews, preferences, status)109        tasks = [110            Task { await w.observe() }, Task { await p.observe() }, Task { await c.observe() }, Task { await pr.observe() },111            Task { await n.observe() }, Task { await ws.observe() }, Task { await r.observe() }, Task { await pf.observe() }, Task { await st.observe() },112            Task { [weak self] in for await hint in await e.hints() { self?.onHint?(hint) } },113            Task { [weak self] in114                for await event in await e.events() {115                    if case .objectsChanged(let kinds) = event { self?.onObjectsChanged?(kinds) }116                    if case .statusChanged(let s) = event, s.lastPulledAt != nil, self?.hasPulled == false { self?.hasPulled = true; await self?.afterFirstPull() }117                }118            },119        ]120        startup = Task {121            do { try await e.load() } catch { migrationNotes.append("La file d’écritures locales était illisible et a été abandonnée.") }122            await migrateLocalData()123            await e.start()124        }125    }126    private var startup: Task<Void, Never>?127    /// Waits until the replica is loaded and the 1.0 migration has run (tests, and the first screen after sign-in).128    func ready() async { await startup?.value }129130    /// Reads the object from the engine (replica + queue, not the screen's last snapshot), edits it and queues the131    /// write. `create` is the starting value when the object does not exist. Returns the failure, if any.132    @discardableResult133    func edit<T: VQSyncData>(_ type: T.Type = T.self, id: String, create: T? = nil, _ change: @Sendable (inout T) -> Void) async -> VQError? {134        guard var data = await engine.object(T.self, id: id)?.data ?? create else { return nil }135        change(&data)136        do { _ = try await engine.put(data, id: id); return nil }137        catch let e as VQError { return e }138        catch { return VQError(.rejected, message: String(describing: error)) }139    }140141    /// iOS closed the stream while the app was suspended: one round now, the stream reconnects by itself.142    func becameActive() {143        guard person != nil else { return }144        Task { await engine.start(); try? await engine.syncNow() }145    }146    func enteredBackground() { Task { await engine.stop() } }147148    /// One pull-and-flush round (pull to refresh, background refresh).149    @discardableResult150    func syncNow() async -> Bool {151        guard person != nil else { return false }152        do { try await engine.syncNow(); return true } catch { return false }153    }154155    /// Sign-out or dead session: the replica, the queue and the conflict records of this device are erased.156    func wipe() {157        stopObserving()158        let old = engine159        Task { await old.reset() }160        if let person { try? FileManager.default.removeItem(at: Self.directory(person: person, isTest: isTest, root: root)) }161        person = nil; hasPulled = false; migrationNotes = []162        let e = VQSyncEngine(client: client, storage: VQMemorySyncStorage())163        engine = e164        watchlists = VQSyncedCollection(engine: e); portfolios = VQSyncedCollection(engine: e); charts = VQSyncedCollection(engine: e)165        projects = VQSyncedCollection(engine: e); notes = VQSyncedCollection(engine: e); workspaces = VQSyncedCollection(engine: e)166        reviews = VQSyncedCollection(engine: e); preferences = VQSyncedCollection(engine: e)167        status = VQSyncStatusStore(engine: e)168    }169170    private func stopObserving() { for t in tasks { t.cancel() }; tasks = [] }171172    // MARK: migration of VQuant 1.0 device data173174    private func migrated(_ what: String) -> Bool { defaults.bool(forKey: "migrated.\(what).\(person ?? "")") }175    private func setMigrated(_ what: String) { defaults.set(true, forKey: "migrated.\(what).\(person ?? "")") }176177    /// 1.0 kept the watchlist in a JSON file of the app group. It becomes one synced `watchlist` object with a fixed178    /// id: a second device that migrates the same account meets a 409 and the engine merges the symbols (union), so179    /// nothing is lost and nothing is duplicated. The file is kept as `watchlist.migrated.json`.180    private func migrateLocalData() async {181        guard person != nil, !migrated("watchlist") else { return }182        let file = WatchlistFile(url: legacyWatchlist)183        let fm = FileManager.default184        guard fm.fileExists(atPath: file.url.path) else { setMigrated("watchlist"); return }185        let symbols = file.load().map(\.symbol)186        if !symbols.isEmpty {187            var list = await engine.object(VQWatchlist.self, id: watchlistId)?.data ?? VQWatchlist(name: "Liste de suivi", symbols: [])188            for s in symbols { list.add(s) }189            do {190                _ = try await engine.put(list, id: watchlistId)191                migrationNotes.append("Liste de suivi de la version 1.0 (\(symbols.count) symboles) migrée vers le compte.")192            } catch { return }                                   // nothing written: the file stays, the next launch tries again193        }194        let backup = file.url.deletingLastPathComponent().appendingPathComponent("watchlist.migrated.json")195        try? fm.removeItem(at: backup)196        try? fm.moveItem(at: file.url, to: backup)197        setMigrated("watchlist")198    }199200    /// A new account with no watchlist at all gets the same starting list 1.0 created on the device.201    private func afterFirstPull() async {202        guard person != nil else { return }203        // Test runs work on their own portfolio, never on `main`.204        if isTest, await engine.object(VQPortfolio.self, id: testPortfolioId) == nil {205            _ = try? await engine.put(VQPortfolio(name: "ios-test — portefeuille", baseCurrency: "USD"), id: testPortfolioId)206        }207        guard !defaults.bool(forKey: "seeded.watchlist.\(person ?? "")") else { return }208        let existing = await engine.objects(of: VQWatchlist.self)209        let mine = existing.contains { $0.id == watchlistId }210        if existing.isEmpty || (isTest && !mine) {211            _ = try? await engine.put(VQWatchlist(name: isTest ? "ios-test — liste de suivi" : "Liste de suivi", symbols: WatchlistFile.defaults), id: watchlistId)212        }213        defaults.set(true, forKey: "seeded.watchlist.\(person ?? "")")214    }215}216
Files main
Menu

Theme