forked from grpc/grpc-swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHTTP2ToRawGRPCServerCodec.swift
356 lines (308 loc) · 10.2 KB
/
HTTP2ToRawGRPCServerCodec.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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
/*
* Copyright 2020, gRPC Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Logging
import NIOCore
import NIOHPACK
import NIOHTTP2
internal final class HTTP2ToRawGRPCServerCodec: ChannelInboundHandler, GRPCServerResponseWriter {
typealias InboundIn = HTTP2Frame.FramePayload
typealias OutboundOut = HTTP2Frame.FramePayload
private var logger: Logger
private var state: HTTP2ToRawGRPCStateMachine
private let errorDelegate: ServerErrorDelegate?
private var context: ChannelHandlerContext!
private let servicesByName: [Substring: CallHandlerProvider]
private let encoding: ServerMessageEncoding
private let normalizeHeaders: Bool
private let maxReceiveMessageLength: Int
/// The configuration state of the handler.
private var configurationState: Configuration = .notConfigured
/// Whether we are currently reading data from the `Channel`. Should be set to `false` once a
/// burst of reading has completed.
private var isReading = false
/// Indicates whether a flush event is pending. If a flush is received while `isReading` is `true`
/// then it is held until the read completes in order to elide unnecessary flushes.
private var flushPending = false
private enum Configuration {
case notConfigured
case configured(GRPCServerHandlerProtocol)
var isConfigured: Bool {
switch self {
case .configured:
return true
case .notConfigured:
return false
}
}
mutating func tearDown() -> GRPCServerHandlerProtocol? {
switch self {
case .notConfigured:
return nil
case let .configured(handler):
self = .notConfigured
return handler
}
}
}
init(
servicesByName: [Substring: CallHandlerProvider],
encoding: ServerMessageEncoding,
errorDelegate: ServerErrorDelegate?,
normalizeHeaders: Bool,
maximumReceiveMessageLength: Int,
logger: Logger
) {
self.logger = logger
self.errorDelegate = errorDelegate
self.servicesByName = servicesByName
self.encoding = encoding
self.normalizeHeaders = normalizeHeaders
self.maxReceiveMessageLength = maximumReceiveMessageLength
self.state = HTTP2ToRawGRPCStateMachine()
}
internal func handlerAdded(context: ChannelHandlerContext) {
self.context = context
}
internal func handlerRemoved(context: ChannelHandlerContext) {
self.context = nil
self.configurationState = .notConfigured
}
internal func errorCaught(context: ChannelHandlerContext, error: Error) {
switch self.configurationState {
case .notConfigured:
context.close(mode: .all, promise: nil)
case let .configured(hander):
hander.receiveError(error)
}
}
internal func channelInactive(context: ChannelHandlerContext) {
if let handler = self.configurationState.tearDown() {
handler.finish()
} else {
context.fireChannelInactive()
}
}
internal func channelRead(context: ChannelHandlerContext, data: NIOAny) {
self.isReading = true
let payload = self.unwrapInboundIn(data)
switch payload {
case let .headers(payload):
let receiveHeaders = self.state.receive(
headers: payload.headers,
eventLoop: context.eventLoop,
errorDelegate: self.errorDelegate,
remoteAddress: context.channel.remoteAddress,
logger: self.logger,
allocator: context.channel.allocator,
responseWriter: self,
closeFuture: context.channel.closeFuture,
services: self.servicesByName,
encoding: self.encoding,
normalizeHeaders: self.normalizeHeaders
)
switch receiveHeaders {
case let .configure(handler):
assert(!self.configurationState.isConfigured)
self.configurationState = .configured(handler)
self.configured()
case let .rejectRPC(trailers):
assert(!self.configurationState.isConfigured)
// We're not handling this request: write headers and end stream.
let payload = HTTP2Frame.FramePayload.headers(.init(headers: trailers, endStream: true))
context.writeAndFlush(self.wrapOutboundOut(payload), promise: nil)
}
case let .data(payload):
switch payload.data {
case var .byteBuffer(buffer):
let action = self.state.receive(buffer: &buffer, endStream: payload.endStream)
switch action {
case .tryReading:
self.tryReadingMessage()
case .finishHandler:
let handler = self.configurationState.tearDown()
handler?.finish()
case .nothing:
()
}
case .fileRegion:
preconditionFailure("Unexpected IOData.fileRegion")
}
// Ignored.
case .alternativeService,
.goAway,
.origin,
.ping,
.priority,
.pushPromise,
.rstStream,
.settings,
.windowUpdate:
()
}
}
internal func channelReadComplete(context: ChannelHandlerContext) {
self.isReading = false
if self.flushPending {
self.flushPending = false
context.flush()
}
context.fireChannelReadComplete()
}
/// Called when the pipeline has finished configuring.
private func configured() {
switch self.state.pipelineConfigured() {
case let .forwardHeaders(headers):
switch self.configurationState {
case .notConfigured:
preconditionFailure()
case let .configured(handler):
handler.receiveMetadata(headers)
}
case let .forwardHeadersAndRead(headers):
switch self.configurationState {
case .notConfigured:
preconditionFailure()
case let .configured(handler):
handler.receiveMetadata(headers)
}
self.tryReadingMessage()
}
}
/// Try to read a request message from the buffer.
private func tryReadingMessage() {
// This while loop exists to break the recursion in `.forwardMessageThenReadNextMessage`.
// Almost all cases return directly out of the loop.
while true {
let action = self.state.readNextRequest(
maxLength: self.maxReceiveMessageLength
)
switch action {
case .none:
return
case let .forwardMessage(buffer):
switch self.configurationState {
case .notConfigured:
preconditionFailure()
case let .configured(handler):
handler.receiveMessage(buffer)
}
return
case let .forwardMessageThenReadNextMessage(buffer):
switch self.configurationState {
case .notConfigured:
preconditionFailure()
case let .configured(handler):
handler.receiveMessage(buffer)
}
continue
case .forwardEnd:
switch self.configurationState {
case .notConfigured:
preconditionFailure()
case let .configured(handler):
handler.receiveEnd()
}
return
case let .errorCaught(error):
switch self.configurationState {
case .notConfigured:
preconditionFailure()
case let .configured(handler):
handler.receiveError(error)
}
return
}
}
}
internal func sendMetadata(
_ headers: HPACKHeaders,
flush: Bool,
promise: EventLoopPromise<Void>?
) {
switch self.state.send(headers: headers) {
case let .success(headers):
let payload = HTTP2Frame.FramePayload.headers(.init(headers: headers))
self.context.write(self.wrapOutboundOut(payload), promise: promise)
if flush {
self.markFlushPoint()
}
case let .failure(error):
promise?.fail(error)
}
}
internal func sendMessage(
_ buffer: ByteBuffer,
metadata: MessageMetadata,
promise: EventLoopPromise<Void>?
) {
let writeBuffer = self.state.send(
buffer: buffer,
allocator: self.context.channel.allocator,
compress: metadata.compress
)
switch writeBuffer {
case let .success((buffer, maybeBuffer)):
if let actuallyBuffer = maybeBuffer {
let payload1 = HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(buffer)))
self.context.write(self.wrapOutboundOut(payload1), promise: nil)
let payload2 = HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(actuallyBuffer)))
self.context.write(self.wrapOutboundOut(payload2), promise: promise)
} else {
let payload = HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(buffer)))
self.context.write(self.wrapOutboundOut(payload), promise: promise)
}
if metadata.flush {
self.markFlushPoint()
}
case let .failure(error):
promise?.fail(error)
}
}
internal func sendEnd(
status: GRPCStatus,
trailers: HPACKHeaders,
promise: EventLoopPromise<Void>?
) {
switch self.state.send(status: status, trailers: trailers) {
case let .sendTrailers(trailers):
self.sendTrailers(trailers, promise: promise)
case let .sendTrailersAndFinish(trailers):
self.sendTrailers(trailers, promise: promise)
// 'finish' the handler.
let handler = self.configurationState.tearDown()
handler?.finish()
case let .failure(error):
promise?.fail(error)
}
}
private func sendTrailers(_ trailers: HPACKHeaders, promise: EventLoopPromise<Void>?) {
// Always end stream for status and trailers.
let payload = HTTP2Frame.FramePayload.headers(.init(headers: trailers, endStream: true))
self.context.write(self.wrapOutboundOut(payload), promise: promise)
// We'll always flush on end.
self.markFlushPoint()
}
/// Mark a flush as pending - to be emitted once the read completes - if we're currently reading,
/// or emit a flush now if we are not.
private func markFlushPoint() {
if self.isReading {
self.flushPending = true
} else {
self.flushPending = false
self.context.flush()
}
}
}