tempest_fastapi_sdk.eventsourcing¶
Event sourcing: o protocolo de event store com backends SQL e KurrentDB.
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 (kurrentdbextra, 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$alland 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
¶
Event type of snapshot events, kept out of $all reads by the filter.
Aggregate
¶
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;
|
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
¶
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
¶
Return the state as JSON-compatible data, or None to opt out.
Returns:
| Type | Description |
|---|---|
dict[str, Any] | None
|
dict[str, Any] | None: |
restore
¶
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
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
stream_id
¶
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
¶
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 |
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 |
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
¶
What an append wrote.
Attributes:
| Name | Type | Description |
|---|---|---|
version |
int
|
The stream version of the last appended event —
the |
position |
int
|
The |
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
¶
Return the name this class is stored under.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
|
str
|
or inherits it from a |
|
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
¶
Return every registered type name.
Returns:
| Type | Description |
|---|---|
frozenset[str]
|
frozenset[str]: The registered names. |
register
¶
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 |
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 |
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 |
position |
int
|
Its position in the store-wide log ( |
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
¶
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]: |
dict[str, Any]
|
|
dict[str, Any]
|
|
Snapshot
dataclass
¶
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 |
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
¶
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 |
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 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: |
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
|
ValueError
|
When |
TypeError
|
When |
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
|
backwards
|
bool
|
Read from newest to oldest. |
False
|
limit
|
int | None
|
Maximum events; |
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
¶
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 |
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
|
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
|
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 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 |
required |
state
|
Mapping[str, Any]
|
JSON-compatible state. |
required |
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, |
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 |
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 |
CheckpointStore
¶
Bases: Protocol
Where a projection keeps the last $all position it processed.
load
async
¶
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 |
save
async
¶
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
¶
Checkpoints in a dict — for tests and projections rebuilt at boot.
Create an empty store.
load
async
¶
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 |
save
async
¶
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: |
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 |
run_once
async
¶
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
¶
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
¶
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 |
save
async
¶
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: |
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 |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
AppendResult |
AppendResult
|
The new stream version and |
Raises:
| Type | Description |
|---|---|
WrongExpectedVersionException
|
When the stream does not match
|
ValueError
|
When |
TypeError
|
When |
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
|
backwards
|
bool
|
Read from newest to oldest. |
False
|
limit
|
int | None
|
Maximum events; |
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
¶
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 |
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
|
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
|
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 |
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 |
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 |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
When the store has no |
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: |
required |
metadata
|
EventMetadata | None
|
Metadata stored with every event of this call. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
AppendResult |
AppendResult
|
The new stream version and |
Raises:
| Type | Description |
|---|---|
WrongExpectedVersionException
|
When the stream does not match
|
ValueError
|
When |
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
|
backwards
|
bool
|
Read from newest to oldest. |
False
|
limit
|
int | None
|
Maximum events to return; |
None
|
Returns:
| Type | Description |
|---|---|
list[RecordedEvent]
|
list[RecordedEvent]: The events; empty for a missing stream. |
stream_version
async
¶
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 |
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
|
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
|
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 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 |
required |
state
|
Mapping[str, Any]
|
JSON-compatible state. |
required |
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: |
actual_version |
int | None
|
The stream's last version when the
append was refused, or |
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
|
required |