Ir para o conteúdo

tempest_fastapi_sdk.eventsourcing

Event sourcing: o protocolo de event store com backends SQL e KurrentDB.

« Tempo real e mensageria


eventsourcing

Event sourcing — an event store protocol with SQL and KurrentDB backends.

  • :class:EventStore — the protocol: append with optimistic concurrency, read a stream forwards or backwards, read and subscribe to the store-wide log ($all) by position, snapshots.
  • :class:SqlEventStore — on the PostgreSQL / SQLite the service already has, over the abstract tables in :mod:~tempest_fastapi_sdk.eventsourcing.models; can write every event to the transactional outbox in the same transaction.
  • :class:KurrentDBEventStore — on KurrentDB, through the official client (kurrentdb extra, imported only when used).
  • :class:DomainEvent + :class:EventRegistry — typed Pydantic payloads, stored by type name.
  • :class:Aggregate + :class:AggregateRepository — load by replay (after a snapshot), save by one append.
  • :class:ProjectionRunner — feed a read model from $all and a checkpoint.

Both stores raise :class:~tempest_fastapi_sdk.WrongExpectedVersionException (409) when an append's expected_version does not match the stream.

SNAPSHOT_EVENT_TYPE module-attribute

SNAPSHOT_EVENT_TYPE: str = 'TempestSnapshot'

Event type of snapshot events, kept out of $all reads by the filter.

Aggregate

Aggregate(aggregate_id: str)

Base for an event-sourced aggregate.

Subclasses implement :meth:apply — how each event changes the state — and call :meth:record from their command methods. Opt into snapshots by implementing :meth:snapshot and :meth:restore.

Attributes:

Name Type Description
aggregate_id str

The aggregate id.

version int | None

The stream version the state reflects; None for an aggregate whose stream does not exist yet.

Create an empty aggregate.

Parameters:

Name Type Description Default
aggregate_id str

The aggregate id.

required

pending_events property

pending_events: tuple[DomainEvent, ...]

Return events recorded since the last load or save.

Returns:

Type Description
tuple[DomainEvent, ...]

tuple[DomainEvent, ...]: The unsaved events, in order.

apply

apply(event: DomainEvent) -> None

Change the state for one event. Must not fail or have effects.

Parameters:

Name Type Description Default
event DomainEvent

The event.

required

Raises:

Type Description
NotImplementedError

Unless a subclass implements it.

record

record(event: DomainEvent) -> None

Apply a new event and queue it for the next save.

Parameters:

Name Type Description Default
event DomainEvent

The event the command decided on.

required

mark_saved

mark_saved(version: int) -> None

Forget the pending events after they were appended at version.

Parameters:

Name Type Description Default
version int

The stream version of the last appended event.

required

snapshot

snapshot() -> dict[str, Any] | None

Return the state as JSON-compatible data, or None to opt out.

Returns:

Type Description
dict[str, Any] | None

dict[str, Any] | None: None unless a subclass overrides it.

restore

restore(state: dict[str, Any]) -> None

Restore the state from :meth:snapshot output.

Parameters:

Name Type Description Default
state dict[str, Any]

The saved state.

required

Raises:

Type Description
NotImplementedError

Unless a subclass implements it.

AggregateRepository

AggregateRepository(
    store: EventStore,
    factory: Callable[[str], A],
    *,
    stream_prefix: str = "",
    snapshot_every: int | None = None,
)

Bases: Generic[A]

Load aggregates by replaying their stream, save them by appending.

The stream of an aggregate is stream_prefix + aggregate_id — "order-" gives KurrentDB's category convention (order-42).

Example

orders = AggregateRepository(store, Order, stream_prefix="order-") order = await orders.load("42") or Order("42") order.place(total_cents=990) await orders.save(order)

Initialize the repository.

Parameters:

Name Type Description Default
store EventStore

Any event store.

required
factory Callable[[str], A]

Builds an empty aggregate from its id — usually the aggregate class itself.

required
stream_prefix str

Prefix of the stream name.

''
snapshot_every int | None

Save a snapshot each time the stream crosses a multiple of this many events. None never reads or writes snapshots.

None

Raises:

Type Description
ValueError

If snapshot_every is not positive.

stream_id

stream_id(aggregate_id: str) -> str

