fastapi / asyncer

Asyncer, async and await, focused on developer experience.
https://asyncer.tiangolo.com/
MIT License
1.62k stars 57 forks source link

🐛 Fix `syncify` with `raise_sync_error=False` on AnyIO 4.x.x, do not start new event loops unnecessarily #130

Closed tiangolo closed 7 months ago

tiangolo commented 7 months ago

🐛 Fix syncify with raise_sync_error=False on AnyIO 4.x.x, do not start new event loops unnecessarily

Currently, when using syncify(do_stuff, raise_sync_error=False)() and AnyIO 4.x.x, when running on an async context (there is a parent main async function, e.g. with FastAPI), it will instead of sending the async task to the async event loop in the main thread as it should, it will start a new event loop for this async task, which is incorrect behavior when there's a parent async function, it's the correct behavior only when there's no async parent function.

This is because AnyIO 4.x.x changed the internal name current_async_module with current_async_backend and Asyncer was only checking for that.

This includes the fix and tests that verify that jumping from async to sync to async and all those possible async sandwiches behave correctly, running things in the correct thread (the main thread with the event loop or worker threads for sync functions under async parents).