Skip to content

Commit

Permalink
Merge pull request #4 from dymmond/feature/run_sync
Browse files Browse the repository at this point in the history
Add run_sync
  • Loading branch information
tarsil authored Jan 5, 2024
2 parents de464be + a95ff2e commit 62f4f9c
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 6 deletions.
16 changes: 15 additions & 1 deletion backgrounder/concurrency.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import asyncio
import functools
from typing import Any, Awaitable, Callable, TypeVar
from concurrent import futures
from typing import Any, Awaitable, Callable, Coroutine, TypeVar

import anyio.to_thread

Expand All @@ -8,6 +10,18 @@
T = TypeVar("T")


def run_sync(async_function: Coroutine) -> Any:
"""
Runs the queries in sync mode
"""
try:
return asyncio.run(async_function)
except RuntimeError:
with futures.ThreadPoolExecutor(max_workers=1) as executor:
future = executor.submit(asyncio.run, async_function)
return future.result()


async def run_in_threadpool(func: Callable[..., T], *args: Any, **kwargs: Any) -> T:
"""
Runs a callable in a threapool.
Expand Down
7 changes: 2 additions & 5 deletions backgrounder/decorator.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import asyncio
import functools
from typing import Any, Callable

Expand All @@ -7,7 +6,7 @@
import nest_asyncio
import sniffio

from backgrounder.concurrency import AsyncCallable
from backgrounder.concurrency import AsyncCallable, run_sync
from backgrounder.tasks import Task

nest_asyncio.apply()
Expand All @@ -25,13 +24,11 @@ def wrapper(*args: Any, **kwargs: Any) -> Any:
The wrapper covers for the decorator as individual as
well as coming from the classes.
"""

task = Task(fn, *args, **kwargs)
try:
sniffio.current_async_library()
async_callable = AsyncCallable(fn)
loop = asyncio.get_event_loop()
return loop.run_until_complete(async_callable(*args, **kwargs))
return run_sync(async_callable(*args, **kwargs)) # type: ignore
except sniffio.AsyncLibraryNotFoundError:
return anyio.run(task)

Expand Down

0 comments on commit 62f4f9c

Please sign in to comment.