-
Notifications
You must be signed in to change notification settings - Fork 123
/
Copy pathHTTPConnectionPool+HTTP2StateMachine.swift
526 lines (464 loc) · 23.8 KB
/
HTTPConnectionPool+HTTP2StateMachine.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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
//===----------------------------------------------------------------------===//
//
// This source file is part of the AsyncHTTPClient open source project
//
// Copyright (c) 2021 Apple Inc. and the AsyncHTTPClient project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of AsyncHTTPClient project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIOCore
import NIOHTTP2
extension HTTPConnectionPool {
struct HTTP2StateMachine {
typealias Action = HTTPConnectionPool.StateMachine.Action
typealias ConnectionMigrationAction = HTTPConnectionPool.StateMachine.ConnectionMigrationAction
typealias EstablishedAction = HTTPConnectionPool.StateMachine.EstablishedAction
typealias EstablishedConnectionAction = HTTPConnectionPool.StateMachine.EstablishedConnectionAction
private enum State: Equatable {
case running
case shuttingDown(unclean: Bool)
case shutDown
}
private var lastConnectFailure: Error?
private var failedConsecutiveConnectionAttempts = 0
private(set) var connections: HTTP2Connections
private(set) var http1Connections: HTTP1Connections?
private(set) var requests: RequestQueue
private let idGenerator: Connection.ID.Generator
private var state: State = .running
init(
idGenerator: Connection.ID.Generator
) {
self.idGenerator = idGenerator
self.requests = RequestQueue()
self.connections = HTTP2Connections(generator: idGenerator)
}
mutating func migrateFromHTTP1(
http1State: HTTP1StateMachine,
newHTTP2Connection: Connection,
maxConcurrentStreams: Int
) -> Action {
self.migrateFromHTTP1(
http1Connections: http1State.connections,
http2Connections: http1State.http2Connections,
requests: http1State.requests,
newHTTP2Connection: newHTTP2Connection,
maxConcurrentStreams: maxConcurrentStreams
)
}
mutating func migrateFromHTTP1(
http1Connections: HTTP1Connections,
http2Connections: HTTP2Connections? = nil,
requests: RequestQueue,
newHTTP2Connection: Connection,
maxConcurrentStreams: Int
) -> Action {
let migrationAction = self.migrateConnectionsAndRequestsFromHTTP1(
http1Connections: http1Connections,
http2Connections: http2Connections,
requests: requests
)
let newConnectionAction = self._newHTTP2ConnectionEstablished(
newHTTP2Connection,
maxConcurrentStreams: maxConcurrentStreams
)
return .init(
request: newConnectionAction.request,
connection: .combined(migrationAction, newConnectionAction.connection)
)
}
private mutating func migrateConnectionsAndRequestsFromHTTP1(
http1Connections: HTTP1Connections,
http2Connections: HTTP2Connections?,
requests: RequestQueue
) -> ConnectionMigrationAction {
precondition(self.connections.isEmpty, "expected an empty state machine but connections are not empty")
precondition(self.http1Connections == nil, "expected an empty state machine but http1Connections are not nil")
precondition(self.requests.isEmpty, "expected an empty state machine but requests are not empty")
self.requests = requests
// we may have remaining open http2 connections from a pervious migration to http1
if let http2Connections = http2Connections {
self.connections = http2Connections
}
var http1Connections = http1Connections // make http1Connections mutable
let context = http1Connections.migrateToHTTP2()
self.connections.migrateFromHTTP1(
starting: context.starting,
backingOff: context.backingOff
)
let createConnections = self.connections.createConnectionsAfterMigrationIfNeeded(
requiredEventLoopsOfPendingRequests: requests.eventLoopsWithPendingRequests()
)
if !http1Connections.isEmpty {
self.http1Connections = http1Connections
}
// TODO: Potentially cancel unneeded bootstraps (Needs cancellable ClientBootstrap)
return .init(
closeConnections: context.close,
createConnections: createConnections
)
}
mutating func executeRequest(_ request: Request) -> Action {
switch self.state {
case .running:
if let eventLoop = request.requiredEventLoop {
return self.executeRequest(request, onRequired: eventLoop)
} else {
return self.executeRequest(request, onPreferred: request.preferredEventLoop)
}
case .shutDown, .shuttingDown:
// it is fairly unlikely that this condition is met, since the ConnectionPoolManager
// also fails new requests immediately, if it is shutting down. However there might
// be race conditions in which a request passes through a running connection pool
// manager, but hits a connection pool that is already shutting down.
//
// (Order in one lock does not guarantee order in the next lock!)
return .init(
request: .failRequest(request, HTTPClientError.alreadyShutdown, cancelTimeout: false),
connection: .none
)
}
}
private mutating func executeRequest(
_ request: Request,
onRequired eventLoop: EventLoop
) -> Action {
if let (connection, context) = self.connections.leaseStream(onRequired: eventLoop) {
/// 1. we have a stream available and can execute the request immediately
if context.wasIdle {
return .init(
request: .executeRequest(request, connection, cancelTimeout: false),
connection: .cancelTimeoutTimer(connection.id)
)
} else {
return .init(
request: .executeRequest(request, connection, cancelTimeout: false),
connection: .none
)
}
}
/// 2. No available stream so we definitely need to wait until we have one
self.requests.push(request)
if self.connections.hasConnectionThatCanOrWillBeAbleToExecuteRequests(for: eventLoop) {
/// 3. we already have a connection, we just need to wait until until it becomes available
return .init(
request: .scheduleRequestTimeout(for: request, on: eventLoop),
connection: .none
)
} else {
/// 4. we do *not* have a connection, need to create a new one and wait until it is connected.
let connectionId = self.connections.createNewConnection(on: eventLoop)
return .init(
request: .scheduleRequestTimeout(for: request, on: eventLoop),
connection: .createConnection(connectionId, on: eventLoop)
)
}
}
private mutating func executeRequest(
_ request: Request,
onPreferred eventLoop: EventLoop
) -> Action {
if let (connection, context) = self.connections.leaseStream(onPreferred: eventLoop) {
/// 1. we have a stream available and can execute the request immediately
if context.wasIdle {
return .init(
request: .executeRequest(request, connection, cancelTimeout: false),
connection: .cancelTimeoutTimer(connection.id)
)
} else {
return .init(
request: .executeRequest(request, connection, cancelTimeout: false),
connection: .none
)
}
}
/// 2. No available stream so we definitely need to wait until we have one
self.requests.push(request)
if self.connections.hasConnectionThatCanOrWillBeAbleToExecuteRequests {
/// 3. we already have a connection, we just need to wait until until it becomes available
return .init(
request: .scheduleRequestTimeout(for: request, on: eventLoop),
connection: .none
)
} else {
/// 4. we do *not* have a connection, need to create a new one and wait until it is connected.
let connectionId = self.connections.createNewConnection(on: eventLoop)
return .init(
request: .scheduleRequestTimeout(for: request, on: eventLoop),
connection: .createConnection(connectionId, on: eventLoop)
)
}
}
mutating func newHTTP2ConnectionEstablished(_ connection: Connection, maxConcurrentStreams: Int) -> Action {
.init(self._newHTTP2ConnectionEstablished(connection, maxConcurrentStreams: maxConcurrentStreams))
}
private mutating func _newHTTP2ConnectionEstablished(_ connection: Connection, maxConcurrentStreams: Int) -> EstablishedAction {
self.failedConsecutiveConnectionAttempts = 0
self.lastConnectFailure = nil
let (index, context) = self.connections.newHTTP2ConnectionEstablished(
connection,
maxConcurrentStreams: maxConcurrentStreams
)
return self.nextActionForAvailableConnection(at: index, context: context)
}
private mutating func nextActionForAvailableConnection(
at index: Int,
context: HTTP2Connections.EstablishedConnectionContext
) -> EstablishedAction {
switch self.state {
case .running:
// We prioritise requests with a required event loop over those without a requirement.
// This can cause starvation for request without a required event loop.
// We should come up with a better algorithm in the future.
var requestsToExecute = self.requests.popFirst(max: context.availableStreams, for: context.eventLoop)
let remainingAvailableStreams = context.availableStreams - requestsToExecute.count
// use the remaining available streams for requests without a required event loop
requestsToExecute += self.requests.popFirst(max: remainingAvailableStreams, for: nil)
let requestAction = { () -> HTTPConnectionPool.StateMachine.RequestAction in
if requestsToExecute.isEmpty {
return .none
} else {
// we can only lease streams if the connection has available streams.
// Otherwise we might crash even if we try to lease zero streams,
// because the connection might already be in the draining state.
let (connection, _) = self.connections.leaseStreams(at: index, count: requestsToExecute.count)
return .executeRequestsAndCancelTimeouts(requestsToExecute, connection)
}
}()
let connectionAction = { () -> EstablishedConnectionAction in
if context.isIdle, requestsToExecute.isEmpty {
return .scheduleTimeoutTimer(context.connectionID, on: context.eventLoop)
} else {
return .none
}
}()
return .init(
request: requestAction,
connection: connectionAction
)
case .shuttingDown(let unclean):
guard context.isIdle else {
return .none
}
let connection = self.connections.closeConnection(at: index)
if self.http1Connections == nil, self.connections.isEmpty {
return .init(
request: .none,
connection: .closeConnection(connection, isShutdown: .yes(unclean: unclean))
)
}
return .init(
request: .none,
connection: .closeConnection(connection, isShutdown: .no)
)
case .shutDown:
preconditionFailure("It the pool is already shutdown, all connections must have been torn down.")
}
}
mutating func newHTTP2MaxConcurrentStreamsReceived(_ connectionID: Connection.ID, newMaxStreams: Int) -> Action {
let (index, context) = self.connections.newHTTP2MaxConcurrentStreamsReceived(connectionID, newMaxStreams: newMaxStreams)
return .init(self.nextActionForAvailableConnection(at: index, context: context))
}
mutating func http2ConnectionGoAwayReceived(_ connectionID: Connection.ID) -> Action {
let context = self.connections.goAwayReceived(connectionID)
return self.nextActionForClosingConnection(on: context.eventLoop)
}
mutating func http2ConnectionClosed(_ connectionID: Connection.ID) -> Action {
guard let (index, context) = self.connections.failConnection(connectionID) else {
// When a connection close is initiated by the connection pool, the connection will
// still report its close to the state machine. In those cases we must ignore the
// event.
return .none
}
return self.nextActionForFailedConnection(at: index, on: context.eventLoop)
}
private mutating func nextActionForFailedConnection(at index: Int, on eventLoop: EventLoop) -> Action {
switch self.state {
case .running:
let hasPendingRequest = !self.requests.isEmpty(for: eventLoop) || !self.requests.isEmpty(for: nil)
guard hasPendingRequest else {
return .none
}
let (newConnectionID, previousEventLoop) = self.connections.createNewConnectionByReplacingClosedConnection(at: index)
precondition(previousEventLoop === eventLoop)
return .init(
request: .none,
connection: .createConnection(newConnectionID, on: eventLoop)
)
case .shuttingDown(let unclean):
assert(self.requests.isEmpty)
self.connections.removeConnection(at: index)
if self.connections.isEmpty {
return .init(
request: .none,
connection: .cleanupConnections(.init(), isShutdown: .yes(unclean: unclean))
)
}
return .none
case .shutDown:
preconditionFailure("If the pool is already shutdown, all connections must have been torn down.")
}
}
private mutating func nextActionForClosingConnection(on eventLoop: EventLoop) -> Action {
switch self.state {
case .running:
let hasPendingRequest = !self.requests.isEmpty(for: eventLoop) || !self.requests.isEmpty(for: nil)
guard hasPendingRequest else {
return .none
}
let newConnectionID = self.connections.createNewConnection(on: eventLoop)
return .init(
request: .none,
connection: .createConnection(newConnectionID, on: eventLoop)
)
case .shutDown, .shuttingDown:
return .none
}
}
mutating func http2ConnectionStreamClosed(_ connectionID: Connection.ID) -> Action {
let (index, context) = self.connections.releaseStream(connectionID)
return .init(self.nextActionForAvailableConnection(at: index, context: context))
}
mutating func failedToCreateNewConnection(_ error: Error, connectionID: Connection.ID) -> Action {
self.failedConsecutiveConnectionAttempts += 1
self.lastConnectFailure = error
let eventLoop = self.connections.backoffNextConnectionAttempt(connectionID)
let backoff = calculateBackoff(failedAttempt: self.failedConsecutiveConnectionAttempts)
return .init(request: .none, connection: .scheduleBackoffTimer(connectionID, backoff: backoff, on: eventLoop))
}
mutating func connectionCreationBackoffDone(_ connectionID: Connection.ID) -> Action {
// The naming of `failConnection` is a little confusing here. All it does is moving the
// connection state from `.backingOff` to `.closed` here. It also returns the
// connection's index.
guard let (index, context) = self.connections.failConnection(connectionID) else {
preconditionFailure("Backing off a connection that is unknown to us?")
}
return self.nextActionForFailedConnection(at: index, on: context.eventLoop)
}
mutating func timeoutRequest(_ requestID: Request.ID) -> Action {
// 1. check requests in queue
if let request = self.requests.remove(requestID) {
var error: Error = HTTPClientError.getConnectionFromPoolTimeout
if let lastError = self.lastConnectFailure {
error = lastError
} else if !self.connections.hasActiveConnections {
error = HTTPClientError.connectTimeout
}
return .init(
request: .failRequest(request, error, cancelTimeout: false),
connection: .none
)
}
// 2. This point is reached, because the request may have already been scheduled. A
// connection might have become available shortly before the request timeout timer
// fired.
return .none
}
mutating func cancelRequest(_ requestID: Request.ID) -> Action {
// 1. check requests in queue
if self.requests.remove(requestID) != nil {
return .init(
request: .cancelRequestTimeout(requestID),
connection: .none
)
}
// 2. This is point is reached, because the request may already have been forwarded to
// an idle connection. In this case the connection will need to handle the
// cancellation.
return .none
}
mutating func connectionIdleTimeout(_ connectionID: Connection.ID) -> Action {
guard let connection = connections.closeConnectionIfIdle(connectionID) else {
// because of a race this connection (connection close runs against trigger of timeout)
// was already removed from the state machine.
return .none
}
precondition(self.state == .running, "If we are shutting down, we must not have any idle connections")
return .init(
request: .none,
connection: .closeConnection(connection, isShutdown: .no)
)
}
mutating func http1ConnectionClosed(_ connectionID: Connection.ID) -> Action {
guard let index = self.http1Connections?.failConnection(connectionID)?.0 else {
return .none
}
self.http1Connections!.removeConnection(at: index)
if self.http1Connections!.isEmpty {
self.http1Connections = nil
}
switch self.state {
case .running:
return .none
case .shuttingDown(let unclean):
if self.http1Connections == nil, self.connections.isEmpty {
return .init(
request: .none,
connection: .cleanupConnections(.init(), isShutdown: .yes(unclean: unclean))
)
} else {
return .none
}
case .shutDown:
preconditionFailure("If the pool is already shutdown, all connections must have been torn down.")
}
}
mutating func http1ConnectionReleased(_ connectionID: Connection.ID) -> Action {
// It is save to bang the http1Connections here. If we get this callback but we don't have
// http1 connections something has gone terribly wrong.
let (index, _) = self.http1Connections!.releaseConnection(connectionID)
// Any http1 connection that becomes idle should be closed right away after the transition
// to http2.
let connection = self.http1Connections!.closeConnection(at: index)
guard self.http1Connections!.isEmpty else {
return .init(request: .none, connection: .closeConnection(connection, isShutdown: .no))
}
// if there are no more http1Connections, we can remove the struct.
self.http1Connections = nil
// we must also check, if we are shutting down. Was this maybe out last connection?
switch self.state {
case .running:
return .init(request: .none, connection: .closeConnection(connection, isShutdown: .no))
case .shuttingDown(let unclean):
if self.connections.isEmpty {
// if the http2connections are empty as well, there are no more connections. Shutdown completed.
return .init(request: .none, connection: .closeConnection(connection, isShutdown: .yes(unclean: unclean)))
} else {
return .init(request: .none, connection: .closeConnection(connection, isShutdown: .no))
}
case .shutDown:
preconditionFailure("If the pool is already shutdown, all connections must have been torn down.")
}
}
mutating func shutdown() -> Action {
// If we have remaining request queued, we should fail all of them with a cancelled
// error.
let waitingRequests = self.requests.removeAll()
var requestAction: StateMachine.RequestAction = .none
if !waitingRequests.isEmpty {
requestAction = .failRequestsAndCancelTimeouts(waitingRequests, HTTPClientError.cancelled)
}
// clean up the connections, we can cleanup now!
let cleanupContext = self.connections.shutdown()
// If there aren't any more connections, everything is shutdown
let isShutdown: StateMachine.ConnectionAction.IsShutdown
let unclean = !(cleanupContext.cancel.isEmpty && waitingRequests.isEmpty && self.http1Connections == nil)
if self.connections.isEmpty && self.http1Connections == nil {
isShutdown = .yes(unclean: unclean)
self.state = .shutDown
} else {
isShutdown = .no
self.state = .shuttingDown(unclean: unclean)
}
return .init(
request: requestAction,
connection: .cleanupConnections(cleanupContext, isShutdown: isShutdown)
)
}
}
}