-
-
Notifications
You must be signed in to change notification settings - Fork 42
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
base: 2.x.x
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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 } | ||
|
||
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) | ||
} | ||
// 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 { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 | ||
} | ||
|
||
// 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() | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This shouldn't be needed. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The reason I do this is because I want to trigger |
||
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 | ||
} 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)") | ||
|
There was a problem hiding this comment.
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