Skip to content

Commit

Permalink
Ensure we are running on EventLoop after AsyncMiddleware (#357)
Browse files Browse the repository at this point in the history
  • Loading branch information
adam-fowler authored Jan 24, 2024
1 parent 02ab651 commit 7f7dbef
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
8 changes: 6 additions & 2 deletions Sources/Hummingbird/AsyncAwaitSupport/AsyncMiddleware.swift
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,14 @@ struct HBPropagateServiceContextResponder: HBResponder {
func respond(to request: HBRequest) -> EventLoopFuture<HBResponse> {
if let serviceContext = ServiceContext.$current.get() {
return request.withServiceContext(serviceContext) { request in
self.responder.respond(to: request)
return request.eventLoop.flatSubmit {
self.responder.respond(to: request)
}
}
} else {
return self.responder.respond(to: request)
return request.eventLoop.flatSubmit {
self.responder.respond(to: request)
}
}
}
}
Expand Down
24 changes: 24 additions & 0 deletions Tests/HummingbirdTests/AsyncAwaitTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -228,4 +228,28 @@ final class AsyncAwaitTests: XCTestCase {
XCTAssertEqual(String(buffer: body), "abcdefghijklmnopqrstuvwxyz")
}
}

func testAfterAsyncMiddleware() throws {
struct EmptyAsyncMiddleware: HBAsyncMiddleware {
func apply(to request: HBRequest, next: HBResponder) async throws -> HBResponse {
return try await next.respond(to: request)
}
}
struct TestOnEventLoopMiddleware: HBMiddleware {
func apply(to request: HBRequest, next: HBResponder) -> EventLoopFuture<HBResponse> {
request.eventLoop.preconditionInEventLoop()
return next.respond(to: request)
}
}
let app = HBApplication(testing: .asyncTest)
app.middleware.add(EmptyAsyncMiddleware())
app.middleware.add(TestOnEventLoopMiddleware())
app.router.get { _ in HTTPResponseStatus.ok }

try app.XCTStart()
defer { app.XCTStop() }
try app.XCTExecute(uri: "/", method: .GET) { response in
XCTAssertEqual(response.status, .ok)
}
}
}

0 comments on commit 7f7dbef

Please sign in to comment.