Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/VQuantKit/Sync/VQSyncStorage.swift3// Description: Where the sync engine keeps its replica: a tiny named-blob store with atomic writes, a file4// implementation with an optional encryption hook, and an in-memory one.5import Foundation67/// Named blobs. Names are relative paths made of `[A-Za-z0-9_.-]` segments (`meta.json`, `objects/note/<id>.json`).8/// `write` must be atomic: after a crash a name holds either the old or the new bytes, never a mix.9public protocol VQSyncStorage: Sendable {10 func read(_ name: String) throws -> Data?11 func write(_ name: String, _ data: Data) throws12 func remove(_ name: String) throws13 /// Every name that starts with `prefix`.14 func list(prefix: String) throws -> [String]15}1617/// Encryption hook: the apps already encrypt their caches (a key in the Keychain); they pass the same sealing here.18public protocol VQSyncCipher: Sendable {19 func seal(_ plaintext: Data) throws -> Data20 func open(_ sealed: Data) throws -> Data21}2223/// Files under a directory the app provides (Application Support, or the app group container to share with widgets).24public final class VQFileSyncStorage: VQSyncStorage {25 public let directory: URL26 private let cipher: (any VQSyncCipher)?2728 public init(directory: URL, cipher: (any VQSyncCipher)? = nil) throws {29 self.directory = directory; self.cipher = cipher30 try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)31 }3233 private func url(_ name: String) throws -> URL {34 let parts = name.split(separator: "/", omittingEmptySubsequences: false)35 let ok = !parts.isEmpty && parts.allSatisfy { p in36 !p.isEmpty && p != "." && p != ".." && p.utf8.allSatisfy { ($0 >= 48 && $0 <= 57) || ($0 >= 65 && $0 <= 90) || ($0 >= 97 && $0 <= 122) || $0 == 95 || $0 == 45 || $0 == 46 }37 }38 guard ok else { throw CocoaError(.fileWriteInvalidFileName) }39 return parts.reduce(directory) { $0.appendingPathComponent(String($1)) }40 }4142 public func read(_ name: String) throws -> Data? {43 let u = try url(name)44 guard FileManager.default.fileExists(atPath: u.path) else { return nil }45 let raw = try Data(contentsOf: u)46 return try cipher.map { try $0.open(raw) } ?? raw47 }4849 public func write(_ name: String, _ data: Data) throws {50 let u = try url(name)51 try FileManager.default.createDirectory(at: u.deletingLastPathComponent(), withIntermediateDirectories: true)52 let bytes = try cipher.map { try $0.seal(data) } ?? data53 try bytes.write(to: u, options: [.atomic]) // temporary file + rename54 }5556 public func remove(_ name: String) throws {57 let u = try url(name)58 if FileManager.default.fileExists(atPath: u.path) { try FileManager.default.removeItem(at: u) }59 }6061 public func list(prefix: String) throws -> [String] {62 let root = directory.standardizedFileURL.path63 guard let e = FileManager.default.enumerator(at: directory, includingPropertiesForKeys: [.isRegularFileKey]) else { return [] }64 var out: [String] = []65 for case let u as URL in e {66 guard (try? u.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) == true else { continue }67 let p = u.standardizedFileURL.path68 guard p.hasPrefix(root) else { continue }69 let name = String(p.dropFirst(root.count).drop(while: { $0 == "/" }))70 if name.hasPrefix(prefix) { out.append(name) }71 }72 return out.sorted()73 }7475 /// Removes the whole replica (sign-out).76 public func erase() throws {77 for name in try list(prefix: "") { try remove(name) }78 }79}8081/// In memory (previews, tests, a signed-out session).82public final class VQMemorySyncStorage: VQSyncStorage, @unchecked Sendable {83 private let lock = NSLock()84 private var blobs: [String: Data] = [:]85 public init() {}86 public func read(_ name: String) throws -> Data? { lock.withLock { blobs[name] } }87 public func write(_ name: String, _ data: Data) throws { lock.withLock { blobs[name] = data } }88 public func remove(_ name: String) throws { lock.withLock { blobs[name] = nil } }89 public func list(prefix: String) throws -> [String] { lock.withLock { blobs.keys.filter { $0.hasPrefix(prefix) }.sorted() } }90}91