Return the stream name of an aggregate.

Parameters:

Name Type Description Default
aggregate_id str

The aggregate id.

required

Returns:

Name Type Description
str str

The stream name.

load async

load(aggregate_id: str) -> A | None

Rebuild an aggregate from its snapshot and stream.

Parameters:

Name Type Description Default
aggregate_id str

The aggregate id.

required

Returns:

Type Description
A | None

A | None: The aggregate, or None when its stream does not

A | None

exist.

save async

save(aggregate: A, *, metadata: EventMetadata | None = None) -> AppendResult | None

Append the aggregate's pending events.

Parameters:

Name Type Description Default
aggregate A

The aggregate.

required
metadata EventMetadata | None

Metadata for the events.

None

Returns:

Type Description
AppendResult | None

AppendResult | None: What was appended, or None when there

AppendResult | None

was nothing pending.

Raises:

Type Description
WrongExpectedVersionException

When the stream moved since the aggregate was loaded; the pending events are kept.

AppendResult dataclass

AppendResult(version: int, position: int, event_ids: tuple[UUID, ...] = ())

What an append wrote.

Attributes:

Name Type Description
version int

The stream version of the last appended event — the expected_version for the next append.

position int

The $all position of the last appended event.

event_ids tuple[UUID, ...]

The ids given to the appended events, in order.

DomainEvent

Bases: BaseModel

Base class for the typed payload of an event.

Subclass it once per event and register the subclass in an :class:EventRegistry. The stored type name is the class attribute event_type when the subclass declares one, otherwise the class name — declare it explicitly once events are stored, so renaming the class does not orphan the rows already written under the old name.

Instances are frozen: an event is a fact that already happened. Unknown fields are ignored on decode, so removing a field from the class keeps old events readable; adding a field needs a default for the same reason.

This is a plain Pydantic model on purpose, not :class:~tempest_fastapi_sdk.BaseSchema: that base strips whitespace from every string, which would store a different payload from the one the caller built.

Example

class OrderPlaced(DomainEvent): ... event_type: ClassVar[str] = "order.placed" ... order_id: str ... total_cents: int

type_name classmethod

type_name() -> str

Return the name this class is stored under.

Returns:

Name Type Description
str str

event_type when the class declares it in its own body

str

or inherits it from a DomainEvent subclass, else the class

str

name.

EventMetadata

Bases: BaseModel

Metadata appended alongside every event of one append call.

correlation_id ties together everything one request or workflow caused; causation_id names the message (command or event) that directly caused this one. The recording time is not here: the store sets it (:attr:RecordedEvent.recorded_at).

Attributes:

Name Type Description
correlation_id str | None

The workflow the event belongs to.

causation_id str | None

The message that caused the event.

extra dict[str, Any]

Any other JSON-compatible metadata.

EventRegistry

EventRegistry(*events: type[DomainEvent])

Registry of :class:DomainEvent classes by stored type name.

The store encodes an event as (type name, JSON object) and decodes it back through this registry, so a read returns the same class the writer appended.

Example

registry = EventRegistry(OrderPlaced, OrderCancelled) @registry.register ... class OrderShipped(DomainEvent): ... order_id: str

Create the registry, registering events.

Parameters:

Name Type Description Default
*events type[DomainEvent]

Event classes to register.

()

types property

types: frozenset[str]

Return every registered type name.

Returns:

Type Description
frozenset[str]

frozenset[str]: The registered names.

register

register(event: type[E]) -> type[E]

Register an event class; usable as a class decorator.

Registering the same class twice is a no-op.

Parameters:

Name Type Description Default
event type[E]

The event class.

required

Returns:

Type Description
type[E]

type[E]: The same class, so the method works as a decorator.

Raises:

Type Description
TypeError

If event is not a :class:DomainEvent subclass.

ValueError

If another class is already registered under the same type name.

encode

encode(event: DomainEvent) -> tuple[str, dict[str, Any]]

Encode an event as its type name and a JSON-compatible object.

Parameters:

Name Type Description Default
event DomainEvent

The event.

required

Returns:

Type Description
tuple[str, dict[str, Any]]

tuple[str, dict[str, Any]]: The type name and the payload.

Raises:

Type Description
UnknownEventTypeError

If the event's class is not registered — appending a type nobody can decode would poison the stream.

