import Foundation import RastrilloApple /// One HTTP request to the person API, relative to the instance origin. public struct APIRequest: Sendable, Equatable { public var method: String public var path: String public var query: [URLQueryItem] = [] public var body: Data? public var bearer: String? public var idempotencyKey: String? public var ifMatch: Int64? public var nativeSession: NativeSession? var contentType = "application/json" var contentDisposition: String? var uploadProgress: UploadProgress? var maximumResponseBytes = 4 * 1024 * 1024 public init(_ method: String, _ path: String, query: [URLQueryItem] = [], body: Data? = nil, bearer: String? = nil, idempotencyKey: String? = nil, ifMatch: Int64? = nil, nativeSession: NativeSession? = nil) { self.method = method; self.path = path; self.query = query; self.body = body self.nativeSession = nativeSession self.bearer = bearer; self.idempotencyKey = idempotencyKey; self.ifMatch = ifMatch } /// The request as URLSession sends it. Bearer requests never carry cookies. public func urlRequest(origin: URL) throws -> URLRequest { guard var components = URLComponents(url: origin.appendingPathComponent("api/v1" + path), resolvingAgainstBaseURL: false) else { throw EquipoAPIError.badOrigin } if !query.isEmpty { components.queryItems = query } guard let url = components.url else { throw EquipoAPIError.badOrigin } var r = URLRequest(url: url) r.httpMethod = method r.httpShouldHandleCookies = false r.cachePolicy = .reloadIgnoringLocalAndRemoteCacheData r.timeoutInterval = 30 r.setValue("application/json", forHTTPHeaderField: "Accept") if let body { r.httpBody = body r.setValue(contentType, forHTTPHeaderField: "Content-Type") } if let contentDisposition { r.setValue(contentDisposition, forHTTPHeaderField: "Content-Disposition") } if let nativeSession { // Only the bridge may send a cookie. Engine and pairing requests // stay bearer-only, including after renewal. guard path == "/auth/devices/native", method == "POST", bearer == nil else { throw EquipoAPIError.badOrigin } r.setValue(origin.absoluteString, forHTTPHeaderField: "Origin") r.setValue("\(nativeSession.name)=\(nativeSession.value)", forHTTPHeaderField: "Cookie") } if let bearer { r.setValue("Bearer \(bearer)", forHTTPHeaderField: "Authorization") } if let idempotencyKey { r.setValue(idempotencyKey, forHTTPHeaderField: "Idempotency-Key") } if let ifMatch { r.setValue("\"\(ifMatch)\"", forHTTPHeaderField: "If-Match") } return r } } public struct APIResponse: Sendable { public var status: Int public var data: Data public init(status: Int, data: Data) { self.status = status; self.data = data } } /// What the client needs from the network. Tests use a scripted one. public protocol EquipoTransport: Sendable { var origin: URL { get } /// Returns any status. Throws `EquipoAPIError.offline` when the request /// never reached the server or its answer never came back. func send(_ request: APIRequest) async throws -> APIResponse /// The lines of a streamed response (Server-Sent Events). Throws the /// API error when the stream is refused. func lines(_ request: APIRequest) async throws -> AsyncThrowingStream } /// URLSession, ephemeral: no cookie store, no cache, no redirects. Each /// outcome is reported to RastrilloApple's connectivity, so the offline /// banner follows real traffic. public final class URLSessionTransport: NSObject, EquipoTransport, URLSessionTaskDelegate, @unchecked Sendable { public let origin: URL public static let maxBytes = 4 * 1024 * 1024 private let session: URLSession let streamSession: URLSession let observe: @Sendable (NativeTransportOutcome) -> Void public init(origin: URL, observe: (@Sendable (NativeTransportOutcome) -> Void)? = nil) { self.origin = origin let config = URLSessionConfiguration.ephemeral config.httpCookieStorage = nil config.httpShouldSetCookies = false config.urlCache = nil config.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData config.waitsForConnectivity = false self.observe = observe ?? { outcome in Task { @MainActor in NativeConnectivity.shared.record(outcome, origin: origin) } } let delegate = RedirectRefuser() self.session = URLSession(configuration: config, delegate: delegate, delegateQueue: nil) let streaming = config.copy() as! URLSessionConfiguration streaming.timeoutIntervalForRequest = 60 streaming.timeoutIntervalForResource = 24 * 60 * 60 self.streamSession = URLSession(configuration: streaming, delegate: delegate, delegateQueue: nil) super.init() } public func send(_ request: APIRequest) async throws -> APIResponse { var r = try request.urlRequest(origin: origin) do { let data: Data, response: URLResponse if let progress = request.uploadProgress, let body = request.body { r.httpBody = nil (data, response) = try await session.upload(for: r, from: body, delegate: UploadDelegate(progress)) } else { (data, response) = try await session.data(for: r) } guard let http = response as? HTTPURLResponse else { throw EquipoAPIError.offline } observe(.responded(status: http.statusCode)) guard data.count <= request.maximumResponseBytes else { throw EquipoAPIError.tooLarge } return APIResponse(status: http.statusCode, data: data) } catch let error as URLError where error.code == .cancelled { // This app stopped asking (the stream closed, pairing cancelled): // the team was not unreachable. throw CancellationError() } catch let error as URLError { observe(.offline(error.code)) throw EquipoAPIError.offline } } } extension URLSessionTransport { public func lines(_ request: APIRequest) async throws -> AsyncThrowingStream { var r = try request.urlRequest(origin: origin) r.setValue("text/event-stream", forHTTPHeaderField: "Accept") r.timeoutInterval = 60 let (bytes, response): (URLSession.AsyncBytes, URLResponse) do { (bytes, response) = try await streamSession.bytes(for: r) } catch let error as URLError where error.code == .cancelled { throw CancellationError() } catch let error as URLError { observe(.offline(error.code)); throw EquipoAPIError.offline } guard let http = response as? HTTPURLResponse else { throw EquipoAPIError.offline } observe(.responded(status: http.statusCode)) guard http.statusCode == 200 else { var data = Data() for try await byte in bytes { data.append(byte); if data.count > 64 * 1024 { break } } if let body = try? EquipoJSON.decoder.decode(APIErrorBody.self, from: data) { throw EquipoAPIError.server(status: http.statusCode, body: body) } throw EquipoAPIError.status(http.statusCode) } return AsyncThrowingStream { continuation in let task = Task { do { for try await line in bytes.lines { continuation.yield(line) } continuation.finish() } catch { continuation.finish(throwing: EquipoAPIError.offline) } } continuation.onTermination = { _ in task.cancel() } } } } /// A bearer must never follow a redirect to another place. private final class RedirectRefuser: NSObject, URLSessionTaskDelegate { func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest) async -> URLRequest? { nil } }