"""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)