Skip to content
Source
Sign inSign up
samwillis/jerry
Open History to see the last commit

JOLSyncStore.swift

174 lines10.4 KB

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