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

JOLController.swift

393 lines24.1 KB

1import AppKit
2import SwiftUI
3​
4@MainActor
5final class JOLController: ObservableObject {
6 @Published var address = UserDefaults.standard.string(forKey: "jolAddress") ?? ""
7 @Published var sharePhotos = false
8 @Published var shareDetails = false
9 @Published var includeHistory = false
10 @Published private(set) var backfillDetails = false
11 @Published private(set) var backfillPhotos = false
12 @Published private(set) var manifest: JOLManifest?
13 @Published private(set) var connected = false
14 @Published private(set) var working = false
15 @Published private(set) var status = "Optional. Jerry works without a JOL account."
16 @Published private(set) var remoteArmed = false
17 @Published private(set) var lastSync: Date?
18 @Published private(set) var sharingIssue: String?
19 var execute: ((JOLCommand) async -> JOLCommandResult)?
20 var isBusy: (() -> Bool)?
21 var interruptRemote: (() -> Void)?
22 private let credentials = JOLCredentials()
23 private let journalDirectory: URL?
24 private let journalStore: ExpeditionJournalStore?
25 private var sync: JOLSyncStore?
26 private var loop: Task<Void, Never>?
27 private var signIn: Task<Void, Never>?
28 private var presence: Task<Void, Never>?
29 private var eventStream: Task<Void, Never>?
30 private var commandCheck: Task<Void, Never>?
31 private var execution: Task<Void, Never>?
32 private var epoch = UUID()
33 private var needsCommandCheck = true
34 private var streamLive = false
35 private var presenceReady = false
36 private var presenceIssue: String?
37 private var lastClaim = Date.distantPast
38 init(journalDirectory: URL?, journalStore: ExpeditionJournalStore? = nil) { self.journalDirectory = journalDirectory; self.journalStore = journalStore }
39 func start() {
40 guard journalDirectory != nil, UserDefaults.standard.bool(forKey: "jolConnected") else { return }
41 do {
42 guard let account = try credentials.load() else { status = "Reconnect Jerry On Line to resume sharing."; return }
43 manifest = account.manifest; address = account.manifest.origin; connected = true
44 sharePhotos = UserDefaults.standard.bool(forKey: "jolSharePhotos"); shareDetails = UserDefaults.standard.bool(forKey: "jolShareDetails")
45 includeHistory = UserDefaults.standard.bool(forKey: "jolHistory")
46 backfillDetails = UserDefaults.standard.bool(forKey: "jolBackfillDetails")
47 backfillPhotos = UserDefaults.standard.bool(forKey: "jolBackfillPhotos")
48 try makeSync(account); runLoop()
49 } catch { status = error.localizedDescription }
50 }
51 func checkServer() {
52 signIn?.cancel(); working = true; manifest = nil; status = "Finding your JOL server…"
53 signIn = Task { [weak self] in
54 guard let self else { return }; defer { self.working = false }
55 do {
56 let url = try JOLManifest.serverURL(self.address)
57 let data = try await JOLHTTP.data(URLRequest(url: url.appendingPathComponent(".well-known/jerry-online")))
58 let found = try JSONDecoder().decode(JOLManifest.self, from: data); try found.validate(for: url)
59 try Task.checkCancellation(); self.manifest = found; self.status = "\(found.name) · \(url.host ?? found.origin)"
60 } catch is CancellationError {} catch { self.status = error.localizedDescription }
61 }
62 }
63 func connect() {
64 guard let manifest, let journalDirectory else { return }
65 working = true; status = "Finish signing in in your browser…"
66 signIn = Task { [weak self] in
67 guard let self else { return }; defer { self.working = false }
68 do {
69 let account = try await self.credentials.signIn(manifest)
70 var request = URLRequest(url: URL(string: manifest.origin + "/api/devices")!); request.httpMethod = "POST"
71 request.setValue("Bearer " + account.accessToken, forHTTPHeaderField: "Authorization"); request.setValue("application/json", forHTTPHeaderField: "Content-Type")
72 request.httpBody = try JSONSerialization.data(withJSONObject: ["id":account.deviceID.uuidString,"name":String((Host.current().localizedName ?? "My Mac").prefix(80)),"credential":account.deviceCredential])
73 _ = try await JOLHTTP.data(request); try Task.checkCancellation(); try self.credentials.save(account)
74 let defaults = UserDefaults.standard
75 defaults.set(manifest.origin, forKey: "jolAddress"); defaults.set(Date(), forKey: "jolSince")
76 defaults.set(self.sharePhotos, forKey: "jolSharePhotos"); defaults.set(self.shareDetails, forKey: "jolShareDetails"); defaults.set(self.includeHistory, forKey: "jolHistory")
77 self.backfillDetails = false
78 self.backfillPhotos = false
79 defaults.set(false, forKey: "jolBackfillDetails")
80 defaults.set(false, forKey: "jolBackfillPhotos")
81 defaults.set(true, forKey: "jolConnected"); self.connected = true
82 try self.makeSync(account); self.runLoop()
83 } catch is CancellationError {} catch { self.status = error.localizedDescription }
84 _ = journalDirectory
85 }
86 }
87 func cancelSignIn() { signIn?.cancel(); credentials.cancel(); working = false; status = "Connection cancelled. Jerry is still working locally." }
88 func disconnect() {
89 let saved = try? credentials.load()
90 if execution != nil { interruptRemote?() }
91 epoch = UUID(); remoteArmed = false; loop?.cancel(); presence?.cancel(); eventStream?.cancel(); commandCheck?.cancel(); execution?.cancel(); signIn?.cancel()
92 loop = nil; presence = nil; eventStream = nil; commandCheck = nil; execution = nil; sync = nil
93 connected = false; working = false; manifest = nil; lastSync = nil; sharingIssue = nil
94 UserDefaults.standard.set(false, forKey: "jolConnected")
95 // A local disconnect is immediate even if the server cannot be reached.
96 if let saved {
97 Task {
98 var request = URLRequest(url: URL(string: saved.manifest.origin + "/api/devices/\(saved.deviceID.uuidString.lowercased())/revoke")!); request.httpMethod = "POST"
99 request.setValue("Bearer " + saved.accessToken, forHTTPHeaderField: "Authorization"); _ = try? await JOLHTTP.data(request)
100 }
101 }
102 credentials.clear(); status = "Disconnected. Local journals are unchanged; the shared copy remains on JOL."
103 }
104 func setRemoteArmed(_ value: Bool) {
105 let armed = connected && value
106 guard armed != remoteArmed else { return }
107 remoteArmed = armed
108 if !armed && execution != nil { interruptRemote?() }
109 if !armed { eventStream?.cancel(); eventStream = nil; streamLive = false }
110 startPresence(generation: epoch)
111 }
112 func wakeCommands() {
113 guard remoteArmed else { return }
114 needsCommandCheck = true
115 scheduleCommandCheck(generation: epoch)
116 }
117 func serverAddressChanged() { if !connected { manifest = nil } }
118 func localTakeover() { if remoteArmed { setRemoteArmed(false); status = "Remote missions paused for local control. Re-enable them when you’re ready." } }
119 func openWebsite() { if let manifest, let url = URL(string: manifest.origin) { NSWorkspace.shared.open(url) } }
120 func shareOlderExpeditions() {
121 guard connected, let sync else { return }
122 includeHistory = true
123 UserDefaults.standard.set(true, forKey: "jolHistory")
124 Task { await sync.enableHistory() }
125 }
126 func shareTechnicalDetails() {
127 guard connected, let sync, !working else { return }
128 let generation = epoch
129 working = true
130 sharingIssue = nil
131 Task {
132 defer { if epoch == generation { working = false } }
133 do {
134 let found = try await refreshManifest()
135 guard connected, epoch == generation else { return }
136 guard found.capabilities.detailsBackfill == true else {
137 sharingIssue = "Update your JOL server to share technical details on an existing connection."
138 return
139 }
140 backfillDetails = true
141 UserDefaults.standard.set(true, forKey: "jolBackfillDetails")
142 await sync.enableDetails()
143 } catch {
144 if epoch == generation { sharingIssue = error.localizedDescription }
145 }
146 }
147 }
148 func shareJournalPhotos() {
149 guard connected, let sync, !working, !sharePhotos, !backfillPhotos else { return }
150 let generation = epoch
151 working = true
152 sharingIssue = nil
153 Task {
154 defer { if epoch == generation { working = false } }
155 do {
156 let found = try await refreshManifest()
157 guard connected, epoch == generation else { return }
158 guard found.capabilities.photos, found.capabilities.photosBackfill == true else {
159 sharingIssue = "Update your JOL server to share photographs on an existing connection."
160 return
161 }
162 backfillPhotos = true
163 UserDefaults.standard.set(true, forKey: "jolBackfillPhotos")
164 await sync.enablePhotos()
165 } catch {
166 if epoch == generation { sharingIssue = error.localizedDescription }
167 }
168 }
169 }
170 private func refreshManifest() async throws -> JOLManifest {
171 guard let manifest, let url = URL(string: manifest.origin) else { throw CancellationError() }
172 let data = try await JOLHTTP.data(URLRequest(url: url.appendingPathComponent(".well-known/jerry-online")))
173 let found = try JSONDecoder().decode(JOLManifest.self, from: data)
174 try found.validate(for: url)
175 guard found.instanceID == manifest.instanceID else { throw JOLError(message: "This JOL server has changed. Reconnect to share your journal.") }
176 return found
177 }
178 private func makeSync(_ account: JOLCredentials.Account) throws {
179 guard let journalDirectory else { return }
180 let support = journalDirectory.deletingLastPathComponent().appendingPathComponent("JOL/\(account.manifest.instanceID)/\(account.deviceID.uuidString)")
181 sync = try JOLSyncStore(journals: journalDirectory, directory: support, since: UserDefaults.standard.object(forKey: "jolSince") as? Date ?? Date(), includeHistory: includeHistory, details: shareDetails, photos: sharePhotos, writer: journalStore, backfillDetails: backfillDetails, backfillPhotos: backfillPhotos)
182 }
183 private func request(_ path: String, body: Data? = nil, method: String? = nil, contentType: String = "application/json", generation: UUID) async throws -> Data {
184 guard connected, epoch == generation, !Task.isCancelled, let account = try credentials.load() else { throw CancellationError() }
185 var request = URLRequest(url: URL(string: account.manifest.origin + "/api" + path)!)
186 request.httpMethod = method ?? (body == nil ? "GET" : "POST"); request.httpBody = body
187 let bearer = try await credentials.token()
188 guard connected, epoch == generation else { throw CancellationError() }
189 request.setValue("Bearer " + bearer, forHTTPHeaderField: "Authorization")
190 request.setValue(account.deviceCredential, forHTTPHeaderField: "X-JOL-Device")
191 if body != nil { request.setValue(contentType, forHTTPHeaderField: "Content-Type") }
192 return try await JOLHTTP.data(request)
193 }
194 private func json(_ object: [String: Any]) throws -> Data { try JSONSerialization.data(withJSONObject: object) }
195 private var devicePath: String { get throws { guard let account = try credentials.load() else { throw CancellationError() }; return "/devices/" + account.deviceID.uuidString.lowercased() } }
196 private func runLoop() {
197 loop?.cancel(); eventStream?.cancel(); eventStream = nil; let generation = UUID(); epoch = generation
198 status = "Connecting… Remote missions are off until you enable them."
199 startPresence(generation: generation)
200 loop = Task { [weak self] in
201 var failures = 0
202 while !Task.isCancelled {
203 guard let self, self.connected, self.epoch == generation, let sync = self.sync else { return }
204 do {
205 let path = try self.devicePath
206 var uploaded = false
207 for receipt in await sync.pendingReceipts() {
208 try await self.ack(receipt.command, status: receipt.status, result: receipt.result, generation: generation)
209 try await sync.acknowledgeReceipt(receipt.command.id)
210 }
211 for batch in try await sync.nextBatches() {
212 struct Payload: Encodable { let start: Int; let records: [JournalRecord] }
213 let encoder = JSONEncoder(); encoder.dateEncodingStrategy = .millisecondsSince1970
214 let result = try await self.request(path + "/expeditions/\(batch.expeditionID.uuidString.lowercased())/batches", body: encoder.encode(Payload(start: batch.start, records: batch.records)), generation: generation)
215 struct Ack: Decodable { let cursor: Int }
216 try await sync.acknowledge(batch, cursor: JSONDecoder().decode(Ack.self, from: result).cursor)
217 uploaded = true
218 }
219 for batch in try await sync.nextDetails() {
220 if !batch.changes.isEmpty {
221 let encoder = JSONEncoder()
222 encoder.dateEncodingStrategy = .millisecondsSince1970
223 _ = try await self.request(path + "/expeditions/\(batch.expeditionID.uuidString.lowercased())/details",
224 body: encoder.encode(batch.changes), method: "PATCH", generation: generation)
225 uploaded = true
226 }
227 try await sync.acknowledgeDetails(batch)
228 }
229 if self.manifest?.capabilities.photos == true || self.backfillPhotos {
230 for photo in try await sync.nextPhotos() {
231 let upload = path + "/expeditions/\(photo.expeditionID.uuidString.lowercased())/photos/\(photo.filename.lowercased())"
232 let entry = self.backfillPhotos ? "?entry=\(photo.entryID.uuidString.lowercased())" : ""
233 let response = try await self.request(upload + entry, body: photo.data, method: "PUT", contentType: "image/jpeg", generation: generation)
234 if self.backfillPhotos {
235 struct PhotoAck: Decodable { let entryLinked: Bool? }
236 guard try JSONDecoder().decode(PhotoAck.self, from: response).entryLinked == true else {
237 throw JOLError(message: "JOL did not attach the photograph to its journal entry.")
238 }
239 }
240 try await sync.acknowledgePhoto(photo)
241 uploaded = true
242 }
243 }
244 guard self.connected, self.epoch == generation, !Task.isCancelled else { return }
245 failures = 0
246 if uploaded { self.lastSync = Date() }
247 if let issue = self.presenceIssue { self.status = "JOL connection waiting: " + issue }
248 else if self.presenceReady {
249 self.status = self.remoteArmed ? "On line · remote missions enabled" : "On line · sharing journals. Remote missions are off."
250 }
251 } catch is CancellationError { return }
252 catch { guard self.epoch == generation else { return }; failures += 1; self.status = "Journal sync waiting: " + error.localizedDescription }
253 try? await Task.sleep(for: .seconds(min(30, failures == 0 ? 2 : pow(2, Double(min(failures, 4))))))
254 }
255 }
256 }
257 private func startPresence(generation: UUID) {
258 presence?.cancel()
259 presenceReady = false
260 presenceIssue = nil
261 presence = Task { [weak self] in
262 var nextHeartbeat = Date.distantPast
263 while !Task.isCancelled {
264 guard let self, self.connected, self.epoch == generation else { return }
265 if Date() >= nextHeartbeat {
266 do {
267 let armed = self.remoteArmed
268 _ = try await self.request(try self.devicePath + "/heartbeat",
269 body: self.json(["remoteEnabled": armed]), generation: generation)
270 guard !Task.isCancelled, self.epoch == generation, self.remoteArmed == armed else { return }
271 if !self.presenceReady && armed { self.needsCommandCheck = true }
272 self.presenceReady = true
273 self.presenceIssue = nil
274 nextHeartbeat = Date().addingTimeInterval(20)
275 } catch {
276 if Task.isCancelled || self.epoch != generation { return }
277 self.presenceReady = false
278 self.presenceIssue = error.localizedDescription
279 }
280 }
281 if self.remoteArmed && self.presenceReady {
282 if self.manifest?.capabilities.realtime == true && self.eventStream == nil {
283 self.startEvents(generation: generation)
284 }
285 // Recover missed hints or expired leases. A healthy stream
286 // wakes the claim immediately, independently of journal uploads.
287 if Date().timeIntervalSince(self.lastClaim) >= (self.streamLive ? 90 : 10) {
288 self.needsCommandCheck = true
289 }
290 self.scheduleCommandCheck(generation: generation)
291 }
292 try? await Task.sleep(for: .seconds(5))
293 }
294 }
295 }
296 private func startEvents(generation: UUID) {
297 eventStream = Task { [weak self] in
298 guard let self, self.epoch == generation, self.connected, self.remoteArmed, !Task.isCancelled else { return }
299 defer {
300 if self.epoch == generation && !Task.isCancelled {
301 self.eventStream = nil
302 self.streamLive = false
303 }
304 }
305 do {
306 guard let account = try self.credentials.load() else { return }
307 var request = URLRequest(url: URL(string: account.manifest.origin + "/api" + (try self.devicePath) + "/events")!); request.timeoutInterval = 60
308 request.setValue("Bearer " + (try await self.credentials.token()), forHTTPHeaderField: "Authorization"); request.setValue(account.deviceCredential, forHTTPHeaderField: "X-JOL-Device")
309 guard self.connected, self.remoteArmed, self.epoch == generation, !Task.isCancelled else { return }
310 let (bytes, response) = try await JOLHTTP.session.bytes(for: request)
311 guard (response as? HTTPURLResponse)?.statusCode == 200 else { return }
312 for try await line in bytes.lines {
313 guard !Task.isCancelled, self.epoch == generation else { return }
314 if line == "event: live" {
315 self.streamLive = true
316 self.wakeCommands()
317 } else if line == "event: commands_changed" {
318 self.wakeCommands()
319 }
320 }
321 } catch { /* The periodic durable queue read remains active. */ }
322 }
323 }
324 private func scheduleCommandCheck(generation: UUID) {
325 guard connected, remoteArmed, presenceReady, epoch == generation,
326 needsCommandCheck, commandCheck == nil else { return }
327 needsCommandCheck = false
328 lastClaim = Date()
329 commandCheck = Task { [weak self] in
330 guard let self else { return }
331 var succeeded = false
332 defer {
333 if self.epoch == generation {
334 self.commandCheck = nil
335 if succeeded { self.scheduleCommandCheck(generation: generation) }
336 else { self.needsCommandCheck = true }
337 }
338 }
339 guard self.remoteArmed, self.epoch == generation, !Task.isCancelled else { return }
340 do {
341 try await self.checkCommands(generation: generation)
342 succeeded = true
343 } catch {
344 // Presence maintenance retries without delaying journal uploads.
345 }
346 }
347 }
348 private func ack(_ command: JOLCommand, status: String, result: String = "", generation: UUID) async throws {
349 guard epoch == generation else { throw CancellationError() }
350 _ = try await request((try devicePath) + "/commands/\(command.id.uuidString.lowercased())/ack", body: json(["fence":command.fence,"status":status,"result":String(result.prefix(1000))]), generation: generation)
351 }
352 private func checkCommands(generation: UUID) async throws {
353 guard epoch == generation, connected, !Task.isCancelled else { throw CancellationError() }
354 guard let sync else { return }
355 struct Claim: Decodable { let command: JOLCommand? }
356 let data = try await request((try devicePath) + "/commands/claim", body: json(["busy":execution != nil || (isBusy?() ?? true)]), generation: generation)
357 guard let command = try JSONDecoder().decode(Claim.self, from: data).command else { return }
358 if await sync.priorCommand(command.id) != nil {
359 try await ack(command, status: "uncertain", result: "Jerry already accepted this direction. Give a fresh direction to continue safely.", generation: generation); return
360 }
361 guard remoteArmed, epoch == generation else { return }
362 try await sync.rememberCommand(command.id, status: "started")
363 try await ack(command, status: "started", generation: generation)
364 guard epoch == generation else { throw CancellationError() }
365 guard remoteArmed else { try await ack(command, status: "failed", result: "Remote missions were paused locally before starting", generation: generation); return }
366 if command.kind == "stop" {
367 let result = await execute?(command) ?? .init(status: "failed", message: "Jerry is unavailable")
368 try await sync.complete(command, status: result.status, result: result.message)
369 try await ack(command, status: result.status, result: result.message, generation: generation); try await sync.acknowledgeReceipt(command.id); return
370 }
371 execution = Task { [weak self] in
372 guard let self else { return }
373 defer { if self.epoch == generation { self.execution = nil; self.wakeCommands() } }
374 guard self.epoch == generation, self.remoteArmed, !Task.isCancelled else { return }
375 let renew = Task { [weak self] in
376 while !Task.isCancelled {
377 try? await Task.sleep(for: .seconds(20)); guard !Task.isCancelled, let self, self.epoch == generation else { return }
378 do { try await self.ack(command, status: "started", generation: generation) }
379 catch { guard self.epoch == generation else { return }; self.setRemoteArmed(false); self.interruptRemote?(); return }
380 }
381 }
382 let result = await self.execute?(command) ?? .init(status: "failed", message: "Jerry is unavailable")
383 renew.cancel()
384 guard self.epoch == generation else { return }
385 do {
386 try await sync.complete(command, status: result.status, result: result.message)
387 try await self.ack(command, status: result.status, result: result.message, generation: generation)
388 try await sync.acknowledgeReceipt(command.id)
389 }
390 catch { if self.epoch == generation { self.status = "Direction completed locally; its acknowledgement is waiting for a connection." } }
391 }
392 }