Skip to content

notify delegate about connect errors #245

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 7 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
2 changes: 1 addition & 1 deletion Sources/AsyncHTTPClient/ConnectionPool.swift
Original file line number Diff line number Diff line change
Expand Up @@ -562,7 +562,7 @@ class HTTP1ConnectionProvider {
error = HTTPClient.NWErrorHandler.translateError(error)
}
#endif
return self.eventLoop.makeFailedFuture(error)
return eventLoop.makeFailedFuture(error)
Copy link
Contributor

Choose a reason for hiding this comment

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

think this is the wrong way around, no?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

No, I think this is correct, all channel related stuff should be on channel EL, not on providers default EL

Copy link
Contributor

Choose a reason for hiding this comment

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

@artemredkin sorry, I meant from self. to missing self, eventLoop isn't a local variable, is it?

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, yes, this is a channel EL, I can rename it to make it more obvious

Copy link
Contributor

Choose a reason for hiding this comment

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

@artemredkin yes, I think that'd be a good idea tbh

}
}

Expand Down
21 changes: 14 additions & 7 deletions Sources/AsyncHTTPClient/HTTPClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -511,6 +511,14 @@ public class HTTPClient {
deadline: deadline,
setupComplete: setupComplete.futureResult,
logger: logger)

let taskHandler = TaskHandler(task: task,
kind: request.kind,
delegate: delegate,
redirectHandler: redirectHandler,
ignoreUncleanSSLShutdown: self.configuration.ignoreUncleanSSLShutdown,
logger: logger)

connection.flatMap { connection -> EventLoopFuture<Void> in
logger.debug("got connection for request",
metadata: ["ahc-connection": "\(connection)",
Expand All @@ -527,12 +535,6 @@ public class HTTPClient {
}

return future.flatMap {
let taskHandler = TaskHandler(task: task,
kind: request.kind,
delegate: delegate,
redirectHandler: redirectHandler,
ignoreUncleanSSLShutdown: self.configuration.ignoreUncleanSSLShutdown,
logger: logger)
return channel.pipeline.addHandler(taskHandler)
}.flatMap {
task.setConnection(connection)
Expand All @@ -556,7 +558,12 @@ public class HTTPClient {
}
}.always { _ in
setupComplete.succeed(())
}.cascadeFailure(to: task.promise)
}.whenFailure { error in
taskHandler.callOutToDelegateFireAndForget { task in
delegate.didReceiveError(task: task, error)
}
task.promise.fail(error)
}

return task
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ extension HTTPClientInternalTests {
("testUploadStreamingIsCalledOnTaskEL", testUploadStreamingIsCalledOnTaskEL),
("testWeCanActuallyExactlySetTheEventLoops", testWeCanActuallyExactlySetTheEventLoops),
("testTaskPromiseBoundToEL", testTaskPromiseBoundToEL),
("testConnectErrorCalloutOnCorrectEL", testConnectErrorCalloutOnCorrectEL),
]
}
}
39 changes: 39 additions & 0 deletions Tests/AsyncHTTPClientTests/HTTPClientInternalTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -959,4 +959,43 @@ class HTTPClientInternalTests: XCTestCase {
XCTAssertTrue(task.futureResult.eventLoop === el2)
XCTAssertNoThrow(try task.wait())
}

func testConnectErrorCalloutOnCorrectEL() throws {
class TestDelegate: HTTPClientResponseDelegate {
typealias Response = Void

let expectedEL: EventLoop
var receivedError: Bool = false

init(expectedEL: EventLoop) {
self.expectedEL = expectedEL
}

func didFinishRequest(task: HTTPClient.Task<Void>) throws {}

func didReceiveError(task: HTTPClient.Task<Void>, _ error: Error) {
self.receivedError = true
XCTAssertTrue(self.expectedEL.inEventLoop)
}
}

let elg = getDefaultEventLoopGroup(numberOfThreads: 2)
let el1 = elg.next()
let el2 = elg.next()

let httpBin = HTTPBin(refusesConnections: true)
let client = HTTPClient(eventLoopGroupProvider: .shared(elg))

defer {
XCTAssertNoThrow(try client.syncShutdown())
XCTAssertNoThrow(try elg.syncShutdownGracefully())
}

let request = try HTTPClient.Request(url: "http://localhost:\(httpBin.port)/get")
let delegate = TestDelegate(expectedEL: el1)
XCTAssertNoThrow(try httpBin.shutdown())
let task = client.execute(request: request, delegate: delegate, eventLoop: .init(.testOnly_exact(channelOn: el2, delegateOn: el1)))
XCTAssertThrowsError(try task.wait())
XCTAssertTrue(delegate.receivedError)
}
}
1 change: 1 addition & 0 deletions Tests/AsyncHTTPClientTests/HTTPClientTests+XCTest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ extension HTTPClientTests {
("testNothingIsLoggedAtInfoOrHigher", testNothingIsLoggedAtInfoOrHigher),
("testAllMethodsLog", testAllMethodsLog),
("testClosingIdleConnectionsInPoolLogsInTheBackground", testClosingIdleConnectionsInPoolLogsInTheBackground),
("testConnectErrorPropagatedToDelegate", testConnectErrorPropagatedToDelegate),
("testDelegateCallinsTolerateRandomEL", testDelegateCallinsTolerateRandomEL),
("testContentLengthTooLongFails", testContentLengthTooLongFails),
("testContentLengthTooShortFails", testContentLengthTooShortFails),
Expand Down
34 changes: 34 additions & 0 deletions Tests/AsyncHTTPClientTests/HTTPClientTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2008,6 +2008,40 @@ class HTTPClientTests: XCTestCase {
self.defaultClient = nil // so it doesn't get shut down again.
}

func testConnectErrorPropagatedToDelegate() throws {
class TestDelegate: HTTPClientResponseDelegate {
typealias Response = Void
var error: Error?
func didFinishRequest(task: HTTPClient.Task<Void>) throws {}
func didReceiveError(task: HTTPClient.Task<Response>, _ error: Error) {
self.error = error
}
}

let httpBin = HTTPBin()
let httpClient = HTTPClient(eventLoopGroupProvider: .shared(self.clientGroup))
defer {
XCTAssertNoThrow(try httpClient.syncShutdown())
}

let delegate = TestDelegate()
let request = try HTTPClient.Request(url: "http://localhost:\(httpBin.port)/get")
do {
try httpBin.shutdown()
Copy link
Contributor

Choose a reason for hiding this comment

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

this should be in an XCTAssertNoThrow

_ = try httpClient.execute(request: request, delegate: delegate).wait()
Copy link
Contributor

Choose a reason for hiding this comment

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

please use

XCTThrowsError(try httpClient.execute(...).wait()) { error in
   XCTAssert(...)
}

we literally had security issues before because of this pattern.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

done, thank you for catching this!

XCTFail("Should fail")
} catch {
switch (error, delegate.error) {
case (_ as NIOConnectionError, _ as NIOConnectionError):
break
case (_ as NIOConnectionError, .none):
XCTFail("Delegate error is not \(error)")
default:
XCTFail("Unexpected error: \(error)")
}
}
}

func testDelegateCallinsTolerateRandomEL() throws {
class TestDelegate: HTTPClientResponseDelegate {
typealias Response = Void
Expand Down