Open History to see the last commit
1import Foundation
2
3/// Versioned append-only records. Streaming changes store deltas, not repeated
4/// copies of the whole response. The directory is reserved for future assets.
5struct JournalRecord: Codable, Sendable {
6 enum Event: String, Codable, Sendable { case created, entry, textAppended, textReplaced, detailsAppended, state, titleChanged, redacted }
7 struct Header: Codable, Sendable { let id: UUID; let date: Date; var title: String }
8 var version = 1
9 var id = UUID()
10 var date = Date()
11 let event: Event
12 var expedition: Header?
13 var entry: ExpeditionJournal.Entry?
14 var entryID: UUID?
15 var text: String?
16 var status: String?
17 var isRunning: Bool?
18 var isFinished: Bool?
19}
20
21/// All mutable writer state is confined to queue. No credentials or provider
22/// transcripts are written here; the journal contains its visible entries/details.
23final class ExpeditionJournalStore: @unchecked Sendable {
24 struct Loaded: Sendable {
25 var header: JournalRecord.Header
26 var entries: [ExpeditionJournal.Entry] = []
27 var status = "Ready for your next direction"
28 var wasRunning = false
29 var isFinished = false
30 }
31 struct Restored { var expeditions: [Loaded] = []; var warning: String? }
32 let directory: URL
33 private let queue = DispatchQueue(label: "com.jerry.journal-storage", qos: .utility)
34 private let report: @Sendable (String?) -> Void
35 private var pending: [UUID: [JournalRecord]] = [:]
36 private var scheduled: DispatchWorkItem?
37 private let encoder: JSONEncoder = {
38 let encoder = JSONEncoder(); encoder.dateEncodingStrategy = .millisecondsSince1970
39 encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]; return encoder
40 }()
41 init(directory: URL, report: @escaping @Sendable (String?) -> Void) { self.directory = directory; self.report = report }
42 func append(_ record: JournalRecord, to expedition: UUID) {
43 queue.async { [self] in
44 pending[expedition, default: []].append(record)
45 guard scheduled == nil else { return }
46 let work = DispatchWorkItem { [weak self] in self?.writePending() }
47 scheduled = work; queue.asyncAfter(deadline: .now() + 0.2, execute: work)
48 }
49 }
50 func savePhoto(_ data: Data, to expedition: UUID) async throws -> String {
51 try await withCheckedThrowingContinuation { continuation in
52 queue.async { [self] in
53 do {
54 let folder = directory.appendingPathComponent(expedition.uuidString, isDirectory: true)
55 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
56 guard try folder.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink != true else { throw CocoaError(.fileWriteNoPermission) }
57 let filename = UUID().uuidString + ".jpg"
58 let url = folder.appendingPathComponent(filename)
59 try data.write(to: url, options: .atomic)
60 try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: url.path)
61 continuation.resume(returning: filename)
62 } catch { continuation.resume(throwing: error) }
63 }
64 }
65 }
66 func retry() { queue.async { [self] in writePending() } }
67 /// Take the sync snapshot on the writer queue, after fsync. A failed local
68 /// write must never be published remotely as a successfully saved note.
69 func committedData(for expedition: UUID) async throws -> Data? {
70 try await withCheckedThrowingContinuation { continuation in
71 queue.async { [self] in
72 writePending()
73 guard pending[expedition] == nil else { continuation.resume(returning: nil); return }
74 let url = directory.appendingPathComponent(expedition.uuidString).appendingPathComponent("journal.jsonl")
75 do { continuation.resume(returning: try Data(contentsOf: url)) }
76 catch { continuation.resume(throwing: error) }
77 }
78 }
79 }
80 /// Used at task boundaries and shutdown; drains preceding queued records too.
81 func flush() { queue.sync { writePending() } }
82 private func writePending() {
83 scheduled?.cancel(); scheduled = nil
84 guard !pending.isEmpty else { return }
85 var failed = false
86 for (id, records) in pending {
87 do {
88 let folder = directory.appendingPathComponent(id.uuidString, isDirectory: true)
89 try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
90 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
91 let folderValues = try folder.resourceValues(forKeys: [.isSymbolicLinkKey])
92 guard folderValues.isSymbolicLink != true else { throw CocoaError(.fileWriteNoPermission) }
93 let url = folder.appendingPathComponent("journal.jsonl")
94 if !FileManager.default.fileExists(atPath: url.path) {
95 guard FileManager.default.createFile(atPath: url.path, contents: nil, attributes: [.posixPermissions: 0o600]) else { throw CocoaError(.fileWriteUnknown) }
96 }
97 let fileValues = try url.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey])
98 guard fileValues.isRegularFile == true, fileValues.isSymbolicLink != true else { throw CocoaError(.fileWriteNoPermission) }
99 let handle = try FileHandle(forUpdating: url); defer { try? handle.close() }
100 let end = try handle.seekToEnd()
101 var data = Data()
102 if end > 0 {
103 try handle.seek(toOffset: end - 1)
104 if try handle.read(upToCount: 1)?.first != 10 { data.append(10) }
105 try handle.seekToEnd()
106 }
107 for record in records { data.append(try encoder.encode(record)); data.append(10) }
108 try handle.write(contentsOf: data); try handle.synchronize()
109 pending[id] = nil
110 } catch {
111 failed = true
112 // Keep unsaved records for Retry or the next update. Event IDs
113 // make a retry safe even after a partially completed append.
114 report("The journal couldn’t be saved. \(error.localizedDescription)")
115 }
116 }
117 if !failed { report(nil) }
118 }
119 func restore() -> Restored {
120 queue.sync {
121 var result = Restored()
122 guard FileManager.default.fileExists(atPath: directory.path) else { return result }
123 do {
124 let children = try FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: [.isDirectoryKey, .isSymbolicLinkKey], options: [.skipsHiddenFiles])
125 for folder in children {
126 guard let id = UUID(uuidString: folder.lastPathComponent) else { continue }
127 let values = try folder.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey])
128 guard values.isDirectory == true, values.isSymbolicLink != true else { continue }
129 do {
130 if let loaded = try load(folder: folder, id: id, warning: &result.warning) { result.expeditions.append(loaded) }
131 } catch { result.warning = "Some saved expeditions couldn’t be read. Their files have been kept." }
132 }
133 result.expeditions.sort { $0.header.date == $1.header.date ? $0.header.id.uuidString < $1.header.id.uuidString : $0.header.date < $1.header.date }
134 } catch { result.warning = "Saved expeditions couldn’t be opened. \(error.localizedDescription)" }
135 return result
136 }
137 }
138 private func load(folder: URL, id: UUID, warning: inout String?) throws -> Loaded? {
139 let url = folder.appendingPathComponent("journal.jsonl")
140 guard FileManager.default.fileExists(atPath: url.path) else { return nil }
141 let values = try url.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey])
142 guard values.isRegularFile == true, values.isSymbolicLink != true else { return nil }
143 let data = try Data(contentsOf: url)
144 let decoder = JSONDecoder(); decoder.dateDecodingStrategy = .millisecondsSince1970
145 var loaded: Loaded?, seen = Set<UUID>()
146 for line in data.split(separator: 10) where !line.isEmpty {
147 let record: JournalRecord
148 do {
149 struct Version: Decodable { let version: Int }
150 guard try decoder.decode(Version.self, from: Data(line)).version == 1 else {
151 warning = "An expedition uses a newer journal format and was left untouched."; return nil
152 }
153 record = try decoder.decode(JournalRecord.self, from: Data(line))
154 }
155 catch { warning = "Some incomplete journal records were skipped. The original files have been kept."; continue }
156 guard record.version == 1 else { warning = "An expedition uses a newer journal format and was left untouched."; return nil }
157 guard seen.insert(record.id).inserted else { continue }
158 if record.event == .created {
159 guard let header = record.expedition, header.id == id else { throw CocoaError(.fileReadCorruptFile) }
160 guard loaded == nil else { continue }
161 loaded = Loaded(header: header); continue
162 }
163 guard var expedition = loaded else { continue }
164 switch record.event {
165 case .created, .redacted: break
166 case .titleChanged:
167 if let title = record.text, !title.isEmpty { expedition.header.title = title }
168 case .entry:
169 if let entry = record.entry, !expedition.entries.contains(where: { $0.id == entry.id }) { expedition.entries.append(entry) }
170 case .textAppended, .textReplaced, .detailsAppended:
171 if let id = record.entryID, let text = record.text, let index = expedition.entries.firstIndex(where: { $0.id == id }) {
172 switch record.event {
173 case .textAppended: expedition.entries[index].text += text
174 case .textReplaced: expedition.entries[index].text = text
175 default: expedition.entries[index].details += text
176 }
177 }
178 case .state:
179 if let status = record.status { expedition.status = status }
180 if let running = record.isRunning { expedition.wasRunning = running }
181 if let finished = record.isFinished { expedition.isFinished = finished }
182 }
183 loaded = expedition
184 }
185 if loaded == nil && !data.isEmpty { warning = "An incomplete expedition could not be restored. Its file has been kept." }
186 return loaded
187 }
188}