oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1import Foundation
2import RastrilloApple
3
4/// One HTTP request to the person API, relative to the instance origin.
5public struct APIRequest: Sendable, Equatable {
6 public var method: String
7 public var path: String
8 public var query: [URLQueryItem] = []
9 public var body: Data?
10 public var bearer: String?
11 public var idempotencyKey: String?
12 public var ifMatch: Int64?
13 public var nativeSession: NativeSession?
14 var contentType = "application/json"
15 var contentDisposition: String?
16 var uploadProgress: UploadProgress?
17 var maximumResponseBytes = 4 * 1024 * 1024
18
19 public init(_ method: String, _ path: String, query: [URLQueryItem] = [], body: Data? = nil,
20 bearer: String? = nil, idempotencyKey: String? = nil, ifMatch: Int64? = nil, nativeSession: NativeSession? = nil) {
21 self.method = method; self.path = path; self.query = query; self.body = body
22 self.nativeSession = nativeSession
23 self.bearer = bearer; self.idempotencyKey = idempotencyKey; self.ifMatch = ifMatch
24 }
25
26 /// The request as URLSession sends it. Bearer requests never carry cookies.
27 public func urlRequest(origin: URL) throws -> URLRequest {
28 guard var components = URLComponents(url: origin.appendingPathComponent("api/v1" + path), resolvingAgainstBaseURL: false) else {
29 throw EquipoAPIError.badOrigin
30 }
31 if !query.isEmpty { components.queryItems = query }
32 guard let url = components.url else { throw EquipoAPIError.badOrigin }
33 var r = URLRequest(url: url)
34 r.httpMethod = method
35 r.httpShouldHandleCookies = false
36 r.cachePolicy = .reloadIgnoringLocalAndRemoteCacheData
37 r.timeoutInterval = 30
38 r.setValue("application/json", forHTTPHeaderField: "Accept")
39 if let body {
40 r.httpBody = body
41 r.setValue(contentType, forHTTPHeaderField: "Content-Type")
42 }
43 if let contentDisposition { r.setValue(contentDisposition, forHTTPHeaderField: "Content-Disposition") }
44 if let nativeSession {
45 // Only the bridge may send a cookie. Engine and pairing requests
46 // stay bearer-only, including after renewal.
47 guard path == "/auth/devices/native", method == "POST", bearer == nil else { throw EquipoAPIError.badOrigin }
48 r.setValue(origin.absoluteString, forHTTPHeaderField: "Origin")
49 r.setValue("\(nativeSession.name)=\(nativeSession.value)", forHTTPHeaderField: "Cookie")
50 }
51 if let bearer { r.setValue("Bearer \(bearer)", forHTTPHeaderField: "Authorization") }
52 if let idempotencyKey { r.setValue(idempotencyKey, forHTTPHeaderField: "Idempotency-Key") }
53 if let ifMatch { r.setValue("\"\(ifMatch)\"", forHTTPHeaderField: "If-Match") }
54 return r
55 }
56}
57
58public struct APIResponse: Sendable {
59 public var status: Int
60 public var data: Data
61 public init(status: Int, data: Data) { self.status = status; self.data = data }
62}
63
64/// What the client needs from the network. Tests use a scripted one.
65public protocol EquipoTransport: Sendable {
66 var origin: URL { get }
67 /// Returns any status. Throws `EquipoAPIError.offline` when the request
68 /// never reached the server or its answer never came back.
69 func send(_ request: APIRequest) async throws -> APIResponse
70 /// The lines of a streamed response (Server-Sent Events). Throws the
71 /// API error when the stream is refused.
72 func lines(_ request: APIRequest) async throws -> AsyncThrowingStream<String, Error>
73}
74
75/// URLSession, ephemeral: no cookie store, no cache, no redirects. Each
76/// outcome is reported to RastrilloApple's connectivity, so the offline
77/// banner follows real traffic.
78public final class URLSessionTransport: NSObject, EquipoTransport, URLSessionTaskDelegate, @unchecked Sendable {
79 public let origin: URL
80 public static let maxBytes = 4 * 1024 * 1024
81 private let session: URLSession
82 let streamSession: URLSession
83 let observe: @Sendable (NativeTransportOutcome) -> Void
84
85 public init(origin: URL, observe: (@Sendable (NativeTransportOutcome) -> Void)? = nil) {
86 self.origin = origin
87 let config = URLSessionConfiguration.ephemeral
88 config.httpCookieStorage = nil
89 config.httpShouldSetCookies = false
90 config.urlCache = nil
91 config.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData
92 config.waitsForConnectivity = false
93 self.observe = observe ?? { outcome in Task { @MainActor in NativeConnectivity.shared.record(outcome, origin: origin) } }
94 let delegate = RedirectRefuser()
95 self.session = URLSession(configuration: config, delegate: delegate, delegateQueue: nil)
96 let streaming = config.copy() as! URLSessionConfiguration
97 streaming.timeoutIntervalForRequest = 60
98 streaming.timeoutIntervalForResource = 24 * 60 * 60
99 self.streamSession = URLSession(configuration: streaming, delegate: delegate, delegateQueue: nil)
100 super.init()
101 }
102
103 public func send(_ request: APIRequest) async throws -> APIResponse {
104 var r = try request.urlRequest(origin: origin)
105 do {
106 let data: Data, response: URLResponse
107 if let progress = request.uploadProgress, let body = request.body {
108 r.httpBody = nil
109 (data, response) = try await session.upload(for: r, from: body, delegate: UploadDelegate(progress))
110 } else { (data, response) = try await session.data(for: r) }
111 guard let http = response as? HTTPURLResponse else { throw EquipoAPIError.offline }
112 observe(.responded(status: http.statusCode))
113 guard data.count <= request.maximumResponseBytes else { throw EquipoAPIError.tooLarge }
114 return APIResponse(status: http.statusCode, data: data)
115 } catch let error as URLError where error.code == .cancelled {
116 // This app stopped asking (the stream closed, pairing cancelled):
117 // the team was not unreachable.
118 throw CancellationError()
119 } catch let error as URLError {
120 observe(.offline(error.code))
121 throw EquipoAPIError.offline
122 }
123 }
124}
125
126extension URLSessionTransport {
127 public func lines(_ request: APIRequest) async throws -> AsyncThrowingStream<String, Error> {
128 var r = try request.urlRequest(origin: origin)
129 r.setValue("text/event-stream", forHTTPHeaderField: "Accept")
130 r.timeoutInterval = 60
131 let (bytes, response): (URLSession.AsyncBytes, URLResponse)
132 do { (bytes, response) = try await streamSession.bytes(for: r) }
133 catch let error as URLError where error.code == .cancelled { throw CancellationError() }
134 catch let error as URLError { observe(.offline(error.code)); throw EquipoAPIError.offline }
135 guard let http = response as? HTTPURLResponse else { throw EquipoAPIError.offline }
136 observe(.responded(status: http.statusCode))
137 guard http.statusCode == 200 else {
138 var data = Data()
139 for try await byte in bytes { data.append(byte); if data.count > 64 * 1024 { break } }
140 if let body = try? EquipoJSON.decoder.decode(APIErrorBody.self, from: data) { throw EquipoAPIError.server(status: http.statusCode, body: body) }
141 throw EquipoAPIError.status(http.statusCode)
142 }
143 return AsyncThrowingStream { continuation in
144 let task = Task {
145 do {
146 for try await line in bytes.lines { continuation.yield(line) }
147 continuation.finish()
148 } catch { continuation.finish(throwing: EquipoAPIError.offline) }
149 }
150 continuation.onTermination = { _ in task.cancel() }
151 }
152 }
153}
154
155/// A bearer must never follow a redirect to another place.
156private final class RedirectRefuser: NSObject, URLSessionTaskDelegate {
157 func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse,
158 newRequest request: URLRequest) async -> URLRequest? { nil }
159}
160