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

JOLController.swift

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