decode

decode(event_type: str, data: Mapping[str, Any]) -> DomainEvent

Decode a stored payload back into its event class.

Parameters:

Name Type Description Default
event_type str

The stored type name.

required
data Mapping[str, Any]

The stored payload.

required

Returns:

Name Type Description
DomainEvent DomainEvent

The validated event.

Raises:

Type Description
UnknownEventTypeError

If event_type is not registered.

RecordedEvent dataclass

RecordedEvent(
    event_id: UUID,
    stream_id: str,
    version: int,
    position: int,
    event_type: str,
    event: DomainEvent,
    metadata: EventMetadata,
    recorded_at: datetime | None,
)

An event as stored, returned by every read of an event store.

Attributes:

Name Type Description
event_id UUID

The event's unique id.

stream_id str

The stream it belongs to.

version int

Its 0-based position in that stream — the first event of a stream is version 0.

position int

Its position in the store-wide log ($all). Increases with every append, but is only comparable within one store: the SQL store numbers events 1, 2, 3, ..., KurrentDB reports its commit position, which skips values.

event_type str

The registered type name.

event DomainEvent

The decoded payload.

metadata EventMetadata

Correlation, causation and extras.

recorded_at datetime | None

When the store recorded it, in UTC. The SQL store always sets it; KurrentDB reports it from the server, and the client types it as optional.

to_payload

to_payload() -> dict[str, Any]

Return a JSON-compatible dict of the whole record.

This is the body the SQL store writes to the outbox, so a consumer on the broker side sees the same fields a projection sees.

Returns:

Type Description
dict[str, Any]

dict[str, Any]: event_id, stream_id, version,

dict[str, Any]

position, event_type, data, metadata and

dict[str, Any]

recorded_at (ISO 8601, or None).

Snapshot dataclass

Snapshot(stream_id: str, version: int, state: dict[str, Any])

A saved aggregate state, to skip replaying a long stream.

Attributes:

Name Type Description
stream_id str

The stream the state was built from.

version int

The last stream version folded into state.

state dict[str, Any]

The JSON-compatible state.

StreamStateEnum

Bases: StrEnum

Expected stream states that are not an exact version number.

  • ANY — append whatever the stream holds (no concurrency check).
  • NO_STREAM — the stream must not exist yet (creating an aggregate).
  • EXISTS — the stream must exist, at any version.

UnknownEventTypeError

UnknownEventTypeError(event_type: str)

Bases: LookupError

Raised when a stored event's type is not registered.

Reading a stream decodes every event, so an aggregate stream holding a type the service no longer registers fails loudly instead of replaying a partial history. read_all and subscribe_all never raise it: they only return registered types.

Attributes:

Name Type Description
event_type str

The unregistered type name.

Initialize the error.

Parameters:

Name Type Description Default
event_type str

The unregistered type name.

required

KurrentDBEventStore

KurrentDBEventStore(
    client: AsyncKurrentDBClient,
    *,
    registry: EventRegistry,
    snapshot_stream_prefix: str = "snapshot-",
)

:class:~tempest_fastapi_sdk.eventsourcing.EventStore on KurrentDB.

Build it from a connection string with :meth:from_uri, or hand it an AsyncKurrentDBClient you already configured. The client connects on its first call; :meth:close closes it.

Snapshots live in a stream of their own, snapshot_stream_prefix + stream_id, capped at one event with $maxCount.

Example

store = KurrentDBEventStore.from_uri( ... "kurrentdb://127.0.0.1:2113?Tls=false", registry=registry ... ) await store.append( ... "order-42", [OrderPlaced(order_id="42", total_cents=990)], ... expected_version=StreamStateEnum.NO_STREAM, ... )

Initialize the store over an existing client.

Parameters:

Name Type Description Default
client AsyncKurrentDBClient

The client.

required
registry EventRegistry

The event classes this store reads and writes.

required
snapshot_stream_prefix str

Prefix of the snapshot streams.

'snapshot-'

from_uri classmethod

from_uri(
    uri: str,
    *,
    registry: EventRegistry,
    root_certificates: str | bytes | None = None,
    snapshot_stream_prefix: str = "snapshot-",
) -> KurrentDBEventStore

Build the store and its client from a connection string.

Parameters:

Name Type Description Default
uri str

