From 7f7dbef47d0fa4847e8200cae9bf7881d8612aff Mon Sep 17 00:00:00 2001 From: Adam Fowler Date: Wed, 24 Jan 2024 13:19:33 +0000 Subject: [PATCH] Ensure we are running on EventLoop after AsyncMiddleware (#357) --- .../AsyncAwaitSupport/AsyncMiddleware.swift | 8 +++++-- Tests/HummingbirdTests/AsyncAwaitTests.swift | 24 +++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/Sources/Hummingbird/AsyncAwaitSupport/AsyncMiddleware.swift b/Sources/Hummingbird/AsyncAwaitSupport/AsyncMiddleware.swift index 3a6f9f302..8e1b3b3c7 100644 --- a/Sources/Hummingbird/AsyncAwaitSupport/AsyncMiddleware.swift +++ b/Sources/Hummingbird/AsyncAwaitSupport/AsyncMiddleware.swift @@ -42,10 +42,14 @@ struct HBPropagateServiceContextResponder: HBResponder { func respond(to request: HBRequest) -> EventLoopFuture { 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) + } } } } diff --git a/Tests/HummingbirdTests/AsyncAwaitTests.swift b/Tests/HummingbirdTests/AsyncAwaitTests.swift index ee8e126ac..d3ded28f8 100644 --- a/Tests/HummingbirdTests/AsyncAwaitTests.swift +++ b/Tests/HummingbirdTests/AsyncAwaitTests.swift @@ -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 { + 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) + } + } }