Skip to content
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

Add request task cancellation, and improve handling of graceful shutdown #379

Open
wants to merge 2 commits into
base: 2.x.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
124 changes: 59 additions & 65 deletions Sources/HummingbirdCore/Server/HTTP/HTTPChannelHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -33,83 +33,77 @@
case closeConnection
}

enum HTTPState: Int, AtomicValue {
case idle
case processing
case cancelled
}

extension HTTPChannelHandler {
public func handleHTTP(asyncChannel: NIOAsyncChannel<HTTPRequestPart, HTTPResponsePart>, logger: Logger) async {
let processingRequest = ManagedAtomic(HTTPState.idle)
do {
try await withGracefulShutdownHandler {
try await asyncChannel.executeThenClose { inbound, outbound in
let responseWriter = HBHTTPServerBodyWriter(outbound: outbound)
var iterator = inbound.makeAsyncIterator()

// read first part, verify it is a head
guard let part = try await iterator.next() else { return }
guard case .head(var head) = part else {
throw HTTPChannelError.unexpectedHTTPPart(part)
}

while true {
// set to processing unless it is cancelled then exit
guard processingRequest.exchange(.processing, ordering: .relaxed) == .idle else { break }
Copy link
Contributor Author

Choose a reason for hiding this comment

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

I didn't add the graceful check here, I wasn't sure if that was "correct" because we already received .head


let bodyStream = NIOAsyncChannelRequestBody(iterator: iterator)
let request = HBRequest(head: head, body: .init(asyncSequence: bodyStream))
let response: HBResponse
do {
response = try await self.responder(request, asyncChannel.channel)
} catch {
response = self.getErrorResponse(from: error, allocator: asyncChannel.channel.allocator)
}
do {
try await outbound.write(.head(response.head))
let tailHeaders = try await response.body.write(responseWriter)
try await outbound.write(.end(tailHeaders))
} catch {
throw error
}
if request.headers[.connection] == "close" {
throw HTTPChannelError.closeConnection
try await withThrowingDiscardingTaskGroup { taskGroup in
taskGroup.addTask {
try await asyncChannel.executeThenClose { inbound, outbound in
let responseWriter = HBHTTPServerBodyWriter(outbound: outbound)
var iterator = inbound.makeAsyncIterator()

// read first part, verify it is a head
guard let part = try await iterator.next() else { return }
guard case .head(var head) = part else {
throw HTTPChannelError.unexpectedHTTPPart(part)

Check warning on line 48 in Sources/HummingbirdCore/Server/HTTP/HTTPChannelHandler.swift

View check run for this annotation

Codecov / codecov/patch

Sources/HummingbirdCore/Server/HTTP/HTTPChannelHandler.swift#L48

Added line #L48 was not covered by tests
}
// set to idle unless it is cancelled then exit
guard processingRequest.exchange(.idle, ordering: .relaxed) == .processing else { break }

// Flush current request
// read until we don't have a body part
var part: HTTPRequestPart?
while true {
part = try await iterator.next()
guard case .body = part else { break }
let bodyStream = NIOAsyncChannelRequestBody(iterator: iterator)
let request = HBRequest(head: head, body: .init(asyncSequence: bodyStream))
let response: HBResponse
do {
response = try await self.responder(request, asyncChannel.channel)
} catch {
response = self.getErrorResponse(from: error, allocator: asyncChannel.channel.allocator)
}
do {
try await outbound.write(.head(response.head))
let tailHeaders = try await response.body.write(responseWriter)
try await outbound.write(.end(tailHeaders))
} catch {
throw error
}
if request.headers[.connection] == "close" {
throw HTTPChannelError.closeConnection
}

// Flush current request
// read until we don't have a body part
var part: HTTPRequestPart?
while true {
part = try await iterator.next()
guard case .body = part else { break }
}
// if we have an end then read the next part
if case .end = part {
part = try await iterator.next()
}

// if part is nil break out of loop
guard let part else {
break
}

// Process next request unless it is cancelled then exit
if Task.isShuttingDownGracefully || Task.isCancelled {
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Cancellation check is moved down. I can imagine that some clients might fail if we do respond, but don't consume the body before closing the connection.

return

Check warning on line 90 in Sources/HummingbirdCore/Server/HTTP/HTTPChannelHandler.swift

View check run for this annotation

Codecov / codecov/patch

Sources/HummingbirdCore/Server/HTTP/HTTPChannelHandler.swift#L90

Added line #L90 was not covered by tests
}

// part should be a head, if not throw error
guard case .head(let newHead) = part else { throw HTTPChannelError.unexpectedHTTPPart(part) }
head = newHead
}
// if we have an end then read the next part
if case .end = part {
part = try await iterator.next()
}

// if part is nil break out of loop
guard let part else {
break
}

// part should be a head, if not throw error
guard case .head(let newHead) = part else { throw HTTPChannelError.unexpectedHTTPPart(part) }
head = newHead
}
}
} onGracefulShutdown: {
// set to cancelled
if processingRequest.exchange(.cancelled, ordering: .relaxed) == .idle {
// only close the channel input if it is idle
asyncChannel.channel.close(mode: .input, promise: nil)
}

try await asyncChannel.channel.closeFuture.get()

Choose a reason for hiding this comment

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

This shouldn't be needed. executeThenClose makes sure that the channel is closed

Copy link
Contributor Author

Choose a reason for hiding this comment

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

The reason I do this is because I want to trigger .cancelAll() if the channel closes while a request is still being handled

taskGroup.cancelAll()
}
} catch HTTPChannelError.closeConnection {
// channel is being closed because we received a connection: close header
} catch is CancellationError {
// Task hierarchy was cancelled, either due to a closed socket or a graceful shutdown

Check warning on line 106 in Sources/HummingbirdCore/Server/HTTP/HTTPChannelHandler.swift

View check run for this annotation

Codecov / codecov/patch

Sources/HummingbirdCore/Server/HTTP/HTTPChannelHandler.swift#L106

Added line #L106 was not covered by tests
} catch {
// we got here because we failed to either read or write to the channel
logger.trace("Failed to read/write to Channel. Error: \(error)")
Expand Down
2 changes: 1 addition & 1 deletion Sources/HummingbirdCore/Server/Server.swift
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ public actor HBServer<ChildChannel: HBChildChannel>: Service {
await withDiscardingTaskGroup { group in
do {
try await asyncChannel.executeThenClose { inbound in
for try await childChannel in inbound {
for try await childChannel in inbound.cancelOnGracefulShutdown() {
adam-fowler marked this conversation as resolved.
Show resolved Hide resolved
group.addTask {
await childChannelSetup.handle(value: childChannel, logger: logger)
}
Expand Down