http: throw on unsuccessful responses (#246)
- Commit
76b005f6d81714aadd25b70628be10bcb2c1d19b- Author
- Rob <[email protected]>
- When
- 2026-09-08 20:48 UTC (2 months ago)
- Parents
ae2bef7
Ref #243. `makeRequest` never inspected `response.status`, so a non-2xx body was returned as if it had succeeded. Every caller decodes that body as a property list or JSON, so Apple answering with an HTML error page surfaced as: ``` Error: DecodingError.dataCorrupted: Data was corrupted. Debug description: The given data was not a valid property list.. Underlying error: ... Encountered unknown tag html on line 1 ``` which says nothing about what actually happened. In the case that prompted #243, GSA was returning `503 Service Temporarily Unavailable` for the `apptokens` operation. It now reads: ``` Error: POST https://gsa.apple.com/grandslam/GsService2 failed: HTTP 503 Service Unavailable (text/html): <html> <head><title>503 Service Temporarily Unavailable</title></head> ... ``` ### Notes - The response body is only included in the message for `text/html` and `text/plain`, i.e. gateway error pages. Bodies from the auth endpoints can carry account details (the 2FA requests use `Accept: application/x-buddyml`), and errors get printed verbatim in places such as `DevCommand.swift:164`, so those are left out. It also avoids emitting replacement characters for binary bodies. - The non-2xx path does not report progress, so `XADIProvider`'s download no longer prints `100%` immediately before failing. - Body collection moved to `collect(_:onProgress:)` so there is a single exit point. Buffer pre-sizing and progress reporting are unchanged. - `SDKBuilder` already does this check by hand on `send()`, so it is unaffected. ### Behaviour changes worth a look - `XADIProvider` writes the Apple Music APK download straight to disk; a failed download now throws instead of leaving a corrupt `applemusic.apk`. - The 2FA requests (`GrandSlamTrustedDeviceRequest`, `GrandSlamSMSAuthRequest`, `GrandSlamValidateRequest`) use no-op decoders, so a rejected request is currently discarded and xtool goes on to prompt for a code that was never sent — the symptom in #235. Those now fail loudly. ### Two things I left alone - `GrandSlamTwoFactorAuthenticateOperation.swift:47` catches `GrandSlamOperationError` with code `-21669` to report an incorrect verification code, but that error is only thrown by `GrandSlamOperationDecoder`, which the validate requests do not use, so the catch is unreachable. With this change a wrong code surfaces as a raw HTTP error instead. Mapping the status back to `incorrectVerificationCode` seemed like your call, since I do not know what GSA returns for a bad code. - If any endpoint reports errors in a decodable body under a non-2xx status, this guard would pre-empt it. I could not find one — `developerservices2` returns HTTP 200 with `resultCode`/`userString` in the body, which is untouched here. Built and linted on Linux (`swift build --product xtool`, `make lint`: 0 violations). --------- Co-authored-by: Robetronica <[email protected]> Co-authored-by: Kabir Oberai <[email protected]>
Diff
Sources/XKit/HTTPClientProtocol/HTTPClientProtocol.swift
diff --git a/Sources/XKit/HTTPClientProtocol/HTTPClientProtocol.swift b/Sources/XKit/HTTPClientProtocol/HTTPClientProtocol.swiftindex 2e90522..a8dc664 100644--- a/Sources/XKit/HTTPClientProtocol/HTTPClientProtocol.swift+++ b/Sources/XKit/HTTPClientProtocol/HTTPClientProtocol.swift@@ -41,28 +41,72 @@ extension HTTPClientProtocol { public func makeRequest( _ request: HTTPRequest, body: Data? = nil,+ requireHTTPSuccess: Bool = true, onProgress: @isolated(any) (Double?) -> Void = { _ in } ) async throws -> (response: HTTPResponse, body: Data) { await onProgress(0)- let (response, body) = try await send(request, body: body.map { HTTPBody($0) })- guard let body else {- return (response, Data())+ let (response, responseBody) = try await send(request, body: body.map { HTTPBody($0) })+ guard !requireHTTPSuccess || response.status.kind == .successful else {+ let errorBody = (try? await responseBody.collect()) ?? Data()+ throw HTTPResponseError(+ method: request.method,+ url: "\(request.scheme ?? "https")://\(request.authority ?? "")\(request.path ?? "")",+ status: response.status,+ // we don't use `decoding:as:` because we want to validate the UTF8+ body: String(data: errorBody, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines)+ ) }- switch body.length {+ return (response, try await responseBody.collect(onProgress: onProgress))+ }+}++extension HTTPBody? {+ fileprivate func collect(+ onProgress: @isolated(any) (Double?) -> Void = { _ in }+ ) async throws -> Data {+ try await self?.collect(onProgress: onProgress) ?? Data()+ }+}++extension HTTPBody {+ fileprivate func collect(+ onProgress: @isolated(any) (Double?) -> Void+ ) async throws -> Data {+ switch self.length { case .unknown:- return (response, try await body.reduce(into: Data()) { $0 += $1 })+ return try await self.reduce(into: Data()) { $0 += $1 } case .known(let length): var data = Data(capacity: Int(length)) let total = Double(length)- for try await chunk in body {+ for try await chunk in self { data += chunk- await onProgress(min(Double(data.count) / total, 1))+ await onProgress(Swift.min(Double(data.count) / total, 1)) }- return (response, data)+ return data } } } +public struct HTTPResponseError: Error, LocalizedError, Sendable, CustomStringConvertible {+ public let method: HTTPRequest.Method+ public let url: String+ public let status: HTTPResponse.Status+ public let body: String?++ public var description: String {+ var description = "\(method.rawValue) \(url) failed: HTTP \(status.code)"+ if !status.reasonPhrase.isEmpty {+ description += " \(status.reasonPhrase)"+ }+ if let body, !body.isEmpty {+ description += ". Details:\n\(body)"+ }+ return description+ }++ public var errorDescription: String? { description }+}+ private struct UnimplementedHTTPClient: HTTPClientProtocol, ClientTransport { public var asOpenAPITransport: ClientTransport { self }