Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraStorage/FileStore.swift8// Module : Qyvora Storage9// Repository : https://git.spboucher.ai/qyvora10// Project Website : Not specified11// Created : 2026-12-0412// Last Modified : 2026-12-0413//14// Author : Simon-Pierre Boucher15// Position : Professor of Finance16// Institution : Université du Québec en Outaouais (UQO)17// Organization : SP Boucher18// Website : https://spboucher.ai19// Git : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development : dev@spboucher.ai23// Support : support@spboucher.ai24// Security/Admin : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Foundation42import QyvoraMath4344/// Errors of the storage layer. None of them carries file contents or secret data.45public enum StorageError: Error, Equatable, Sendable {46 /// The file or Keychain item does not exist.47 case notFound48 /// The file name is empty or contains a path separator.49 case invalidName50 /// A file-system operation failed (`operation` is a fixed label, `code` the Cocoa or POSIX error code).51 case io(operation: String, code: Int)52 /// The Keychain refused the operation (`OSStatus`).53 case keychain(status: Int32)54 /// The user cancelled or failed the biometric / passcode check protecting the item.55 case authenticationFailed56 /// The item exists but needs user interaction that was not allowed for this call.57 case interactionNotAllowed58 /// No Secure Enclave on this device (simulator, some Macs).59 case secureEnclaveUnavailable60 /// A stored blob does not have the expected structure or failed authentication.61 case invalidData62}6364/// Atomic file storage for the vault and the settings.65///66/// - Every write goes to a temporary file in the same directory, is flushed to disk, then renamed over the67/// destination (`rename(2)` is atomic on APFS): a crash leaves either the old or the new file, never a mix.68/// - Before the rename, the current file is copied to `<name>.previous`, so one older generation survives69/// a corrupted write.70/// - On iOS every file receives the data-protection class chosen at creation (`complete` by default).71/// - The directory and its files are excluded from iCloud and Finder/iTunes backups.72public struct FileStore: Sendable {73 public enum Protection: Sendable, Equatable {74 /// `NSFileProtectionComplete`: unreadable while the device is locked.75 case complete76 /// `NSFileProtectionCompleteUnlessOpen`: a file opened before locking stays usable.77 case completeUnlessOpen78 }7980 public let root: URL81 public let protection: Protection8283 /// Suffix of the older generation kept next to each file.84 public static let previousSuffix = ".previous"8586 /// Uses (and creates) the directory `root`.87 public init(root: URL, protection: Protection = .complete) throws(StorageError) {88 self.root = root89 self.protection = protection90 do {91 try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)92 } catch {93 throw .io(operation: "createDirectory", code: (error as NSError).code)94 }95 applyAttributes(root)96 }9798 /// `Application Support/<subdirectory>` of the current user (inside the app container on iOS).99 public static func applicationSupport(subdirectory: String = "Qyvora", protection: Protection = .complete) throws(StorageError) -> FileStore {100 let base: URL101 do {102 base = try FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)103 } catch {104 throw .io(operation: "applicationSupport", code: (error as NSError).code)105 }106 return try FileStore(root: base.appendingPathComponent(subdirectory, isDirectory: true), protection: protection)107 }108109 public func url(for name: String) throws(StorageError) -> URL {110 guard !name.isEmpty, !name.contains("/"), !name.contains("\0"), name != ".", name != ".." else { throw .invalidName }111 return root.appendingPathComponent(name, isDirectory: false)112 }113114 public func exists(_ name: String) -> Bool {115 guard let u = try? url(for: name) else { return false }116 return FileManager.default.fileExists(atPath: u.path)117 }118119 public func previousExists(_ name: String) -> Bool { exists(name + Self.previousSuffix) }120121 public func read(_ name: String) throws(StorageError) -> Bytes {122 let u = try url(for: name)123 guard FileManager.default.fileExists(atPath: u.path) else { throw .notFound }124 do {125 return Bytes(try Data(contentsOf: u))126 } catch {127 throw .io(operation: "read", code: (error as NSError).code)128 }129 }130131 /// The older generation of `name`, when one exists.132 public func readPrevious(_ name: String) throws(StorageError) -> Bytes {133 try read(name + Self.previousSuffix)134 }135136 /// Atomically replaces `name` with `data`. With `keepPrevious`, the file being replaced becomes `<name>.previous`;137 /// without it the existing `.previous` copy is left untouched.138 public func write(_ data: Bytes, to name: String, keepPrevious: Bool = true) throws(StorageError) {139 let target = try url(for: name)140 let fm = FileManager.default141 if keepPrevious, fm.fileExists(atPath: target.path) {142 let previous = try url(for: name + Self.previousSuffix)143 let staging = root.appendingPathComponent(".\(name).prev-\(UUID().uuidString)", isDirectory: false)144 do {145 try fm.copyItem(at: target, to: staging)146 } catch {147 throw .io(operation: "copyPrevious", code: (error as NSError).code)148 }149 applyAttributes(staging)150 try rename(staging, previous)151 }152 let temporary = root.appendingPathComponent(".\(name).tmp-\(UUID().uuidString)", isDirectory: false)153 do {154 try Data(data).write(to: temporary, options: writingOptions)155 let handle = try FileHandle(forWritingTo: temporary)156 try handle.synchronize()157 try handle.close()158 } catch {159 try? fm.removeItem(at: temporary)160 throw .io(operation: "writeTemporary", code: (error as NSError).code)161 }162 applyAttributes(temporary)163 try rename(temporary, target)164 // flush the directory entry (best effort)165 if let dir = try? FileHandle(forReadingFrom: root) {166 try? dir.synchronize()167 try? dir.close()168 }169 }170171 /// Removes `name` and its `.previous` copy. Missing files are not an error.172 public func remove(_ name: String) throws(StorageError) {173 for n in [name, name + Self.previousSuffix] {174 let u = try url(for: n)175 guard FileManager.default.fileExists(atPath: u.path) else { continue }176 do {177 try FileManager.default.removeItem(at: u)178 } catch {179 throw .io(operation: "remove", code: (error as NSError).code)180 }181 }182 }183184 /// Removes only the `.previous` copy of `name`.185 public func removePrevious(_ name: String) throws(StorageError) {186 let u = try url(for: name + Self.previousSuffix)187 guard FileManager.default.fileExists(atPath: u.path) else { return }188 do {189 try FileManager.default.removeItem(at: u)190 } catch {191 throw .io(operation: "removePrevious", code: (error as NSError).code)192 }193 }194195 // MARK: - Internals196197 private var writingOptions: Data.WritingOptions {198 #if os(iOS)199 return protection == .complete ? [.completeFileProtection] : [.completeFileProtectionUnlessOpen]200 #else201 return []202 #endif203 }204205 private func rename(_ from: URL, _ to: URL) throws(StorageError) {206 let status = from.withUnsafeFileSystemRepresentation { src in207 to.withUnsafeFileSystemRepresentation { dst -> Int32 in208 guard let src, let dst else { return -1 }209 return Foundation.rename(src, dst)210 }211 }212 guard status == 0 else {213 let code = Int(errno)214 try? FileManager.default.removeItem(at: from)215 throw .io(operation: "rename", code: code)216 }217 }218219 /// Data protection (iOS) and backup exclusion. Best effort: a failure here never loses data.220 private func applyAttributes(_ url: URL) {221 #if os(iOS)222 let key: FileProtectionType = protection == .complete ? .complete : .completeUnlessOpen223 try? FileManager.default.setAttributes([.protectionKey: key], ofItemAtPath: url.path)224 #endif225 var u = url226 var values = URLResourceValues()227 values.isExcludedFromBackup = true228 try? u.setResourceValues(values)229 }230}231232/// Small non-secret settings persisted as one JSON document (sorted keys) through `FileStore`.233public struct SettingsStore: Sendable {234 public let fileStore: FileStore235 public let name: String236237 public init(fileStore: FileStore, name: String = "settings.json") {238 self.fileStore = fileStore239 self.name = name240 }241242 /// The stored value, or nil when nothing was saved yet. A file that does not decode throws `invalidData`.243 public func load<T: Decodable>(_ type: T.Type) throws(StorageError) -> T? {244 guard fileStore.exists(name) else { return nil }245 let bytes = try fileStore.read(name)246 guard let value = try? JSONDecoder().decode(T.self, from: Data(bytes)) else { throw .invalidData }247 return value248 }249250 public func save<T: Encodable>(_ value: T) throws(StorageError) {251 let encoder = JSONEncoder()252 encoder.outputFormatting = [.sortedKeys, .prettyPrinted]253 guard let data = try? encoder.encode(value) else { throw .invalidData }254 try fileStore.write(Bytes(data), to: name)255 }256257 public func remove() throws(StorageError) {258 try fileStore.remove(name)259 }260}261