Repository Public
1import Foundation2import HTTPTypes3import OpenAPIRuntime45/// Per-call options carried through the generated client by a task local (the generated operations have no6/// room for them).7public struct RequestContext: Sendable {8 /// Setup-transaction token of an exchanged invitation (`X-MCC-Setup-Transaction`). Kept in memory only.9 public var setupToken: String?10 /// False for the setup flow of a new account, which must not be confused with an existing session.11 public var includeBearer = true12 @TaskLocal public static var current = RequestContext()13}1415extension HTTPField.Name {16 static let setupTransaction = HTTPField.Name("X-MCC-Setup-Transaction")!17 static let correlationID = HTTPField.Name("X-Correlation-Id")!18}1920enum OperationSets {21 /// Operations that never carry a bearer token.22 static let publicOperations: Set<String> = [23 "beginAuthentication", "finishAuthentication", "refreshSession", "exchangeInvitation",24 "getLiveness", "getReadiness", "getVersion",25 ]26 /// Non-GET operations that stay allowed while the client believes it is offline: identity only. Everything else27 /// (actions, edits) is refused locally — no dangerous operation is ever queued for later.28 static let allowedOffline: Set<String> = [29 "beginAuthentication", "finishAuthentication", "refreshSession", "exchangeInvitation", "logout",30 "beginStepUp", "finishStepUp", "beginRegistration", "finishRegistration", "setInvitationProfile",31 "abandonInvitationTransaction", "linkInvitationToAccount",32 ]33}3435/// Outermost middleware: turns every non-2xx response into a thrown `APIError` (code, message, details,36/// correlation id), records reachability and refuses mutations while offline.37struct ErrorMappingMiddleware: ClientMiddleware {38 let connectivity: Connectivity39 let guardOffline: Bool4041 func intercept(_ request: HTTPRequest, body: HTTPBody?, baseURL: URL, operationID: String,42 next: @Sendable (HTTPRequest, HTTPBody?, URL) async throws -> (HTTPResponse, HTTPBody?)) async throws -> (HTTPResponse, HTTPBody?) {43 if guardOffline, request.method != .get, connectivity.isOffline, !OperationSets.allowedOffline.contains(operationID) {44 throw APIError.offline45 }46 let response: HTTPResponse, responseBody: HTTPBody?47 do {48 (response, responseBody) = try await next(request, body, baseURL)49 } catch {50 let e = APIError.from(error)51 if e.isTransport { connectivity.recordTransportFailure() }52 throw e53 }54 connectivity.recordResponse()55 guard response.status.code >= 400 else { return (response, responseBody) }56 var data = Data()57 if let responseBody { data = (try? await Data(collecting: responseBody, upTo: 1 << 20)) ?? Data() }58 throw Self.decode(status: response.status.code, headers: response.headerFields, body: data)59 }6061 static func decode(status: Int, headers: HTTPFields, body: Data) -> APIError {62 struct Envelope: Decodable {63 struct Body: Decodable {64 var code: String65 var message: String66 var details: [String: JSONValue]?67 var correlation_id: String?68 }69 var error: Body70 }71 let headerCorrelation = headers[.correlationID]72 let retryAfter = headers[.retryAfter].flatMap(TimeInterval.init)73 if let env = try? JSONDecoder().decode(Envelope.self, from: body) {74 return APIError(status: status, code: env.error.code, message: env.error.message,75 correlationID: env.error.correlation_id ?? headerCorrelation, details: env.error.details, retryAfter: retryAfter)76 }77 // Not our envelope (a proxy answered, or the body is empty): keep what is known, invent nothing.78 return APIError(status: status, code: "http_\(status)", message: HTTPURLResponse.localizedString(forStatusCode: status),79 correlationID: headerCorrelation, retryAfter: retryAfter)80 }81}8283/// Retries idempotent GETs only (transport failures and 502/503/504), with jittered exponential backoff.84/// Mutations are never retried: the caller decides, with the same `Idempotency-Key` where the contract has one.85struct RetryMiddleware: ClientMiddleware {86 var maxAttempts = 387 var backoff = Backoff(base: 0.25, cap: 2)8889 func intercept(_ request: HTTPRequest, body: HTTPBody?, baseURL: URL, operationID: String,90 next: @Sendable (HTTPRequest, HTTPBody?, URL) async throws -> (HTTPResponse, HTTPBody?)) async throws -> (HTTPResponse, HTTPBody?) {91 guard request.method == .get, maxAttempts > 1 else { return try await next(request, body, baseURL) }92 var attempt = 193 while true {94 do {95 let (response, responseBody) = try await next(request, nil, baseURL)96 if [502, 503, 504].contains(response.status.code), attempt < maxAttempts {97 // fall through to the backoff98 } else {99 return (response, responseBody)100 }101 } catch {102 let e = APIError.from(error)103 if !e.isTransport || attempt >= maxAttempts { throw error }104 }105 try await Task.sleep(for: .seconds(backoff.delay(attempt: attempt)))106 attempt += 1107 }108 }109}110111/// Bearer injection and the single-flight refresh on `401`.112struct AuthMiddleware: ClientMiddleware {113 let tokens: TokenManager114115 func intercept(_ request: HTTPRequest, body: HTTPBody?, baseURL: URL, operationID: String,116 next: @Sendable (HTTPRequest, HTTPBody?, URL) async throws -> (HTTPResponse, HTTPBody?)) async throws -> (HTTPResponse, HTTPBody?) {117 var request = request118 let context = RequestContext.current119 // Buffer the body: a streamed body could not be replayed after a refresh.120 let buffered: Data?121 if let body { buffered = try await Data(collecting: body, upTo: 4 << 20) } else { buffered = nil }122 let makeBody: @Sendable () -> HTTPBody? = { buffered.map { HTTPBody($0) } }123124 if let setup = context.setupToken { request.headerFields[.setupTransaction] = setup }125 let wantsBearer = context.includeBearer && !OperationSets.publicOperations.contains(operationID)126 guard wantsBearer, let token = try await tokens.accessToken() else {127 return try await next(request, makeBody(), baseURL)128 }129 request.headerFields[.authorization] = "Bearer \(token)"130 let (response, responseBody) = try await next(request, makeBody(), baseURL)131 guard response.status.code == 401 else { return (response, responseBody) }132 // Access token expired or revoked: refresh once (shared by every concurrent request), then replay.133 let fresh = try await tokens.refreshAfterRejection(of: token)134 request.headerFields[.authorization] = "Bearer \(fresh)"135 return try await next(request, makeBody(), baseURL)136 }137}138139/// `date-time` transcoding tolerant of fractional seconds (Go emits up to nanoseconds, Foundation's default140/// ISO 8601 parser refuses them).141struct FlexibleDateTranscoder: DateTranscoder {142 func encode(_ date: Date) throws -> String {143 date.formatted(Date.ISO8601FormatStyle(includingFractionalSeconds: true))144 }145146 func decode(_ string: String) throws -> Date {147 if let d = Self.parse(string) { return d }148 throw DecodingError.dataCorrupted(.init(codingPath: [], debugDescription: "Expected an RFC 3339 date-time, got \(string)"))149 }150151 static func parse(_ string: String) -> Date? {152 var base = string153 var fraction = 0.0154 if let dot = string.firstIndex(of: ".") {155 let after = string[string.index(after: dot)...]156 let digits = after.prefix { $0.isNumber }157 guard !digits.isEmpty else { return nil }158 fraction = Double("0." + digits) ?? 0159 base = String(string[..<dot]) + after.dropFirst(digits.count)160 }161 guard let d = try? Date.ISO8601FormatStyle().parse(base) else { return nil }162 return d.addingTimeInterval(fraction)163 }164}165166/// `Idempotency-Key` helper: one key per user intent, stable across the retries of that same intent.167///168/// Create the intent when the user opens the confirmation (not at each tap on "send"): re-submitting after a169/// timeout or a step-up then reaches the server with the same key and the same body, and the server answers with170/// the original action instead of creating a second one. A changed form is a new intent.171public struct IdempotencyIntent: Sendable, Hashable, Codable {172 public let key: String173 public let createdAt: Date174 public init() {175 key = UUID().uuidString.lowercased()176 createdAt = Date()177 }178}179180/// Tracks the intent attached to a form: the key survives retries and is renewed only when the request body181/// changes or after a success.182public struct IdempotencyTracker: Sendable {183 private var intent = IdempotencyIntent()184 private var fingerprint: String?185 public init() {}186187 /// The key to send for a request whose canonical body is `body`.188 public mutating func key(forBody body: String) -> String {189 if let f = fingerprint, f != body { intent = IdempotencyIntent() }190 fingerprint = body191 return intent.key192 }193194 /// Call after the server accepted the request: the next submission is a new intent.195 public mutating func complete() {196 intent = IdempotencyIntent()197 fingerprint = nil198 }199}200