From 792abeab1f7d18a5ab98cb685d9a7877b7640fda Mon Sep 17 00:00:00 2001 From: Guoye Zhang Date: Mon, 7 Aug 2023 18:09:53 -0700 Subject: [PATCH] Support Codable --- Sources/HTTPTypes/HTTPField.swift | 61 +++++++++++-- Sources/HTTPTypes/HTTPFieldName.swift | 28 ++++++ Sources/HTTPTypes/HTTPFields.swift | 25 ++++++ Sources/HTTPTypes/HTTPRequest.swift | 104 +++++++++++++++++++++- Sources/HTTPTypes/HTTPResponse.swift | 70 +++++++++++++++ Tests/HTTPTypesTests/HTTPTypesTests.swift | 49 ++++++++++ 6 files changed, 329 insertions(+), 8 deletions(-) diff --git a/Sources/HTTPTypes/HTTPField.swift b/Sources/HTTPTypes/HTTPField.swift index 0a9bcf4..e7e7678 100644 --- a/Sources/HTTPTypes/HTTPField.swift +++ b/Sources/HTTPTypes/HTTPField.swift @@ -20,19 +20,33 @@ public struct HTTPField: Sendable, Hashable { /// The strategy for whether the field is indexed in the HPACK or QPACK dynamic table. public struct DynamicTableIndexingStrategy: Sendable, Hashable { /// Default strategy. - public static var automatic: Self { .init(rawValue: 0) } + public static var automatic: Self { .init(uncheckedValue: 0) } /// Always put this field in the dynamic table if possible. - public static var prefer: Self { .init(rawValue: 1) } + public static var prefer: Self { .init(uncheckedValue: 1) } /// Don't put this field in the dynamic table. - public static var avoid: Self { .init(rawValue: 2) } + public static var avoid: Self { .init(uncheckedValue: 2) } /// Don't put this field in the dynamic table, and set a flag to disallow intermediaries to /// index this field. - public static var disallow: Self { .init(rawValue: 3) } + public static var disallow: Self { .init(uncheckedValue: 3) } - private let rawValue: UInt8 + fileprivate let rawValue: UInt8 + + private static let maxRawValue: UInt8 = 3 + + private init(uncheckedValue: UInt8) { + assert(uncheckedValue <= Self.maxRawValue) + self.rawValue = uncheckedValue + } + + fileprivate init?(rawValue: UInt8) { + if rawValue > Self.maxRawValue { + return nil + } + self.rawValue = rawValue + } } /// Create an HTTP field from a name and a value. @@ -181,8 +195,43 @@ extension HTTPField: CustomPlaygroundDisplayConvertible { } } +extension HTTPField: Codable { + enum CodingKeys: String, CodingKey { + case name + case value + case indexingStrategy + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(self.name, forKey: .name) + try container.encode(self.rawValue._storage, forKey: .value) + if self.indexingStrategy != .automatic { + try container.encode(self.indexingStrategy.rawValue, forKey: .indexingStrategy) + } + } + + private enum DecodingError: Error { + case invalidValue(String) + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let name = try container.decode(Name.self, forKey: .name) + let value = try container.decode(String.self, forKey: .value) + guard Self.isValidValue(value) else { + throw DecodingError.invalidValue(value) + } + self.init(name: name, uncheckedValue: ISOLatin1String(unchecked: value)) + if let indexingStrategyValue = try container.decodeIfPresent(UInt8.self, forKey: .indexingStrategy), + let indexingStrategy = DynamicTableIndexingStrategy(rawValue: indexingStrategyValue) { + self.indexingStrategy = indexingStrategy + } + } +} + extension HTTPField { - static func isValidToken(_ token: String) -> Bool { + static func isValidToken(_ token: some StringProtocol) -> Bool { !token.isEmpty && token.utf8.allSatisfy { switch $0 { case 0x21, 0x23, 0x24, 0x25, 0x26, 0x27, 0x2A, 0x2B, 0x2D, 0x2E, 0x5E, 0x5F, 0x60, 0x7C, 0x7E: diff --git a/Sources/HTTPTypes/HTTPFieldName.swift b/Sources/HTTPTypes/HTTPFieldName.swift index a20b5ac..14f14c8 100644 --- a/Sources/HTTPTypes/HTTPFieldName.swift +++ b/Sources/HTTPTypes/HTTPFieldName.swift @@ -77,6 +77,34 @@ extension HTTPField.Name: CustomPlaygroundDisplayConvertible { } } +extension HTTPField.Name: Codable { + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + try container.encode(self.rawName) + } + + private enum DecodingError: Error { + case invalidString(String) + } + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + let nameString = try container.decode(String.self) + if nameString.hasPrefix(":") { + guard nameString.lowercased() == nameString, + HTTPField.isValidToken(nameString.dropFirst()) else { + throw DecodingError.invalidString(nameString) + } + self.init(rawName: nameString, canonicalName: nameString) + } else { + guard let name = Self(nameString) else { + throw DecodingError.invalidString(nameString) + } + self = name + } + } +} + extension HTTPField.Name { static var method: Self { .init(rawName: ":method", canonicalName: ":method") } static var scheme: Self { .init(rawName: ":scheme", canonicalName: ":scheme") } diff --git a/Sources/HTTPTypes/HTTPFields.swift b/Sources/HTTPTypes/HTTPFields.swift index d538ecc..b4ee390 100644 --- a/Sources/HTTPTypes/HTTPFields.swift +++ b/Sources/HTTPTypes/HTTPFields.swift @@ -306,6 +306,31 @@ extension HTTPFields: CustomDebugStringConvertible { } } +extension HTTPFields: Codable { + public func encode(to encoder: Encoder) throws { + var container = encoder.unkeyedContainer() + try container.encode(contentsOf: self) + } + + private enum DecodingError: Error { + case isPseudo(String) + } + + public init(from decoder: Decoder) throws { + var container = try decoder.unkeyedContainer() + if let count = container.count { + self.reserveCapacity(count) + } + while !container.isAtEnd { + let field = try container.decode(HTTPField.self) + guard !field.name.rawName.hasPrefix(":") else { + throw DecodingError.isPseudo(field.name.rawName) + } + self.append(field) + } + } +} + extension Array { // `removalIndices` must be ordered. mutating func remove(at removalIndices: some Sequence) { diff --git a/Sources/HTTPTypes/HTTPRequest.swift b/Sources/HTTPTypes/HTTPRequest.swift index 8712d91..0bbc498 100644 --- a/Sources/HTTPTypes/HTTPRequest.swift +++ b/Sources/HTTPTypes/HTTPRequest.swift @@ -43,7 +43,7 @@ public struct HTTPRequest: Sendable, Hashable { self.init(rawValue) } - private init(unchecked: String) { + fileprivate init(unchecked: String) { self.rawValue = unchecked } @@ -57,7 +57,7 @@ public struct HTTPRequest: Sendable, Hashable { /// A convenient way to access the value of the ":method" pseudo header field. public var method: Method { get { - Method(self.pseudoHeaderFields.method.rawValue._storage)! + Method(unchecked: self.pseudoHeaderFields.method.rawValue._storage) } set { self.pseudoHeaderFields.method.rawValue = ISOLatin1String(unchecked: newValue.rawValue) @@ -224,6 +224,106 @@ extension HTTPRequest: CustomDebugStringConvertible { } } +extension HTTPRequest.PseudoHeaderFields: Codable { + public func encode(to encoder: Encoder) throws { + var container = encoder.unkeyedContainer() + try container.encode(self.method) + if let scheme = self.scheme { + try container.encode(scheme) + } + if let authority = self.authority { + try container.encode(authority) + } + if let path = self.path { + try container.encode(path) + } + if let extendedConnectProtocol = self.extendedConnectProtocol { + try container.encode(extendedConnectProtocol) + } + } + + private enum DecodingError: Error { + case missingMethod + case multipleMethod + case multipleScheme + case multipleAuthority + case multiplePath + case multipleExtendedConnectProtocol + case invalidMethod(String) + case notPseudo(String) + } + + public init(from decoder: Decoder) throws { + var container = try decoder.unkeyedContainer() + var method: HTTPField? + var scheme: HTTPField? + var authority: HTTPField? + var path: HTTPField? + var extendedConnectProtocol: HTTPField? + while !container.isAtEnd { + let field = try container.decode(HTTPField.self) + switch field.name { + case .method: + guard method == nil else { + throw DecodingError.multipleMethod + } + method = field + case .scheme: + guard scheme == nil else { + throw DecodingError.multipleScheme + } + scheme = field + case .authority: + guard authority == nil else { + throw DecodingError.multipleAuthority + } + authority = field + case .path: + guard path == nil else { + throw DecodingError.multiplePath + } + path = field + case .protocol: + guard extendedConnectProtocol == nil else { + throw DecodingError.multipleExtendedConnectProtocol + } + extendedConnectProtocol = field + default: + guard field.name.rawName.hasPrefix(":") else { + throw DecodingError.notPseudo(field.name.rawName) + } + } + } + guard let method else { + throw DecodingError.missingMethod + } + guard HTTPField.isValidToken(method.rawValue._storage) else { + throw DecodingError.invalidMethod(method.rawValue._storage) + } + self.init(method: method, scheme: scheme, authority: authority, path: path, + extendedConnectProtocol: extendedConnectProtocol) + } +} + +extension HTTPRequest: Codable { + enum CodingKeys: String, CodingKey { + case pseudoHeaderFields + case headerFields + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(self.pseudoHeaderFields, forKey: .pseudoHeaderFields) + try container.encode(self.headerFields, forKey: .headerFields) + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + self.pseudoHeaderFields = try container.decode(PseudoHeaderFields.self, forKey: .pseudoHeaderFields) + self.headerFields = try container.decode(HTTPFields.self, forKey: .headerFields) + } +} + extension HTTPRequest.Method { /// GET public static var get: Self { .init(unchecked: "GET") } diff --git a/Sources/HTTPTypes/HTTPResponse.swift b/Sources/HTTPTypes/HTTPResponse.swift index c0ac2f3..5edb027 100644 --- a/Sources/HTTPTypes/HTTPResponse.swift +++ b/Sources/HTTPTypes/HTTPResponse.swift @@ -205,6 +205,76 @@ extension HTTPResponse: CustomDebugStringConvertible { } } +extension HTTPResponse.PseudoHeaderFields: Codable { + public func encode(to encoder: Encoder) throws { + var container = encoder.unkeyedContainer() + try container.encode(self.status) + } + + private enum DecodingError: Error { + case missingStatus + case multipleStatus + case invalidStatus(String) + case notPseudo(String) + } + + public init(from decoder: Decoder) throws { + var container = try decoder.unkeyedContainer() + var status: HTTPField? + while !container.isAtEnd { + let field = try container.decode(HTTPField.self) + switch field.name { + case .status: + guard status == nil else { + throw DecodingError.missingStatus + } + status = field + default: + guard field.name.rawName.hasPrefix(":") else { + throw DecodingError.notPseudo(field.name.rawName) + } + } + } + guard let status else { + throw DecodingError.missingStatus + } + guard HTTPResponse.Status.isValidStatus(status.rawValue._storage) else { + throw DecodingError.invalidStatus(status.rawValue._storage) + } + self.init(status: status) + } +} + +extension HTTPResponse: Codable { + enum CodingKeys: String, CodingKey { + case pseudoHeaderFields + case headerFields + case reasonPhrase + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(self.pseudoHeaderFields, forKey: .pseudoHeaderFields) + try container.encode(self.reasonPhrase, forKey: .reasonPhrase) + try container.encode(self.headerFields, forKey: .headerFields) + } + + private enum DecodingError: Error { + case invalidReasonPhrase(String) + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + self.pseudoHeaderFields = try container.decode(PseudoHeaderFields.self, forKey: .pseudoHeaderFields) + let reasonPhrase = try container.decode(String.self, forKey: .reasonPhrase) + guard Status.isValidReasonPhrase(reasonPhrase) else { + throw DecodingError.invalidReasonPhrase(reasonPhrase) + } + self.reasonPhrase = reasonPhrase + self.headerFields = try container.decode(HTTPFields.self, forKey: .headerFields) + } +} + extension HTTPResponse.Status { // MARK: 1xx diff --git a/Tests/HTTPTypesTests/HTTPTypesTests.swift b/Tests/HTTPTypesTests/HTTPTypesTests.swift index ff3ed79..9a18e35 100644 --- a/Tests/HTTPTypesTests/HTTPTypesTests.swift +++ b/Tests/HTTPTypesTests/HTTPTypesTests.swift @@ -99,4 +99,53 @@ final class HTTPTypesTests: XCTestCase { XCTAssertTrue(isSendable(status)) XCTAssertTrue(isSendable(responsePseudoHeaderFields)) } + + func testRequestCoding() throws { + let request = HTTPRequest(method: .put, scheme: "https", authority: "www.example.com", path: "/upload", headerFields: [ + .acceptEncoding: "br", + .acceptEncoding: "gzip", + .contentLength: "1024", + ]) + let encoded = try JSONEncoder().encode(request) + + let json = try JSONSerialization.jsonObject(with: encoded) + XCTAssertEqual(json as? NSDictionary, [ + "pseudoHeaderFields": [ + ["name": ":method", "value": "PUT"], + ["name": ":scheme", "value": "https"], + ["name": ":authority", "value": "www.example.com"], + ["name": ":path", "value": "/upload"], + ], + "headerFields": [ + ["name": "Accept-Encoding", "value": "br"], + ["name": "Accept-Encoding", "value": "gzip"], + ["name": "Content-Length", "value": "1024"], + ] + ]) + + let decoded = try JSONDecoder().decode(HTTPRequest.self, from: encoded) + XCTAssertEqual(request, decoded) + } + + func testResponseCoding() throws { + var response = HTTPResponse(status: .noContent, headerFields: [ + .server: "HTTPServer/1.0", + ]) + response.headerFields[0].indexingStrategy = .prefer + let encoded = try JSONEncoder().encode(response) + + let json = try JSONSerialization.jsonObject(with: encoded) + XCTAssertEqual(json as? NSDictionary, [ + "pseudoHeaderFields": [ + ["name": ":status", "value": "204"], + ], + "reasonPhrase": "No Content", + "headerFields": [ + ["name": "Server", "value": "HTTPServer/1.0", "indexingStrategy": 1], + ] + ]) + + let decoded = try JSONDecoder().decode(HTTPResponse.self, from: encoded) + XCTAssertEqual(response, decoded) + } }