Metadata-Version: 2.4
Name: flowlet
Version: 0.5.0
Summary: A minimal async pipeline library
License-Expression: BSD-3-Clause
Requires-Python: >=3.14
Description-Content-Type: text/markdown

# flowlet

Async pipelines for Python with a concurrency limit on every stage. Zero dependencies.

Fetch 20 pages at a time, extract their links, and write them in batches of 100:

```python
import asyncio
from flowlet import pipe


async def main() -> None:
    await (
        pipe(urls)
        .map(fetch_page, concurrency=20)
        .flat_map(extract_links, concurrency=4)
        .filter(is_internal)
        .batch(100)
        .map(bulk_insert, concurrency=4)
        .drain()
    )


asyncio.run(main())
```

- **Lazy and streaming**: nothing runs until you consume it. If the consumer falls behind, upstream stages slow down instead of buffering everything up front like `asyncio.gather`.
- **Concurrency per stage**: give each step its own limit, and opt into `ordered=True` when you need results in input order.
- **Cleans up after itself**: when a stage fails or you close the pipeline, in-flight tasks are cancelled, and the source and any iterators `flat_map` opened get closed.
- **Plays well with blocking code**: `in_thread` and `in_process` move blocking I/O and CPU work off the event loop, and `thread_local` gives each worker thread its own client.

## Installation

```bash
pip install flowlet
```

You'll need Python 3.14 or newer. Concurrent stages start tasks with `eager_start=True`, so any custom event loop or task factory must accept it (`uvloop` 0.23+ does).

## Core API

