Branchwell

Glimmer / app · glimmertoday.ai / native / Glimmer / JournalReplica.swift

1import Foundation
2
3/// Sync independent journal records so offline changes on two devices can both survive.
4struct JournalReplica: Codable, Equatable, Sendable {
5 struct Key: Codable, Hashable, Sendable {
6 let path: [String]
7 init(_ components: String...) { path = components }
8 }
9
10 struct Stamp: Codable, Equatable, Comparable, Sendable {
11 let revision: UInt64
12 let device: UUID
13
14 static func < (lhs: Self, rhs: Self) -> Bool {
15 if lhs.revision != rhs.revision { return lhs.revision < rhs.revision }
16 return lhs.device.uuidString < rhs.device.uuidString
17 }
18 }
19
20 struct Entry: Codable, Equatable, Sendable {
21 let stamp: Stamp
22 let insertion: Stamp
23 let position: Int
24 let data: Data?
25 }
26
27 private(set) var entries: [Key: Entry] = [:]
28
29 // Older clients reject unknown fields inside entries. Keep additive fields in a
30 // sibling section so those clients can continue to sync every field they understand.
31 private enum CodingKeys: String, CodingKey { case entries, readerDayEntries, choreEntries, seasonalEntries, personalTodoEntries, toolkitEntries }
32 private static let toolkitFields: Set<String> = ["todoSteps", "todoEstimates"]
33 private static let choreFields: Set<String> = ["favoriteChores", "recentChores"]
34
35 init(from decoder: Decoder) throws {
36 let fields = try decoder.container(keyedBy: CodingKeys.self)
37 entries = try fields.decode([Key: Entry].self, forKey: .entries)
38 let days = try fields.decodeIfPresent([Key: Entry].self, forKey: .readerDayEntries) ?? [:]
39 guard days.keys.allSatisfy({ $0.path.first == "readerDays" && $0.path.count == 2 }) else {
40 throw CocoaError(.fileReadCorruptFile)
41 }
42 entries.merge(days) { _, extensionEntry in extensionEntry }
43 let chores = try fields.decodeIfPresent([Key: Entry].self, forKey: .choreEntries) ?? [:]
44 guard chores.keys.allSatisfy({
45 ($0.path.count == 2 && $0.path[0] == "favoriteChores") ||
46 ($0.path.count == 3 && $0.path[0] == "recentChores")
47 }) else {
48 throw CocoaError(.fileReadCorruptFile)
49 }
50 entries.merge(chores) { _, extensionEntry in extensionEntry }
51 let seasonal = try fields.decodeIfPresent([Key: Entry].self, forKey: .seasonalEntries) ?? [:]
52 guard seasonal.keys.allSatisfy({ $0.path.first == "seasonalChecks" && $0.path.count == 3 }) else {
53 throw CocoaError(.fileReadCorruptFile)
54 }
55 entries.merge(seasonal) { _, extensionEntry in extensionEntry }
56 let todos = try fields.decodeIfPresent([Key: Entry].self, forKey: .personalTodoEntries) ?? [:]
57 guard todos.keys.allSatisfy({ $0.path.first == "personalTodos" && $0.path.count == 2 }) else {
58 throw CocoaError(.fileReadCorruptFile)
59 }
60 entries.merge(todos) { _, extensionEntry in extensionEntry }
61 let toolkit = try fields.decodeIfPresent([Key: Entry].self, forKey: .toolkitEntries) ?? [:]
62 guard toolkit.keys.allSatisfy({ $0.path.count == 2 && Self.toolkitFields.contains($0.path[0]) }) else {
63 throw CocoaError(.fileReadCorruptFile)
64 }
65 entries.merge(toolkit) { _, extensionEntry in extensionEntry }
66 }
67
68 func encode(to encoder: Encoder) throws {
69 var fields = encoder.container(keyedBy: CodingKeys.self)
70 try fields.encode(entries.filter {
71 $0.key.path.first != "readerDays" && $0.key.path.first != "seasonalChecks" && $0.key.path.first != "personalTodos"
72 && !Self.choreFields.contains($0.key.path.first ?? "") && !Self.toolkitFields.contains($0.key.path.first ?? "")
73 }, forKey: .entries)
74 let days = entries.filter { $0.key.path.first == "readerDays" }
75 if !days.isEmpty { try fields.encode(days, forKey: .readerDayEntries) }
76 let chores = entries.filter { Self.choreFields.contains($0.key.path.first ?? "") }
77 if !chores.isEmpty { try fields.encode(chores, forKey: .choreEntries) }
78 let seasonal = entries.filter { $0.key.path.first == "seasonalChecks" }
79 if !seasonal.isEmpty { try fields.encode(seasonal, forKey: .seasonalEntries) }
80 let todos = entries.filter { $0.key.path.first == "personalTodos" }
81 if !todos.isEmpty { try fields.encode(todos, forKey: .personalTodoEntries) }
82 let toolkit = entries.filter { Self.toolkitFields.contains($0.key.path.first ?? "") }
83 if !toolkit.isEmpty { try fields.encode(toolkit, forKey: .toolkitEntries) }
84 }
85
86 init() {}
87
88 init(seed: Journal, device: UUID) throws {
89 try observe(from: Journal(), to: seed, device: device)
90 }
91
92 mutating func observe(from old: Journal, to new: Journal, device: UUID) throws {
93 let before = try Self.project(old)
94 let after = try Self.project(new)
95 let revision = entries.values.map(\.stamp.revision).max() ?? 0
96 guard revision < UInt64.max else { throw CocoaError(.fileWriteUnknown) }
97 let stamp = Stamp(revision: revision + 1, device: device)
98 for key in Set(before.keys).union(after.keys) where before[key]?.data != after[key]?.data {
99 let existing = entries[key]
100 entries[key] = Entry(stamp: stamp, insertion: existing?.insertion ?? stamp,
101 position: existing?.position ?? after[key]?.position ?? 0, data: after[key]?.data)
102 }
103 }
104
105 mutating func merge(_ other: Self) {
106 entries.merge(other.entries) { local, remote in
107 // Retain the earliest known insertion so concurrent edits cannot reorder the list.
108 let first = Self.precedes(local, remote) ? local : remote
109 let newest: Entry
110 if local.stamp != remote.stamp {
111 newest = local.stamp < remote.stamp ? remote : local
112 } else if let localData = local.data, let remoteData = remote.data {
113 newest = localData.lexicographicallyPrecedes(remoteData) ? remote : local
114 } else {
115 newest = local.data == nil ? local : remote
116 }
117 return Entry(stamp: newest.stamp, insertion: first.insertion, position: first.position, data: newest.data)
118 }
119 }
120
121 func materialize(keepingEngagement engagement: Engagement) throws -> Journal {
122 var json = try Self.object(Journal())
123 var groups: [String: [(Key, Entry)]] = [:]
124 for (key, entry) in entries {
125 guard let field = key.path.first, Self.schema[field] != nil else { throw CocoaError(.fileReadCorruptFile) }
126 groups[field, default: []].append((key, entry))
127 }
128 for (field, atoms) in groups {
129 var live = [(path: [String], value: Any)]()
130 for (key, entry) in atoms.sorted(by: {
131 if $0.1.insertion != $1.1.insertion || $0.1.position != $1.1.position { return Self.precedes($0.1, $1.1) }
132 return $0.0.path.lexicographicallyPrecedes($1.0.path)
133 }) {
134 guard let data = entry.data else { continue }
135 live.append((Array(key.path.dropFirst()), try JSONSerialization.jsonObject(with: data, options: .fragmentsAllowed)))
136 }
137 switch Self.schema[field] {
138 case .scalar:
139 // A deleted scalar returns to its original default, including absent optional fields.
140 if let value = live.first?.value { json[field] = value }
141 case .records, .members:
142 json[field] = live.map(\.value)
143 case .dictionary:
144 var result: [String: Any] = [:]
145 for atom in live where atom.path.count == 1 { result[atom.path[0]] = atom.value }
146 json[field] = result
147 case .dailyMembership:
148 var result: [String: [Any]] = [:]
149 for atom in live where atom.path.count == 2 { result[atom.path[0], default: []].append(atom.value) }
150 json[field] = result
151 case .lessons:
152 var lessons: [String: [String: Any]] = [:]
153 for atom in live where atom.path.count == 2 || atom.path.count == 3 {
154 var lesson = lessons[atom.path[0]] ?? ["page": 0, "completed": false, "choices": [String: Any]()]
155 if atom.path.count == 3 {
156 var choices = lesson["choices"] as? [String: Any] ?? [:]
157 choices[atom.path[2]] = atom.value
158 lesson["choices"] = choices
159 } else {
160 lesson[atom.path[1]] = atom.value
161 }
162 lessons[atom.path[0]] = lesson
163 }
164 json[field] = lessons
165 case .experiment:
166 if var active = live.first(where: { $0.path.isEmpty })?.value as? [String: Any],
167 let id = active["id"] as? String {
168 var checkins: [String: Any] = [:]
169 for atom in live where atom.path.count == 2 && atom.path[0] == id {
170 checkins[atom.path[1]] = atom.value
171 }
172 active["checkins"] = checkins
173 json[field] = active
174 }
175 case nil: break
176 }
177 }
178 var journal = try JournalStore.decode(try Self.encode(json))
179 journal.engagement = engagement
180 if journal.coins >= 80 { journal.coffeeUnlocked = true }
181 return journal
182 }
183
184 private static func precedes(_ lhs: Entry, _ rhs: Entry) -> Bool {
185 if lhs.insertion != rhs.insertion { return lhs.insertion < rhs.insertion }
186 return lhs.position < rhs.position
187 }
188
189 private enum Field {
190 case scalar, records(String), members, dictionary, dailyMembership, lessons, experiment
191 }
192
193 private static let schema: [String: Field] = [
194 "started": .scalar, "name": .scalar, "onboardingIndex": .scalar, "tracker": .scalar,
195 "coffeeUnlocked": .scalar, "answers": .dictionary, "energy": .dictionary,
196 "moods": .dictionary, "rewards": .dictionary, "challenges": .dictionary, "cleaningLast": .dictionary,
197 "tasks": .records("id"), "moments": .records("id"), "history": .records("id"), "queued": .records("title"),
198 "personalTodos": .records("id"), "todoSteps": .records("id"), "todoEstimates": .records("id"),
199 "readerDays": .members, "favoriteSources": .members, "customSources": .members, "completions": .dailyMembership,
200 "favoriteChores": .members, "recentChores": .dailyMembership,
201 "seasonalChecks": .dailyMembership,
202 "habits": .dailyMembership, "cleaningChecks": .dailyMembership, "lessons": .lessons, "experiment": .experiment
203 ]
204
205 private struct Atom {
206 let data: Data
207 let position: Int
208 }
209
210 private static func project(_ journal: Journal) throws -> [Key: Atom] {
211 let json = try object(journal)
212 var result: [Key: Atom] = [:]
213 func add(_ key: Key, _ value: Any, position: Int = 0) throws {
214 result[key] = Atom(data: try encode(value), position: position)
215 }
216
217 for (field, rule) in schema {
218 guard let value = json[field] else { continue }
219 switch rule {
220 case .scalar:
221 try add(Key(field), value)
222 case .records(let idField):
223 for (position, original) in (value as? [[String: Any]] ?? []).enumerated() {
224 guard let id = original[idField] as? String else { throw CocoaError(.fileReadCorruptFile) }
225 var record = original
226 if let weekdays = record["weekdays"] as? [Int] { record["weekdays"] = weekdays.sorted() }
227 try add(Key(field, id), record, position: position)
228 }
229 case .members:
230 for (position, member) in (value as? [String] ?? []).enumerated() {
231 try add(Key(field, member), member, position: position)
232 }
233 case .dictionary:
234 for (key, item) in value as? [String: Any] ?? [:] { try add(Key(field, key), item) }
235 case .dailyMembership:
236 for (day, items) in value as? [String: [Any]] ?? [:] {
237 for item in items { try add(Key(field, day, try encode(item).base64EncodedString()), item) }
238 }
239 case .lessons:
240 for (id, lesson) in value as? [String: [String: Any]] ?? [:] {
241 if let page = lesson["page"] as? Int, page != 0 { try add(Key(field, id, "page"), page) }
242 if lesson["completed"] as? Bool == true { try add(Key(field, id, "completed"), true) }
243 for (question, choice) in lesson["choices"] as? [String: Any] ?? [:] {
244 try add(Key(field, id, "choices", question), choice)
245 }
246 }
247 case .experiment:
248 guard var active = value as? [String: Any], let id = active["id"] as? String else {
249 throw CocoaError(.fileReadCorruptFile)
250 }
251 let checkins = active.removeValue(forKey: "checkins") as? [String: Any] ?? [:]
252 try add(Key(field), active)
253 for (day, outcome) in checkins { try add(Key(field, id, day), outcome) }
254 }
255 }
256 return result
257 }
258
259 private static func object(_ journal: Journal) throws -> [String: Any] {
260 guard let json = try JSONSerialization.jsonObject(with: JSONEncoder().encode(journal)) as? [String: Any] else {
261 throw CocoaError(.fileReadCorruptFile)
262 }
263 return json
264 }
265
266 private static func encode(_ value: Any) throws -> Data {
267 try JSONSerialization.data(withJSONObject: value, options: [.fragmentsAllowed, .sortedKeys])
268 }
269}