import Foundation import RastrilloApple /// Why a call to Base failed, typed so the app can tell an ended session /// from Ask's own states and from the network. public enum BaseAPIError: Error, Sendable, Equatable { /// Base doesn't know the session (`401 {"code":"unauthenticated"}`): /// the client has already told the kit (`sessionRejected()`). case unauthenticated /// The request never reached Base, or its answer never came back. A /// write's outcome is unknown: resend it with the same key. case offline /// Base answered with a status outside 2xx. `state` is Ask's (ask.go: /// `reconnect`, `norunner`, …), `code` the API's (`card_stale`, /// `cursor_expired`, …), when the body says. case server(status: Int, code: String?, state: String?) /// A 2xx whose body isn't what the contract says. case badResponse } /// Base's API for the apps, over the kit's transport: `NativeHTTP` sends /// the native session's cookie and `Origin` (so Base's CSRF check passes) /// and `Accept: application/json`, and refuses redirects. Ask's routes are /// the web's own (P4); the rest are `/api/v1` reads. /// /// Exactly `401 {"code":"unauthenticated"}` is Base refusing the session: /// it calls `rejected` (the kit's `sessionRejected()`) before it throws. /// Any other 401 or a 303 is only thrown. Equipo refusing Base's key for this person is Ask's /// own state, `409 {"state":"reconnect"}`, and is only thrown. public struct BaseClient: Sendable { public let transport: NativeTransport let rejected: @Sendable () async -> Void public init(transport: NativeTransport, rejected: @escaping @Sendable () async -> Void) { self.transport = transport self.rejected = rejected } public var origin: URL { transport.origin } /// What a refused session calls, for tests. func rejectedForTests() async { await rejected() } // MARK: Reads public func me() async throws(BaseAPIError) -> Me { try await get("/api/v1/me") } public func home() async throws(BaseAPIError) -> HomeData { try await get("/api/v1/home") } public func askState() async throws(BaseAPIError) -> AskSnapshot { try await get("/ask/state") } // MARK: Ask's writes (the forms ask.js posts) public func send(_ text: String, key: String) async throws(BaseAPIError) -> AskSent { try await post("/ask/messages", form: [("text", text), ("key", key)]) } public func cancel(turn id: String, key: String) async throws(BaseAPIError) { let _: Ignored = try await post("/ask/turns/\(Self.segment(id))/cancel", form: [("key", key)]) } public func answer(card id: String, choice: String, revision: Int64, key: String) async throws(BaseAPIError) -> AskAnswered { try await post("/ask/cards/\(Self.segment(id))/answer", form: [("revision", String(revision)), ("choice", choice), ("key", key)]) } /// A paused job's "Carry on now", at the revision the person saw. public func carryOn(card id: String, revision: Int64, key: String) async throws(BaseAPIError) -> AskCarriedOn { try await post("/ask/cards/\(Self.segment(id))/carry_on", form: [("revision", String(revision)), ("key", key)]) } /// `POST /api/v1/ask/oficina` (Task 7): connects Ask with an Oficina ID /// assertion addressed to Equipo. `auto`: the app set Ask up by itself /// (at sign-in, a renewal, a reconnect), which Base refuses with /// `409 {"state":"disconnected"}` while the member has disconnected; /// the person's own Set up sends none, and clears that. public func connectAsk(assertion: String, verifier: String, auto: Bool = false) async throws(BaseAPIError) -> AskSetupAnswer { var fields: [String: Any] = ["assertion": assertion, "verifier": verifier] if auto { fields["auto"] = true } let body = try? JSONSerialization.data(withJSONObject: fields) return try await call("/api/v1/ask/oficina", method: "POST", body: body, contentType: "application/json") } // MARK: Settings' forms (the web's own, answering 303 to /settings) /// Settings' Appearance, kept for the member on the web too. public func setAppearance(_ appearance: BaseAppearance) async throws(BaseAPIError) { try await postSettling("/settings/appearance", form: [("theme", appearance.rawValue)]) } /// Settings' Disconnect for Ask, whichever way it was connected. public func disconnectAsk() async throws(BaseAPIError) { try await postSettling("/ask/disconnect", form: []) } /// A form the web answers with `303 /settings` once done. NativeHTTP /// follows no redirect, so the 303 is the answer: to /settings it is /// success; anything else is thrown. func postSettling(_ path: String, form fields: [(String, String)]) async throws(BaseAPIError) { let response: NativeResponse do { response = try await transport.responseDetails(path, method: "POST", body: Data(Self.form(fields).utf8), contentType: "application/x-www-form-urlencoded") } catch { throw await mapped(error) } let location = response.headers["location"] ?? "" if response.status == 303, location == "/settings" || location.hasSuffix("/settings") { return } if (200..<300).contains(response.status) { return } throw await refused(status: response.status, body: response.data) } // MARK: Ask's events /// `GET /ask/events?after=`: Base's relay of the conversation's events, /// each handed to `onEvent` with its id (nil for a live-only glance). /// Returns when the stream ends cleanly (Base ends one after ten /// minutes; reconnect with the last id) and throws as the other calls /// do. `onRetry` hears the stream's `retry:` advice. public func events(after cursor: Int64?, onOpen: @escaping @Sendable () async -> Void = {}, onRetry: @escaping @Sendable (Int) async -> Void = { _ in }, onEvent: @escaping @Sendable (AskEvent, Int64?) async -> Void) async throws(BaseAPIError) { var path = "/ask/events" if let cursor { path += "?after=\(cursor)" } let parser = SSEStream() do { try await transport.stream(path, onOpen: { await onOpen() }) { line in guard let event = await parser.feed(line) else { return } if let retry = event.retry { await onRetry(retry) } guard let decoded = AskEvent.decode(event) else { return } await onEvent(decoded, event.id.flatMap { Int64($0) }) } } catch { throw await mapped(error) } } // MARK: Plumbing struct Ignored: Decodable { init(from decoder: Decoder) throws {} } func get(_ path: String) async throws(BaseAPIError) -> T { try await call(path, method: "GET", body: nil, contentType: "application/json") } func post(_ path: String, form fields: [(String, String)]) async throws(BaseAPIError) -> T { try await call(path, method: "POST", body: Data(Self.form(fields).utf8), contentType: "application/x-www-form-urlencoded") } func call(_ path: String, method: String, body: Data?, contentType: String) async throws(BaseAPIError) -> T { let response: NativeResponse do { response = try await transport.responseDetails(path, method: method, body: body, contentType: contentType) } catch { throw await mapped(error) } guard (200..<300).contains(response.status) else { throw await refused(status: response.status, body: response.data) } do { return try JSONDecoder().decode(T.self, from: response.data) } catch { throw .badResponse } } /// The error for a status outside 2xx, telling the kit first if it is /// Base refusing the session. func refused(status: Int, body: Data) async -> BaseAPIError { let fields = (try? JSONSerialization.jsonObject(with: body)) as? [String: Any] let code = fields?["code"] as? String, state = fields?["state"] as? String // Only exactly 401 {"code":"unauthenticated"} is Base ending the // session (the contract); any other 401, or a redirect, is not. if status == 401, code == "unauthenticated" { await rejected() return .unauthenticated } return .server(status: status, code: code, state: state) } func mapped(_ error: Error) async -> BaseAPIError { if let error = error as? BaseAPIError { return error } switch error as? NativeClientError { case .offline?: return .offline case .unauthorized?: // The kit's stream refusal carries no body: it can't say whether // this is Base ending the session. The caller reads /ask/state // afresh, whose answer says. return .server(status: 401, code: nil, state: nil) case .conflict(let body)?: return await refused(status: 409, body: body) case .rejected(let status, let body)?: return await refused(status: status, body: body) case .server(let status)?: return .server(status: status, code: nil, state: nil) case .forbidden?: return .server(status: 403, code: nil, state: nil) case .notFound?: return .server(status: 404, code: nil, state: nil) case .tooLarge?: return .server(status: 413, code: nil, state: nil) case .rateLimited?: return .server(status: 429, code: nil, state: nil) case .transport?: return .offline default: return .badResponse } } /// `application/x-www-form-urlencoded`, as a browser's form posts it. static func form(_ fields: [(String, String)]) -> String { var allowed = CharacterSet.alphanumerics allowed.insert(charactersIn: "-._*") return fields.map { name, value in let v = value.addingPercentEncoding(withAllowedCharacters: allowed) ?? "" return "\(name)=\(v)" }.joined(separator: "&") } /// One path segment, escaped. static func segment(_ id: String) -> String { var allowed = CharacterSet.alphanumerics allowed.insert(charactersIn: "-._~") return id.addingPercentEncoding(withAllowedCharacters: allowed) ?? "" } /// A fresh idempotency key: 16 random bytes in hex, as ask.js makes one. public static func newKey() -> String { var bytes = [UInt8](repeating: 0, count: 16) for i in bytes.indices { bytes[i] = UInt8.random(in: .min ... .max) } return bytes.map { String(format: "%02x", $0) }.joined() } } /// The SSE parser behind one stream, shared by its line callbacks. actor SSEStream { private var parser = SSEParser() func feed(_ line: String) -> SSEEvent? { parser.feed(line) } }