| 1 | import Foundation |
| 2 | |
| 3 | /// A write that must be retried as itself: the same key, body and revision |
| 4 | /// until its result is known (equipo-v1.md, "Retry writes"). Keep it until |
| 5 | /// the call returns a result or a definite error; resend it after `.offline`. |
| 6 | public struct PendingWrite: Sendable, Equatable, Codable { |
| 7 | public let key: String |
| 8 | public let body: Data |
| 9 | public let ifMatch: Int64? |
| 10 | public init(body: Data, ifMatch: Int64? = nil, key: String = UUID().uuidString.lowercased()) { |
| 11 | self.key = key; self.body = body; self.ifMatch = ifMatch |
| 12 | } |
| 13 | public static func json<T: Encodable>(_ value: T, ifMatch: Int64? = nil) throws -> PendingWrite { |
| 14 | PendingWrite(body: try EquipoJSON.encoder.encode(value), ifMatch: ifMatch) |
| 15 | } |
| 16 | } |
| 17 | |
| 18 | /// The person API, for one instance and one device credential. |
| 19 | public struct EquipoClient: Sendable { |
| 20 | public let transport: EquipoTransport |
| 21 | public let token: String? |
| 22 | |
| 23 | public init(transport: EquipoTransport, token: String?) { |
| 24 | self.transport = transport; self.token = token |
| 25 | } |
| 26 | public var origin: URL { transport.origin } |
| 27 | |
| 28 | // MARK: Reads (the conversation engine, as a device bearer reads it) |
| 29 | |
| 30 | public func me() async throws -> Me { try await get("/me") } |
| 31 | public func snapshot() async throws -> Snapshot { try await get("/snapshot") } |
| 32 | public func olderMessages(before: String, limit: Int = 50) async throws -> MessagePage { |
| 33 | try await get("/messages", [URLQueryItem(name: "before", value: before), URLQueryItem(name: "limit", value: String(min(max(limit, 1), 200)))]) |
| 34 | } |
| 35 | public func tasks() async throws -> ThinList<ThinTask> { try await get("/tasks") } |
| 36 | public func needsYou() async throws -> ThinList<ThinTask> { try await get("/needs-you") } |
| 37 | public func task(_ id: String) async throws -> ThinTask { try await get("/tasks/\(escape(id))") } |
| 38 | public func projects() async throws -> ProjectList { try await get("/projects") } |
| 39 | public func devices() async throws -> Page<Device> { try await get("/auth/devices") } |
| 40 | |
| 41 | /// The conversation's events after `cursor`, as Server-Sent Event lines. |
| 42 | public func events(after cursor: Int64) async throws -> AsyncThrowingStream<String, Error> { |
| 43 | try await transport.lines(APIRequest("GET", "/events", query: [URLQueryItem(name: "after", value: String(cursor))], bearer: token)) |
| 44 | } |
| 45 | |
| 46 | // MARK: Writes. Each takes a PendingWrite so a retry is the same request. |
| 47 | |
| 48 | /// A message; the engine takes its key in the body as well as the header. |
| 49 | public static func message(_ text: String, projectID: String? = nil, attachments: [String] = []) throws -> PendingWrite { |
| 50 | let key = UUID().uuidString.lowercased() |
| 51 | var body: [String: AnyEncodable] = ["text": .init(text), "idempotency_key": .init(key)] |
| 52 | guard attachments.count <= AttachmentLimits.maxCount, Set(attachments).count == attachments.count else { throw EquipoAPIError.status(422) } |
| 53 | if let projectID { body["project_id"] = .init(projectID) } |
| 54 | if !attachments.isEmpty { body["attachments"] = .init(attachments) } |
| 55 | return PendingWrite(body: try EquipoJSON.encoder.encode(body), key: key) |
| 56 | } |
| 57 | public func send(_ write: PendingWrite) async throws -> Sent { try await post("/messages", write) } |
| 58 | public func postThread(task taskID: String, _ write: PendingWrite) async throws -> ThreadEntry { |
| 59 | try await post("/tasks/\(escape(taskID))/thread", write) |
| 60 | } |
| 61 | |
| 62 | /// An answer to a card, bound to the card revision the person saw. |
| 63 | public static func answer(_ choice: String, note: String? = nil, rememberName: String? = nil, to card: ThinCard) throws -> PendingWrite { |
| 64 | var body: [String: AnyEncodable] = ["choice": .init(choice), "revision": .init(card.revision)] |
| 65 | if let note, !note.isEmpty { body["note"] = .init(note) } |
| 66 | if let rememberName { body["remember_name"] = .init(rememberName) } |
| 67 | return PendingWrite(body: try EquipoJSON.encoder.encode(body), ifMatch: card.revision) |
| 68 | } |
| 69 | public func answer(card id: String, _ write: PendingWrite) async throws -> Answered { |
| 70 | guard write.ifMatch != nil else { throw EquipoAPIError.status(428) } |
| 71 | return try await post("/cards/\(escape(id))/answer", write) |
| 72 | } |
| 73 | /// Stops the coordinator's turn; only that turn. |
| 74 | /// POST /tasks/{id}/run-now: Run now on the held step at its revision. |
| 75 | public func runNow(task id: String, step: String, revision: Int64, offer: String) async throws -> RunNowAccepted { |
| 76 | try await post("/tasks/\(escape(id))/run-now", try .json(RunNowInput(step: step, stepRevision: revision, offer: offer))) |
| 77 | } |
| 78 | /// PUT /time-zone: this device's IANA zone. |
| 79 | public func setTimeZone(_ zone: String) async throws -> TimeZoneValue { |
| 80 | try await send(APIRequest("PUT", "/time-zone", body: try EquipoJSON.encoder.encode(TimeZoneValue(timeZone: zone)), bearer: token)) |
| 81 | } |
| 82 | public func cancelTurn(_ id: String) async throws { |
| 83 | let _: EmptyResponse = try await post("/turns/\(escape(id))/cancel", PendingWrite(body: Data("{}".utf8))) |
| 84 | } |
| 85 | |
| 86 | public func revokeDevice(_ id: String, _ write: PendingWrite) async throws -> Ack { |
| 87 | try await send(APIRequest("DELETE", "/auth/devices/\(escape(id))", body: write.body, bearer: token, |
| 88 | idempotencyKey: write.key, ifMatch: write.ifMatch)) |
| 89 | } |
| 90 | public static func empty(ifMatch: Int64? = nil) -> PendingWrite { PendingWrite(body: Data("{}".utf8), ifMatch: ifMatch) } |
| 91 | |
| 92 | // MARK: Pairing. No bearer: the device has none yet. |
| 93 | |
| 94 | public func beginDevice(_ write: PendingWrite) async throws -> DeviceChallenge { |
| 95 | try await send(APIRequest("POST", "/auth/devices", body: write.body, idempotencyKey: write.key)) |
| 96 | } |
| 97 | public func exchangeDevice(_ write: PendingWrite) async throws -> DeviceCredential { |
| 98 | try await send(APIRequest("POST", "/auth/devices/exchange", body: write.body, idempotencyKey: write.key)) |
| 99 | } |
| 100 | |
| 101 | // MARK: Plumbing |
| 102 | |
| 103 | func escape(_ id: String) -> String { |
| 104 | id.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed.subtracting(CharacterSet(charactersIn: "/"))) ?? id |
| 105 | } |
| 106 | func get<T: Decodable>(_ path: String, _ query: [URLQueryItem] = []) async throws -> T { |
| 107 | try await send(APIRequest("GET", path, query: query, bearer: token)) |
| 108 | } |
| 109 | func post<T: Decodable>(_ path: String, _ write: PendingWrite) async throws -> T { |
| 110 | try await send(APIRequest("POST", path, body: write.body, bearer: token, idempotencyKey: write.key, ifMatch: write.ifMatch)) |
| 111 | } |
| 112 | func send<T: Decodable>(_ request: APIRequest) async throws -> T { |
| 113 | if T.self == EmptyResponse.self { |
| 114 | let response = try await transport.send(request) |
| 115 | guard (200..<300).contains(response.status) else { throw Self.error(response) } |
| 116 | return EmptyResponse() as! T |
| 117 | } |
| 118 | let response = try await transport.send(request) |
| 119 | guard (200..<300).contains(response.status) else { throw Self.error(response) } |
| 120 | do { return try EquipoJSON.decoder.decode(T.self, from: response.data) } |
| 121 | catch { throw EquipoAPIError.undecodable } |
| 122 | } |
| 123 | |
| 124 | static func error(_ response: APIResponse) -> EquipoAPIError { |
| 125 | if let conflict = try? EquipoJSON.decoder.decode(CardConflict.self, from: response.data) { |
| 126 | return .card(status: response.status, code: conflict.code, card: conflict.card) |
| 127 | } |
| 128 | if let body = try? EquipoJSON.decoder.decode(APIErrorBody.self, from: response.data) { |
| 129 | return .server(status: response.status, body: body) |
| 130 | } |
| 131 | return .status(response.status) |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | public struct EmptyResponse: Decodable, Sendable { public init() {} } |
| 136 | |
| 137 | /// Lets one JSON body mix strings and numbers. |
| 138 | public struct AnyEncodable: Encodable, Sendable { |
| 139 | private let encodeValue: @Sendable (Encoder) throws -> Void |
| 140 | public init<T: Encodable & Sendable>(_ value: T) { encodeValue = { try value.encode(to: $0) } } |
| 141 | public func encode(to encoder: Encoder) throws { try encodeValue(encoder) } |
| 142 | } |
| 143 | |