OpenTalon / app / native / Sources / OpenTalon / Service.swift
| 1 | import AppKit |
| 2 | import CompanionCore |
| 3 | import Foundation |
| 4 | |
| 5 | struct ServiceFailure: LocalizedError { |
| 6 | var code: String |
| 7 | var message: String |
| 8 | var current: WorkItem? |
| 9 | var errorDescription: String? { message } |
| 10 | } |
| 11 | |
| 12 | struct EmptyResponse: Decodable {} |
| 13 | struct ValueResponse: Decodable { let value: String } |
| 14 | struct PathResponse: Decodable { let path: String } |
| 15 | struct ItemResponse: Decodable { let task: WorkItem } |
| 16 | struct BoardResponse: Decodable { let board: Board } |
| 17 | |
| 18 | @MainActor |
| 19 | final class Service { |
| 20 | private let input = Pipe() |
| 21 | private let output = Pipe() |
| 22 | private let process = Process() |
| 23 | private let io = DispatchQueue(label: "com.protomota.opentalon.service") |
| 24 | private var pending: [String: CheckedContinuation<Data, Error>] = [:] |
| 25 | private var buffer = ServiceLineBuffer() |
| 26 | private(set) var ready = false |
| 27 | private var closed = false |
| 28 | var onReady: (() -> Void)? |
| 29 | var onChange: (() -> Void)? |
| 30 | var onBackupChange: (() -> Void)? |
| 31 | var onChatActivity: ((String, String?) -> Void)? |
| 32 | var onFailure: ((ServiceFailure) -> Void)? |
| 33 | var onExit: (() -> Void)? |
| 34 | |
| 35 | func start(profile: URL, visible: Bool) throws { |
| 36 | guard let resources = Bundle.main.resourceURL, let executable = Bundle.main.executableURL else { |
| 37 | throw ServiceFailure(code: "BUNDLE", message: "Open the built OpenTalon app from Finder.") |
| 38 | } |
| 39 | process.executableURL = resources.deletingLastPathComponent().appendingPathComponent("Helpers/node") |
| 40 | process.currentDirectoryURL = profile |
| 41 | process.arguments = [ |
| 42 | resources.appendingPathComponent("service/service.cjs").path, profile.path, |
| 43 | executable.path, Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "0.1.0", |
| 44 | visible ? "visible" : "hidden" |
| 45 | ] |
| 46 | var environment = ProcessInfo.processInfo.environment |
| 47 | environment.removeValue(forKey: "ELECTRON_RUN_AS_NODE") |
| 48 | environment.removeValue(forKey: "NODE_OPTIONS") |
| 49 | environment.removeValue(forKey: "NODE_PATH") |
| 50 | environment["PWD"] = profile.path |
| 51 | process.environment = environment |
| 52 | process.standardInput = input |
| 53 | process.standardOutput = output |
| 54 | process.terminationHandler = { [weak self] process in |
| 55 | let status = process.terminationStatus |
| 56 | Task { @MainActor in self?.didExit(status: status) } |
| 57 | } |
| 58 | // All byte chunks go to the same main-queue consumer in order. |
| 59 | output.fileHandleForReading.readabilityHandler = { [weak self] file in |
| 60 | let bytes = file.availableData |
| 61 | if bytes.isEmpty { file.readabilityHandler = nil } |
| 62 | DispatchQueue.main.async { self?.receive(bytes) } |
| 63 | } |
| 64 | do { |
| 65 | try process.run() |
| 66 | } catch { |
| 67 | output.fileHandleForReading.readabilityHandler = nil |
| 68 | throw error |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | func call<Response: Decodable>(_ name: String, _ fields: [String: Any] = [:]) async throws -> Response { |
| 73 | let id = UUID().uuidString |
| 74 | var packet = try JSONSerialization.data(withJSONObject: ["id": id, "name": name, "input": fields], |
| 75 | options: .withoutEscapingSlashes) |
| 76 | guard packet.count <= 20 * 1024 * 1024 else { |
| 77 | throw ServiceFailure(code: "INVALID_ARGUMENT", message: "This request is too large.") |
| 78 | } |
| 79 | packet.append(0x0a) |
| 80 | let bytes = packet |
| 81 | let response: Data = try await withCheckedThrowingContinuation { continuation in |
| 82 | guard ready, !closed else { |
| 83 | continuation.resume(throwing: unavailable) |
| 84 | return |
| 85 | } |
| 86 | pending[id] = continuation |
| 87 | let writer = input.fileHandleForWriting |
| 88 | io.async { [weak self] in |
| 89 | do { try writer.write(contentsOf: bytes) } |
| 90 | catch { |
| 91 | DispatchQueue.main.async { |
| 92 | self?.pending.removeValue(forKey: id)?.resume(throwing: error) |
| 93 | } |
| 94 | } |
| 95 | } |
| 96 | } |
| 97 | return try JSONDecoder().decode(Response.self, from: response) |
| 98 | } |
| 99 | |
| 100 | private var unavailable: ServiceFailure { |
| 101 | ServiceFailure(code: "SERVICE_CLOSED", message: "The local workspace service closed. Reopen OpenTalon to continue.") |
| 102 | } |
| 103 | |
| 104 | private func receive(_ bytes: Data) { |
| 105 | for line in buffer.append(bytes) { |
| 106 | guard let object = (try? JSONSerialization.jsonObject(with: line)) as? [String: Any] else { continue } |
| 107 | switch object["event"] as? String { |
| 108 | case "ready": |
| 109 | ready = true |
| 110 | onReady?() |
| 111 | case "changed": |
| 112 | if ready { onChange?() } |
| 113 | case "backup-changed": |
| 114 | onBackupChange?() |
| 115 | case "agent-chat-activity": |
| 116 | if let name = object["name"] as? String { onChatActivity?(name, object["title"] as? String) } |
| 117 | case "failed": |
| 118 | onFailure?(failure(object["error"] as? [String: Any])) |
| 119 | default: |
| 120 | guard let id = object["id"] as? String, |
| 121 | let continuation = pending.removeValue(forKey: id) else { continue } |
| 122 | if let error = object["error"] as? [String: Any] { |
| 123 | continuation.resume(throwing: failure(error)) |
| 124 | } else { |
| 125 | do { |
| 126 | let data = try JSONSerialization.data(withJSONObject: object["data"] ?? NSNull(), options: .fragmentsAllowed) |
| 127 | continuation.resume(returning: data) |
| 128 | } catch { continuation.resume(throwing: error) } |
| 129 | } |
| 130 | } |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | private func failure(_ fields: [String: Any]?) -> ServiceFailure { |
| 135 | var current: WorkItem? |
| 136 | if let details = fields?["details"] as? [String: Any], let record = details["current"], |
| 137 | let data = try? JSONSerialization.data(withJSONObject: record) { |
| 138 | current = try? JSONDecoder().decode(WorkItem.self, from: data) |
| 139 | } |
| 140 | return ServiceFailure( |
| 141 | code: fields?["code"] as? String ?? "SERVICE_ERROR", |
| 142 | message: fields?["message"] as? String ?? unavailable.message, |
| 143 | current: current |
| 144 | ) |
| 145 | } |
| 146 | |
| 147 | func stop() { |
| 148 | guard !closed else { return } |
| 149 | closed = true |
| 150 | let writer = input.fileHandleForWriting |
| 151 | io.async { try? writer.close() } |
| 152 | } |
| 153 | |
| 154 | private func didExit(status: Int32) { |
| 155 | let wasClosing = closed |
| 156 | ready = false |
| 157 | closed = true |
| 158 | output.fileHandleForReading.readabilityHandler = nil |
| 159 | for continuation in pending.values { continuation.resume(throwing: unavailable) } |
| 160 | pending.removeAll() |
| 161 | if !wasClosing { |
| 162 | NSLog("OpenTalon workspace service exited with status %d", status) |
| 163 | onFailure?(unavailable) |
| 164 | } |
| 165 | onExit?() |
| 166 | } |
| 167 | } |