Static typing: async middleware is rejected by `use()` and `NextMiddleware` even though `resolve_async` supports it
Static type checker used
mypy (project's standard)
AWS Lambda function runtime
3.10
Powertools for AWS Lambda (Python) version
3.40.0
Static type checker info
We actually use ty (which is not an option in the template type checker selection), however the issue is flagged with mypy as well.
mypy 2.4.1 with its default configuration (mypy repro.py):
repro.py:12: error: Incompatible types in "await" (actual type "Response[Any]", expected type "Awaitable[Any]") [misc]
repro.py:15: error: List item 0 has incompatible type "Callable[[APIGatewayRestResolver, NextMiddleware], Coroutine[Any, Any, Response[Any]]]"; expected "Callable[..., Response[Any]]" [list-item]
Found 2 errors in 1 file (checked 1 source file)
Happy to open a PR if it is agreed that this should be addressed!
Code snippet
import asyncio
from typing import Any
from aws_lambda_powertools.event_handler import APIGatewayRestResolver, Response
from aws_lambda_powertools.event_handler.middlewares import NextMiddleware
app = APIGatewayRestResolver()
async def async_middleware(app: APIGatewayRestResolver, next_middleware: NextMiddleware) -> Response[Any]:
return await next_middleware(app)
app.use(middlewares=[async_middleware])
@app.get("/hello")
async def hello() -> dict[str, bool]:
return {"ok": True}
def lambda_handler(event: dict[str, Any], context: Any) -> dict[str, Any]:
return asyncio.run(app.resolve_async(event, context))
Possible Solution
- Widen
BaseRouter.use(self, middlewares: list[Callable[..., Response]])to acceptCallable[..., Response | Awaitable[Response]] - A separate protocol for async middleware, e.g.
AsyncNextMiddlewarewith__call__(self, app) -> Awaitable[Response], exported fromaws_lambda_powertools.event_handler.middlewares
Thanks for opening your first issue here! We'll come back to you as soon as we can. In the meantime, check out the #python channel on our Powertools for AWS Lambda Discord: Invite link
Thanks for opening your first issue here! We'll come back to you as soon as we can. In the meantime, check out our GitHub Discussions: Join the conversation
Hi @thejchap I'd like to work on this issue. I've investigated the current middleware typing definitions and async resolution implementation, and I believe this can be addressed by improving the typing contracts while preserving the existing runtime behavior. Could you please assign this issue to me? Thanks!
@coughlmao I am not a maintainer, but thanks for offering!
Got it @thejchap, thanks for clarifying, I'll wait for maintainer triage before proceeding. Appreciate your response!