Open History to see the last commit
1import Foundation
2
3/// Reads complete, fsynced journal records. Networking never observes UI-only notes.
4actor JOLSyncStore {
5 struct Receipt: Codable, Sendable { let command: JOLCommand; let status: String; let result: String }
6 struct Batch: Sendable { let expeditionID: UUID; let start: Int; let records: [JournalRecord] }
7 struct Photo: Sendable { let expeditionID: UUID; let entryID: UUID; let filename: String; let data: Data }
8 struct DetailChange: Encodable, Sendable {
9 let sequence: Int
10 let id: UUID
11 let date: Date
12 let event: JournalRecord.Event
13 let entryID: UUID
14 let text: String
15 }
16 struct DetailBatch: Sendable {
17 let expeditionID: UUID
18 let through: Int
19 let changes: [DetailChange]
20 }
21 private struct State: Codable {
22 var cursors: [String: Int] = [:]
23 var detailCursors: [String: Int]?
24 var photos: Set<String> = []
25 var commands: [String: String] = [:]
26 var receipts: [String: Receipt] = [:]
27 }
28 private let journals: URL
29 private let writer: ExpeditionJournalStore?
30 private let stateURL: URL
31 private let since: Date
32 private var includeHistory: Bool
33 private let details: Bool
34 private var backfillDetails: Bool
35 private let photos: Bool
36 private var backfillPhotos: Bool
37 private var state: State
38 private var eligible: [UUID: Bool] = [:]
39 private struct Snapshot { let size: Int; let modified: Date?; let records: [JournalRecord] }
40 private var snapshots: [UUID: Snapshot] = [:]
41 init(journals: URL, directory: URL, since: Date, includeHistory: Bool, details: Bool, photos: Bool, writer: ExpeditionJournalStore? = nil, backfillDetails: Bool = false, backfillPhotos: Bool = false) throws {
42 self.journals = journals; self.since = since; self.includeHistory = includeHistory; self.details = details; self.photos = photos
43 self.writer = writer
44 self.backfillDetails = backfillDetails
45 self.backfillPhotos = backfillPhotos
46 try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
47 stateURL = directory.appendingPathComponent("sync.json")
48 if FileManager.default.fileExists(atPath: stateURL.path) { state = try JSONDecoder().decode(State.self, from: Data(contentsOf: stateURL)) }
49 else { state = State() }
50 }
51 private func save() throws {
52 try JSONEncoder().encode(state).write(to: stateURL, options: .atomic)
53 try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: stateURL.path)
54 }
55 func acknowledge(_ batch: Batch, cursor: Int) throws {
56 guard cursor >= batch.start + batch.records.count - 1 else { throw JOLError(message: "JOL did not confirm the full journal batch.") }
57 state.cursors[batch.expeditionID.uuidString] = cursor; try save()
58 }
59 func rememberCommand(_ id: UUID, status: String) throws { state.commands[id.uuidString] = status; try save() }
60 func priorCommand(_ id: UUID) -> String? { state.commands[id.uuidString] }
61 func complete(_ command: JOLCommand, status: String, result: String) throws {
62 state.commands[command.id.uuidString] = status
63 state.receipts[command.id.uuidString] = Receipt(command: command, status: status, result: result)
64 try save()
65 }
66 func pendingReceipts() -> [Receipt] { Array(state.receipts.values) }
67 func acknowledgeReceipt(_ id: UUID) throws { state.receipts[id.uuidString] = nil; try save() }
68 func enableHistory() { includeHistory = true }
69 func enableDetails() { backfillDetails = true }
70 func enablePhotos() { backfillPhotos = true }
71 func nextBatches() async throws -> [Batch] {
72 try await expeditions().compactMap { id, records in
73 let cursor = state.cursors[id.uuidString] ?? 0
74 guard cursor <= records.count else { throw JOLError(message: "A shared journal changed on disk. Reconnect to create a fresh sync connection.") }
75 let pending = records.dropFirst(cursor).prefix(100).map { source in
76 var record = source
77 if !details {
78 if record.event == .detailsAppended {
79 return JournalRecord(id: record.id, date: record.date, event: .redacted)
80 }
81 if record.entry != nil { record.entry?.details = "" }
82 }
83 if !photos { record.entry?.photo = nil }
84 return record
85 }
86 return pending.isEmpty ? nil : Batch(expeditionID: id, start: cursor + 1, records: pending)
87 }
88 }
89 func nextDetails() async throws -> [DetailBatch] {
90 guard backfillDetails, !details else { return [] }
91 var result: [DetailBatch] = []
92 for (id, records) in try await expeditions() {
93 let cursor = state.detailCursors?[id.uuidString] ?? 0
94 let accepted = min(state.cursors[id.uuidString] ?? 0, records.count)
95 guard cursor < accepted else { continue }
96 var through = cursor, bytes = 0
97 var changes: [DetailChange] = []
98 for index in cursor..<min(accepted, cursor + 100) {
99 let record = records[index]
100 let entryID = record.event == .detailsAppended ? record.entryID : record.entry?.id
101 let text = record.event == .detailsAppended ? record.text : record.entry?.details
102 if let entryID, let text, !text.isEmpty {
103 if !changes.isEmpty && bytes + text.utf8.count > 400_000 { break }
104 changes.append(.init(sequence: index + 1, id: record.id, date: record.date,
105 event: record.event, entryID: entryID, text: text))
106 bytes += text.utf8.count
107 }
108 through = index + 1
109 }
110 result.append(.init(expeditionID: id, through: through, changes: changes))
111 if result.count >= 5 { break }
112 }
113 return result
114 }
115 func acknowledgeDetails(_ batch: DetailBatch) throws {
116 if state.detailCursors == nil { state.detailCursors = [:] }
117 state.detailCursors?[batch.expeditionID.uuidString] = batch.through
118 try save()
119 }
120 func nextPhotos() async throws -> [Photo] {
121 guard photos || backfillPhotos else { return [] }
122 var result: [Photo] = []
123 for (id, records) in try await expeditions() {
124 for record in records.prefix(state.cursors[id.uuidString] ?? 0) {
125 guard let entry = record.entry, let filename = entry.photo, filename.hasSuffix(".jpg"), UUID(uuidString: String(filename.dropLast(4))) != nil,
126 !state.photos.contains(id.uuidString + "/" + filename) else { continue }
127 let url = journals.appendingPathComponent(id.uuidString).appendingPathComponent(filename)
128 guard let values = try? url.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey]), values.isRegularFile == true, values.isSymbolicLink != true,
129 (values.fileSize ?? 0) <= 4_000_000, let data = try? Data(contentsOf: url) else { continue }
130 result.append(Photo(expeditionID: id, entryID: entry.id, filename: filename, data: data))
131 if result.count >= 3 { return result }
132 }
133 }
134 return result
135 }
136 func acknowledgePhoto(_ photo: Photo) throws { state.photos.insert(photo.expeditionID.uuidString + "/" + photo.filename); try save() }
137 private func expeditions() async throws -> [(UUID, [JournalRecord])] {
138 guard FileManager.default.fileExists(atPath: journals.path) else { return [] }
139 let decoder = JSONDecoder(); decoder.dateDecodingStrategy = .millisecondsSince1970
140 let folders = try FileManager.default.contentsOfDirectory(at: journals, includingPropertiesForKeys: [.isSymbolicLinkKey])
141 var result: [(UUID, [JournalRecord])] = []
142 for folder in folders.sorted(by: { $0.lastPathComponent < $1.lastPathComponent }) {
143 guard let id = UUID(uuidString: folder.lastPathComponent), try folder.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink != true else { continue }
144 let file = folder.appendingPathComponent("journal.jsonl")
145 guard let attributes = try? file.resourceValues(forKeys: [.isSymbolicLinkKey, .isRegularFileKey, .fileSizeKey, .contentModificationDateKey]), attributes.isRegularFile == true, attributes.isSymbolicLink != true else { continue }
146 if !includeHistory {
147 if eligible[id] == nil {
148 // Inspect just the immutable creation record before asking the
149 // writer for a full snapshot of an old, unshared journal.
150 let handle = try FileHandle(forReadingFrom: file); defer { try? handle.close() }
151 let prefix = try handle.read(upToCount: 16_384) ?? Data()
152 if let end = prefix.firstIndex(of: 10), let header = try? decoder.decode(JournalRecord.self, from: prefix[..<end]),
153 header.event == .created, let created = header.expedition { eligible[id] = created.date >= since }
154 }
155 guard eligible[id] == true else { continue }
156 }
157 if let cached = snapshots[id], cached.size == attributes.fileSize, cached.modified == attributes.contentModificationDate {
158 result.append((id, cached.records)); continue
159 }
160 let snapshot: Data?
161 if let writer { snapshot = try await writer.committedData(for: id) }
162 else { snapshot = try? Data(contentsOf: file) }
163 guard let data = snapshot, let end = data.lastIndex(of: 10) else { continue }
164 var seen: Set<UUID> = [], records: [JournalRecord] = []
165 for line in data[..<end].split(separator: 10) {
166 // Preserve the existing journal loader's tolerance of interrupted/malformed lines.
167 guard let record = try? decoder.decode(JournalRecord.self, from: Data(line)), seen.insert(record.id).inserted else { continue }
168 guard record.version == 1 else { throw JOLError(message: "This journal uses a newer format; update Jerry before syncing it.") }
169 records.append(record)
170 }
171 guard let first = records.first, first.event == .created, first.expedition?.id == id,
172 includeHistory || (first.expedition?.date ?? .distantPast) >= since else { continue }
173 snapshots[id] = Snapshot(size: attributes.fileSize ?? data.count, modified: attributes.contentModificationDate, records: records)
174 result.append((id, records))
175 }
176 return result
177 }
178}