Repository Public
1// SP Notes Core2// File: Sources/SPNotesSync/Repositories/RepositorySupport.swift3// Description: What every repository shares: the typed error (`.offline` when a server-only write cannot reach the4// server — nothing is queued silently), the `Cached` wrapper with its fetch date and staleness helper, the5// cache policies, and the context (store + API + engine) with the read-through cache of the read models.6// How the apps use the repositories: docs/REPOSITORIES.md.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation11import SPNotesAPI12import SPNotesStore1314/// Every failure of a repository call.15public enum RepositoryError: Error, Sendable, Equatable {16 /// The server cannot be reached (no connectivity, connection failure, timeout). For a kind that is written online17 /// only (database rows, properties, views, relations, concepts, references…) **nothing was queued**: ask again18 /// when the network is back.19 case offline20 /// There is no valid session any more.21 case signedOut22 /// The server does not provide this feature (a 2.x server, or `501 not_implemented`).23 case unsupported(feature: String)24 /// Offline (or cache-only) and nothing was ever fetched for this read model.25 case notCached26 /// The object does not exist (any more), locally or on the server.27 case notFound(String)28 /// The server answered with an error; the typed accessors of `APIError` give the details (`code`, `detail(_:)`…).29 case server(APIError)30 /// The local store failed.31 case store(String)32 /// The call itself is wrong (empty title, unknown id…): nothing was sent.33 case invalid(String)34 /// What the decision was made on has changed since it was read (a newer server copy, a local edit): nothing was35 /// written — read again and ask again.36 case stale3738 /// The stable code of the server error, when there is one.39 public var code: String? {40 if case .server(let error) = self { return error.code }41 return nil42 }4344 public var isOffline: Bool { self == .offline }4546 /// Maps what the API client or the store throws.47 public static func from(_ error: Error) -> RepositoryError {48 if let already = error as? RepositoryError { return already }49 if let api = error as? APIError {50 switch api {51 case .offline, .transport, .timeout: return .offline52 default: break53 }54 if api.isUnauthenticated { return .signedOut }55 if api.isNotImplemented { return .unsupported(feature: api.code ?? "not_implemented") }56 if api.isRouteMissing { return .unsupported(feature: "route") } // the HTML 404 / 405 of a server without the route57 if api.isNotFound { return .notFound(api.message) }58 return .server(api)59 }60 if let store = error as? StoreError {61 if case .notFound(let what) = store { return .notFound(what) }62 return .store(String(describing: store))63 }64 if error is CancellationError { return .server(.cancelled) }65 return .store(String(describing: error))66 }67}6869extension RepositoryError: LocalizedError {70 public var errorDescription: String? {71 switch self {72 case .offline: return "Hors ligne : cette action a besoin du serveur."73 case .signedOut: return "La session a expiré."74 case .unsupported(let feature): return "Le serveur ne propose pas cette fonction (\(feature))."75 case .notCached: return "Aucune copie hors ligne de ces données."76 case .notFound(let what): return "Introuvable : \(what)"77 case .server(let error): return error.message78 case .store(let detail): return "Base locale : \(detail)"79 case .invalid(let detail): return detail80 case .stale: return "Les données ont changé entre-temps ; rechargez et recommencez."81 }82 }83}8485/// A value computed by the server with the date it was fetched. Show the date whenever `source` is `.cache`86/// (« mis à jour il y a … »): nothing is ever recomputed on the device.87public struct Cached<Value: Sendable>: Sendable {88 public enum Source: Sendable, Equatable { case network, cache }89 public var value: Value90 public var fetchedAt: Date91 public var source: Source9293 public init(value: Value, fetchedAt: Date, source: Source) {94 self.value = value95 self.fetchedAt = fetchedAt96 self.source = source97 }9899 public func age(now: Date = Date()) -> TimeInterval { now.timeIntervalSince(fetchedAt) }100 /// Whether the copy is older than `maxAge` seconds.101 public func isStale(maxAge: TimeInterval, now: Date = Date()) -> Bool { Staleness.isStale(fetchedAt: fetchedAt, maxAge: maxAge, now: now) }102 public func map<T: Sendable>(_ transform: (Value) throws -> T) rethrows -> Cached<T> { Cached<T>(value: try transform(value), fetchedAt: fetchedAt, source: source == .network ? .network : .cache) }103}104105extension Cached: Equatable where Value: Equatable {}106107/// Staleness of the cached read models.108public enum Staleness {109 /// Suggested maximum ages (seconds) before a read model is refreshed in the background.110 public static let brief: TimeInterval = 15 * 60111 public static let health: TimeInterval = 60 * 60112 public static let graph: TimeInterval = 30 * 60113 public static let insights: TimeInterval = 60 * 60114 public static let events: TimeInterval = 5 * 60115 public static let zoom: TimeInterval = 24 * 60 * 60116 public static let query: TimeInterval = 5 * 60117 public static let models: TimeInterval = 24 * 60 * 60118 public static let timeMachine: TimeInterval = 7 * 24 * 60 * 60119120 public static func isStale(fetchedAt: Date, maxAge: TimeInterval, now: Date = Date()) -> Bool { now.timeIntervalSince(fetchedAt) > maxAge }121}122123/// Where a read model comes from.124public enum CachePolicy: Sendable, Equatable {125 /// Ask the server; when it cannot be reached, the cached copy (throws `.notCached` when there is none). Default.126 case networkFirst127 /// The cached copy when it is younger than `maxAge`; otherwise like `.networkFirst`.128 case cacheFirst(maxAge: TimeInterval)129 /// Never touches the network (`.notCached` when nothing was fetched yet).130 case cacheOnly131 /// Never reads the cache (the answer is still stored); `.offline` when unreachable.132 case networkOnly133}134135/// Store + API + engine, shared by the repositories.136public struct RepositoryContext: Sendable {137 public let store: NotesStore138 public let api: NotesAPI139 /// Asked to run a cycle after a local edit; nil in read-only tools and in some tests.140 public let engine: SyncEngine?141 /// False = a local edit does not ask the engine for a cycle (`scheduleSync` does nothing). For tests that drive142 /// every cycle themselves: a cycle scheduled 400 ms after an edit otherwise runs at an unpredictable moment.143 public var schedulesSyncAfterEdits = true144145 public init(store: NotesStore, api: NotesAPI, engine: SyncEngine? = nil) {146 self.store = store147 self.api = api148 self.engine = engine149 }150151 /// What the server supports: the engine's last answer, else the copy cached by an earlier session, else nil152 /// (never asked — treat as unknown, not as 2.x).153 public func knownFeatures() async -> ServerMeta? {154 if let meta = await engine?.serverFeatures() { return meta }155 guard let cached = try? await store.cached(CacheKey.meta) else { return nil }156 return try? JSONDecoder().decode(ServerMeta.self, from: cached.json)157 }158159 /// Asks `/api/meta` now (and caches it). `.offline` when unreachable.160 public func refreshFeatures() async throws -> ServerMeta {161 do {162 let meta = try await api.meta()163 if let data = try? JSONEncoder().encode(meta) { try? await store.setCached(CacheKey.meta, json: data) }164 return meta165 } catch { throw RepositoryError.from(error) }166 }167168 /// Throws `.unsupported` when the server is KNOWN not to have the feature. Unknown (never asked) passes: the169 /// route itself will answer.170 public func require(_ feature: String) async throws {171 if let meta = await knownFeatures(), !meta.has(feature) { throw RepositoryError.unsupported(feature: feature) }172 }173174 /// Runs a server call, mapping its failure to `RepositoryError` (`.offline` when unreachable).175 public func online<T: Sendable>(_ work: @Sendable () async throws -> T) async throws -> T {176 do { return try await work() } catch { throw RepositoryError.from(error) }177 }178179 /// Requests a sync cycle soon (after a local, offline-capable edit).180 public func scheduleSync() async {181 guard schedulesSyncAfterEdits else { return }182 await engine?.schedule(after: .milliseconds(400))183 }184185 /// A read model: fetched, stored in the key-value cache with its fetch date, served from it when the server cannot186 /// be reached or when the policy says so.187 public func read<T: Codable & Sendable>(_ key: String, policy: CachePolicy = .networkFirst, fetch: @Sendable () async throws -> T) async throws -> Cached<T> {188 func fromCache() async throws -> Cached<T>? {189 guard let cached = try await store.cached(key) else { return nil }190 guard let value = try? APIJSON.decoder().decode(T.self, from: cached.json) else { return nil }191 return Cached(value: value, fetchedAt: cached.fetchedAt, source: .cache)192 }193 switch policy {194 case .cacheOnly:195 guard let cached = try await fromCache() else { throw RepositoryError.notCached }196 return cached197 case .cacheFirst(let maxAge):198 if let cached = try await fromCache(), !cached.isStale(maxAge: maxAge) { return cached }199 case .networkFirst, .networkOnly:200 break201 }202 do {203 let value = try await fetch()204 let now = Date()205 if let data = try? APIJSON.encoder().encode(value) { try? await store.setCached(key, json: data, fetchedAt: now) }206 return Cached(value: value, fetchedAt: now, source: .network)207 } catch {208 let mapped = RepositoryError.from(error)209 guard mapped == .offline, policy != .networkOnly else { throw mapped }210 guard let cached = try await fromCache() else { throw RepositoryError.notCached }211 return cached212 }213 }214215 /// Decodes the cached entity rows of a kind (rows this build cannot read are skipped, never fatal).216 func decodeEntities<T: Decodable>(_ type: T.Type, _ records: [EntityRecord]) -> [T] {217 let decoder = APIJSON.decoder()218 return records.compactMap { try? decoder.decode(T.self, from: $0.json) }219 }220221 /// Stores the server's answer for an entity written online (the feed will bring the same row; the revision222 /// makes that a no-op).223 func cacheEntity<T: Encodable>(kind: EntityKind, id: String, row: T, rev: Int64?, index: EntityIndex? = nil) async {224 guard let json = try? APIJSON.encoder().encode(row) else { return }225 _ = try? await store.applyRemoteEntities([RemoteEntity(kind: kind, id: id, rev: rev ?? 0, json: json, index: index)])226 }227228 /// Removes an entity deleted online from the local cache.229 func uncacheEntity(kind: EntityKind, id: String) async {230 _ = try? await store.applyRemoteEntities([], tombstones: [EntityTombstone(kind: kind, id: id)])231 }232}233