Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP GlassKit7// File : Apps/GlassStudio/Kit/Stores/AtomicFileStore.swift8// Module : GlassStudio9// Repository : https://git.spboucher.ai/sp-glasskit10// Project Website : https://glass.spboucher.ai11// Created : 2026-12-0212// Last Modified : 2026-12-0213//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 : MIT33//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 Foundation4243/// Reads and writes one Codable document on disk, atomically and with a way back.44///45/// Each save writes the new content to a temporary file and renames it over the document, after copying the46/// previous version to `<name>.bak`. A document that cannot be decoded is never deleted: it is moved to47/// `<name>.corrupted-<timestamp>`, the backup is tried, and only then does the caller get the default value.48public struct AtomicFileStore<Document: Codable & Sendable>: Sendable {49 public enum LoadOutcome: Equatable, Sendable {50 case loaded51 case missing52 /// The document was unreadable; the previous backup was restored.53 case recoveredFromBackup(quarantined: String)54 /// The document and its backup were unreadable; the default value is used.55 case resetToDefault(quarantined: String)56 }5758 public let url: URL59 public let maximumBytes: Int6061 public init(url: URL, maximumBytes: Int = 4 * 1024 * 1024) {62 self.url = url63 self.maximumBytes = maximumBytes64 }6566 private var backupURL: URL { url.appendingPathExtension("bak") }6768 public func load(default defaultValue: Document, migrate: (Data) throws -> Document = { try JSONDecoder().decode(Document.self, from: $0) }) -> (document: Document, outcome: LoadOutcome) {69 let fileManager = FileManager.default70 guard fileManager.fileExists(atPath: url.path) else { return (defaultValue, .missing) }71 if let document = read(url, migrate: migrate) { return (document, .loaded) }7273 let stamp = Int(Date().timeIntervalSince1970)74 let quarantine = url.deletingLastPathComponent().appendingPathComponent("\(url.lastPathComponent).corrupted-\(stamp)")75 try? fileManager.removeItem(at: quarantine)76 try? fileManager.moveItem(at: url, to: quarantine)77 if let document = read(backupURL, migrate: migrate) {78 try? save(document, keepBackup: false)79 return (document, .recoveredFromBackup(quarantined: quarantine.lastPathComponent))80 }81 return (defaultValue, .resetToDefault(quarantined: quarantine.lastPathComponent))82 }8384 public func save(_ document: Document, keepBackup: Bool = true) throws {85 let fileManager = FileManager.default86 try fileManager.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)87 let encoder = JSONEncoder()88 encoder.outputFormatting = [.prettyPrinted, .sortedKeys]89 let data = try encoder.encode(document)90 if keepBackup, fileManager.fileExists(atPath: url.path) {91 try? fileManager.removeItem(at: backupURL)92 try? fileManager.copyItem(at: url, to: backupURL)93 }94 try data.write(to: url, options: .atomic)95 }9697 private func read(_ url: URL, migrate: (Data) throws -> Document) -> Document? {98 guard let size = try? FileManager.default.attributesOfItem(atPath: url.path)[.size] as? Int, size <= maximumBytes,99 let data = try? Data(contentsOf: url) else { return nil }100 return try? migrate(data)101 }102}103104public enum StudioPaths {105 /// The Studio's data directory. Tests and UI tests pass their own directory.106 public static func dataDirectory(override: URL? = nil) -> URL {107 if let override { return override }108 let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first ?? FileManager.default.temporaryDirectory109 return base.appendingPathComponent("GlassStudio", isDirectory: true)110 }111}112