| API | Purpose | Cardinality |
| :--- | :--- | :--- |
| `pipe(source)` | Start a lazy pipeline from a sync or async iterable | — |
| `.map(fn, *, concurrency=1, ordered=False)` | Transform each item (sync or async `fn`) | 1 → 1 |
| `.filter(pred, *, concurrency=1, ordered=False)` | Keep items accepted by `pred` (sync or async) | 1 → 0..1 |
| `.flat_map(fn, *, concurrency=1, buffer=256, ordered=False)` | Expand each item into an iterable or async iterable | 1 → 0..N |
| `.batch(size)` | Group items into `list`s of up to `size` | N → 1 |
| `.through(flow)` | Apply a reusable [`Flow`](#reuse-and-other-styles) | Varies |
| `.collect()` | Consume the pipeline into a `list` | Consumer |
| `.drain()` | Consume for side effects, discarding results | Consumer |
| `async for item in pipeline` | Stream results lazily | Consumer |

- **Immutable**: adding a stage returns a new `Pipeline`, so reusing one is safe. One catch: a generator or other one-shot iterator still only runs once. Run a pipeline over it twice and the second pass sees nothing.
- **`None` is just data**: stages never treat `None` as an end-of-stream sentinel. If you want `None`s gone, filter them out.

### `flat_map` and `batch`

`flat_map(fn)` accepts a sync or async function returning any iterable or async iterable. Each expansion streams into the pipeline as its values arrive, rather than waiting to finish first.

Values flow through a bounded buffer (`256` by default) shared across expansions, plus one value per expansion waiting for room. That caps an unordered stage at `buffer + concurrency` values (see [Ordering](#ordering) for `ordered=True`). Raise `buffer` to trade memory for throughput on wide expansions:

```python
rows = pipe(files).flat_map(parse_rows, concurrency=8, buffer=2048)
```

`batch(size)` groups items into lists of up to `size`. If the source runs out mid-group, the last list is shorter:

```python
await pipe([1, 2, 3, 4, 5]).batch(2).collect()
# [[1, 2], [3, 4], [5]]
```

### Consuming streams

Use `async for` when you don't want everything in memory at once, and always for unbounded streams, where `.collect()` would grow a list forever. `.drain()` works there too in constant memory if the stages do the useful work:

```python
async for link in pipe(events).map(parse).filter(is_interesting):
    await handle(link)
```

If you might break out early, wrap the iterator in `contextlib.aclosing`:

```python
from contextlib import aclosing

items = []
async with aclosing(aiter(pipe(events).map(parse, concurrency=10))) as stream:
    async for item in stream:
        items.append(item)
        if len(items) == 100:
            break
```

A bare `break` leaves cleanup to the garbage collector, so in-flight tasks can keep running after the loop and cleanup errors won't reach you. `aclosing` shuts the pipeline down as soon as the block exits.

## Concurrency and ordering

Each stage sets its own concurrency:

- **`concurrency=1` (default)**: one input at a time. The stage won't pull the next item until the current one's output has gone downstream.
- **`concurrency > 1`**: up to `concurrency` calls run at once. When the consumer falls behind, the stage pauses and stops pulling new input.

### Ordering

**Concurrent stages emit results as they finish, not in input order.** Pass `ordered=True` to `map`, `flat_map`, or `filter` to keep input order without giving up concurrency:

```python
# Completion order: may return [3, 1, 2]
items = await pipe([1, 2, 3]).filter(async_pred, concurrency=3).collect()

# Input order: always [1, 2, 3], with three predicates running at once
items = await pipe([1, 2, 3]).filter(async_pred, concurrency=3, ordered=True).collect()
```

With `ordered=True`, you get the same output as `concurrency=1`: same values, same order, same ordinary failures. Only the timing changes.

Cancellation is the exception: `CancelledError` starts teardown right away in either mode. Teardown still waits for the stage's tasks, though, so a task that swallows cancellation delays it either way.

Ordering has two trade-offs:

- **Failures wait their turn**: if item 1 is slow and item 2 fails, an ordered stage waits for item 1 before raising. An unordered stage cancels pending work right away.
- **Ordered `flat_map` holds more**: each running expansion gets its own buffer, so the stage can hold up to `concurrency * (buffer + 1)` values instead of `buffer + concurrency`. Because an endless expansion blocks everything behind it, only use ordered mode for finite expansions.

## Error handling

**Pipelines fail fast.** When a stage raises, `flowlet` cancels pending work, runs cleanup, and re-raises.

To handle per-item failures without stopping the pipeline, catch them in your function and use `.flat_map(...)` to drop failed items:

```python
async def safe_fetch(url: str) -> list[Page]:
    try:
        return [await fetch(url)]
    except Exception:
        return []


items = await pipe(urls).flat_map(safe_fetch, concurrency=20).collect()
```

## Blocking work

Blocking sync code stalls the event loop. Wrap blocking I/O in `in_thread` and CPU-bound work in `in_process`.

Either way, at most `min(concurrency, max_workers)` calls run at once. Cancelling the pipeline stops waiting for a submitted call, but it can't interrupt sync code that's already running in a worker thread or process.

### Blocking I/O with `in_thread`

`in_thread(fn, *, executor=None)` runs `fn` in a thread pool and copies `contextvars` into the worker thread. With `executor=None`, it uses asyncio's default pool:

```python
from flowlet import in_thread, pipe

items = await pipe(keys).map(in_thread(load_s3), concurrency=64).collect()
```

Pass your own `ThreadPoolExecutor` to cap threads or share one pool across stages:

```python
from concurrent.futures import ThreadPoolExecutor
from flowlet import in_thread, pipe

with ThreadPoolExecutor(max_workers=16) as pool:
    items = await (
        pipe(keys)
        .map(in_thread(load_s3, executor=pool), concurrency=8)
        .map(in_thread(parse_blob, executor=pool), concurrency=4)
        .collect()
    )
```

With `flat_map(in_thread(fn))`, return a `list` or `tuple`, not a lazy generator. A generator gets created on the worker thread and iterated later on the event loop, which defeats the point.

### Per-thread resources with `thread_local`

Use `@thread_local` to create a blocking client or session once per worker thread and reuse it on every later call in that thread. A plain function works if there's nothing to clean up. For cleanup, make it a generator: `flowlet` caches the first value it yields, and the `finally` block runs on `.close()` or when the thread exits.

To control when cleanup runs, manage the `ThreadPoolExecutor` with a `with` block. When the block exits, the worker threads shut down and their clients close:

```python
from collections.abc import Generator
from concurrent.futures import ThreadPoolExecutor
from flowlet import in_thread, pipe, thread_local


@thread_local
def session() -> Generator[HttpClient]:
    client = HttpClient()
    try:
        yield client
    finally:
        # Runs once per worker thread when the pool shuts down.
        client.close()


def fetch(url: str) -> Page:
    return session().get(url)


with ThreadPoolExecutor(max_workers=16) as pool:
    pages = await (
        pipe(urls)
        .map(in_thread(fetch, executor=pool), concurrency=64)
        .collect()
    )
```

A few details on lifetime:

- **Explicit close**: `session.close()` closes and clears only the calling thread's instance.
- **Cleanup errors**: exceptions on thread exit go to `sys.unraisablehook`, since there's no caller left to catch them.
- **Default pool**: resources created on asyncio's default pool stay open until the pool shuts down, which with `asyncio.run` is when the event loop closes.

### CPU-bound work with `in_process`

`in_process(fn, *, executor)` runs CPU-bound work in a `ProcessPoolExecutor`. There's no default pool, so you create one and manage its lifetime:

```python
from concurrent.futures import ProcessPoolExecutor
from flowlet import in_process, pipe

with ProcessPoolExecutor(max_workers=8) as pool:
    items = await (
        pipe(keys)
        .map(in_process(crunch, executor=pool), concurrency=8)
        .collect()
    )
```

A few process-pool rules apply:

- **Pickling**: the worker function, its arguments, and its return value must all be picklable. Define workers at module level rather than as lambdas or local functions.
- **Start methods**: Python 3.14 defaults to `forkserver` on Linux and `spawn` on macOS and Windows. Both re-import your main module, so put script entry points behind `if __name__ == "__main__":`.
- **No `contextvars`**: unlike `in_thread`, `in_process` doesn't copy `contextvars` to worker processes.

## Reuse and other styles

### Reusable fragments with `Flow`

A `Flow` is a pipeline without a source. Use it to name, test, and reuse a group of stages across different pipelines:

```python
from flowlet import Flow, pipe

extract: Flow[Page, str] = (
    Flow[Page]()
    .flat_map(find_links)
    .filter(is_internal)
    .map(normalize_url)
)

links = await pipe(pages).through(extract).collect()
```

You can also compose flows with `.through(...)`, or run one directly on a source with `extract.apply(pages)`.

For type checking, start with `Flow[T]()` so the input type flows through every stage (`Flow[T, U]` takes `T` and produces `U`). Bare `Flow()` works too, but starts as `Flow[Any, Any]`.

### Pipe operator (`|`) with `op`

Each function in `flowlet.op` builds a one-step `Flow`, and `|` chains them. It runs the same as method chaining, and it's handy for naming a reusable fragment without writing `Flow[T]()`:

```python
from flowlet import op, pipe

extract = (
    op.flat_map(find_links)
    | op.filter(is_internal)
    | op.map(normalize_url)
)

links = await (pipe(pages) | extract).collect()  # same as .through(extract)
```

### Functional API

`flowlet.functional` exposes the curried operators behind everything above. Compose them with `chain`:

```python
import flowlet.functional as F

process = F.chain(
    F.map(fetch, concurrency=20),
    F.flat_map(extract_links),
    F.filter(is_valid),
)

items = await F.collect(process(urls))
```

You can also call any operator directly: `F.map(fetch, concurrency=20)(urls)` returns an `AsyncGenerator`.
