-
Notifications
You must be signed in to change notification settings - Fork 82
/
HTTP2ToHTTPCodec.swift
265 lines (237 loc) · 9.85 KB
/
HTTP2ToHTTPCodec.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
//===----------------------------------------------------------------------===//
//
// 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, RemovableChannelHandler {
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, RemovableChannelHandler {
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)
}
}