| 1 | import Foundation |
| 2 | import RastrilloApple |
| 3 | |
| 4 | /// Why a call to Base failed, typed so the app can tell an ended session |
| 5 | /// from Ask's own states and from the network. |
| 6 | public enum BaseAPIError: Error, Sendable, Equatable { |
| 7 | /// Base doesn't know the session (`401 {"code":"unauthenticated"}`): |
| 8 | /// the client has already told the kit (`sessionRejected()`). |
| 9 | case unauthenticated |
| 10 | /// The request never reached Base, or its answer never came back. A |
| 11 | /// write's outcome is unknown: resend it with the same key. |
| 12 | case offline |
| 13 | /// Base answered with a status outside 2xx. `state` is Ask's (ask.go: |
| 14 | /// `reconnect`, `norunner`, …), `code` the API's (`card_stale`, |
| 15 | /// `cursor_expired`, …), when the body says. |
| 16 | case server(status: Int, code: String?, state: String?) |
| 17 | /// A 2xx whose body isn't what the contract says. |
| 18 | case badResponse |
| 19 | } |
| 20 | |
| 21 | /// Base's API for the apps, over the kit's transport: `NativeHTTP` sends |
| 22 | /// the native session's cookie and `Origin` (so Base's CSRF check passes) |
| 23 | /// and `Accept: application/json`, and refuses redirects. Ask's routes are |
| 24 | /// the web's own (P4); the rest are `/api/v1` reads. |
| 25 | /// |
| 26 | /// Exactly `401 {"code":"unauthenticated"}` is Base refusing the session: |
| 27 | /// it calls `rejected` (the kit's `sessionRejected()`) before it throws. |
| 28 | /// Any other 401 or a 303 is only thrown. Equipo refusing Base's key for this person is Ask's |
| 29 | /// own state, `409 {"state":"reconnect"}`, and is only thrown. |
| 30 | public struct BaseClient: Sendable { |
| 31 | public let transport: NativeTransport |
| 32 | let rejected: @Sendable () async -> Void |
| 33 | |
| 34 | public init(transport: NativeTransport, rejected: @escaping @Sendable () async -> Void) { |
| 35 | self.transport = transport |
| 36 | self.rejected = rejected |
| 37 | } |
| 38 | |
| 39 | public var origin: URL { transport.origin } |
| 40 | |
| 41 | /// What a refused session calls, for tests. |
| 42 | func rejectedForTests() async { await rejected() } |
| 43 | |
| 44 | // MARK: Reads |
| 45 | |
| 46 | public func me() async throws(BaseAPIError) -> Me { try await get("/api/v1/me") } |
| 47 | public func home() async throws(BaseAPIError) -> HomeData { try await get("/api/v1/home") } |
| 48 | public func askState() async throws(BaseAPIError) -> AskSnapshot { try await get("/ask/state") } |
| 49 | |
| 50 | // MARK: Ask's writes (the forms ask.js posts) |
| 51 | |
| 52 | public func send(_ text: String, key: String) async throws(BaseAPIError) -> AskSent { |
| 53 | try await post("/ask/messages", form: [("text", text), ("key", key)]) |
| 54 | } |
| 55 | |
| 56 | public func cancel(turn id: String, key: String) async throws(BaseAPIError) { |
| 57 | let _: Ignored = try await post("/ask/turns/\(Self.segment(id))/cancel", form: [("key", key)]) |
| 58 | } |
| 59 | |
| 60 | public func answer(card id: String, choice: String, revision: Int64, key: String) async throws(BaseAPIError) -> AskAnswered { |
| 61 | try await post("/ask/cards/\(Self.segment(id))/answer", form: [("revision", String(revision)), ("choice", choice), ("key", key)]) |
| 62 | } |
| 63 | |
| 64 | /// A paused job's "Carry on now", at the revision the person saw. |
| 65 | public func carryOn(card id: String, revision: Int64, key: String) async throws(BaseAPIError) -> AskCarriedOn { |
| 66 | try await post("/ask/cards/\(Self.segment(id))/carry_on", form: [("revision", String(revision)), ("key", key)]) |
| 67 | } |
| 68 | |
| 69 | /// `POST /api/v1/ask/oficina` (Task 7): connects Ask with an Oficina ID |
| 70 | /// assertion addressed to Equipo. `auto`: the app set Ask up by itself |
| 71 | /// (at sign-in, a renewal, a reconnect), which Base refuses with |
| 72 | /// `409 {"state":"disconnected"}` while the member has disconnected; |
| 73 | /// the person's own Set up sends none, and clears that. |
| 74 | public func connectAsk(assertion: String, verifier: String, auto: Bool = false) async throws(BaseAPIError) -> AskSetupAnswer { |
| 75 | var fields: [String: Any] = ["assertion": assertion, "verifier": verifier] |
| 76 | if auto { fields["auto"] = true } |
| 77 | let body = try? JSONSerialization.data(withJSONObject: fields) |
| 78 | return try await call("/api/v1/ask/oficina", method: "POST", body: body, contentType: "application/json") |
| 79 | } |
| 80 | |
| 81 | // MARK: Settings' forms (the web's own, answering 303 to /settings) |
| 82 | |
| 83 | /// Settings' Appearance, kept for the member on the web too. |
| 84 | public func setAppearance(_ appearance: BaseAppearance) async throws(BaseAPIError) { |
| 85 | try await postSettling("/settings/appearance", form: [("theme", appearance.rawValue)]) |
| 86 | } |
| 87 | |
| 88 | /// Settings' Disconnect for Ask, whichever way it was connected. |
| 89 | public func disconnectAsk() async throws(BaseAPIError) { |
| 90 | try await postSettling("/ask/disconnect", form: []) |
| 91 | } |
| 92 | |
| 93 | /// A form the web answers with `303 /settings` once done. NativeHTTP |
| 94 | /// follows no redirect, so the 303 is the answer: to /settings it is |
| 95 | /// success; anything else is thrown. |
| 96 | func postSettling(_ path: String, form fields: [(String, String)]) async throws(BaseAPIError) { |
| 97 | let response: NativeResponse |
| 98 | do { |
| 99 | response = try await transport.responseDetails(path, method: "POST", body: Data(Self.form(fields).utf8), |
| 100 | contentType: "application/x-www-form-urlencoded") |
| 101 | } catch { |
| 102 | throw await mapped(error) |
| 103 | } |
| 104 | let location = response.headers["location"] ?? "" |
| 105 | if response.status == 303, location == "/settings" || location.hasSuffix("/settings") { return } |
| 106 | if (200..<300).contains(response.status) { return } |
| 107 | throw await refused(status: response.status, body: response.data) |
| 108 | } |
| 109 | |
| 110 | // MARK: Ask's events |
| 111 | |
| 112 | /// `GET /ask/events?after=`: Base's relay of the conversation's events, |
| 113 | /// each handed to `onEvent` with its id (nil for a live-only glance). |
| 114 | /// Returns when the stream ends cleanly (Base ends one after ten |
| 115 | /// minutes; reconnect with the last id) and throws as the other calls |
| 116 | /// do. `onRetry` hears the stream's `retry:` advice. |
| 117 | public func events(after cursor: Int64?, onOpen: @escaping @Sendable () async -> Void = {}, |
| 118 | onRetry: @escaping @Sendable (Int) async -> Void = { _ in }, |
| 119 | onEvent: @escaping @Sendable (AskEvent, Int64?) async -> Void) async throws(BaseAPIError) { |
| 120 | var path = "/ask/events" |
| 121 | if let cursor { path += "?after=\(cursor)" } |
| 122 | let parser = SSEStream() |
| 123 | do { |
| 124 | try await transport.stream(path, onOpen: { await onOpen() }) { line in |
| 125 | guard let event = await parser.feed(line) else { return } |
| 126 | if let retry = event.retry { await onRetry(retry) } |
| 127 | guard let decoded = AskEvent.decode(event) else { return } |
| 128 | await onEvent(decoded, event.id.flatMap { Int64($0) }) |
| 129 | } |
| 130 | } catch { |
| 131 | throw await mapped(error) |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | // MARK: Plumbing |
| 136 | |
| 137 | struct Ignored: Decodable { init(from decoder: Decoder) throws {} } |
| 138 | |
| 139 | func get<T: Decodable>(_ path: String) async throws(BaseAPIError) -> T { |
| 140 | try await call(path, method: "GET", body: nil, contentType: "application/json") |
| 141 | } |
| 142 | |
| 143 | func post<T: Decodable>(_ path: String, form fields: [(String, String)]) async throws(BaseAPIError) -> T { |
| 144 | try await call(path, method: "POST", body: Data(Self.form(fields).utf8), contentType: "application/x-www-form-urlencoded") |
| 145 | } |
| 146 | |
| 147 | func call<T: Decodable>(_ path: String, method: String, body: Data?, contentType: String) async throws(BaseAPIError) -> T { |
| 148 | let response: NativeResponse |
| 149 | do { |
| 150 | response = try await transport.responseDetails(path, method: method, body: body, contentType: contentType) |
| 151 | } catch { |
| 152 | throw await mapped(error) |
| 153 | } |
| 154 | guard (200..<300).contains(response.status) else { |
| 155 | throw await refused(status: response.status, body: response.data) |
| 156 | } |
| 157 | do { return try JSONDecoder().decode(T.self, from: response.data) } catch { throw .badResponse } |
| 158 | } |
| 159 | |
| 160 | /// The error for a status outside 2xx, telling the kit first if it is |
| 161 | /// Base refusing the session. |
| 162 | func refused(status: Int, body: Data) async -> BaseAPIError { |
| 163 | let fields = (try? JSONSerialization.jsonObject(with: body)) as? [String: Any] |
| 164 | let code = fields?["code"] as? String, state = fields?["state"] as? String |
| 165 | // Only exactly 401 {"code":"unauthenticated"} is Base ending the |
| 166 | // session (the contract); any other 401, or a redirect, is not. |
| 167 | if status == 401, code == "unauthenticated" { |
| 168 | await rejected() |
| 169 | return .unauthenticated |
| 170 | } |
| 171 | return .server(status: status, code: code, state: state) |
| 172 | } |
| 173 | |
| 174 | func mapped(_ error: Error) async -> BaseAPIError { |
| 175 | if let error = error as? BaseAPIError { return error } |
| 176 | switch error as? NativeClientError { |
| 177 | case .offline?: return .offline |
| 178 | case .unauthorized?: |
| 179 | // The kit's stream refusal carries no body: it can't say whether |
| 180 | // this is Base ending the session. The caller reads /ask/state |
| 181 | // afresh, whose answer says. |
| 182 | return .server(status: 401, code: nil, state: nil) |
| 183 | case .conflict(let body)?: return await refused(status: 409, body: body) |
| 184 | case .rejected(let status, let body)?: return await refused(status: status, body: body) |
| 185 | case .server(let status)?: return .server(status: status, code: nil, state: nil) |
| 186 | case .forbidden?: return .server(status: 403, code: nil, state: nil) |
| 187 | case .notFound?: return .server(status: 404, code: nil, state: nil) |
| 188 | case .tooLarge?: return .server(status: 413, code: nil, state: nil) |
| 189 | case .rateLimited?: return .server(status: 429, code: nil, state: nil) |
| 190 | case .transport?: return .offline |
| 191 | default: return .badResponse |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | /// `application/x-www-form-urlencoded`, as a browser's form posts it. |
| 196 | static func form(_ fields: [(String, String)]) -> String { |
| 197 | var allowed = CharacterSet.alphanumerics |
| 198 | allowed.insert(charactersIn: "-._*") |
| 199 | return fields.map { name, value in |
| 200 | let v = value.addingPercentEncoding(withAllowedCharacters: allowed) ?? "" |
| 201 | return "\(name)=\(v)" |
| 202 | }.joined(separator: "&") |
| 203 | } |
| 204 | |
| 205 | /// One path segment, escaped. |
| 206 | static func segment(_ id: String) -> String { |
| 207 | var allowed = CharacterSet.alphanumerics |
| 208 | allowed.insert(charactersIn: "-._~") |
| 209 | return id.addingPercentEncoding(withAllowedCharacters: allowed) ?? "" |
| 210 | } |
| 211 | |
| 212 | /// A fresh idempotency key: 16 random bytes in hex, as ask.js makes one. |
| 213 | public static func newKey() -> String { |
| 214 | var bytes = [UInt8](repeating: 0, count: 16) |
| 215 | for i in bytes.indices { bytes[i] = UInt8.random(in: .min ... .max) } |
| 216 | return bytes.map { String(format: "%02x", $0) }.joined() |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | /// The SSE parser behind one stream, shared by its line callbacks. |
| 221 | actor SSEStream { |
| 222 | private var parser = SSEParser() |
| 223 | func feed(_ line: String) -> SSEEvent? { parser.feed(line) } |
| 224 | } |
| 225 | |