|
12 | 12 | //
|
13 | 13 | //===----------------------------------------------------------------------===//
|
14 | 14 |
|
| 15 | +import Logging |
15 | 16 | import NIO
|
| 17 | +import NIOConcurrencyHelpers |
| 18 | +import NIOHTTP1 |
| 19 | +import NIOSSL |
| 20 | +import NIOTLS |
| 21 | +import NIOTransportServices |
| 22 | +#if canImport(Network) |
| 23 | + import Network |
| 24 | + import Security |
| 25 | +#endif |
16 | 26 |
|
17 |
| -enum HTTPConnectionPool { |
18 |
| - |
| 27 | +protocol HTTPConnectionPoolDelegate { |
| 28 | + func connectionPoolDidShutdown(_ pool: HTTPConnectionPool, unclean: Bool) |
| 29 | +} |
| 30 | + |
| 31 | +class HTTPConnectionPool { |
19 | 32 | struct Connection: Equatable {
|
20 | 33 | typealias ID = Int
|
21 | 34 |
|
@@ -145,6 +158,327 @@ enum HTTPConnectionPool {
|
145 | 158 | }
|
146 | 159 | }
|
147 | 160 |
|
| 161 | + let stateLock = Lock() |
| 162 | + private var _state: StateMachine { |
| 163 | + didSet { |
| 164 | + self.logger.trace("Connection Pool State changed", metadata: [ |
| 165 | + "key": "\(self.key)", |
| 166 | + "state": "\(self._state)", |
| 167 | + ]) |
| 168 | + } |
| 169 | + } |
| 170 | + |
| 171 | + let timerLock = Lock() |
| 172 | + private var _waiters = [Waiter.ID: Scheduled<Void>]() |
| 173 | + private var _timer = [Connection.ID: Scheduled<Void>]() |
| 174 | + |
| 175 | + let key: ConnectionPool.Key |
| 176 | + var logger: Logger |
| 177 | + |
| 178 | + let eventLoopGroup: EventLoopGroup |
| 179 | + let connectionFactory: ConnectionFactory |
| 180 | + let idleConnectionTimeout: TimeAmount |
| 181 | + |
| 182 | + let delegate: HTTPConnectionPoolDelegate |
| 183 | + |
| 184 | + init(eventLoopGroup: EventLoopGroup, |
| 185 | + sslContextCache: SSLContextCache, |
| 186 | + tlsConfiguration: TLSConfiguration?, |
| 187 | + clientConfiguration: HTTPClient.Configuration, |
| 188 | + key: ConnectionPool.Key, |
| 189 | + delegate: HTTPConnectionPoolDelegate, |
| 190 | + idGenerator: Connection.ID.Generator, |
| 191 | + logger: Logger) { |
| 192 | + self.eventLoopGroup = eventLoopGroup |
| 193 | + self.connectionFactory = ConnectionFactory( |
| 194 | + key: key, |
| 195 | + tlsConfiguration: tlsConfiguration, |
| 196 | + clientConfiguration: clientConfiguration, |
| 197 | + sslContextCache: sslContextCache |
| 198 | + ) |
| 199 | + self.key = key |
| 200 | + self.delegate = delegate |
| 201 | + self.logger = logger |
| 202 | + |
| 203 | + self.idleConnectionTimeout = clientConfiguration.connectionPool.idleTimeout |
| 204 | + |
| 205 | + self._state = StateMachine( |
| 206 | + eventLoopGroup: eventLoopGroup, |
| 207 | + idGenerator: idGenerator, |
| 208 | + maximumConcurrentHTTP1Connections: 8 |
| 209 | + ) |
| 210 | + } |
| 211 | + |
| 212 | + func execute(request: HTTPRequestTask) { |
| 213 | + let (eventLoop, required) = request.resolveEventLoop() |
| 214 | + |
| 215 | + let action = self.stateLock.withLock { () -> StateMachine.Action in |
| 216 | + self._state.executeTask(request, onPreffered: eventLoop, required: required) |
| 217 | + } |
| 218 | + self.run(action: action) |
| 219 | + } |
| 220 | + |
| 221 | + func shutdown() { |
| 222 | + let action = self.stateLock.withLock { () -> StateMachine.Action in |
| 223 | + self._state.shutdown() |
| 224 | + } |
| 225 | + self.run(action: action) |
| 226 | + } |
| 227 | + |
| 228 | + func run(action: StateMachine.Action) { |
| 229 | + self.run(connectionAction: action.connection) |
| 230 | + self.run(taskAction: action.task) |
| 231 | + } |
| 232 | + |
| 233 | + func run(connectionAction: StateMachine.ConnectionAction) { |
| 234 | + switch connectionAction { |
| 235 | + case .createConnection(let connectionID, let eventLoop): |
| 236 | + self.createConnection(connectionID, on: eventLoop) |
| 237 | + |
| 238 | + case .scheduleTimeoutTimer(let connectionID): |
| 239 | + self.scheduleTimerForConnection(connectionID) |
| 240 | + |
| 241 | + case .cancelTimeoutTimer(let connectionID): |
| 242 | + self.cancelTimerForConnection(connectionID) |
| 243 | + |
| 244 | + case .replaceConnection(let oldConnection, with: let newConnectionID, on: let eventLoop): |
| 245 | + oldConnection.close() |
| 246 | + self.createConnection(newConnectionID, on: eventLoop) |
| 247 | + |
| 248 | + case .closeConnection(let connection, isShutdown: let isShutdown): |
| 249 | + connection.close() |
| 250 | + |
| 251 | + if case .yes(let unclean) = isShutdown { |
| 252 | + self.delegate.connectionPoolDidShutdown(self, unclean: unclean) |
| 253 | + } |
| 254 | + |
| 255 | + case .cleanupConnection(let close, let cancel, isShutdown: let isShutdown): |
| 256 | + for connection in close { |
| 257 | + connection.close() |
| 258 | + } |
| 259 | + |
| 260 | + for connection in cancel { |
| 261 | + connection.cancel() |
| 262 | + } |
| 263 | + |
| 264 | + if case .yes(let unclean) = isShutdown { |
| 265 | + self.delegate.connectionPoolDidShutdown(self, unclean: unclean) |
| 266 | + } |
| 267 | + |
| 268 | + case .none: |
| 269 | + break |
| 270 | + } |
| 271 | + } |
| 272 | + |
| 273 | + func run(taskAction: StateMachine.TaskAction) { |
| 274 | + switch taskAction { |
| 275 | + case .executeTask(let request, let connection, let waiterID): |
| 276 | + connection.execute(request: request) |
| 277 | + if let waiterID = waiterID { |
| 278 | + self.cancelWaiterTimeout(waiterID) |
| 279 | + } |
| 280 | + |
| 281 | + case .executeTasks(let requests, let connection): |
| 282 | + for (request, waiterID) in requests { |
| 283 | + connection.execute(request: request) |
| 284 | + if let waiterID = waiterID { |
| 285 | + self.cancelWaiterTimeout(waiterID) |
| 286 | + } |
| 287 | + } |
| 288 | + |
| 289 | + case .failTask(let request, let error, cancelWaiter: let waiterID): |
| 290 | + request.fail(error) |
| 291 | + |
| 292 | + if let waiterID = waiterID { |
| 293 | + self.cancelWaiterTimeout(waiterID) |
| 294 | + } |
| 295 | + |
| 296 | + case .failTasks(let requests, let error): |
| 297 | + for (request, waiterID) in requests { |
| 298 | + request.fail(error) |
| 299 | + |
| 300 | + if let waiterID = waiterID { |
| 301 | + self.cancelWaiterTimeout(waiterID) |
| 302 | + } |
| 303 | + } |
| 304 | + |
| 305 | + case .scheduleWaiterTimeout(let waiterID, let task, on: let eventLoop): |
| 306 | + self.scheduleWaiterTimeout(waiterID, task, on: eventLoop) |
| 307 | + |
| 308 | + case .cancelWaiterTimeout(let waiterID): |
| 309 | + self.cancelWaiterTimeout(waiterID) |
| 310 | + |
| 311 | + case .none: |
| 312 | + break |
| 313 | + } |
| 314 | + } |
| 315 | + |
| 316 | + // MARK: Run actions |
| 317 | + |
| 318 | + func createConnection(_ connectionID: Connection.ID, on eventLoop: EventLoop) { |
| 319 | + self.connectionFactory.makeConnection( |
| 320 | + for: self, |
| 321 | + connectionID: connectionID, |
| 322 | + eventLoop: eventLoop, |
| 323 | + logger: self.logger |
| 324 | + ) |
| 325 | + } |
| 326 | + |
| 327 | + func scheduleWaiterTimeout(_ id: Waiter.ID, _ task: HTTPRequestTask, on eventLoop: EventLoop) { |
| 328 | + let deadline = task.connectionDeadline |
| 329 | + let scheduled = eventLoop.scheduleTask(deadline: deadline) { |
| 330 | + // The timer has fired. Now we need to do a couple of things: |
| 331 | + // |
| 332 | + // 1. Remove ourselfes from the timer dictionary to not leak any data. If our |
| 333 | + // waiter entry still exist, we need to tell the state machine, that we want |
| 334 | + // to fail the request. |
| 335 | + |
| 336 | + let timeout = self.timerLock.withLock { |
| 337 | + self._waiters.removeValue(forKey: id) != nil |
| 338 | + } |
| 339 | + |
| 340 | + // 2. If the entry did not exists anymore, we can assume that the request was |
| 341 | + // scheduled on another connection. The timer still fired anyhow because of a |
| 342 | + // race. In such a situation we don't need to do anything. |
| 343 | + guard timeout else { return } |
| 344 | + |
| 345 | + // 3. Tell the state machine about the time |
| 346 | + let action = self.stateLock.withLock { |
| 347 | + self._state.waiterTimeout(id) |
| 348 | + } |
| 349 | + |
| 350 | + self.run(action: action) |
| 351 | + } |
| 352 | + |
| 353 | + self.timerLock.withLockVoid { |
| 354 | + precondition(self._waiters[id] == nil) |
| 355 | + self._waiters[id] = scheduled |
| 356 | + } |
| 357 | + |
| 358 | + task.requestWasQueued(self) |
| 359 | + } |
| 360 | + |
| 361 | + func cancelWaiterTimeout(_ id: Waiter.ID) { |
| 362 | + let scheduled = self.timerLock.withLock { |
| 363 | + self._waiters.removeValue(forKey: id) |
| 364 | + } |
| 365 | + |
| 366 | + scheduled?.cancel() |
| 367 | + } |
| 368 | + |
| 369 | + func scheduleTimerForConnection(_ connectionID: Connection.ID) { |
| 370 | + assert(self._timer[connectionID] == nil) |
| 371 | + |
| 372 | + let scheduled = self.eventLoopGroup.next().scheduleTask(in: self.idleConnectionTimeout) { |
| 373 | + // there might be a race between a cancelTimer call and the triggering |
| 374 | + // of this scheduled task. both want to acquire the lock |
| 375 | + self.stateLock.withLockVoid { |
| 376 | + guard self._timer.removeValue(forKey: connectionID) != nil else { |
| 377 | + // a cancel method has potentially won |
| 378 | + return |
| 379 | + } |
| 380 | + |
| 381 | + let action = self._state.connectionTimeout(connectionID) |
| 382 | + self.run(action: action) |
| 383 | + } |
| 384 | + } |
| 385 | + |
| 386 | + self._timer[connectionID] = scheduled |
| 387 | + } |
| 388 | + |
| 389 | + func cancelTimerForConnection(_ connectionID: Connection.ID) { |
| 390 | + guard let cancelTimer = self._timer.removeValue(forKey: connectionID) else { |
| 391 | + return |
| 392 | + } |
| 393 | + |
| 394 | + cancelTimer.cancel() |
| 395 | + } |
| 396 | +} |
| 397 | + |
| 398 | +extension HTTPConnectionPool { |
| 399 | + func http1ConnectionCreated(_ connection: HTTP1Connection) { |
| 400 | + let action = self.stateLock.withLock { |
| 401 | + self._state.newHTTP1ConnectionCreated(.http1_1(connection)) |
| 402 | + } |
| 403 | + self.run(action: action) |
| 404 | + } |
| 405 | + |
| 406 | + func http2ConnectionCreated(_ connection: HTTP2Connection) { |
| 407 | + let action = self.stateLock.withLock { () -> StateMachine.Action in |
| 408 | + if let settings = connection.settings { |
| 409 | + return self._state.newHTTP2ConnectionCreated(.http2(connection), settings: settings) |
| 410 | + } else { |
| 411 | + // immidiate connection closure before we can register with state machine |
| 412 | + // is the only reason we don't have settings |
| 413 | + struct ImmidiateConnectionClose: Error {} |
| 414 | + return self._state.failedToCreateNewConnection(ImmidiateConnectionClose(), connectionID: connection.id) |
| 415 | + } |
| 416 | + } |
| 417 | + self.run(action: action) |
| 418 | + } |
| 419 | + |
| 420 | + func failedToCreateHTTPConnection(_ connectionID: Connection.ID, error: Error) { |
| 421 | + let action = self.stateLock.withLock { |
| 422 | + self._state.failedToCreateNewConnection(error, connectionID: connectionID) |
| 423 | + } |
| 424 | + self.run(action: action) |
| 425 | + } |
| 426 | +} |
| 427 | + |
| 428 | +extension HTTPConnectionPool: HTTP1ConnectionDelegate { |
| 429 | + func http1ConnectionClosed(_ connection: HTTP1Connection) { |
| 430 | + let action = self.stateLock.withLock { |
| 431 | + self._state.connectionClosed(connection.id) |
| 432 | + } |
| 433 | + self.run(action: action) |
| 434 | + } |
| 435 | + |
| 436 | + func http1ConnectionReleased(_ connection: HTTP1Connection) { |
| 437 | + let action = self.stateLock.withLock { |
| 438 | + self._state.http1ConnectionReleased(connection.id) |
| 439 | + } |
| 440 | + self.run(action: action) |
| 441 | + } |
| 442 | +} |
| 443 | + |
| 444 | +extension HTTPConnectionPool: HTTP2ConnectionDelegate { |
| 445 | + func http2ConnectionClosed(_ connection: HTTP2Connection) { |
| 446 | + self.stateLock.withLock { |
| 447 | + let action = self._state.connectionClosed(connection.id) |
| 448 | + self.run(action: action) |
| 449 | + } |
| 450 | + } |
| 451 | + |
| 452 | + func http2ConnectionStreamClosed(_ connection: HTTP2Connection, availableStreams: Int) { |
| 453 | + self.stateLock.withLock { |
| 454 | + let action = self._state.http2ConnectionStreamClosed(connection.id, availableStreams: availableStreams) |
| 455 | + self.run(action: action) |
| 456 | + } |
| 457 | + } |
| 458 | +} |
| 459 | + |
| 460 | +extension HTTPConnectionPool: HTTP1RequestQueuer { |
| 461 | + func cancelRequest(task: HTTPRequestTask) { |
| 462 | + let waiterID = Waiter.ID(task) |
| 463 | + let action = self.stateLock.withLock { |
| 464 | + self._state.cancelWaiter(waiterID) |
| 465 | + } |
| 466 | + |
| 467 | + self.run(action: action) |
| 468 | + } |
| 469 | +} |
| 470 | + |
| 471 | +extension HTTPRequestTask { |
| 472 | + fileprivate func resolveEventLoop() -> (EventLoop, Bool) { |
| 473 | + switch self.eventLoopPreference.preference { |
| 474 | + case .indifferent: |
| 475 | + return (self.eventLoop, false) |
| 476 | + case .delegate(let el): |
| 477 | + return (el, false) |
| 478 | + case .delegateAndChannel(let el), .testOnly_exact(let el, _): |
| 479 | + return (el, true) |
| 480 | + } |
| 481 | + } |
148 | 482 | }
|
149 | 483 |
|
150 | 484 | struct EventLoopID: Hashable {
|
|
0 commit comments