Source code for s365b.core.concurrency

"""Run a group of coroutines that live and die together."""

from __future__ import annotations

import asyncio
from collections.abc import Coroutine, Iterable
from typing import Any


[docs] async def all_or_cancel[T](coros: Iterable[Coroutine[Any, Any, T]]) -> list[T]: """Run coroutines concurrently; if one fails, cancel the rest and wait for them. Unlike :func:`asyncio.gather`, nothing is left running when this returns or raises, so a caller can safely close clients and release locks afterwards. Args: coros: The coroutines. Returns: Their results, in order. Raises: Exception: The first failure, unwrapped from the task group's exception group. """ tasks: list[asyncio.Task[T]] = [] try: async with asyncio.TaskGroup() as group: tasks = [group.create_task(c) for c in coros] except BaseExceptionGroup as eg: first = next( (e for e in eg.exceptions if not isinstance(e, asyncio.CancelledError)), eg.exceptions[0], ) raise first from None return [t.result() for t in tasks]