Add HTTP types adapter for SwiftNIO (#202)

* Add HTTP types adapter for SwiftNIO

* swiftformat

* Guard on Swift 5.8

* Review comments

* Update swift-http-types to 0.1.1

* Update swift-http-types to 1.0.0

* Review feedback

* Review feedback

* Bump minimum Swift version to 5.7.1

* Allow Host in any order
This commit is contained in:
Guoye Zhang authored and GitHub committed 2023-10-20 17:55:23 +01:00
1 parent 6c3819cf2a
commit 798c962495
12 files changed
+1489 -5

No files matched your search

@@ -0,0 +1,117 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2023 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import HTTPTypes
import NIOCore
import NIOHTTP1
import NIOHTTPTypes
/// A simple channel handler that translates HTTP/1 messages into shared HTTP types,
/// and vice versa, for use on the client side.
public final class HTTP1ToHTTPClientCodec: ChannelDuplexHandler {
public typealias InboundIn = HTTPClientResponsePart
public typealias InboundOut = HTTPResponsePart
public typealias OutboundIn = HTTPRequestPart
public typealias OutboundOut = HTTPClientRequestPart
/// Initializes a `HTTP1ToHTTPClientCodec`.
public init() {}
public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
switch self.unwrapInboundIn(data) {
case .head(let head):
do {
let newResponse = try HTTPResponse(head)
context.fireChannelRead(self.wrapInboundOut(.head(newResponse)))
} catch {
context.fireErrorCaught(error)
}
case .body(let body):
context.fireChannelRead(self.wrapInboundOut(.body(body)))
case .end(let trailers):
let newTrailers = trailers.map { HTTPFields($0, splitCookie: false) }
context.fireChannelRead(self.wrapInboundOut(.end(newTrailers)))
}
}
public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
switch self.unwrapOutboundIn(data) {
case .head(let request):
do {
let oldRequest = try HTTPRequestHead(request)
context.write(self.wrapOutboundOut(.head(oldRequest)), promise: promise)
} catch {
context.fireErrorCaught(error)
promise?.fail(error)
}
case .body(let body):
context.write(self.wrapOutboundOut(.body(.byteBuffer(body))), promise: promise)
case .end(let trailers):
context.write(self.wrapOutboundOut(.end(trailers.map(HTTPHeaders.init))), promise: promise)
}
}
}
/// A simple channel handler that translates HTTP/1 messages into shared HTTP types,
/// and vice versa, for use on the server side.
public final class HTTP1ToHTTPServerCodec: ChannelDuplexHandler {
public typealias InboundIn = HTTPServerRequestPart
public typealias InboundOut = HTTPRequestPart
public typealias OutboundIn = HTTPResponsePart
public typealias OutboundOut = HTTPServerResponsePart
private let secure: Bool
private let splitCookie: Bool
/// Initializes a `HTTP1ToHTTPServerCodec`.
/// - Parameters:
/// - secure: Whether "https" or "http" is used.
/// - splitCookie: Whether the cookies received from the server should be split
/// into multiple header fields. Defaults to false.
public init(secure: Bool, splitCookie: Bool = false) {
self.secure = secure
self.splitCookie = splitCookie
}
public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
switch self.unwrapInboundIn(data) {
case .head(let head):
do {
let newRequest = try HTTPRequest(head, secure: self.secure, splitCookie: self.splitCookie)
context.fireChannelRead(self.wrapInboundOut(.head(newRequest)))
} catch {
context.fireErrorCaught(error)
}
case .body(let body):
context.fireChannelRead(self.wrapInboundOut(.body(body)))
case .end(let trailers):
let newTrailers = trailers.map { HTTPFields($0, splitCookie: false) }
context.fireChannelRead(self.wrapInboundOut(.end(newTrailers)))
}
}
public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
switch self.unwrapOutboundIn(data) {
case .head(let response):
let oldResponse = HTTPResponseHead(response)
context.write(self.wrapOutboundOut(.head(oldResponse)), promise: promise)
case .body(let body):
context.write(self.wrapOutboundOut(.body(.byteBuffer(body))), promise: promise)
case .end(let trailers):
context.write(self.wrapOutboundOut(.end(trailers.map(HTTPHeaders.init))), promise: promise)
}
}
}
@@ -0,0 +1,134 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2023 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import HTTPTypes
import NIOCore
import NIOHTTP1
import NIOHTTPTypes
/// A simple channel handler that translates shared HTTP types into HTTP/1 messages,
/// and vice versa, for use on the client side.
///
/// This is intended for compatibility purposes where a channel handler working with
/// HTTP/1 messages needs to work on top of the new version-independent HTTP types
/// abstraction.
public final class HTTPToHTTP1ClientCodec: ChannelDuplexHandler {
public typealias InboundIn = HTTPResponsePart
public typealias InboundOut = HTTPClientResponsePart
public typealias OutboundIn = HTTPClientRequestPart
public typealias OutboundOut = HTTPRequestPart
private let secure: Bool
private let splitCookie: Bool
/// Initializes a `HTTPToHTTP1ClientCodec`.
/// - Parameters:
/// - secure: Whether "https" or "http" is used.
/// - splitCookie: Whether the cookies sent by the client should be split
/// into multiple header fields. Splitting the `Cookie`
/// header field improves the performance of HTTP/2 and
/// HTTP/3 clients by allowing individual cookies to be
/// indexed separately in the dynamic table. It has no
/// effects in HTTP/1. Defaults to true.
public init(secure: Bool, splitCookie: Bool = true) {
self.secure = secure
self.splitCookie = splitCookie
}
public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
switch self.unwrapInboundIn(data) {
case .head(let head):
let oldResponse = HTTPResponseHead(head)
context.fireChannelRead(self.wrapInboundOut(.head(oldResponse)))
case .body(let body):
context.fireChannelRead(self.wrapInboundOut(.body(body)))
case .end(let trailers):
context.fireChannelRead(self.wrapInboundOut(.end(trailers.map(HTTPHeaders.init))))
}
}
public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
switch self.unwrapOutboundIn(data) {
case .head(let request):
do {
let newRequest = try HTTPRequest(request, secure: self.secure, splitCookie: self.splitCookie)
context.write(self.wrapOutboundOut(.head(newRequest)), promise: promise)
} catch {
context.fireErrorCaught(error)
promise?.fail(error)
}
case .body(.byteBuffer(let body)):
context.write(self.wrapOutboundOut(.body(body)), promise: promise)
case .body:
fatalError("File region not supported")
case .end(let trailers):
let newTrailers = trailers.map { HTTPFields($0, splitCookie: false) }
context.write(self.wrapOutboundOut(.end(newTrailers)), promise: promise)
}
}
}
/// A simple channel handler that translates shared HTTP types into HTTP/1 messages,
/// and vice versa, for use on the server side.
///
/// This is intended for compatibility purposes where a channel handler working with
/// HTTP/1 messages needs to work on top of the new version-independent HTTP types
/// abstraction.
public final class HTTPToHTTP1ServerCodec: ChannelDuplexHandler {
public typealias InboundIn = HTTPRequestPart
public typealias InboundOut = HTTPServerRequestPart
public typealias OutboundIn = HTTPServerResponsePart
public typealias OutboundOut = HTTPResponsePart
/// Initializes a `HTTPToHTTP1ServerCodec`.
public init() {}
public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
switch self.unwrapInboundIn(data) {
case .head(let head):
do {
let oldRequest = try HTTPRequestHead(head)
context.fireChannelRead(self.wrapInboundOut(.head(oldRequest)))
} catch {
context.fireErrorCaught(error)
}
case .body(let body):
context.fireChannelRead(self.wrapInboundOut(.body(body)))
case .end(let trailers):
context.fireChannelRead(self.wrapInboundOut(.end(trailers.map(HTTPHeaders.init))))
}
}
public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
switch self.unwrapOutboundIn(data) {
case .head(let response):
do {
let newResponse = try HTTPResponse(response)
context.write(self.wrapOutboundOut(.head(newResponse)), promise: promise)
} catch {
context.fireErrorCaught(error)
promise?.fail(error)
}
case .body(.byteBuffer(let body)):
context.write(self.wrapOutboundOut(.body(body)), promise: promise)
case .body:
fatalError("File region not supported")
case .end(let trailers):
let newTrailers = trailers.map { HTTPFields($0, splitCookie: false) }
context.write(self.wrapOutboundOut(.end(newTrailers)), promise: promise)
}
}
}
@@ -0,0 +1,212 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2023 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import HTTPTypes
import NIOHTTP1
private enum HTTP1TypeConversionError: Error {
case invalidMethod
case missingPath
case invalidStatusCode
}
extension HTTPMethod {
init(_ newMethod: HTTPRequest.Method) {
switch newMethod {
case .get: self = .GET
case .head: self = .HEAD
case .post: self = .POST
case .put: self = .PUT
case .delete: self = .DELETE
case .connect: self = .CONNECT
case .options: self = .OPTIONS
case .trace: self = .TRACE
case .patch: self = .PATCH
default:
let rawValue = newMethod.rawValue
switch rawValue {
case "ACL": self = .ACL
case "COPY": self = .COPY
case "LOCK": self = .LOCK
case "MOVE": self = .MOVE
case "BIND": self = .BIND
case "LINK": self = .LINK
case "MKCOL": self = .MKCOL
case "MERGE": self = .MERGE
case "PURGE": self = .PURGE
case "NOTIFY": self = .NOTIFY
case "SEARCH": self = .SEARCH
case "UNLOCK": self = .UNLOCK
case "REBIND": self = .REBIND
case "UNBIND": self = .UNBIND
case "REPORT": self = .REPORT
case "UNLINK": self = .UNLINK
case "MSEARCH": self = .MSEARCH
case "PROPFIND": self = .PROPFIND
case "CHECKOUT": self = .CHECKOUT
case "PROPPATCH": self = .PROPPATCH
case "SUBSCRIBE": self = .SUBSCRIBE
case "MKCALENDAR": self = .MKCALENDAR
case "MKACTIVITY": self = .MKACTIVITY
case "UNSUBSCRIBE": self = .UNSUBSCRIBE
case "SOURCE": self = .SOURCE
default: self = .RAW(value: rawValue)
}
}
}
}
extension HTTPRequest.Method {
init(_ oldMethod: HTTPMethod) throws {
switch oldMethod {
case .GET: self = .get
case .PUT: self = .put
case .ACL: self = .init("ACL")!
case .HEAD: self = .head
case .POST: self = .post
case .COPY: self = .init("COPY")!
case .LOCK: self = .init("LOCK")!
case .MOVE: self = .init("MOVE")!
case .BIND: self = .init("BIND")!
case .LINK: self = .init("LINK")!
case .PATCH: self = .patch
case .TRACE: self = .trace
case .MKCOL: self = .init("MKCOL")!
case .MERGE: self = .init("MERGE")!
case .PURGE: self = .init("PURGE")!
case .NOTIFY: self = .init("NOTIFY")!
case .SEARCH: self = .init("SEARCH")!
case .UNLOCK: self = .init("UNLOCK")!
case .REBIND: self = .init("REBIND")!
case .UNBIND: self = .init("UNBIND")!
case .REPORT: self = .init("REPORT")!
case .DELETE: self = .delete
case .UNLINK: self = .init("UNLINK")!
case .CONNECT: self = .connect
case .MSEARCH: self = .init("MSEARCH")!
case .OPTIONS: self = .options
case .PROPFIND: self = .init("PROPFIND")!
case .CHECKOUT: self = .init("CHECKOUT")!
case .PROPPATCH: self = .init("PROPPATCH")!
case .SUBSCRIBE: self = .init("SUBSCRIBE")!
case .MKCALENDAR: self = .init("MKCALENDAR")!
case .MKACTIVITY: self = .init("MKACTIVITY")!
case .UNSUBSCRIBE: self = .init("UNSUBSCRIBE")!
case .SOURCE: self = .init("SOURCE")!
case .RAW(value: let value):
guard let method = HTTPRequest.Method(value) else {
throw HTTP1TypeConversionError.invalidMethod
}
self = method
}
}
}
extension HTTPHeaders {
init(_ newFields: HTTPFields) {
let fields = newFields.map { ($0.name.rawName, $0.value) }
self.init(fields)
}
}
extension HTTPFields {
init(_ oldHeaders: HTTPHeaders, splitCookie: Bool) {
self.init()
self.reserveCapacity(count)
var firstHost = true
for field in oldHeaders {
if firstHost && field.name.lowercased() == "host" {
firstHost = false
continue
}
if let name = HTTPField.Name(field.name) {
if splitCookie && name == .cookie, #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) {
self.append(contentsOf: field.value.split(separator: "; ", omittingEmptySubsequences: false).map {
HTTPField(name: name, value: String($0))
})
} else {
self.append(HTTPField(name: name, value: field.value))
}
}
}
}
}
extension HTTPRequestHead {
init(_ newRequest: HTTPRequest) throws {
guard let path = newRequest.method == .connect ? newRequest.authority : newRequest.path else {
throw HTTP1TypeConversionError.missingPath
}
var headers = HTTPHeaders()
headers.reserveCapacity(newRequest.headerFields.count + 1)
if let authority = newRequest.authority {
headers.add(name: "Host", value: authority)
}
var firstCookie = true
for field in newRequest.headerFields {
if field.name == .cookie {
if firstCookie {
firstCookie = false
headers.add(name: field.name.rawName, value: newRequest.headerFields[.cookie]!)
}
} else {
headers.add(name: field.name.rawName, value: field.value)
}
}
self.init(
version: .http1_1,
method: HTTPMethod(newRequest.method),
uri: path,
headers: headers
)
}
}
extension HTTPRequest {
init(_ oldRequest: HTTPRequestHead, secure: Bool, splitCookie: Bool) throws {
let method = try Method(oldRequest.method)
let scheme = secure ? "https" : "http"
let authority = oldRequest.headers["Host"].first
self.init(
method: method,
scheme: scheme,
authority: authority,
path: oldRequest.uri,
headerFields: HTTPFields(oldRequest.headers, splitCookie: splitCookie)
)
}
}
extension HTTPResponseHead {
init(_ newResponse: HTTPResponse) {
self.init(
version: .http1_1,
status: HTTPResponseStatus(
statusCode: newResponse.status.code,
reasonPhrase: newResponse.status.reasonPhrase
),
headers: HTTPHeaders(newResponse.headerFields)
)
}
}
extension HTTPResponse {
init(_ oldResponse: HTTPResponseHead) throws {
guard oldResponse.status.code <= 999 else {
throw HTTP1TypeConversionError.invalidStatusCode
}
let status = HTTPResponse.Status(code: Int(oldResponse.status.code), reasonPhrase: oldResponse.status.reasonPhrase)
self.init(status: status, headerFields: HTTPFields(oldResponse.headers, splitCookie: false))
}
}