The previous version allowed us to create our own asyncio event loop because it used asyncio.get_event_loop(). The new version (0.20.0), in newer versions of Python, uses asyncio.run() which creates its own event loop, and destroys the loop when done.
Not only does this change break our Mangum use-cases, it also means that you cannot keep the event loop across Lambda warm invokes. Which means that you can no longer follow "best practice" and retain, e.g. a global httpx AsyncClient for reuse, because httpx binds its AsyncClient to the current event loop. AWS recommends this kind of retention as an efficiency measure. It would be a shame if asyncio/ASGI-oriented apps could no longer follow this best practice and be forced to recreate such resources on every Lambda invoke.
It would be helpful if we had the option to pass in an event_loop factory so that we could retain the useful behavior of not treating each warm Lambda invoke as a completely new context. By making this an opt-in feature, people could have the simplicity of letting Mangum take care of spinning up the asyncio event loop (on every Lambda event) without precluding more advanced use-cases.
Is this idea of an "event loop factory" acceptable as a possible PR? Or is there another approach here that would let us continue to enjoy the old behavior?
The previous version allowed us to create our own asyncio event loop because it used
asyncio.get_event_loop(). The new version (0.20.0), in newer versions of Python, usesasyncio.run()which creates its own event loop, and destroys the loop when done.Not only does this change break our Mangum use-cases, it also means that you cannot keep the event loop across Lambda warm invokes. Which means that you can no longer follow "best practice" and retain, e.g. a global
httpxAsyncClientfor reuse, becausehttpxbinds itsAsyncClientto the current event loop. AWS recommends this kind of retention as an efficiency measure. It would be a shame if asyncio/ASGI-oriented apps could no longer follow this best practice and be forced to recreate such resources on every Lambda invoke.It would be helpful if we had the option to pass in an event_loop factory so that we could retain the useful behavior of not treating each warm Lambda invoke as a completely new context. By making this an opt-in feature, people could have the simplicity of letting Mangum take care of spinning up the asyncio event loop (on every Lambda event) without precluding more advanced use-cases.
Is this idea of an "event loop factory" acceptable as a possible PR? Or is there another approach here that would let us continue to enjoy the old behavior?