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