A kurrentdb:// or kurrentdb+discover:// URI.

required
registry EventRegistry

The event classes.

required
root_certificates str | bytes | None

PEM certificates that sign the server's TLS certificate, for a secure node.

None
snapshot_stream_prefix str

Prefix of the snapshot streams.

'snapshot-'

Returns:

Name Type Description
KurrentDBEventStore KurrentDBEventStore

The store; the client connects on first use.

close async

close() -> None

Close the client's connection; a no-op if it never connected.

The client raises ProgrammingError("Connection was never established") when closed before its first call, which would turn a shutdown hook of an idle service into an error.

append async

append(
    stream_id: str,
    events: Sequence[DomainEvent],
    /,
    *,
    expected_version: int | StreamStateEnum,
    metadata: EventMetadata | None = None,
) -> AppendResult

Append events to a stream, all or nothing.

Parameters:

Name Type Description Default
stream_id str

The stream.

required
events Sequence[DomainEvent]

One or more registered events.

required
expected_version int | StreamStateEnum

The stream's current last version, or a :class:StreamStateEnum condition.

required
metadata EventMetadata | None

Metadata stored with every event of this call.

None

Returns:

Name Type Description
AppendResult AppendResult

The new stream version and commit position.

Raises:

Type Description
WrongExpectedVersionException

