-
Notifications
You must be signed in to change notification settings - Fork 84
/
HTTP2StreamMultiplexer.swift
416 lines (378 loc) · 18.7 KB
/
HTTP2StreamMultiplexer.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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2021 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 NIOCore
/// A channel handler that creates a child channel for each HTTP/2 stream.
///
/// In general in NIO applications it is helpful to consider each HTTP/2 stream as an
/// independent stream of HTTP/2 frames. This multiplexer achieves this by creating a
/// number of in-memory `HTTP2StreamChannel` objects, one for each stream. These operate
/// on ``HTTP2Frame`` or ``HTTP2Frame/FramePayload`` objects as their base communication
/// atom, as opposed to the regular NIO `SelectableChannel` objects which use `ByteBuffer`
/// and `IOData`.
public final class HTTP2StreamMultiplexer: ChannelInboundHandler, ChannelOutboundHandler {
public typealias InboundIn = HTTP2Frame
public typealias InboundOut = HTTP2Frame
public typealias OutboundIn = HTTP2Frame
public typealias OutboundOut = HTTP2Frame
private let channel: Channel
private var context: ChannelHandlerContext!
private let commonStreamMultiplexer: HTTP2CommonInboundStreamMultiplexer
public func handlerAdded(context: ChannelHandlerContext) {
// We now need to check that we're on the same event loop as the one we were originally given.
// If we weren't, this is a hard failure, as there is a thread-safety issue here.
self.channel.eventLoop.preconditionInEventLoop()
self.context = context
}
public func handlerRemoved(context: ChannelHandlerContext) {
self.context = nil
self.commonStreamMultiplexer.clearDidReadChannels()
}
public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
let frame = self.unwrapInboundIn(data)
self.commonStreamMultiplexer.receivedFrame(
frame,
context: context,
multiplexer: .legacy(LegacyOutboundStreamMultiplexer(multiplexer: self))
)
}
public func channelReadComplete(context: ChannelHandlerContext) {
switch self.commonStreamMultiplexer.propagateReadComplete() {
case .flushNow:
context.flush()
case .noop:
break
}
context.fireChannelReadComplete()
}
public func flush(context: ChannelHandlerContext) {
switch self.commonStreamMultiplexer.flushDesired() {
case .proceed:
context.flush()
case .waitForReadsToComplete:
break // flush will be executed on `channelReadComplete`
}
}
public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
// for now just forward
context.write(data, promise: promise)
}
public func channelActive(context: ChannelHandlerContext) {
// We just got channelActive. Any previously existing channels may be marked active.
self.commonStreamMultiplexer.propagateChannelActive(context: context)
context.fireChannelActive()
}
public func channelInactive(context: ChannelHandlerContext) {
self.commonStreamMultiplexer.propagateChannelInactive()
context.fireChannelInactive()
}
public func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
switch event {
case let evt as StreamClosedEvent:
_ = self.commonStreamMultiplexer.streamClosed(event: evt)
case let evt as NIOHTTP2WindowUpdatedEvent where evt.streamID == .rootStream:
// This force-unwrap is safe: we always have a connection window.
self.newConnectionWindowSize(newSize: evt.inboundWindowSize!, context: context)
case let evt as NIOHTTP2WindowUpdatedEvent:
self.commonStreamMultiplexer.childStreamWindowUpdated(event: evt)
case let evt as NIOHTTP2BulkStreamWindowChangeEvent:
self.commonStreamMultiplexer.initialStreamWindowChanged(event: evt)
case let evt as NIOHTTP2StreamCreatedEvent:
_ = self.commonStreamMultiplexer.streamCreated(event: evt)
default:
self.commonStreamMultiplexer.selectivelyPropagateUserInboundEvent(context: context, event: event)
}
context.fireUserInboundEventTriggered(event)
}
public func channelWritabilityChanged(context: ChannelHandlerContext) {
self.commonStreamMultiplexer.propagateChannelWritabilityChanged(context: context)
context.fireChannelWritabilityChanged()
}
public func errorCaught(context: ChannelHandlerContext, error: Error) {
if let streamError = error as? NIOHTTP2Errors.StreamError {
self.commonStreamMultiplexer.streamError(context: context, streamError)
}
context.fireErrorCaught(error)
}
private func newConnectionWindowSize(newSize: Int, context: ChannelHandlerContext) {
guard let increment = self.commonStreamMultiplexer.newConnectionWindowSize(newSize) else {
return
}
// This is too much flushing, but for now it'll have to do.
let frame = HTTP2Frame(streamID: .rootStream, payload: .windowUpdate(windowSizeIncrement: increment))
context.writeAndFlush(self.wrapOutboundOut(frame), promise: nil)
}
/// Create a new ``HTTP2StreamMultiplexer``.
///
/// - Parameters:
/// - mode: The mode of the HTTP/2 connection being used: server or client.
/// - channel: The Channel to which this ``HTTP2StreamMultiplexer`` belongs.
/// - targetWindowSize: The target inbound connection and stream window size. Defaults to 65535 bytes.
/// - inboundStreamStateInitializer: A block that will be invoked to configure each new child stream
/// channel that is created by the remote peer. For servers, these are channels created by
/// receiving a `HEADERS` frame from a client. For clients, these are channels created by
/// receiving a `PUSH_PROMISE` frame from a server. To initiate a new outbound channel, use
/// ``createStreamChannel(promise:_:)-1jk0q``.
@available(
*,
deprecated,
renamed:
"init(mode:channel:targetWindowSize:outboundBufferSizeHighWatermark:outboundBufferSizeLowWatermark:inboundStreamInitializer:)"
)
public convenience init(
mode: NIOHTTP2Handler.ParserMode,
channel: Channel,
targetWindowSize: Int = 65535,
inboundStreamStateInitializer: NIOChannelInitializerWithStreamID? = nil
) {
// We default to an 8kB outbound buffer size: this is a good trade off for avoiding excessive buffering while ensuring that decent
// throughput can be maintained. We use 4kB as the low water mark.
self.init(
mode: mode,
channel: channel,
targetWindowSize: targetWindowSize,
outboundBufferSizeHighWatermark: 8192,
outboundBufferSizeLowWatermark: 4096,
inboundStreamStateInitializer: .includesStreamID(inboundStreamStateInitializer)
)
}
/// Create a new ``HTTP2StreamMultiplexer``.
///
/// - Parameters:
/// - mode: The mode of the HTTP/2 connection being used: server or client.
/// - channel: The Channel to which this ``HTTP2StreamMultiplexer`` belongs.
/// - targetWindowSize: The target inbound connection and stream window size. Defaults to 65535 bytes.
/// - outboundBufferSizeHighWatermark: The high watermark for the number of bytes of writes that are
/// allowed to be un-sent on any child stream. This is broadly analogous to a regular socket send buffer.
/// Defaults to 8196 bytes.
/// - outboundBufferSizeLowWatermark: The low watermark for the number of bytes of writes that are
/// allowed to be un-sent on any child stream. This is broadly analogous to a regular socket send buffer.
/// Defaults to 4092 bytes.
/// - inboundStreamInitializer: A block that will be invoked to configure each new child stream
/// channel that is created by the remote peer. For servers, these are channels created by
/// receiving a `HEADERS` frame from a client. For clients, these are channels created by
/// receiving a `PUSH_PROMISE` frame from a server. To initiate a new outbound channel, use
/// ``createStreamChannel(promise:_:)-1jk0q``.
public convenience init(
mode: NIOHTTP2Handler.ParserMode,
channel: Channel,
targetWindowSize: Int = 65535,
outboundBufferSizeHighWatermark: Int = 8196,
outboundBufferSizeLowWatermark: Int = 4092,
inboundStreamInitializer: NIOChannelInitializer?
) {
self.init(
mode: mode,
channel: channel,
targetWindowSize: targetWindowSize,
outboundBufferSizeHighWatermark: outboundBufferSizeHighWatermark,
outboundBufferSizeLowWatermark: outboundBufferSizeLowWatermark,
inboundStreamStateInitializer: .excludesStreamID(inboundStreamInitializer)
)
}
/// Create a new ``HTTP2StreamMultiplexer``.
///
/// - Parameters:
/// - mode: The mode of the HTTP/2 connection being used: server or client.
/// - channel: The Channel to which this `HTTP2StreamMultiplexer` belongs.
/// - targetWindowSize: The target inbound connection and stream window size. Defaults to 65535 bytes.
/// - outboundBufferSizeHighWatermark: The high watermark for the number of bytes of writes that are
/// allowed to be un-sent on any child stream. This is broadly analogous to a regular socket send buffer.
/// - outboundBufferSizeLowWatermark: The low watermark for the number of bytes of writes that are
/// allowed to be un-sent on any child stream. This is broadly analogous to a regular socket send buffer.
/// - inboundStreamStateInitializer: A block that will be invoked to configure each new child stream
/// channel that is created by the remote peer. For servers, these are channels created by
/// receiving a `HEADERS` frame from a client. For clients, these are channels created by
/// receiving a `PUSH_PROMISE` frame from a server. To initiate a new outbound channel, use
/// ``createStreamChannel(promise:_:)-1jk0q``.
@available(
*,
deprecated,
renamed:
"init(mode:channel:targetWindowSize:outboundBufferSizeHighWatermark:outboundBufferSizeLowWatermark:inboundStreamInitializer:)"
)
public convenience init(
mode: NIOHTTP2Handler.ParserMode,
channel: Channel,
targetWindowSize: Int = 65535,
outboundBufferSizeHighWatermark: Int,
outboundBufferSizeLowWatermark: Int,
inboundStreamStateInitializer: NIOChannelInitializerWithStreamID? = nil
) {
self.init(
mode: mode,
channel: channel,
targetWindowSize: targetWindowSize,
outboundBufferSizeHighWatermark: outboundBufferSizeHighWatermark,
outboundBufferSizeLowWatermark: outboundBufferSizeLowWatermark,
inboundStreamStateInitializer: .includesStreamID(inboundStreamStateInitializer)
)
}
private init(
mode: NIOHTTP2Handler.ParserMode,
channel: Channel,
targetWindowSize: Int = 65535,
outboundBufferSizeHighWatermark: Int,
outboundBufferSizeLowWatermark: Int,
inboundStreamStateInitializer: MultiplexerAbstractChannel.InboundStreamStateInitializer
) {
self.channel = channel
self.commonStreamMultiplexer = HTTP2CommonInboundStreamMultiplexer(
mode: mode,
channel: channel,
inboundStreamStateInitializer: inboundStreamStateInitializer,
targetWindowSize: targetWindowSize,
streamChannelOutboundBytesHighWatermark: outboundBufferSizeHighWatermark,
streamChannelOutboundBytesLowWatermark: outboundBufferSizeLowWatermark
)
}
}
extension HTTP2StreamMultiplexer {
/// Create a new `Channel` for a new stream initiated by this peer.
///
/// This method is intended for situations where the NIO application is initiating the stream. For clients,
/// this is for all request streams. For servers, this is for pushed streams.
///
/// > Note: Resources for the stream will be freed after it has been closed.
///
/// - Parameters:
/// - promise: An `EventLoopPromise` that will be succeeded with the new activated channel, or
/// failed if an error occurs.
/// - streamStateInitializer: A callback that will be invoked to allow you to configure the
/// `ChannelPipeline` for the newly created channel.
public func createStreamChannel(
promise: EventLoopPromise<Channel>?,
_ streamStateInitializer: @escaping NIOChannelInitializer
) {
let sendableView = HTTP2StreamMultiplexer.SendableView(
http2StreamMultiplexer: self,
eventLoop: self.channel.eventLoop
)
if self.channel.eventLoop.inEventLoop {
sendableView.createStreamChannel(promise: promise, streamStateInitializer)
} else {
self.channel.eventLoop.execute {
sendableView.createStreamChannel(promise: promise, streamStateInitializer)
}
}
}
/// Create a new `Channel` for a new stream initiated by this peer.
///
/// This method is intended for situations where the NIO application is initiating the stream. For clients,
/// this is for all request streams. For servers, this is for pushed streams.
///
/// > Note: Resources for the stream will be freed after it has been closed.
///
/// - Parameters:
/// - initializer: A callback that will be invoked to allow you to configure the
/// `ChannelPipeline` for the newly created channel.
/// - Returns: A future for the initialized `Channel`.
public func createStreamChannel(_ initializer: @escaping NIOChannelInitializer) -> EventLoopFuture<Channel> {
let promise = self.channel.eventLoop.makePromise(of: Channel.self)
self.createStreamChannel(promise: promise, initializer)
return promise.futureResult
}
/// Create a new `Channel` for a new stream initiated by this peer.
///
/// This method is intended for situations where the NIO application is initiating the stream. For clients,
/// this is for all request streams. For servers, this is for pushed streams.
///
/// > Note: Resources for the stream will be freed after it has been closed.
///
/// - Parameters:
/// - promise: An `EventLoopPromise` that will be succeeded with the new activated channel, or
/// failed if an error occurs.
/// - streamStateInitializer: A callback that will be invoked to allow you to configure the
/// `ChannelPipeline` for the newly created channel.
@available(
*,
deprecated,
message: "The signature of 'streamStateInitializer' has changed to '(Channel) -> EventLoopFuture<Void>'"
)
public func createStreamChannel(
promise: EventLoopPromise<Channel>?,
_ streamStateInitializer: @escaping NIOChannelInitializerWithStreamID
) {
let sendableView = HTTP2StreamMultiplexer.SendableView(
http2StreamMultiplexer: self,
eventLoop: self.channel.eventLoop
)
sendableView.createStreamChannel(promise: promise, streamStateInitializer)
}
}
extension HTTP2StreamMultiplexer {
/// HTTP2StreamMultiplexer.SendableView exposes only the thread-safe API of HTTP2StreamMultiplexer
///
/// We use unckecked Sendable here because we always make sure we are on the right event loop
/// from this code on.
struct SendableView: @unchecked Sendable {
let http2StreamMultiplexer: HTTP2StreamMultiplexer
let eventLoop: EventLoop
func createStreamChannel(
promise: EventLoopPromise<Channel>?,
_ streamStateInitializer: @escaping NIOChannelInitializer
) {
// Always create streams channels on the next event loop tick. This avoids re-entrancy
// issues where handlers interposed between the two HTTP/2 handlers could create streams
// in channel active which become activated twice.
self.eventLoop.execute {
self.http2StreamMultiplexer.commonStreamMultiplexer.createStreamChannel(
multiplexer: .legacy(LegacyOutboundStreamMultiplexer(multiplexer: self.http2StreamMultiplexer)),
promise: promise,
streamStateInitializer
)
}
}
@available(
*,
deprecated,
message: "The signature of 'streamStateInitializer' has changed to '(Channel) -> EventLoopFuture<Void>'"
)
func createStreamChannel(
promise: EventLoopPromise<Channel>?,
_ streamStateInitializer: @escaping NIOChannelInitializerWithStreamID
) {
// Always create streams channels on the next event loop tick. This avoids re-entrancy
// issues where handlers interposed between the two HTTP/2 handlers could create streams
// in channel active which become activated twice.
self.eventLoop.execute {
self.http2StreamMultiplexer.commonStreamMultiplexer.createStreamChannel(
multiplexer: .legacy(LegacyOutboundStreamMultiplexer(multiplexer: self.http2StreamMultiplexer)),
promise: promise,
streamStateInitializer
)
}
}
}
}
// MARK:- Child to parent calls
extension HTTP2StreamMultiplexer {
internal func childChannelClosed(streamID: HTTP2StreamID) {
self.commonStreamMultiplexer.childChannelClosed(streamID: streamID)
}
internal func childChannelClosed(channelID: ObjectIdentifier) {
self.commonStreamMultiplexer.childChannelClosed(channelID: channelID)
}
internal func childChannelWrite(_ frame: HTTP2Frame, promise: EventLoopPromise<Void>?) {
self.context.write(self.wrapOutboundOut(frame), promise: promise)
}
internal func childChannelFlush() {
self.flush(context: self.context)
}
/// Requests a ``HTTP2StreamID`` for the given `Channel`.
///
/// - Precondition: The `channel` must not already have a `streamID`.
internal func requestStreamID(forChannel channel: Channel) -> HTTP2StreamID {
self.commonStreamMultiplexer.requestStreamID(forChannel: channel)
}
}