Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions temporalio/client/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,11 @@
ScheduleUpdate,
ScheduleUpdateInput,
)
from ._stream_store import (
StreamConfig,
StreamSelectContext,
StreamStore,
)
from ._worker_versioning import (
BuildIdOp,
BuildIdOpAddNewCompatible,
Expand Down Expand Up @@ -350,6 +355,9 @@
"TaskReachabilityType",
"CloudOperationsClient",
"Plugin",
"StreamConfig",
"StreamSelectContext",
"StreamStore",
"Callback",
"_ClientImpl",
"_apply_headers",
Expand Down
265 changes: 265 additions & 0 deletions temporalio/client/_stream_store.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,265 @@
"""Stream Stores and the Stream config of a client."""

from __future__ import annotations

from abc import ABC, abstractmethod
from collections.abc import Callable, Sequence
from dataclasses import dataclass, field

from temporalio.api.streamservice.v1 import (
AppendRecordsRequest,
AppendRecordsResponse,
CreateStreamRequest,
CreateStreamResponse,
DescribeStreamRequest,
DescribeStreamResponse,
ReadRecordsRequest,
ReadRecordsResponse,
)


class StreamStore(ABC):
"""Base class for a Store that keeps Stream Records.

Methods use request and response messages from
:py:mod:`temporalio.api.streamservice.v1`. Requests contain a Stream id.
The SDK routes each ``StreamRef`` to its registered Store and sets the Store
name on refs returned by create. Stores don't read or set ``StreamRef.store``.

Workflow execution and replay depend on these contracts.

Retention:

* Retention starts at create and restarts after an append that writes a batch.
Retries and reads don't extend it. The Store sets the retention period.
* An expired Stream has no Records and rejects calls with ``EXPIRED``.
* Streams have no stored end. Applications use their own terminal Record.

Records and offsets:

* Keep each body as received. The payload codec has already encoded it.
* Write each append batch atomically, with contiguous Records in request order.
* Record offsets are nonempty and sort bytewise in Record order.
* After a response returns an offset, no later write can insert a Record at
or below it. This also applies to concurrent writes.
* Keep Records unchanged until the Stream expires.

Producers and attempts:

* A Producer identifies a Workflow run, Activity, Local Activity or client.
Its kind and ids determine its identity.
* An attempt identifies a Producer's execution attempt, such as a Workflow
Task or Activity attempt. Every Record retains its Producer and attempt.
* Fencing is optional. A Store that fences rejects an earlier attempt once
a later attempt of that Producer has written to the Stream.

Reject calls with :py:class:`temporalio.exceptions.StreamError` and its reason.
These docs omit the ``STREAM_ERROR_REASON_`` prefix from reason names.
Other exceptions become ``STORE_UNAVAILABLE`` errors. Workflow append and
read refusals record messages of at most 4 KiB in History. All Stream marker
data in an activation must fit within 1 MiB. Keep messages short to avoid
failing the Workflow Task with ``StreamMarkerTooLarge``.

Calls can run concurrently on the event loop. Cancellation can follow a
timeout, eviction or Worker shutdown. A cancelled call may have taken effect.
The Store must remain usable, and overlapping retries must not duplicate a
batch.

SDK Core validates and retries Workflow appends and reads during outages.
Other calls make one attempt. For those calls, the SDK checks each request
with the rules of SDK Core and the append limits from :py:class:`StreamConfig`,
but it doesn't check the answer. Stores must perform any other checks they
require.

.. warning::
This API is experimental and subject to change.
"""

@abstractmethod
def name(self) -> str:
"""Return the Store name registered in :py:class:`StreamConfig`.

The name must remain stable. Separate instances of one Store class can
use different names.
"""
raise NotImplementedError

@abstractmethod
async def create_stream(
self, request: CreateStreamRequest, *, request_id: str
) -> CreateStreamResponse:
"""Create a Stream, or reuse it if the conflict policy permits.

Retries use the same ``request_id``. An empty id never identifies a retry.
The response contains only ``created``.

For an existing Stream, check these conditions in order.

1. An expired Stream fails with ``EXPIRED``.
2. A matching create ``request_id`` returns ``created=True``.
3. ``USE_EXISTING`` returns ``created=False``. ``FAIL`` or an unset policy
fails with ``ALREADY_EXISTS``.

Only a new Stream starts retention. Reusing a Stream doesn't extend it.
"""
raise NotImplementedError

@abstractmethod
async def append_records(
self, request: AppendRecordsRequest, *, request_id: str
) -> AppendRecordsResponse:
"""Append one batch from one Producer.

Retries of one append use the same ``request_id``.
Retain recent request ids for each Producer, including at least its last
batch. Matching Producer, attempt and ``request_id`` identify a resend.
An empty request id never identifies a resend.

Check these conditions in order.

1. Missing or expired Streams fail with ``NOT_FOUND`` or ``EXPIRED``.
2. A resend returns the original offsets without comparing or writing
Records.
3. If fencing is enabled, an attempt older than the latest writer attempt
fails with ``FENCED``.

Return the first and last Record offsets. Only a new batch extends
retention. A resend doesn't extend it.
"""
raise NotImplementedError

@abstractmethod
async def read_records(self, request: ReadRecordsRequest) -> ReadRecordsResponse:
"""Read one page after ``after_offset``, in Stream order.

* Apply ``max_records`` and ``max_bytes``. Zero uses the Store's default.
Include the first Record even if it exceeds ``max_bytes``.
* The next read starts after the last returned Record. An empty page
leaves ``after_offset`` unchanged.
* If no Records are available, wait until one arrives or ``wait`` expires.
An unset wait returns immediately. The SDK converts zero to an unset
wait. Returning empty pages before a requested wait expires can cause
callers to poll repeatedly.
* Accept any offset returned by a response. Reject ``after_offset`` with
``OFFSET_TOO_HIGH`` only if it exceeds the end of the Stream.
"""
raise NotImplementedError

@abstractmethod
async def describe_stream(
self, request: DescribeStreamRequest
) -> DescribeStreamResponse:
"""Return the newest Record's offset, or empty bytes for an empty Stream."""
raise NotImplementedError


@dataclass(frozen=True)
class StreamSelectContext:
"""Context passed to :py:attr:`StreamConfig.store_selector` calls.

.. warning::
This API is experimental and subject to change.
"""

id: str
"""The id of the Stream of the call."""

namespace: str | None = None
"""The namespace of the client or Worker that makes the call."""


@dataclass(frozen=True)
class StreamConfig:
"""Stream Stores shared by a client and its Workers.

Appends that exceed :py:attr:`max_record_bytes`, :py:attr:`max_batch_bytes`
or :py:attr:`max_batch_records` fail with ``STREAM_ERROR_REASON_TOO_LARGE``
before reaching the Store. ``rpc_metadata`` has no effect on Store calls.

Streams have no close. Retention starts at create and restarts after each
append that writes a batch. Applications use their own terminal Record.

In client, Activity and Workflow code, ``read`` and ``read_pages`` continue
after empty pages. ``read_pages`` yields those pages. Callers must stop the
iterator, for example with ``break`` or a timeout. An unset ``wait`` makes the
first request immediate. Later requests wait up to one minute. An explicit
wait applies to every request. Zero disables waiting, so an idle Stream can
cause repeated empty reads. ``read_page`` has no default wait. After a page,
the ``read`` iterator's ``next_request`` includes the next request's wait.

A positive ``rpc_timeout`` caps client and Activity waits below the timeout,
leaving time for the Store to answer. An Activity that heartbeats between
Records needs a wait below its heartbeat timeout, or a separate heartbeat task.

.. warning::
This API is experimental and subject to change.
"""

stores: Sequence[StreamStore]
"""Stores available for Stream calls. At least one Store must be provided,
and each Store must have a unique :py:meth:`StreamStore.name` that isn't
empty.
"""

store_selector: Callable[[StreamSelectContext], StreamStore] | None = None
"""Select the Store for a call whose ``StreamRef`` has no Store name.

Return an instance from :py:attr:`stores`. A selector is required with
multiple Stores. Without one, the sole Store handles these calls.
"""

max_record_bytes: int = 1536 * 1024
"""Maximum stored Record size for an append or a live Workflow read.

Includes its Producer. Defaults to 1.5 MiB and must be at least one.
"""

max_batch_bytes: int = 4 * 1024 * 1024
"""Maximum size in bytes of the Records of one append, each in its stored
size. Defaults to 4 MiB. Must be greater than or equal to one.
"""

max_batch_records: int = 1000
"""Maximum number of Records of one append. Defaults to 1000. Must be
greater than or equal to one.
"""

_by_name: dict[str, StreamStore] = field(
init=False, repr=False, compare=False, default_factory=dict
)
"""Snapshot Store names so later name changes can't change routing."""

def __post_init__(self) -> None:
"""Validate the Stores and the limits.

Raises :exc:`ValueError` if no Store is provided, if a limit is less
than one, if more than one Store is registered without a
:py:attr:`store_selector`, if a Store has an empty name, or if any two
Stores have the same name.
"""
if not self.stores:
raise ValueError("StreamConfig.stores must contain at least one Store.")
for limit in ("max_record_bytes", "max_batch_bytes", "max_batch_records"):
if getattr(self, limit) < 1:
raise ValueError(
f"StreamConfig.{limit} must be greater than or equal to one."
)
if len(self.stores) > 1 and self.store_selector is None:
raise ValueError(
"StreamConfig.store_selector must be specified if multiple Stores "
"are registered."
)
by_name: dict[str, StreamStore] = {}
for store in self.stores:
name = store.name()
if not name:
raise ValueError(
"StreamConfig.stores contains a Store with an empty name."
)
if name in by_name:
raise ValueError(
f"StreamConfig.stores contains multiple Stores with name '{name}'. "
"Each Store must have a unique name."
)
by_name[name] = store
object.__setattr__(self, "_by_name", by_name)
66 changes: 66 additions & 0 deletions temporalio/contrib/streams/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# Stream helpers

> This package is experimental. Its API can change.

`temporalio.contrib.streams` supports the SDK's Stream API. Configure Stores with
`stream_config=StreamConfig(stores=[...])`. Use `create_stream` or `get_stream`
on the client or `temporalio.workflow` to get a `Stream`.

`temporalio.contrib.workflow_streams` is a separate API that stores events in
Workflow state.

## `BufferedAppender`

Use `BufferedAppender` in client or Activity code to combine frequent appends.

```python
from temporalio.contrib.streams import BufferedAppender

async with BufferedAppender(stream) as tokens:
async for token in model_tokens():
tokens.append(token)
```

`append` returns immediately. When no write is active, the appender starts one on
the next turn of the event loop with the buffered Records. Records that arrive
during a write form the next batch. Writes are sequential.

`async with` flushes before exit. Without it, call `await tokens.flush()` before
the Activity ends. Otherwise the last write can run after the Activity ends, even
after a write of a later attempt, and nobody gets its error.

The buffer has no size limit. Await `flush()` periodically if the producer is
faster than the Store. Set the appender's `max_batch_records` to stay within the
client's batch count limit. The client's byte limits still apply.

A failed batch stops later writes. Later `append` and `flush` calls raise that
error, or `RuntimeError` if the write was cancelled. `unwritten` counts Records
in the failed batch and the remaining buffer. The Store may have accepted the
failed batch if only its response was lost.

Workflow code batches values in one Stream `append` call.

## Store a Producer

`current_producer()` returns the running Activity attempt's Producer. Use
`as_producer` to restore it from heartbeat details. Pass the restored value as
`append(..., producer=...)` when resumed work must retain that Producer.

## Read a Stream

Pass `body_type=` or a typed ref such as `StreamRef[str](id=...)` to `get_stream`.
A ref without a body type raises `TypeError` when read. A Stream from
`create_stream` without a body type accepts any body.

A Stream has no close. Stop at the application's terminal Record or cancel the
iterator. `read` and `read_pages` continue after empty pages. `read_pages` yields
those pages. `read_page` returns one page and has no default wait.

With no `wait`, an iterator requests its first page immediately. Later requests
wait up to one minute. An explicit `wait` applies to every page. Zero disables
waiting, so an idle Stream produces repeated empty pages. Client iterators yield
to the event loop between them so cancellation can run.

A positive `rpc_timeout` caps client and Activity waits below the timeout. An
Activity that heartbeats between Records needs a shorter `wait` than its
heartbeat timeout, or a separate heartbeat task.
15 changes: 15 additions & 0 deletions temporalio/contrib/streams/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
"""Helpers on top of the Streams API.

:py:class:`BufferedAppender` batches the appends of one Stream, in client and
Activity code. :py:func:`current_producer` gives the Producer that a write of
the running Activity sends by default, and :py:func:`as_producer` gives back a
Producer that code stored.

.. warning::
This package is experimental and may change in future versions.
"""

from temporalio.contrib.streams._appender import BufferedAppender
from temporalio.contrib.streams._producer import as_producer, current_producer

__all__ = ["BufferedAppender", "as_producer", "current_producer"]
Loading
Loading