Skip to content

Add support for custom cancellation error #683

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 1 commit into from
Apr 13, 2023
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
10 changes: 8 additions & 2 deletions Sources/AsyncHTTPClient/HTTPHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -688,7 +688,7 @@ extension URL {
}

protocol HTTPClientTaskDelegate {
func cancel()
func fail(_ error: Error)
}

extension HTTPClient {
Expand Down Expand Up @@ -780,12 +780,18 @@ extension HTTPClient {

/// Cancels the request execution.
public func cancel() {
self.fail(reason: HTTPClientError.cancelled)
}

/// Cancels the request execution with a custom `Error`.
/// - Parameter reason: the error that is used to fail the promise
public func fail(reason error: Error) {
let taskDelegate = self.lock.withLock { () -> HTTPClientTaskDelegate? in
self._isCancelled = true
return self._taskDelegate
}

taskDelegate?.cancel()
taskDelegate?.fail(error)
}

func succeed<Delegate: HTTPClientResponseDelegate>(promise: EventLoopPromise<Response>?,
Expand Down
8 changes: 1 addition & 7 deletions Sources/AsyncHTTPClient/RequestBag.swift
Original file line number Diff line number Diff line change
Expand Up @@ -394,7 +394,7 @@ final class RequestBag<Delegate: HTTPClientResponseDelegate> {
}
}

extension RequestBag: HTTPSchedulableRequest {
extension RequestBag: HTTPSchedulableRequest, HTTPClientTaskDelegate {
var tlsConfiguration: TLSConfiguration? {
self.request.tlsConfiguration
}
Expand Down Expand Up @@ -511,9 +511,3 @@ extension RequestBag: HTTPExecutableRequest {
}
}
}

extension RequestBag: HTTPClientTaskDelegate {
func cancel() {
self.fail(HTTPClientError.cancelled)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -327,7 +327,7 @@ class HTTP1ClientChannelHandlerTests: XCTestCase {
XCTAssertNoThrow(try embedded.writeInbound(HTTPClientResponsePart.head(responseHead)))

// canceling the request
requestBag.cancel()
requestBag.fail(HTTPClientError.cancelled)
XCTAssertThrowsError(try requestBag.task.futureResult.wait()) {
XCTAssertEqual($0 as? HTTPClientError, .cancelled)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,7 @@ class HTTP2ClientRequestHandlerTests: XCTestCase {
XCTAssertNoThrow(try embedded.writeInbound(HTTPClientResponsePart.head(responseHead)))

// canceling the request
requestBag.cancel()
requestBag.fail(HTTPClientError.cancelled)
XCTAssertThrowsError(try requestBag.task.futureResult.wait()) {
XCTAssertEqual($0 as? HTTPClientError, .cancelled)
}
Expand Down
1 change: 1 addition & 0 deletions Tests/AsyncHTTPClientTests/HTTPClientTests+XCTest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ extension HTTPClientTests {
("testStreaming", testStreaming),
("testFileDownload", testFileDownload),
("testFileDownloadError", testFileDownloadError),
("testFileDownloadCustomError", testFileDownloadCustomError),
("testRemoteClose", testRemoteClose),
("testReadTimeout", testReadTimeout),
("testConnectTimeout", testConnectTimeout),
Expand Down
25 changes: 25 additions & 0 deletions Tests/AsyncHTTPClientTests/HTTPClientTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -569,6 +569,31 @@ final class HTTPClientTests: XCTestCaseHTTPClientTestsBaseClass {
XCTAssertEqual(0, progress.receivedBytes)
}

func testFileDownloadCustomError() throws {
let request = try Request(url: self.defaultHTTPBinURLPrefix + "get")
struct CustomError: Equatable, Error {}

try TemporaryFileHelpers.withTemporaryFilePath { path in
let delegate = try FileDownloadDelegate(path: path, reportHead: { task, head in
XCTAssertEqual(head.status, .ok)
task.fail(reason: CustomError())
}, reportProgress: { _, _ in
XCTFail("should never be called")
})
XCTAssertThrowsError(
try self.defaultClient.execute(
request: request,
delegate: delegate
)
.wait()
) { error in
XCTAssertEqualTypeAndValue(error, CustomError())
}

XCTAssertFalse(TemporaryFileHelpers.fileExists(path: path))
}
}

func testRemoteClose() {
XCTAssertThrowsError(try self.defaultClient.get(url: self.defaultHTTPBinURLPrefix + "close").wait()) {
XCTAssertEqual($0 as? HTTPClientError, .remoteConnectionClosed)
Expand Down
2 changes: 1 addition & 1 deletion Tests/AsyncHTTPClientTests/HTTPConnectionPoolTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -334,7 +334,7 @@ class HTTPConnectionPoolTests: XCTestCase {

pool.executeRequest(requestBag)
XCTAssertNoThrow(try eventLoop.scheduleTask(in: .seconds(1)) {}.futureResult.wait())
requestBag.cancel()
requestBag.fail(HTTPClientError.cancelled)

XCTAssertThrowsError(try requestBag.task.futureResult.wait()) {
XCTAssertEqual($0 as? HTTPClientError, .cancelled)
Expand Down
12 changes: 6 additions & 6 deletions Tests/AsyncHTTPClientTests/RequestBagTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ final class RequestBagTests: XCTestCase {
XCTAssert(bag.eventLoop === embeddedEventLoop)

let executor = MockRequestExecutor(eventLoop: embeddedEventLoop)
bag.cancel()
bag.fail(HTTPClientError.cancelled)

bag.willExecuteRequest(executor)
XCTAssertTrue(executor.isCancelled, "The request bag, should call cancel immediately on the executor")
Expand Down Expand Up @@ -301,7 +301,7 @@ final class RequestBagTests: XCTestCase {
bag.fail(MyError())
XCTAssertEqual(delegate.hitDidReceiveError, 1)

bag.cancel()
bag.fail(HTTPClientError.cancelled)
XCTAssertEqual(delegate.hitDidReceiveError, 1)

XCTAssertThrowsError(try bag.task.futureResult.wait()) {
Expand Down Expand Up @@ -342,7 +342,7 @@ final class RequestBagTests: XCTestCase {
XCTAssertEqual(delegate.hitDidSendRequestHead, 1)
XCTAssertEqual(delegate.hitDidSendRequest, 1)

bag.cancel()
bag.fail(HTTPClientError.cancelled)
XCTAssertTrue(executor.isCancelled, "The request bag, should call cancel immediately on the executor")

XCTAssertThrowsError(try bag.task.futureResult.wait()) {
Expand Down Expand Up @@ -376,7 +376,7 @@ final class RequestBagTests: XCTestCase {
bag.requestWasQueued(queuer)

XCTAssertEqual(queuer.hitCancelCount, 0)
bag.cancel()
bag.fail(HTTPClientError.cancelled)
XCTAssertEqual(queuer.hitCancelCount, 1)

XCTAssertThrowsError(try bag.task.futureResult.wait()) {
Expand Down Expand Up @@ -445,9 +445,9 @@ final class RequestBagTests: XCTestCase {
let executor = MockRequestExecutor(eventLoop: embeddedEventLoop)
executor.runRequest(bag)

// This simulates a race between the user cancelling the task (which invokes `RequestBag.cancel`) and the
// This simulates a race between the user cancelling the task (which invokes `RequestBag.fail(_:)`) and the
// call to `resumeRequestBodyStream` (which comes from the `Channel` event loop and so may have to hop.
bag.cancel()
bag.fail(HTTPClientError.cancelled)
bag.resumeRequestBodyStream()

XCTAssertEqual(executor.isCancelled, true)
Expand Down