File size: 1,086 Bytes
da906bd
bef5045
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
"""Application resource coordination."""
import asyncio
from collections.abc import Callable
from typing import Generic, Protocol, TypeVar

T = TypeVar("T")
_Task = TypeVar("_Task", contravariant=True)


class _WorkerRegistry(Protocol, Generic[_Task]):
    def add(self, task: _Task, /) -> None: ...
    def discard(self, task: _Task, /) -> None: ...


async def run_admitted_worker(workers: Callable[[], _WorkerRegistry[asyncio.Task[T]]],
                              semaphore: asyncio.Semaphore,
                              compute: Callable[..., T], *args: object) -> T:
    """Track an admitted thread until it finishes, even if its waiter cancels."""
    task = asyncio.create_task(asyncio.to_thread(compute, *args))
    workers().add(task)

    def finished(done: asyncio.Task[T]) -> None:
        # Resolve the current registry, but return capacity to the admitting semaphore.
        workers().discard(done)
        semaphore.release()
        if not done.cancelled():
            done.exception()

    task.add_done_callback(finished)
    return await asyncio.shield(task)