When the stream does not match expected_version (the client's WrongCurrentVersionError).

ValueError

When events is empty, or expected_version is a negative number or a string naming no :class:StreamStateEnum member (the member's plain value, "exists", is accepted and means the member).

TypeError

When expected_version is neither an int nor a :class:StreamStateEnum.

UnknownEventTypeError

When an event's class is not registered.

read_stream async

read_stream(
    stream_id: str,
    /,
    *,
    from_version: int | None = None,
    backwards: bool = False,
    limit: int | None = None,
) -> list[RecordedEvent]

Read one stream in version order.

Parameters:

Name Type Description Default
stream_id str

The stream.

required
from_version int | None

First version to return, inclusive. None starts at the beginning (forwards) or the end (backwards).

None
backwards bool

Read from newest to oldest.

False
limit int | None

Maximum events; None reads to the end.

None

Returns:

Type Description
list[RecordedEvent]

list[RecordedEvent]: The events; empty for a missing stream.

Raises:

Type Description
UnknownEventTypeError

When the stream holds an unregistered type.

stream_version async

stream_version(stream_id: str) -> int | None

Return a stream's last version.

Parameters:

Name Type Description Default
stream_id str

The stream.

required

Returns:

Type Description
int | None

int | None: The last version, or None for a missing stream.

read_all async

read_all(*, after_position: int | None = None, limit: int = 500) -> list[RecordedEvent]

Read $all forwards, registered types only.

Parameters:

Name Type Description Default
after_position int | None

Return events strictly after this commit position; None starts at the beginning.

None
limit int

Maximum events to return.

500

Returns:

Type Description
list[RecordedEvent]

list[RecordedEvent]: The events, in position order.

subscribe_all async

subscribe_all(
    *, after_position: int | None = None, poll_interval: float = 1.0
) -> AsyncIterator[RecordedEvent]

Yield registered events after a position, then live ones.

A KurrentDB catch-up subscription to $all filtered to the registered types. The server pushes new events, so poll_interval is accepted for protocol compatibility and ignored.

Parameters:

Name Type Description Default
after_position int | None

Start strictly after this commit position; None starts at the beginning.

None
poll_interval float

Ignored.

1.0

Yields:

Name Type Description
RecordedEvent AsyncIterator[RecordedEvent]

The events, in position order, until the

AsyncIterator[RecordedEvent]

consumer stops iterating.

save_snapshot async

save_snapshot(stream_id: str, /, *, version: int, state: Mapping[str, Any]) -> None

Save a snapshot, keeping only the newest one.

A snapshot older than the stored one is ignored. The first save sets $maxCount: 1 on the snapshot stream so it never grows.

Parameters:

Name Type Description Default
stream_id str

The stream.

required
version int

The last version folded into state.

required
state Mapping[str, Any]

JSON-compatible state.

required

load_snapshot async

load_snapshot(stream_id: str) -> Snapshot | None

Return the latest snapshot of a stream.

Parameters:

Name Type Description Default
stream_id str

The stream.

required

Returns:

Type Description
Snapshot | None

Snapshot | None: The snapshot, or None.

BaseEventModel

Bases: BaseModel

Abstract event log — one immutable row per event.

id (from :class:~tempest_fastapi_sdk.db.model.BaseModel) is the event id. (stream_id, version) and position are unique, so even a writer that bypassed the store could not record two events in the same slot.

Attributes:

Name Type Description
position int

Store-wide position, 1, 2, 3, ... in commit order.

stream_id str

The stream.

version int

0-based version within the stream.

event_type str

Registered type name.

data dict[str, Any]

The event payload.

correlation_id str | None

Correlation id from the metadata.

causation_id str | None

Causation id from the metadata.

extra dict[str, Any]

Remaining metadata.

recorded_at datetime

When the store recorded the event.

BaseEventSnapshotModel

Bases: BaseModel

Abstract snapshot table — the latest snapshot per stream.

Attributes:

Name Type Description
stream_id str

The stream, unique.

version int

Last version folded into state.

state dict[str, Any]

The folded state.

BaseEventStreamModel

Bases: BaseModel

Abstract stream table — one row per stream with its last version.

An append moves version with UPDATE ... WHERE version = :expected before inserting events, so of two concurrent appends with the same expectation exactly one changes the row.

Attributes:

Name Type Description
stream_id str

The stream, unique.

version int

The stream's last version.

BaseProjectionCheckpointModel

Bases: BaseModel

Abstract checkpoint table — last position each projection processed.

Attributes:

Name Type Description
name str

The projection name, unique.

position int

Last $all position the projection processed.

CheckpointStore

Bases: Protocol

Where a projection keeps the last $all position it processed.

load async

load(name: str) -> int | None

Return the checkpoint of a projection.

Parameters:

Name Type Description Default
name str

The projection name.

required

Returns:

Type Description
int | None

int | None: The last processed position, or None.

save async

save(name: str, position: int) -> None

Store the checkpoint of a projection.

Parameters:

Name Type Description Default
name str

The projection name.

required
position int

The last processed position.

required

InMemoryCheckpointStore

InMemoryCheckpointStore()

Checkpoints in a dict — for tests and projections rebuilt at boot.

Create an empty store.

load async

load(name: str) -> int | None

Return the checkpoint of a projection.

Parameters:

Name Type Description Default
name str

The projection name.

required

Returns:

Type Description
int | None

int | None: The last processed position, or None.

save async

save(name: str, position: int) -> None

Store the checkpoint of a projection.

Parameters:

Name Type Description Default
name str

The projection name.

required
position int

The last processed position.

required

ProjectionRunner

ProjectionRunner(
    store: EventStore,
    *,
    name: str,
    handler: Callable[[RecordedEvent], Awaitable[object]],
    checkpoints: CheckpointStore,
    batch_size: int = 100,
)

Feed a projection handler from $all, keeping its checkpoint.

Example

async def project(event: RecordedEvent) -> None: ... if isinstance(event.event, OrderPlaced): ... totals[event.stream_id] = event.event.total_cents runner = ProjectionRunner( ... store, name="order-totals", handler=project, ... checkpoints=InMemoryCheckpointStore(), ... ) await runner.run_once()

Attributes:

Name Type Description
name str

The projection name, the checkpoint key.

batch_size int

Events read per :meth:run_once.

Initialize the runner.

Parameters:

Name Type Description Default
store EventStore

The event store to read.

required
name str

The projection name.

required
handler Callable[[RecordedEvent], Awaitable[object]]

Async callable applying one event to the read model. Its return value is ignored; raise to stop at that event.

required
checkpoints CheckpointStore

Where the position is kept.

required
batch_size int

Events read per batch.

100

Raises:

Type Description
ValueError

If batch_size is not positive.

run_once async

run_once() -> int

Process one batch after the checkpoint.

The checkpoint is saved after the batch, or — when the handler raises — at the last event it finished, before re-raising, so the failed event is the first one of the next run.

Returns:

Name Type Description
int int

How many events the handler processed.

run async

run(*, poll_interval: float = 1.0, stop_event: Event | None = None) -> None

Loop :meth:run_once until stop_event is set or cancelled.

A batch that failed is logged and retried after poll_interval.

Parameters:

Name Type Description Default
poll_interval float

Seconds to sleep when idle or after a failure.

1.0
stop_event Event | None

Ends the loop after the current batch when set.

None

SqlCheckpointStore

SqlCheckpointStore(
    db: AsyncDatabaseManager, *, model: type[BaseProjectionCheckpointModel]
)

Checkpoints in a :class:BaseProjectionCheckpointModel table.

Initialize the store.

Parameters:

Name Type Description Default
db AsyncDatabaseManager

The database manager.

required
model type[BaseProjectionCheckpointModel]

The concrete table.

required

load async

load(name: str) -> int | None

Return the checkpoint of a projection.

Parameters:

Name Type Description Default
name str

The projection name.

required

Returns:

Type Description
int | None

int | None: The last processed position, or None.

save async

save(name: str, position: int) -> None

Store the checkpoint of a projection.

Parameters:

Name Type Description Default
name str

The projection name.

required
position int

The last processed position.

required

SqlEventStore

SqlEventStore(
    db: AsyncDatabaseManager,
    *,
    registry: EventRegistry,
    event_model: type[BaseEventModel],
    stream_model: type[BaseEventStreamModel],
    snapshot_model: type[BaseEventSnapshotModel] | None = None,
    outbox_model: type[BaseOutboxModel] | None = None,
    outbox_topic: Callable[[RecordedEvent], str] = _default_outbox_topic,
)

:class:~tempest_fastapi_sdk.eventsourcing.EventStore on SQLAlchemy.

Every method opens its own unit of work through the manager unless a session is passed, in which case it works inside the caller's transaction and leaves the commit to the caller — which is how an append and a read-model update commit together.

With outbox_model set, each append also writes one :class:~tempest_fastapi_sdk.db.outbox.BaseOutboxModel row per event in the same transaction, whose payload is :meth:RecordedEvent.to_payload. :class:~tempest_fastapi_sdk.db.outbox.OutboxRelay then publishes them to the broker: an event is in the broker if and only if it is in the store.

Example

store = SqlEventStore( ... db, ... registry=registry, ... event_model=EventModel, ... stream_model=EventStreamModel, ... ) await store.append( ... "order-42", [OrderPlaced(order_id="42", total_cents=990)], ... expected_version=StreamStateEnum.NO_STREAM, ... )

Initialize the store.

Parameters:

Name Type Description Default
db AsyncDatabaseManager

The database manager.

required
registry EventRegistry

The event classes this store reads and writes.

required
event_model type[BaseEventModel]

The concrete event table.

required
stream_model type[BaseEventStreamModel]

The concrete stream table.

required
snapshot_model type[BaseEventSnapshotModel] | None

The concrete snapshot table; required by the snapshot methods.

None
outbox_model type[BaseOutboxModel] | None

When set, every appended event is also written to this outbox table in the same transaction.

None
outbox_topic Callable[[RecordedEvent], str]

Topic of each outbox row. Defaults to the event type.

_default_outbox_topic

append async

append(
    stream_id: str,
    events: Sequence[DomainEvent],
    /,
    *,
    expected_version: int | StreamStateEnum,
    metadata: EventMetadata | None = None,
    session: AsyncSession | None = None,
) -> AppendResult

Append events to a stream, all or nothing.

Parameters:

Name Type Description Default
stream_id str

The stream.

required
events Sequence[DomainEvent]

One or more registered events.

required
expected_version int | StreamStateEnum

The stream's current last version, or a :class:StreamStateEnum condition.

required
metadata EventMetadata | None

Metadata stored with every event of this call.

None
session AsyncSession | None

Append inside this transaction instead of committing one of our own. On PostgreSQL the append lock is held until that transaction ends. On SQLite, a transaction that already read fails with database is locked if another writer committed since that read.

None

Returns:

Name Type Description
AppendResult AppendResult

The new stream version and $all position.

Raises:

Type Description
WrongExpectedVersionException

When the stream does not match expected_version.

ValueError

When events is empty, or expected_version is a negative number or a string naming no :class:StreamStateEnum member (the member's plain value, "exists", is accepted and means the member).

TypeError

When expected_version is neither an int nor a :class:StreamStateEnum.

UnknownEventTypeError

When an event's class is not registered.

read_stream async

read_stream(
    stream_id: str,
    /,
    *,
    from_version: int | None = None,
    backwards: bool = False,
    limit: int | None = None,
    session: AsyncSession | None = None,
) -> list[RecordedEvent]

Read one stream in version order.

Parameters:

Name Type Description Default
stream_id str

The stream.

required
from_version int | None

First version to return, inclusive. None starts at the beginning (forwards) or the end (backwards).

None
backwards bool

Read from newest to oldest.

False
limit int | None

Maximum events; None reads to the end.

None
session AsyncSession | None

Read inside this transaction.

None

Returns:

Type Description
list[RecordedEvent]

list[RecordedEvent]: The events; empty for a missing stream.

Raises:

Type Description
UnknownEventTypeError

When the stream holds an unregistered type.

stream_version async

stream_version(stream_id: str, /, *, session: AsyncSession | None = None) -> int | None

Return a stream's last version.

Parameters:

Name Type Description Default
stream_id str

The stream.

required
session AsyncSession | None

Read inside this transaction.

None

Returns:

Type Description
int | None

int | None: The last version, or None for a missing stream.

read_all async

read_all(
    *,
    after_position: int | None = None,
    limit: int = 500,
    session: AsyncSession | None = None,
) -> list[RecordedEvent]

Read the store-wide log forwards, registered types only.

Parameters:

Name Type Description Default
after_position int | None

Return events strictly after this position; None starts at the beginning.

None
limit int

Maximum events to return.

500
session AsyncSession | None

Read inside this transaction.

None

Returns:

Type Description
list[RecordedEvent]

list[RecordedEvent]: The events, in position order.

subscribe_all async

subscribe_all(
    *,
    after_position: int | None = None,
    poll_interval: float = 1.0,
    batch_size: int = 500,
) -> AsyncIterator[RecordedEvent]

Yield registered events after a position, polling for new ones.

Parameters:

Name Type Description Default
after_position int | None

Start strictly after this position; None starts at the beginning.

None
poll_interval float

Seconds to wait when a poll found nothing.

1.0
batch_size int

Events read per poll.

500

Yields:

Name Type Description
RecordedEvent AsyncIterator[RecordedEvent]

The events, in position order, forever.

save_snapshot async

save_snapshot(
    stream_id: str,
    /,
    *,
    version: int,
    state: Mapping[str, Any],
    session: AsyncSession | None = None,
) -> None

Save a snapshot, keeping the newest one per stream.

A snapshot older than the stored one is ignored, so two writers racing never move the snapshot backwards: the conditional UPDATE matches nothing, and the INSERT that follows hits the unique stream_id and is dropped, keeping the newer row.

Parameters:

Name Type Description Default
stream_id str

The stream.

required
version int

The last version folded into state.

required
state Mapping[str, Any]

JSON-compatible state.

required
session AsyncSession | None

Write inside this transaction.

None

Raises:

Type Description
RuntimeError

When the store has no snapshot_model.

load_snapshot async

load_snapshot(
    stream_id: str, /, *, session: AsyncSession | None = None
) -> Snapshot | None

Return the latest snapshot of a stream.

Parameters:

Name Type Description Default
stream_id str

The stream.

required
session AsyncSession | None

Read inside this transaction.

None

Returns:

Type Description
Snapshot | None

Snapshot | None: The snapshot, or None.

Raises:

Type Description
RuntimeError

When the store has no snapshot_model.

EventStore

Bases: Protocol

An append-only store of event streams with a store-wide log.

Implemented by :class:~tempest_fastapi_sdk.eventsourcing.SqlEventStore (PostgreSQL / SQLite through SQLAlchemy) and :class:~tempest_fastapi_sdk.eventsourcing.KurrentDBEventStore. Code written against this protocol — aggregates, projections — runs on either.

Versions are 0-based per stream: the first event is version 0, and a stream holding three events is at version 2. Positions order the whole store ($all) and only increase; checkpoint them, compare them, never do arithmetic on them.

append async

append(
    stream_id: str,
    events: Sequence[DomainEvent],
    /,
    *,
    expected_version: int | StreamStateEnum,
    metadata: EventMetadata | None = None,
) -> AppendResult

Append events to a stream, all or nothing.

Parameters:

Name Type Description Default
stream_id str

The stream.

required
events Sequence[DomainEvent]

One or more registered events.

required
expected_version int | StreamStateEnum

The stream's current last version, or a :class:StreamStateEnum condition.

required
metadata EventMetadata | None

Metadata stored with every event of this call.

None

Returns:

Name Type Description
AppendResult AppendResult

The new stream version and $all position.

Raises:

Type Description
WrongExpectedVersionException

When the stream does not match expected_version.

ValueError

When events is empty.

UnknownEventTypeError

When an event's class is not registered.

read_stream async

read_stream(
    stream_id: str,
    /,
    *,
    from_version: int | None = None,
    backwards: bool = False,
    limit: int | None = None,
) -> list[RecordedEvent]

Read one stream in version order.

Parameters:

Name Type Description Default
stream_id str

The stream.

required
from_version int | None

First version to return, inclusive. None starts at the beginning (forwards) or at the end (backwards).

None
backwards bool

Read from newest to oldest.

False
limit int | None

Maximum events to return; None reads to the end.

None

Returns:

Type Description
list[RecordedEvent]

list[RecordedEvent]: The events; empty for a missing stream.

stream_version async

stream_version(stream_id: str) -> int | None

Return a stream's last version.

Parameters:

Name Type Description Default
stream_id str

The stream.

required

Returns:

Type Description
int | None

int | None: The last version, or None when the stream does

int | None

not exist.

read_all async

read_all(*, after_position: int | None = None, limit: int = 500) -> list[RecordedEvent]

Read the store-wide log forwards, registered types only.

Parameters:

Name Type Description Default
after_position int | None

Return events strictly after this position — the last one a projection processed. None starts at the beginning.

None
limit int

Maximum events to return.

500

Returns:

Type Description
list[RecordedEvent]

list[RecordedEvent]: The events, in position order.

subscribe_all

subscribe_all(
    *, after_position: int | None = None, poll_interval: float = 1.0
) -> AsyncIterator[RecordedEvent]

Yield every registered event after a position, then wait for more.

A catch-up subscription: it first yields what is already stored, then each new event as it is appended, and never ends on its own — break out of the async for or cancel the task.

Parameters:

Name Type Description Default
after_position int | None

Start strictly after this position; None starts at the beginning.

None
poll_interval float

Seconds between polls, for backends that poll. KurrentDB pushes and ignores it.

1.0

Returns:

Type Description
AsyncIterator[RecordedEvent]

AsyncIterator[RecordedEvent]: The events, in position order.

save_snapshot async

save_snapshot(stream_id: str, /, *, version: int, state: Mapping[str, Any]) -> None

Save a snapshot of a stream's folded state.

Parameters:

Name Type Description Default
stream_id str

The stream.

required
version int

The last version folded into state.

required
state Mapping[str, Any]

JSON-compatible state.

required

load_snapshot async

load_snapshot(stream_id: str) -> Snapshot | None

Return the latest snapshot of a stream.

Parameters:

Name Type Description Default
stream_id str

The stream.

required

Returns:

Type Description
Snapshot | None

Snapshot | None: The snapshot, or None when none was saved.

WrongExpectedVersionException

WrongExpectedVersionException(
    stream_id: str, *, expected_version: int | str, actual_version: int | None
)

Bases: ConflictException

Raised when an append's expected_version does not match the stream.

This is the optimistic-concurrency failure of an event store: someone else appended to the stream between the read that produced expected_version and this append. Both backends raise it — the SQL store from its conditional UPDATE of the stream row, the KurrentDB store by translating the client's WrongCurrentVersionError — so a service handles one exception whatever the backend.

The usual reaction is to reload the aggregate and decide again; retrying the same append blindly would discard the other writer's decision.

Attributes:

Name Type Description
stream_id str

The stream the append targeted.

expected_version int | str

What the caller expected — a version number, or a :class:~tempest_fastapi_sdk.eventsourcing.StreamStateEnum value ("no_stream", "exists").

actual_version int | None

The stream's last version when the append was refused, or None when the stream does not exist.

Initialize the exception.

Parameters:

Name Type Description Default
stream_id str

The stream the append targeted.

required
expected_version int | str

The expected version or state.

required
actual_version int | None

The stream's last version, or None when the stream does not exist.

required