mirror of
https://github.com/apple/swift-nio-http2
synced 2026-11-30 05:28:45 +00:00
Reduce intermediate header copies. (#112)
Motivation: We were copying HTTP headers around quite a lot when transforming from HTTP/1 to HTTP/2 and back. Due to the different underlying representations we cannot get away from needing to do one copy, as the backing array storage is of a different type, but we were frequently incurring CoWs as well that were just totally unnecessary. Modifications: - Refactored the header code to work more confidently on HPACKHeaders. - Removed some mutating functions that triggered unnecessary CoWs. - Improved HPACKHeaders(httpHeaders:) initializer to avoid unnecessary intermediate array - Improved HTTPHeaders(requestHead:protocolString:) to avoid CoWs and reallocations - Improved HTTPHeaders(responseHead:) to avoid CoWs and reallocations Result: Fewer heap allocations
This commit is contained in:
1 parent
c383bfc958
commit
144f9d2a0e
4 files changed
+98
-80
No files matched your search
@@ -58,10 +58,10 @@ public final class HTTP2ToHTTP1ClientCodec: ChannelInboundHandler, ChannelOutbou
|
||||
switch frame.payload {
|
||||
case .headers(let headerContent):
|
||||
do {
|
||||
if case .trailer = try self.headerStateMachine.newHeaders(block: headerContent.headers.asH1Headers()) {
|
||||
context.fireChannelRead(self.wrapInboundOut(.end(headerContent.headers.asH1Headers())))
|
||||
if case .trailer = try self.headerStateMachine.newHeaders(block: headerContent.headers) {
|
||||
context.fireChannelRead(self.wrapInboundOut(.end(HTTPHeaders(regularHeadersFrom: headerContent.headers))))
|
||||
} else {
|
||||
let respHead = try HTTPResponseHead(http2HeaderBlock: headerContent.headers.asH1Headers())
|
||||
let respHead = try HTTPResponseHead(http2HeaderBlock: headerContent.headers)
|
||||
context.fireChannelRead(self.wrapInboundOut(.head(respHead)))
|
||||
if headerContent.endStream {
|
||||
context.fireChannelRead(self.wrapInboundOut(.end(nil)))
|
||||
@@ -147,10 +147,10 @@ public final class HTTP2ToHTTP1ServerCodec: ChannelInboundHandler, ChannelOutbou
|
||||
switch frame.payload {
|
||||
case .headers(let headerContent):
|
||||
do {
|
||||
if case .trailer = try self.headerStateMachine.newHeaders(block: headerContent.headers.asH1Headers()) {
|
||||
context.fireChannelRead(self.wrapInboundOut(.end(headerContent.headers.asH1Headers())))
|
||||
if case .trailer = try self.headerStateMachine.newHeaders(block: headerContent.headers) {
|
||||
context.fireChannelRead(self.wrapInboundOut(.end(HTTPHeaders(regularHeadersFrom: headerContent.headers))))
|
||||
} else {
|
||||
let reqHead = try HTTPRequestHead(http2HeaderBlock: headerContent.headers.asH1Headers())
|
||||
let reqHead = try HTTPRequestHead(http2HeaderBlock: headerContent.headers)
|
||||
context.fireChannelRead(self.wrapInboundOut(.head(reqHead)))
|
||||
if headerContent.endStream {
|
||||
context.fireChannelRead(self.wrapInboundOut(.end(nil)))
|
||||
@@ -361,62 +361,47 @@ internal extension String {
|
||||
// header blocks generated by the HTTP/2 layer.
|
||||
internal extension HTTPRequestHead {
|
||||
/// Create a `HTTPRequestHead` from the header block produced by nghttp2.
|
||||
init(http2HeaderBlock headers: HTTPHeaders) throws {
|
||||
// Take a local copy here.
|
||||
var headers = headers
|
||||
|
||||
// A request head should have only up to four psuedo-headers. We strip them off.
|
||||
let method = HTTPMethod(methodString: try headers.popPseudoHeader(name: ":method"))
|
||||
init(http2HeaderBlock headers: HPACKHeaders) throws {
|
||||
// A request head should have only up to four psuedo-headers.
|
||||
let method = HTTPMethod(methodString: try headers.peekPseudoHeader(name: ":method"))
|
||||
let version = HTTPVersion(major: 2, minor: 0)
|
||||
let uri = try headers.popPseudoHeader(name: ":path")
|
||||
let uri = try headers.peekPseudoHeader(name: ":path")
|
||||
|
||||
// TODO(cory): Right now we're just stripping scheme, but it should probably
|
||||
// be used.
|
||||
_ = try headers.popPseudoHeader(name: ":scheme")
|
||||
// Here we peek :scheme just to confirm it's there: we want the throw effect, but we don't care about the value.
|
||||
_ = try headers.peekPseudoHeader(name: ":scheme")
|
||||
|
||||
// This block works only if the HTTP/2 implementation rejects requests with
|
||||
// mismatched :authority and host headers.
|
||||
let authority = try headers.popPseudoHeader(name: ":authority")
|
||||
let authority = try headers.peekPseudoHeader(name: ":authority")
|
||||
|
||||
// We do a manual implementation of HTTPHeaders(regularHeadersFrom:) here because we may need to add an extra Host:
|
||||
// header here, and that can cause copies if we're unlucky. We need headers.count - 3 spaces: we remove :method,
|
||||
// :path, :scheme, and :authority, but we may add in Host.
|
||||
var rawHeaders: [(String, String)] = []
|
||||
rawHeaders.reserveCapacity(headers.count - 3)
|
||||
if !headers.contains(name: "host") {
|
||||
headers.add(name: "host", value: authority)
|
||||
rawHeaders.append(("host", authority))
|
||||
}
|
||||
rawHeaders.appendRegularHeaders(from: headers)
|
||||
|
||||
self.init(version: version, method: method, uri: uri)
|
||||
self.headers = headers
|
||||
self.init(version: version, method: method, uri: uri, headers: HTTPHeaders(rawHeaders))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
internal extension HTTPResponseHead {
|
||||
/// Create a `HTTPResponseHead` from the header block produced by nghttp2.
|
||||
init(http2HeaderBlock headers: HTTPHeaders) throws {
|
||||
// Take a local copy here.
|
||||
var headers = headers
|
||||
|
||||
init(http2HeaderBlock headers: HPACKHeaders) throws {
|
||||
// A response head should have only one psuedo-header. We strip it off.
|
||||
let statusHeader = try headers.popPseudoHeader(name: ":status")
|
||||
let statusHeader = try headers.peekPseudoHeader(name: ":status")
|
||||
guard let integerStatus = Int(statusHeader, radix: 10) else {
|
||||
throw NIOHTTP2Errors.InvalidStatusValue(statusHeader)
|
||||
}
|
||||
let status = HTTPResponseStatus(statusCode: integerStatus)
|
||||
self.init(version: .init(major: 2, minor: 0), status: status, headers: headers)
|
||||
self.init(version: .init(major: 2, minor: 0), status: status, headers: HTTPHeaders(regularHeadersFrom: headers))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
extension HTTPHeaders {
|
||||
/// Grabs a pseudo-header from a header block and removes it from that block.
|
||||
///
|
||||
/// - parameter:
|
||||
/// - name: The header name to remove.
|
||||
/// - returns: The value for this pseudo-header.
|
||||
/// - throws: If there is no such header, or multiple.
|
||||
internal mutating func popPseudoHeader(name: String) throws -> String {
|
||||
let header = try self.peekPseudoHeader(name: name)
|
||||
self.remove(name: name)
|
||||
return header
|
||||
}
|
||||
|
||||
extension HPACKHeaders {
|
||||
/// Grabs a pseudo-header from a header block. Does not remove it.
|
||||
///
|
||||
/// - parameter:
|
||||
@@ -437,43 +422,76 @@ extension HTTPHeaders {
|
||||
}
|
||||
|
||||
|
||||
fileprivate extension HTTPHeaders {
|
||||
init(requestHead: HTTPRequestHead, protocolString: String) throws {
|
||||
self.init()
|
||||
extension HTTPHeaders {
|
||||
fileprivate init(requestHead: HTTPRequestHead, protocolString: String) throws {
|
||||
// To avoid too much allocation we create an array first, and then initialize the HTTPHeaders from it.
|
||||
// We want to ensure this array is large enough so we only have to allocate once. We will need an
|
||||
// array that is the same as the number of headers in requestHead.headers + 3: we're adding :path,
|
||||
// :method, and :scheme, and transforming Host to :authority.
|
||||
var newHeaders: [(String, String)] = []
|
||||
newHeaders.reserveCapacity(requestHead.headers.count + 3)
|
||||
|
||||
// TODO(cory): This is potentially wrong if the URI contains more than just a path.
|
||||
self.add(name: ":path", value: requestHead.uri)
|
||||
self.add(name: ":method", value: String(httpMethod: requestHead.method))
|
||||
self.add(name: ":scheme", value: protocolString)
|
||||
newHeaders.append((":path", requestHead.uri))
|
||||
newHeaders.append((":method", String(httpMethod: requestHead.method)))
|
||||
newHeaders.append((":scheme", protocolString))
|
||||
|
||||
// Attempt to set the :authority pseudo-header. We don't error if this fails, we allow
|
||||
// the rest of the components to do so to avoid needing to maintain too much state here.
|
||||
var headers = requestHead.headers
|
||||
let authority = headers[canonicalForm: "host"]
|
||||
switch authority.count {
|
||||
case 0:
|
||||
throw NIOHTTP2Errors.MissingHostHeader()
|
||||
case 1:
|
||||
headers.remove(name: "host")
|
||||
self.add(name: ":authority", value: String(authority[0]))
|
||||
default:
|
||||
throw NIOHTTP2Errors.DuplicateHostHeader()
|
||||
// We store a place for the :authority header, even though we don't know what it is. We'll find it later and
|
||||
// change it when we do. This avoids us needing to potentially search this header block twice.
|
||||
var authorityHeader: String? = nil
|
||||
newHeaders.append((":authority", ""))
|
||||
|
||||
// Now fill in the others, except for any Host header we might find, which will become an :authority header.
|
||||
for header in requestHead.headers {
|
||||
if header.name.lowercased() == "host" {
|
||||
if authorityHeader != nil {
|
||||
throw NIOHTTP2Errors.DuplicateHostHeader()
|
||||
}
|
||||
|
||||
authorityHeader = header.value
|
||||
} else {
|
||||
newHeaders.append((header.name, header.value))
|
||||
}
|
||||
}
|
||||
|
||||
headers.forEach { self.add(name: $0.name, value: $0.value) }
|
||||
// Now we go back and fill in the authority header.
|
||||
guard let actualAuthorityHeader = authorityHeader else {
|
||||
throw NIOHTTP2Errors.MissingHostHeader()
|
||||
}
|
||||
newHeaders[3].1 = actualAuthorityHeader
|
||||
|
||||
self.init(newHeaders)
|
||||
}
|
||||
|
||||
init(responseHead: HTTPResponseHead) {
|
||||
self.init()
|
||||
fileprivate init(responseHead: HTTPResponseHead) {
|
||||
// To avoid too much allocation we create an array first, and then initialize the HTTPHeaders from it.
|
||||
// This array will need to be the size of the response headers + 1, for the :status field.
|
||||
var newHeaders: [(String, String)] = []
|
||||
newHeaders.reserveCapacity(responseHead.headers.count + 1)
|
||||
newHeaders.append((":status", String(responseHead.status.code)))
|
||||
responseHead.headers.forEach { newHeaders.append(($0.name, $0.value)) }
|
||||
|
||||
self.add(name: ":status", value: String(responseHead.status.code))
|
||||
responseHead.headers.forEach { self.add(name: $0.name, value: $0.value) }
|
||||
self.init(newHeaders)
|
||||
}
|
||||
|
||||
internal init(regularHeadersFrom oldHeaders: HPACKHeaders) {
|
||||
// We need to create an array to write the header fields into.
|
||||
var newHeaders: [(String, String)] = []
|
||||
newHeaders.reserveCapacity(oldHeaders.count)
|
||||
newHeaders.appendRegularHeaders(from: oldHeaders)
|
||||
self.init(newHeaders)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
extension HPACKHeaders {
|
||||
func asH1Headers() -> HTTPHeaders {
|
||||
return HTTPHeaders(self.map { ($0.0, $0.1) })
|
||||
extension Array where Element == (String, String) {
|
||||
mutating func appendRegularHeaders(from headers: HPACKHeaders) {
|
||||
for (name, value, _) in headers {
|
||||
if name.first == ":" {
|
||||
continue
|
||||
}
|
||||
|
||||
self.append((name, value))
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user