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,118 @@
//===----------------------------------------------------------------------===//
//
// 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 NIOHPACK
import NIOHTTP2
extension HPACKHeaders {
/// Whether this `HTTPHeaders` corresponds to a final response or not.
///
/// This function is only valid if called on a response header block. If the :status header
/// is not present, this will throw.
fileprivate func isInformationalResponse() throws -> Bool {
try self.peekPseudoHeader(name: ":status").first! == "1"
}
/// Grabs a pseudo-header from a header block. Does not remove it.
///
/// - Parameters:
/// - name: The header name to find.
/// - Returns: The value for this pseudo-header.
/// - Throws: `NIOHTTP2Errors` if there is no such header, or multiple.
internal func peekPseudoHeader(name: String) throws -> String {
// This could be done with .lazy.filter.map but that generates way more ARC traffic.
var headerValue: String? = nil
for (fieldName, fieldValue, _) in self {
if name == fieldName {
guard headerValue == nil else {
throw NIOHTTP2Errors.duplicatePseudoHeader(name)
}
headerValue = fieldValue
}
}
if let headerValue {
return headerValue
} else {
throw NIOHTTP2Errors.missingPseudoHeader(name)
}
}
}
/// A state machine that keeps track of the header blocks sent or received and that determines the type of any
/// new header block.
struct HTTP2HeadersStateMachine {
/// The list of possible header frame types.
///
/// This is used in combination with introspection of the HTTP header blocks to determine what HTTP header block
/// a certain HTTP header is.
enum HeaderType {
/// A request header block.
case requestHead
/// An informational response header block. These can be sent zero or more times.
case informationalResponseHead
/// A final response header block.
case finalResponseHead
/// A trailer block. Once this is sent no further header blocks are acceptable.
case trailer
}
/// The previous header block.
private var previousHeader: HeaderType?
/// The mode of this connection: client or server.
private let mode: NIOHTTP2Handler.ParserMode
init(mode: NIOHTTP2Handler.ParserMode) {
self.mode = mode
}
/// Called when about to process an HTTP headers block to determine its type.
mutating func newHeaders(block: HPACKHeaders) throws -> HeaderType {
let newType: HeaderType
switch (self.mode, self.previousHeader) {
case (.server, .none):
// The first header block received on a server mode stream must be a request block.
newType = .requestHead
case (.client, .none),
(.client, .some(.informationalResponseHead)):
// The first header block received on a client mode stream may be either informational or final,
// depending on the value of the :status pseudo-header. Alternatively, if the previous
// header block was informational, the same possibilities apply.
newType = try block.isInformationalResponse() ? .informationalResponseHead : .finalResponseHead
case (.server, .some(.requestHead)),
(.client, .some(.finalResponseHead)):
// If the server has already received a request head, or the client has already received a final response,
// this is a trailer block.
newType = .trailer
case (.server, .some(.informationalResponseHead)),
(.server, .some(.finalResponseHead)),
(.client, .some(.requestHead)):
// These states should not be reachable!
preconditionFailure("Invalid internal state!")
case (.server, .some(.trailer)),
(.client, .some(.trailer)):
// TODO(cory): This should probably throw, as this can happen in malformed programs without the world ending.
preconditionFailure("Sending too many header blocks.")
}
self.previousHeader = newType
return newType
}
}
@@ -0,0 +1,247 @@
//===----------------------------------------------------------------------===//
//
// 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 NIOHPACK
import NIOHTTP2
import NIOHTTPTypes
// MARK: - Client
private struct BaseClientCodec {
private var headerStateMachine: HTTP2HeadersStateMachine = .init(mode: .client)
private var outgoingHTTP1RequestHead: HTTPRequest?
mutating func processInboundData(_ data: HTTP2Frame.FramePayload) throws -> (first: HTTPResponsePart?, second: HTTPResponsePart?) {
switch data {
case .headers(let headerContent):
switch try self.headerStateMachine.newHeaders(block: headerContent.headers) {
case .trailer:
let newTrailers = try HTTPFields(trailers: headerContent.headers)
return (first: .end(newTrailers), second: nil)
case .informationalResponseHead:
let newResponse = try HTTPResponse(headerContent.headers)
return (first: .head(newResponse), second: nil)
case .finalResponseHead:
guard self.outgoingHTTP1RequestHead != nil else {
preconditionFailure("Expected not to get a response without having sent a request")
}
self.outgoingHTTP1RequestHead = nil
let newResponse = try HTTPResponse(headerContent.headers)
let first = HTTPResponsePart.head(newResponse)
var second: HTTPResponsePart?
if headerContent.endStream {
second = .end(nil)
}
return (first: first, second: second)
case .requestHead:
preconditionFailure("A client can not receive request heads")
}
case .data(let content):
guard case .byteBuffer(let b) = content.data else {
preconditionFailure("Received DATA frame with non-bytebuffer IOData")
}
var first = HTTPResponsePart.body(b)
var second: HTTPResponsePart?
if content.endStream {
if b.readableBytes == 0 {
first = .end(nil)
} else {
second = .end(nil)
}
}
return (first: first, second: second)
case .alternativeService, .rstStream, .priority, .windowUpdate, .settings, .pushPromise, .ping, .goAway, .origin:
// These are not meaningful in HTTP messaging, so drop them.
return (first: nil, second: nil)
}
}
mutating func processOutboundData(_ data: HTTPRequestPart, allocator: ByteBufferAllocator) throws -> HTTP2Frame.FramePayload {
switch data {
case .head(let head):
precondition(self.outgoingHTTP1RequestHead == nil, "Only a single HTTP request allowed per HTTP2 stream")
self.outgoingHTTP1RequestHead = head
let headerContent = HTTP2Frame.FramePayload.Headers(headers: HPACKHeaders(head))
return .headers(headerContent)
case .body(let body):
return .data(HTTP2Frame.FramePayload.Data(data: .byteBuffer(body)))
case .end(let trailers):
if let trailers {
return .headers(.init(
headers: HPACKHeaders(trailers),
endStream: true
))
} else {
return .data(.init(data: .byteBuffer(allocator.buffer(capacity: 0)), endStream: true))
}
}
}
}
/// A simple channel handler that translates HTTP/2 concepts into shared HTTP types,
/// and vice versa, for use on the client side.
///
/// Use this channel handler alongside the `HTTP2StreamMultiplexer` to
/// help provide an HTTP transaction-level abstraction on top of an HTTP/2 multiplexed
/// connection.
///
/// This handler uses `HTTP2Frame.FramePayload` as its HTTP/2 currency type.
public final class HTTP2FramePayloadToHTTPClientCodec: ChannelDuplexHandler {
public typealias InboundIn = HTTP2Frame.FramePayload
public typealias InboundOut = HTTPResponsePart
public typealias OutboundIn = HTTPRequestPart
public typealias OutboundOut = HTTP2Frame.FramePayload
private var baseCodec: BaseClientCodec = .init()
public init() {}
public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
let payload = self.unwrapInboundIn(data)
do {
let (first, second) = try self.baseCodec.processInboundData(payload)
if let first {
context.fireChannelRead(self.wrapInboundOut(first))
}
if let second {
context.fireChannelRead(self.wrapInboundOut(second))
}
} catch {
context.fireErrorCaught(error)
}
}
public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
let requestPart = self.unwrapOutboundIn(data)
do {
let transformedPayload = try self.baseCodec.processOutboundData(requestPart, allocator: context.channel.allocator)
context.write(self.wrapOutboundOut(transformedPayload), promise: promise)
} catch {
promise?.fail(error)
context.fireErrorCaught(error)
}
}
}
// MARK: - Server
private struct BaseServerCodec {
private var headerStateMachine: HTTP2HeadersStateMachine = .init(mode: .server)
mutating func processInboundData(_ data: HTTP2Frame.FramePayload) throws -> (first: HTTPRequestPart?, second: HTTPRequestPart?) {
switch data {
case .headers(let headerContent):
if case .trailer = try self.headerStateMachine.newHeaders(block: headerContent.headers) {
let newTrailers = try HTTPFields(trailers: headerContent.headers)
return (first: .end(newTrailers), second: nil)
} else {
let newRequest = try HTTPRequest(headerContent.headers)
let first = HTTPRequestPart.head(newRequest)
var second: HTTPRequestPart?
if headerContent.endStream {
second = .end(nil)
}
return (first: first, second: second)
}
case .data(let dataContent):
guard case .byteBuffer(let b) = dataContent.data else {
preconditionFailure("Received non-byteBuffer IOData from network")
}
var first = HTTPRequestPart.body(b)
var second: HTTPRequestPart?
if dataContent.endStream {
if b.readableBytes == 0 {
first = .end(nil)
} else {
second = .end(nil)
}
}
return (first: first, second: second)
default:
// Any other frame type is ignored.
return (first: nil, second: nil)
}
}
mutating func processOutboundData(_ data: HTTPResponsePart, allocator: ByteBufferAllocator) -> HTTP2Frame.FramePayload {
switch data {
case .head(let head):
let payload = HTTP2Frame.FramePayload.Headers(headers: HPACKHeaders(head))
return .headers(payload)
case .body(let body):
let payload = HTTP2Frame.FramePayload.Data(data: .byteBuffer(body))
return .data(payload)
case .end(let trailers):
if let trailers {
return .headers(.init(
headers: HPACKHeaders(trailers),
endStream: true
))
} else {
return .data(.init(data: .byteBuffer(allocator.buffer(capacity: 0)), endStream: true))
}
}
}
}
/// A simple channel handler that translates HTTP/2 concepts into shared HTTP types,
/// and vice versa, for use on the server side.
///
/// Use this channel handler alongside the `HTTP2StreamMultiplexer` to
/// help provide an HTTP transaction-level abstraction on top of an HTTP/2 multiplexed
/// connection.
///
/// This handler uses `HTTP2Frame.FramePayload` as its HTTP/2 currency type.
public final class HTTP2FramePayloadToHTTPServerCodec: ChannelDuplexHandler {
public typealias InboundIn = HTTP2Frame.FramePayload
public typealias InboundOut = HTTPRequestPart
public typealias OutboundIn = HTTPResponsePart
public typealias OutboundOut = HTTP2Frame.FramePayload
private var baseCodec: BaseServerCodec = .init()
public init() {}
public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
let payload = self.unwrapInboundIn(data)
do {
let (first, second) = try self.baseCodec.processInboundData(payload)
if let first {
context.fireChannelRead(self.wrapInboundOut(first))
}
if let second {
context.fireChannelRead(self.wrapInboundOut(second))
}
} catch {
context.fireErrorCaught(error)
}
}
public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
let responsePart = self.unwrapOutboundIn(data)
let transformedPayload = self.baseCodec.processOutboundData(responsePart, allocator: context.channel.allocator)
context.write(self.wrapOutboundOut(transformedPayload), promise: promise)
}
}
@@ -0,0 +1,263 @@
//===----------------------------------------------------------------------===//
//
// 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 NIOHPACK
private enum HTTP2TypeConversionError: Error {
case multipleMethod
case multipleScheme
case multipleAuthority
case multiplePath
case multipleProtocol
case missingMethod
case invalidMethod
case multipleStatus
case missingStatus
case invalidStatus
case pseudoFieldNotFirst
case pseudoFieldInTrailers
}
private extension HPACKIndexing {
init(_ newIndexingStrategy: HTTPField.DynamicTableIndexingStrategy) {
switch newIndexingStrategy {
case .avoid: self = .nonIndexable
case .disallow: self = .neverIndexed
default: self = .indexable
}
}
}
private extension HTTPField.DynamicTableIndexingStrategy {
init(_ oldIndexing: HPACKIndexing) {
switch oldIndexing {
case .indexable: self = .automatic
case .nonIndexable: self = .avoid
case .neverIndexed: self = .disallow
}
}
}
extension HPACKHeaders {
private mutating func add(newField field: HTTPField) {
self.add(name: field.name.canonicalName, value: field.value, indexing: HPACKIndexing(field.indexingStrategy))
}
init(_ newRequest: HTTPRequest) {
self.init()
self.reserveCapacity(newRequest.headerFields.count + 5)
self.add(newField: newRequest.pseudoHeaderFields.method)
if let field = newRequest.pseudoHeaderFields.scheme {
self.add(newField: field)
}
if let field = newRequest.pseudoHeaderFields.authority {
self.add(newField: field)
}
if let field = newRequest.pseudoHeaderFields.path {
self.add(newField: field)
}
if let field = newRequest.pseudoHeaderFields.extendedConnectProtocol {
self.add(newField: field)
}
for field in newRequest.headerFields {
self.add(newField: field)
}
}
init(_ newResponse: HTTPResponse) {
self.init()
self.reserveCapacity(newResponse.headerFields.count + 1)
self.add(newField: newResponse.pseudoHeaderFields.status)
for field in newResponse.headerFields {
self.add(newField: field)
}
}
init(_ newTrailers: HTTPFields) {
self.init()
self.reserveCapacity(newTrailers.count)
for field in newTrailers {
self.add(newField: field)
}
}
}
extension HTTPRequest {
init(_ hpack: HPACKHeaders) throws {
var methodString: String? = nil
var methodIndexable: HPACKIndexing = .indexable
var schemeString: String? = nil
var schemeIndexable: HPACKIndexing = .indexable
var authorityString: String? = nil
var authorityIndexable: HPACKIndexing = .indexable
var pathString: String? = nil
var pathIndexable: HPACKIndexing = .indexable
var protocolString: String? = nil
var protocolIndexable: HPACKIndexing = .indexable
var i = hpack.startIndex
while i != hpack.endIndex {
let (name, value, indexable) = hpack[i]
if !name.hasPrefix(":") {
break
}
switch name {
case ":method":
if methodString != nil {
throw HTTP2TypeConversionError.multipleMethod
}
methodString = value
methodIndexable = indexable
case ":scheme":
if schemeString != nil {
throw HTTP2TypeConversionError.multipleScheme
}
schemeString = value
schemeIndexable = indexable
case ":authority":
if authorityString != nil {
throw HTTP2TypeConversionError.multipleAuthority
}
authorityString = value
authorityIndexable = indexable
case ":path":
if pathString != nil {
throw HTTP2TypeConversionError.multiplePath
}
pathString = value
pathIndexable = indexable
case ":protocol":
if protocolString != nil {
throw HTTP2TypeConversionError.multipleProtocol
}
protocolString = value
protocolIndexable = indexable
default:
continue
}
i = hpack.index(after: i)
}
guard let methodString else {
throw HTTP2TypeConversionError.missingMethod
}
guard let method = HTTPRequest.Method(methodString) else {
throw HTTP2TypeConversionError.invalidMethod
}
self.init(
method: method,
scheme: schemeString,
authority: authorityString,
path: pathString
)
self.pseudoHeaderFields.method.indexingStrategy = .init(methodIndexable)
self.pseudoHeaderFields.scheme?.indexingStrategy = .init(schemeIndexable)
self.pseudoHeaderFields.authority?.indexingStrategy = .init(authorityIndexable)
self.pseudoHeaderFields.path?.indexingStrategy = .init(pathIndexable)
if let protocolString {
self.extendedConnectProtocol = protocolString
self.pseudoHeaderFields.extendedConnectProtocol?.indexingStrategy = .init(protocolIndexable)
}
self.headerFields.reserveCapacity(hpack.count)
while i != hpack.endIndex {
let (name, value, indexable) = hpack[i]
if name.hasPrefix(":") {
throw HTTP2TypeConversionError.pseudoFieldNotFirst
}
if let fieldName = HTTPField.Name(name) {
var field = HTTPField(name: fieldName, value: value)
field.indexingStrategy = .init(indexable)
self.headerFields.append(field)
}
i = hpack.index(after: i)
}
}
}
extension HTTPResponse {
init(_ hpack: HPACKHeaders) throws {
var statusString: String? = nil
var statusIndexable: HPACKIndexing = .indexable
var i = hpack.startIndex
while i != hpack.endIndex {
let (name, value, indexable) = hpack[i]
if !name.hasPrefix(":") {
break
}
switch name {
case ":status":
if statusString != nil {
throw HTTP2TypeConversionError.multipleStatus
}
statusString = value
statusIndexable = indexable
default:
continue
}
i = hpack.index(after: i)
}
guard let statusString else {
throw HTTP2TypeConversionError.missingStatus
}
guard let status = Int(statusString),
(0 ... 999).contains(status) else {
throw HTTP2TypeConversionError.invalidStatus
}
self.init(status: HTTPResponse.Status(code: status))
self.pseudoHeaderFields.status.indexingStrategy = .init(statusIndexable)
self.headerFields.reserveCapacity(hpack.count)
while i != hpack.endIndex {
let (name, value, indexable) = hpack[i]
if name.hasPrefix(":") {
throw HTTP2TypeConversionError.pseudoFieldNotFirst
}
if let fieldName = HTTPField.Name(name) {
var field = HTTPField(name: fieldName, value: value)
field.indexingStrategy = .init(indexable)
self.headerFields.append(field)
}
i = hpack.index(after: i)
}
}
}
extension HTTPFields {
init(trailers: HPACKHeaders) throws {
self.init()
self.reserveCapacity(trailers.count)
for (name, value, indexable) in trailers {
if name.hasPrefix(":") {
throw HTTP2TypeConversionError.pseudoFieldInTrailers
}
if let fieldName = HTTPField.Name(name) {
var field = HTTPField(name: fieldName, value: value)
field.indexingStrategy = .init(indexable)
self.append(field)
}
}
}
}