Sources/OrgDocument/FileStorage.swift

133 lines · 6532 bytes

  1import CryptoKit
  2import Foundation
  3import OrgCore
  4
  5/// Reads and replaces files under `NSFileCoordinator`, so iCloud and other coordinating
  6/// writers see a consistent file.
  7public struct CoordinatedFileSystem: FileSystem {
  8    /// Write in place when the folder refuses the temporary file, as the sandbox does for a
  9    /// file it granted alone. Not atomic, so only where it is the one way to save.
 10    public let writesInPlaceWhenDenied: Bool
 11
 12    public init(writesInPlaceWhenDenied: Bool = Sandbox.isActive) {
 13        self.writesInPlaceWhenDenied = writesInPlaceWhenDenied
 14    }
 15
 16    public func read(_ url: URL) throws -> [UInt8]? {
 17        try coordinate(reading: url) { url in
 18            FileManager.default.fileExists(atPath: url.path) ? [UInt8](try Data(contentsOf: url)) : nil
 19        }
 20    }
 21
 22    public func replace(_ url: URL, with bytes: [UInt8]) throws -> [UInt8]? {
 23        try coordinate(writing: url) { url in
 24            let manager = FileManager.default
 25            let folder = url.deletingLastPathComponent()
 26            let temporary = folder.appendingPathComponent(".\(url.lastPathComponent).orgstar-\(UUID().uuidString)")
 27            do {
 28                try Data(bytes).write(to: temporary)
 29            } catch where writesInPlaceWhenDenied && Self.isPermissionDenied(error) {
 30                let previous = manager.fileExists(atPath: url.path) ? [UInt8](try Data(contentsOf: url)) : nil
 31                try Data(bytes).write(to: url)
 32                return previous
 33            }
 34            guard manager.fileExists(atPath: url.path) else {
 35                try manager.moveItem(at: temporary, to: url)
 36                return nil
 37            }
 38            // The backup is the file as it was at the moment of replacement, including any
 39            // write that landed after our last check.
 40            let backupName = ".\(url.lastPathComponent).orgstar-backup-\(UUID().uuidString)"
 41            _ = try manager.replaceItemAt(url, withItemAt: temporary, backupItemName: backupName, options: .withoutDeletingBackupItem)
 42            let backup = folder.appendingPathComponent(backupName)
 43            defer { try? manager.removeItem(at: backup) }
 44            return [UInt8](try Data(contentsOf: backup))
 45        }
 46    }
 47
 48    /// Whether `error` is the file system refusing access.
 49    static func isPermissionDenied(_ error: Error) -> Bool {
 50        let error = error as NSError
 51        if error.domain == NSCocoaErrorDomain, error.code == CocoaError.fileWriteNoPermission.rawValue { return true }
 52        if error.domain == NSPOSIXErrorDomain, [Int(EACCES), Int(EPERM)].contains(error.code) { return true }
 53        return (error.userInfo[NSUnderlyingErrorKey] as? Error).map(isPermissionDenied) ?? false
 54    }
 55
 56    private func coordinate<T>(reading url: URL, _ body: (URL) throws -> T) throws -> T {
 57        var coordinationError: NSError?
 58        var result: Result<T, Error>?
 59        NSFileCoordinator(filePresenter: nil).coordinate(readingItemAt: url, options: [], error: &coordinationError) { url in
 60            result = Result { try body(url) }
 61        }
 62        if let coordinationError { throw coordinationError }
 63        return try result!.get()
 64    }
 65
 66    private func coordinate<T>(writing url: URL, _ body: (URL) throws -> T) throws -> T {
 67        var coordinationError: NSError?
 68        var result: Result<T, Error>?
 69        NSFileCoordinator(filePresenter: nil).coordinate(writingItemAt: url, options: .forReplacing, error: &coordinationError) { url in
 70            result = Result { try body(url) }
 71        }
 72        if let coordinationError { throw coordinationError }
 73        return try result!.get()
 74    }
 75}
 76
 77/// Keeps the last `limit` displaced versions per file in `directory/<hash of path>/`, and
 78/// apart from them up to `snapshotLimit` snapshots, the version before a save at most once
 79/// every `snapshotInterval`.
 80public struct FileRecoveryStore: RecoveryStore {
 81    public let directory: URL
 82    public let limit: Int
 83    public static let snapshotLimit = 10
 84    public static let snapshotInterval: TimeInterval = 3600
 85    static let snapshotLabel = "snapshot"
 86    /// The clock, for tests.
 87    public var now: @Sendable () -> Date = { Date() }
 88
 89    public init(directory: URL, limit: Int = 20) {
 90        self.directory = directory
 91        self.limit = limit
 92    }
 93
 94    /// Whether the version file named `name` is a snapshot: after the 20-digit time and `-`.
 95    static func isSnapshot(_ name: String) -> Bool {
 96        name.dropFirst(21).hasPrefix(snapshotLabel + "-")
 97    }
 98
 99    public func keepSnapshot(_ bytes: [UInt8], for url: URL) throws {
100        let last = try versions(for: url).map(\.lastPathComponent).last(where: Self.isSnapshot)
101        if let last, let nanoseconds = UInt64(last.prefix(20)),
102           now().timeIntervalSince1970 - Double(nanoseconds) / 1_000_000_000 < Self.snapshotInterval { return }
103        try keep(bytes, for: url, label: Self.snapshotLabel)
104    }
105
106    public func folder(for url: URL) -> URL {
107        let digest = SHA256.hash(data: Data(url.standardizedFileURL.path.utf8))
108        let name = digest.prefix(8).map { String(format: "%02x", $0) }.joined()
109        return directory.appendingPathComponent(name, isDirectory: true)
110    }
111
112    public func keep(_ bytes: [UInt8], for url: URL, label: String) throws {
113        let folder = folder(for: url)
114        let manager = FileManager.default
115        try manager.createDirectory(at: folder, withIntermediateDirectories: true)
116        // Zero-padded wall-clock nanoseconds sort by time; the UUID keeps same-instant names apart.
117        let stamp = String(format: "%020llu", UInt64(now().timeIntervalSince1970 * 1_000_000_000))
118        let name = "\(stamp)-\(label)-\(UUID().uuidString.prefix(8))-\(url.lastPathComponent)"
119        try Data(bytes).write(to: folder.appendingPathComponent(name))
120        let kept = try manager.contentsOfDirectory(atPath: folder.path).sorted()
121        let snapshots = kept.filter(Self.isSnapshot)
122        for old in kept.filter({ !Self.isSnapshot($0) }).dropLast(limit) + snapshots.dropLast(Self.snapshotLimit) {
123            try manager.removeItem(at: folder.appendingPathComponent(old))
124        }
125    }
126
127    /// Kept versions, oldest first.
128    public func versions(for url: URL) throws -> [URL] {
129        let folder = folder(for: url)
130        guard FileManager.default.fileExists(atPath: folder.path) else { return [] }
131        return try FileManager.default.contentsOfDirectory(atPath: folder.path).sorted().map { folder.appendingPathComponent($0) }
132    }
133}