Skip to content

Tolerate shutdown message after channel is closed #646

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 31 additions & 13 deletions Sources/AsyncHTTPClient/ConnectionPool/HTTP2/HTTP2Connection.swift
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ final class HTTP2Connection {

deinit {
guard case .closed = self.state else {
preconditionFailure("Connection must be closed, before we can deinit it")
preconditionFailure("Connection must be closed, before we can deinit it. Current state: \(self.state)")
}
}

Expand All @@ -129,7 +129,7 @@ final class HTTP2Connection {
delegate: delegate,
logger: logger
)
return connection.start().map { maxStreams in (connection, maxStreams) }
return connection._start0().map { maxStreams in (connection, maxStreams) }
}

func executeRequest(_ request: HTTPExecutableRequest) {
Expand Down Expand Up @@ -164,15 +164,23 @@ final class HTTP2Connection {
return promise.futureResult
}

private func start() -> EventLoopFuture<Int> {
func _start0() -> EventLoopFuture<Int> {
self.channel.eventLoop.assertInEventLoop()

let readyToAcceptConnectionsPromise = self.channel.eventLoop.makePromise(of: Int.self)

self.state = .starting(readyToAcceptConnectionsPromise)
self.channel.closeFuture.whenComplete { _ in
self.state = .closed
self.delegate.http2ConnectionClosed(self)
switch self.state {
case .initialized, .closed:
preconditionFailure("invalid state \(self.state)")
case .starting(let readyToAcceptConnectionsPromise):
self.state = .closed
readyToAcceptConnectionsPromise.fail(HTTPClientError.remoteConnectionClosed)
case .active, .closing:
self.state = .closed
self.delegate.http2ConnectionClosed(self)
}
}

do {
Expand Down Expand Up @@ -258,16 +266,26 @@ final class HTTP2Connection {
private func shutdown0() {
self.channel.eventLoop.assertInEventLoop()

self.state = .closing
switch self.state {
case .active:
self.state = .closing

// inform all open streams, that the currently running request should be cancelled.
self.openStreams.forEach { box in
box.channel.triggerUserOutboundEvent(HTTPConnectionEvent.shutdownRequested, promise: nil)
}
// inform all open streams, that the currently running request should be cancelled.
self.openStreams.forEach { box in
box.channel.triggerUserOutboundEvent(HTTPConnectionEvent.shutdownRequested, promise: nil)
}

// inform the idle connection handler, that connection should be closed, once all streams
// are closed.
self.channel.triggerUserOutboundEvent(HTTPConnectionEvent.shutdownRequested, promise: nil)
// inform the idle connection handler, that connection should be closed, once all streams
// are closed.
self.channel.triggerUserOutboundEvent(HTTPConnectionEvent.shutdownRequested, promise: nil)

case .closed, .closing:
// we are already closing/closed and we need to tolerate this
break

case .initialized, .starting:
preconditionFailure("invalid state \(self.state)")
Comment on lines +286 to +287
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a reason for us not to support going from initialized straight to closed?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is an invalid transition. We require a call to start() before any other interaction which transitions to the starting case. Further interaction is only allowed after the promise returned by .start() is completed which transitions to either the .active or .closed state. This makes sure we don't violate this contract.

}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ extension HTTP2ConnectionTests {
static var allTests: [(String, (HTTP2ConnectionTests) -> () throws -> Void)] {
return [
("testCreateNewConnectionFailureClosedIO", testCreateNewConnectionFailureClosedIO),
("testConnectionToleratesShutdownEventsAfterAlreadyClosed", testConnectionToleratesShutdownEventsAfterAlreadyClosed),
("testSimpleGetRequest", testSimpleGetRequest),
("testEveryDoneRequestLeadsToAStreamAvailableCall", testEveryDoneRequestLeadsToAStreamAvailableCall),
("testCancelAllRunningRequests", testCancelAllRunningRequests),
Expand Down
24 changes: 24 additions & 0 deletions Tests/AsyncHTTPClientTests/HTTP2ConnectionTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,30 @@ class HTTP2ConnectionTests: XCTestCase {
).wait())
}

func testConnectionToleratesShutdownEventsAfterAlreadyClosed() {
let embedded = EmbeddedChannel()
XCTAssertNoThrow(try embedded.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 3000)).wait())

let logger = Logger(label: "test.http2.connection")
let connection = HTTP2Connection(
channel: embedded,
connectionID: 0,
decompression: .disabled,
delegate: TestHTTP2ConnectionDelegate(),
logger: logger
)
let startFuture = connection._start0()

XCTAssertNoThrow(try embedded.close().wait())
// to really destroy the channel we need to tick once
embedded.embeddedEventLoop.run()

XCTAssertThrowsError(try startFuture.wait())

// should not crash
connection.shutdown()
}

func testSimpleGetRequest() {
let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
let eventLoop = eventLoopGroup.next()
Expand Down