# @pipedog/asyncio

> Tasks, cooperative cancellation, timeouts, queues and events with Python asyncio semantics.

Source: https://polvallverdu.github.io/pipedog/docs/api/asyncio/



```ts
import { createTask, Event, Queue, sleep, Task, waitFor } from "@pipedog/asyncio";
```

See [Interruptions & cancellation](https://polvallverdu.github.io/pipedog/docs/concepts/interruptions-and-cancellation.md) for how
cancellation points work.

## Task [#task]

A unit of concurrent work, like `asyncio.Task`. Created with `createTask()`. Awaiting a task (it
is thenable) is a cancellation point, and cancelling the awaiting task also cancels the awaited
one. Only `await` links the two: `task.then(cb)`, `task.promise` and `addDoneCallback` observe the
task without suspending the caller, so cancelling the caller cancels the caller alone.

| Option | Type | Required | Description |
|---|---|---|---|
| `name` | `string` | yes |  |
| `getName` | `() => string` | yes | asyncio Task.get_name() |
| `setName` | `(name: string) => void` | yes |  |
| `signal` | `AbortSignal` | yes | Aborted when cancellation is requested. Pass it to fetch() and friends. Once every request is withdrawn with `uncancel()`, a fresh signal is used. |
| `cancelling` | `() => number` | yes | Number of pending cancellation requests (asyncio Task.cancelling()). |
| `uncancel` | `() => number` | yes |  |
| `setResult` | `(_value: T) => void` | yes |  |
| `setException` | `(_error: unknown) => void` | yes |  |
| `cancel` | `(message?: string) => boolean` | yes | Request cancellation. Returns false if the task is already done. |
| `checkpoint` | `() => void` | yes | Throw CancelledError if a cancellation request is pending. Primitives call this on their fast paths, so a task that resumes from a foreign await after being cancelled stops at the next one. |
| `promise` | `Promise<T>` | yes | A promise that settles with the task, without being a cancellation point. |
| `toString` | `() => string` | yes | Returns a string representation of an object. |
| `done` | `() => boolean` | yes |  |
| `cancelled` | `() => boolean` | yes |  |
| `result` | `() => T` | yes |  |
| `exception` | `() => unknown` | yes |  |
| `addDoneCallback` | `(callback: (future: Task<T>) => void) => void` | yes |  |
| `removeDoneCallback` | `(callback: (future: Task<T>) => void) => number` | yes |  |
| `then` | `<R1 = T, R2 = never>(onfulfilled?: ((value: T) => R1 \| PromiseLike<R1>) \| null \| undefined, onrejected?: ((reason: unknown) => R2 \| PromiseLike<R2>) \| null \| undefined) => Promise<R1 \| R2>` | yes |  |

## Task functions [#task-functions]

| Option | Type | Required | Description |
|---|---|---|---|
| `createTask` | `<T>(fn: TaskFn<T>, name?: string) => Task<T>` | yes |  |
| `currentTask` | `() => Task<unknown> \| undefined` | yes |  |
| `currentSignal` | `() => AbortSignal` | yes |  |
| `abortable` | `<T>(promise: PromiseLike<T>) => Promise<T>` | yes |  |
| `checkCancelled` | `() => void` | yes |  |
| `suspend` | `<T>(register: (resolve: (value: T) => void, reject: (error: unknown) => void) => () => void, onCancel?: () => void) => Promise<T>` | yes |  |
| `rethrowIfCancelled` | `(e: unknown) => void` | yes |  |
| `isCancelledError` | `(e: unknown) => e is CancelledError` | yes |  |

## Timeouts and composition [#timeouts-and-composition]

| Option | Type | Required | Description |
|---|---|---|---|
| `sleep` | `(seconds: number) => Promise<void>` | yes |  |
| `waitFor` | `<T>(aw: Awaitable<T>, timeout: number \| null \| undefined) => Promise<T>` | yes |  |
| `timeout` | `<T>(seconds: number \| null, fn: TaskFn<T>) => Promise<T>` | yes |  |
| `gather` | `<T extends readonly unknown[]>(...aws: { [K in keyof T]: Awaitable<T[K]>; }) => Promise<T>` | yes |  |
| `gatherSettled` | `(...aws: Awaitable<unknown>[]) => Promise<unknown[]>` | yes |  |
| `wait` | `<F extends Future<any>>(tasks: Iterable<F>, options?: { timeout?: number \| null; returnWhen?: ReturnWhen; }) => Promise<[Set<F>, Set<F>]>` | yes |  |
| `shield` | `<T>(aw: Awaitable<T>) => Promise<T>` | yes |  |
| `time` | `() => number` | yes |  |
| `monotonic` | `() => number` | yes |  |
| `monotonicNs` | `() => number` | yes |  |

`waitFor(aw, timeout)` takes an `Awaitable`: pass a **function** so it runs as a child task that
is cancelled on timeout, raising `TimeoutError`. `timeout` is in seconds; `null` waits forever.

## Queue [#queue]

`asyncio.Queue`. `LifoQueue` and `PriorityQueue` subclass it by overriding the storage hooks.
`get()` and `put()` are cancellation points.

| Option | Type | Required | Description |
|---|---|---|---|
| `maxsize` | `number` | yes |  |
| `_items` | `T[]` | yes |  |
| `_head` | `number` | yes |  |
| `_init` | `() => void` | yes |  |
| `_put` | `(item: T) => void` | yes |  |
| `_get` | `() => T` | yes |  |
| `_size` | `() => number` | yes |  |
| `_queued` | `() => readonly T[]` | yes | The queued items in storage order (for subclasses that inspect them). |
| `qsize` | `() => number` | yes |  |
| `empty` | `() => boolean` | yes |  |
| `full` | `() => boolean` | yes |  |
| `put` | `(item: T) => Promise<void>` | yes |  |
| `putNowait` | `(item: T) => void` | yes |  |
| `get` | `() => Promise<T>` | yes |  |
| `getNowait` | `() => T` | yes |  |
| `taskDone` | `() => void` | yes |  |
| `join` | `() => Promise<void>` | yes |  |
| `shutdown` | `(immediate?: boolean) => void` | yes |  |

## Event [#event]

`asyncio.Event`. `wait()` is a cancellation point.

| Option | Type | Required | Description |
|---|---|---|---|
| `isSet` | `() => boolean` | yes |  |
| `set` | `() => void` | yes |  |
| `clear` | `() => void` | yes |  |
| `wait` | `() => Promise<true>` | yes |  |

## Lock and Semaphore [#lock-and-semaphore]

`async with lock:` is `await lock.run(async () => { ... })`.

| Option | Type | Required | Description |
|---|---|---|---|
| `locked` | `() => boolean` | yes |  |
| `acquire` | `() => Promise<true>` | yes |  |
| `release` | `() => void` | yes |  |
| `run` | `<R>(fn: () => Promise<R> \| R) => Promise<R>` | yes | `async with lock:` → `await lock.run(async () => {...})` |

| Option | Type | Required | Description |
|---|---|---|---|
| `locked` | `() => boolean` | yes | Due to state, or FIFO rules (must allow others to run first). |
| `acquire` | `() => Promise<true>` | yes |  |
| `release` | `() => void` | yes |  |
| `run` | `<R>(fn: () => Promise<R> \| R) => Promise<R>` | yes |  |

## Errors [#errors]

| Class                                      | Python                                             |
| ------------------------------------------ | -------------------------------------------------- |
| `CancelledError`                           | `asyncio.CancelledError`                           |
| `TimeoutError`                             | `asyncio.TimeoutError` / `TimeoutError`            |
| `InvalidStateError`                        | `asyncio.InvalidStateError`                        |
| `QueueEmpty`, `QueueFull`, `QueueShutDown` | `asyncio.QueueEmpty`, `QueueFull`, `QueueShutDown` |
