Repository Public
1import Foundation23/// A value together with the instant the client received it from the server.4public struct Snapshot<Value: Sendable>: Sendable {5 public var value: Value6 public var receivedAt: Date7 /// True when the value was restored from the on-disk cache and not confirmed by the server since.8 public var fromCache: Bool9 public init(value: Value, receivedAt: Date, fromCache: Bool = false) {10 self.value = value; self.receivedAt = receivedAt; self.fromCache = fromCache11 }12}13extension Snapshot: Equatable where Value: Equatable {}1415/// On-disk cache of the last successfully loaded read models, shown read-only when the server is unreachable.16///17/// Storage choice: one small versioned JSON file per read model under Application Support, written atomically.18/// The read models are snapshots that are always replaced as a whole and never queried across, so a relational19/// store would add a dependency and a migration surface without any benefit; a schema change is handled by bumping20/// `schemaVersion`, which simply ignores older files. Files use `completeUntilFirstUserAuthentication` protection21/// where the platform supports it (iOS; no-op on macOS) and are excluded from backups.22public actor OfflineCache {23 public static let schemaVersion = 12425 private struct Envelope<V: Codable>: Codable {26 var schema: Int27 var key: String28 var receivedAt: Date29 var value: V30 }3132 public let directory: URL33 private let encoder: JSONEncoder34 private let decoder: JSONDecoder3536 public init(directory: URL) {37 self.directory = directory.appendingPathComponent("v\(Self.schemaVersion)", isDirectory: true)38 let e = JSONEncoder(); e.dateEncodingStrategy = .millisecondsSince197039 let d = JSONDecoder(); d.dateDecodingStrategy = .millisecondsSince197040 encoder = e; decoder = d41 }4243 /// Default location: `Application Support/<bundle id>/OfflineCache/<namespace>`.44 public static func defaultDirectory(namespace: String, bundle: Bundle = .main) -> URL {45 let root = (try? FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true))46 ?? FileManager.default.temporaryDirectory47 let safe = namespace.map { $0.isLetter || $0.isNumber || $0 == "." || $0 == "-" ? $0 : "_" }48 return root.appendingPathComponent(bundle.bundleIdentifier ?? "ai.spboucher.clustr", isDirectory: true)49 .appendingPathComponent("OfflineCache", isDirectory: true)50 .appendingPathComponent(String(safe), isDirectory: true)51 }5253 private func url(_ key: String) -> URL {54 let safe = key.map { $0.isLetter || $0.isNumber || $0 == "." || $0 == "-" ? $0 : "_" }55 return directory.appendingPathComponent(String(safe) + ".json")56 }5758 public func store<V: Codable & Sendable>(_ value: V, key: String, receivedAt: Date) {59 do {60 try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)61 let data = try encoder.encode(Envelope(schema: Self.schemaVersion, key: key, receivedAt: receivedAt, value: value))62 var target = url(key)63 var options: Data.WritingOptions = [.atomic]64 #if os(iOS)65 options.insert(.completeFileProtectionUntilFirstUserAuthentication)66 #endif67 try data.write(to: target, options: options)68 var rv = URLResourceValues(); rv.isExcludedFromBackup = true69 try? target.setResourceValues(rv)70 } catch {71 // A cache write failure must never break the live path; the value is simply not available offline.72 }73 }7475 public func load<V: Codable & Sendable>(_ type: V.Type, key: String) -> Snapshot<V>? {76 guard let data = try? Data(contentsOf: url(key)),77 let env = try? decoder.decode(Envelope<V>.self, from: data),78 env.schema == Self.schemaVersion, env.key == key else { return nil }79 return Snapshot(value: env.value, receivedAt: env.receivedAt, fromCache: true)80 }8182 public func remove(key: String) {83 try? FileManager.default.removeItem(at: url(key))84 }8586 /// Sign-out / revocation: nothing of the previous account stays on disk.87 public func removeAll() {88 try? FileManager.default.removeItem(at: directory)89 }9091 public func keys() -> [String] {92 ((try? FileManager.default.contentsOfDirectory(atPath: directory.path)) ?? [])93 .filter { $0.hasSuffix(".json") }.map { String($0.dropLast(5)) }.sorted()94 }95}96