Skip to content

Use Claude Code, Codex, VSCode, Pi, and OpenCode (and 6 other harnesses) for free (1.3B+ free tokens) from your terminal, app, IDE, or phone, and now from the browser with native browser sessions (multi-harness + multi-model) like OpenClaw (voice supported + ToS friendly)

Python
965 B
Raw Blame
"""A worker boundary that retains ownership through caller cancellation."""

import asyncio
from collections.abc import Callable

from anyio import to_thread


async def run_sync_owned[T](function: Callable[[], T]) -> T:
    """Drain a finite worker before propagating cancellation; never abandon it."""
    return await wait_owned(asyncio.create_task(to_thread.run_sync(function)))


async def wait_owned[T](worker: asyncio.Task[T]) -> T:
    """Finish owned work before propagating any caller cancellation."""
    cancellation: asyncio.CancelledError | None = None
    while not worker.done():
        try:
            await asyncio.wait({worker})
        except asyncio.CancelledError as exc:
            cancellation = exc
    try:
        result = worker.result()
    except BaseException:
        if cancellation is not None:
            raise cancellation from None
        raise
    if cancellation is not None:
        raise cancellation
    return result