Sources/OrgDocument/Saving.swift

99 lines · 4443 bytes

 1import Foundation
 2import OrgCore
 3
 4public protocol FileSystem: Sendable {
 5    /// The file's bytes, or nil if it doesn't exist.
 6    func read(_ url: URL) throws -> [UInt8]?
 7    /// Replaces the file through a temporary file in the same folder. Returns the bytes that
 8    /// were replaced, read from the replaced file itself, or nil if there was none.
 9    func replace(_ url: URL, with bytes: [UInt8]) throws -> [UInt8]?
10}
11
12public protocol RecoveryStore: Sendable {
13    func keep(_ bytes: [UInt8], for url: URL, label: String) throws
14    /// Offered the version a save is about to replace, to keep now and then as a snapshot.
15    func keepSnapshot(_ bytes: [UInt8], for url: URL) throws
16}
17
18extension RecoveryStore {
19    public func keepSnapshot(_ bytes: [UInt8], for url: URL) throws {}
20}
21
22public enum SaveOutcome: Sendable, Equatable {
23    case saved
24    /// The file had changed since it was read; the change merged cleanly into the buffer and
25    /// the merge was written.
26    case mergedAndSaved([TextEdit])
27    /// The file had changed and the change conflicts. Nothing was written; the buffer is
28    /// unchanged.
29    case conflict([MergeConflict])
30    /// Another writer replaced the file between our last check and our write. Ours is on disk;
31    /// theirs is in recovery and was merged into the buffer where possible.
32    case overwroteExternalChange(DocumentState.ExternalChange)
33    /// Another writer changed the file right after our write. Theirs is on disk; ours is in
34    /// recovery.
35    case changedAfterWrite(DocumentState.ExternalChange)
36}
37
38public enum SaveError: Error, Equatable {
39    case fileKeepsChanging
40}
41
42/// The save sequence from the design: read, merge if the file moved, check again, replace,
43/// read back. Emacs and Syncthing don't coordinate, so the sequence can't lock them out; it
44/// narrows the window and makes sure every version it displaces lands in recovery.
45public struct Saver: Sendable {
46    public let fileSystem: FileSystem
47    public let recovery: RecoveryStore
48    public var maxAttempts = 3
49
50    public init(fileSystem: FileSystem, recovery: RecoveryStore) {
51        self.fileSystem = fileSystem
52        self.recovery = recovery
53    }
54
55    public func save(_ state: inout DocumentState, to url: URL) throws -> SaveOutcome {
56        guard state.isEditable else { throw DocumentState.EditError.readOnly }
57        for _ in 0..<maxAttempts {
58            let disk = try fileSystem.read(url)
59            var merged: [TextEdit]?
60            if let disk, disk != state.mergeBase {
61                try recovery.keep(disk, for: url, label: "external")
62                try recovery.keep(state.encodedText(), for: url, label: "local")
63                switch state.diskChanged(to: disk) {
64                case .conflict(let conflicts): return .conflict(conflicts)
65                case .merged(let edits), .reloaded(let edits): merged = edits
66                case .unchanged: break
67                }
68            }
69            let bytes = try state.encodedText()
70            guard try fileSystem.read(url) == disk else { continue }
71            // A snapshot is a convenience: one that can't be kept doesn't stop the save.
72            if let disk, disk != bytes { try? recovery.keepSnapshot(disk, for: url) }
73
74            let replaced = try fileSystem.replace(url, with: bytes)
75            state.didWrite(bytes)
76            if replaced != disk, let replaced {
77                try recovery.keep(replaced, for: url, label: "external")
78                return .overwroteExternalChange(state.mergeOverwritten(replaced, base: disk ?? []))
79            }
80
81            if let after = try fileSystem.read(url), after != bytes {
82                try recovery.keep(bytes, for: url, label: "local")
83                return .changedAfterWrite(state.diskChanged(to: after))
84            }
85            return merged.map { .mergedAndSaved($0) } ?? .saved
86        }
87        throw SaveError.fileKeepsChanging
88    }
89
90    /// Writes the buffer over whatever is on disk, for keeping our version over a conflicting
91    /// one. The replaced version goes to recovery unless it is the merge base.
92    public func overwrite(_ state: inout DocumentState, to url: URL) throws {
93        let bytes = try state.encodedText()
94        if let replaced = try fileSystem.replace(url, with: bytes), replaced != state.mergeBase {
95            try recovery.keep(replaced, for: url, label: "external")
96        }
97        state.didWrite(bytes)
98    }
99}