Skip to content

logicblocks.event.store

class event_store_transaction[AdditionalReturn = Never]

Bases: ABC

Abstract base class for decorators that wrap event store operations.

An instance is used as a decorator on an async function. Each call to the decorated function is passed, as a zero-argument callable, to wrap_handler, which decides how to invoke it, for example retrying or suppressing particular errors.

AdditionalReturn is the type that the wrapper may return in place of the handler’s result, such as None when an error is ignored.

def __call__[**P, R](
    handler: Callable[P, Awaitable[R]],
) -> Callable[P, Coroutine[Any, Any, AdditionalReturn | R]]
async def wrap_handler[R](
    handler: Callable[[], Awaitable[R]],
) -> AdditionalReturn | R

Invoke the handler, applying the transaction’s behaviour.

Parameters:

  • handler (Callable[[], Awaitable[R]]) — A callable that runs the decorated function with the original arguments.

Returns:

  • AdditionalReturn | R — the handler’s result, or an AdditionalReturn value.
class EventCategory(
    adapter: EventStorageAdapter,
    category: CategoryIdentifier,
    logger: FilteringBoundLogger = _default_logger,
)

Bases: EventSource[CategoryIdentifier, StoredEvent]

A class for interacting with a specific category of events.

Since a category consists of zero or more streams, the category can be narrowed to a specific stream using the stream method.

Events in the category can be read using the read or iterate methods. Categories are also async iterable, supporting aiter and async for. Events can be published to multiple streams in the category atomically using the publish method.

Typically obtained via EventStore.category rather than constructed directly.

Parameters:

  • adapter (EventStorageAdapter) — The storage adapter backing the category.
  • category (CategoryIdentifier) — The identifier of the category.
  • logger (FilteringBoundLogger) — The logger to use.
property identifier: CategoryIdentifier

The identifier of the category.

async def latest() -> StoredEvent | None

Get the latest event in the category, across all its streams.

Returns:

  • StoredEvent | None — the event with the highest sequence number in the category, or None if the category is empty.
def stream(*, stream: str) -> EventStream

Get a stream of events in the category.

Parameters:

  • stream (str) — The name of the stream.

Returns:

  • EventStream — an EventStream for the specified stream.
def iterate(
    *,
    constraints: Set[constraints.QueryConstraint] = frozenset(),
) -> AsyncIterator[StoredEvent]

Iterate over the events in the category.

Parameters:

  • constraints (Set[constraints.QueryConstraint]) — A set of query constraints defining which events to include in the iteration.

Returns:

  • AsyncIterator[StoredEvent] — an async iterator over the events in the category, in sequence number order.
async def publish[Name: StringPersistable, Payload: JsonPersistable, Metadata: JsonPersistable](
    *,
    streams: Mapping[str, StreamPublishDefinition[Name, Payload, Metadata]],
) -> Mapping[str, Sequence[StoredEvent[Name, Payload, Metadata]]]

Publish events to multiple streams in the category atomically.

Parameters:

  • streams (Mapping[str, StreamPublishDefinition[Name, Payload, Metadata]]) — A mapping from stream name to the definition of what to publish to that stream. Each definition holds the events to publish and, optionally, the write condition for that stream. Streams without a condition are written unconditionally.

Returns:

  • Mapping[str, Sequence[StoredEvent[Name, Payload, Metadata]]] — a mapping from stream name to the stored events for that stream.

Raises:

  • UnmetWriteConditionError — If any stream’s condition is not met, in which case no events are written to any stream.
class EventLog(
    adapter: EventStorageAdapter,
    log: LogIdentifier = LogIdentifier(),
    logger: FilteringBoundLogger = _default_logger,
)

Bases: EventSource[LogIdentifier, StoredEvent]

A class for interacting with the entire event log.

This class allows reading and iterating over all events in the log, without scoping to a specific category or stream.

Typically obtained via EventStore.log rather than constructed directly.

Parameters:

  • adapter (EventStorageAdapter) — The storage adapter backing the log.
  • log (LogIdentifier) — The identifier of the log.
  • logger (FilteringBoundLogger) — The logger to use.
property identifier: LogIdentifier

The identifier of the log.

async def latest() -> StoredEvent | None

Get the latest event in the log.

Returns:

  • StoredEvent | None — the event with the highest sequence number in the log, or None if the log is empty.
def iterate(
    *,
    constraints: Set[constraints.QueryConstraint] = frozenset(),
) -> AsyncIterator[StoredEvent]

Iterate over all events in the log.

Parameters:

  • constraints (Set[constraints.QueryConstraint]) — A set of query constraints defining which events to include in the iteration.

Returns:

  • AsyncIterator[StoredEvent] — an async iterator over the events in the log, in sequence number order.
class EventStorageAdapter

Bases: ABC

Abstract base class for event storage backends.

Implement this class to provide a custom backend for an EventStore. Implementations must satisfy the following contract:

  • Events within a stream have contiguous, zero-based positions, assigned in the order in which they are saved.
  • Every stored event has a sequence number that is unique across the whole store and increases with the order in which events are saved.
  • A save is atomic: either all of its events are stored or none are.
  • Write conditions are evaluated against the state of each target stream after acquiring the write lock(s) dictated by the adapter’s serialisation guarantee, so that no conflicting write can occur between evaluation and storage.
  • scan and latest order events by sequence number.
@overload
async def save[Name: StringPersistable, Payload: JsonPersistable, Metadata: JsonPersistable](
    *,
    target: StreamIdentifier,
    events: Sequence[NewEvent[Name, Payload, Metadata]],
    condition: WriteCondition = NoCondition(),
) -> Sequence[StoredEvent[Name, Payload, Metadata]]
@overload
async def save[Name: StringPersistable, Payload: JsonPersistable, Metadata: JsonPersistable](
    *,
    target: CategoryIdentifier,
    streams: Mapping[str, StreamPublishDefinition[Name, Payload, Metadata]],
) -> Mapping[str, Sequence[StoredEvent[Name, Payload, Metadata]]]

Save events to a stream, or to multiple streams in a category.

When target is a StreamIdentifier, events are appended to the stream, provided condition is met for the stream.

When target is a CategoryIdentifier, streams maps stream names within the category to StreamPublishDefinitions. Each stream’s events are appended provided its own condition (default NoCondition) is met. All streams are written in a single atomic operation: if any condition is unmet, nothing is written.

Parameters:

  • target (Saveable) — The stream or category to save to.
  • events (Sequence[NewEvent[Name, Payload, Metadata]] | None) — The events to save, in order. Required for a stream target.
  • condition (WriteCondition) — The write condition for a stream target.
  • streams (Mapping[str, StreamPublishDefinition[Name, Payload, Metadata]] | None) — The per-stream definitions. Required for a category target.

Returns:

  • Sequence[StoredEvent[Name, Payload, Metadata]] | Mapping[str, Sequence[StoredEvent[Name, Payload, Metadata]]] — for a stream target, the stored events in the order given; for a category target, a mapping from stream name to the stored events for that stream. Stored events retain the unserialised name, payload and metadata of the new events.

Raises:

  • UnmetWriteConditionError — If a write condition is not met, in which case no events are written.
  • ValueError — If the argument required for the target type is missing, or the target type is unsupported.
async def latest(
    *,
    target: Latestable,
) -> StoredEvent[str, JsonValue, JsonValue] | None

Get the latest event in the log, a category or a stream.

Parameters:

  • target (Latestable) — The log, category or stream to read from.

Returns:

  • StoredEvent[str, JsonValue, JsonValue] | None — the event with the highest sequence number in the target, in serialised form, or None if the target contains no events.
def scan(
    *,
    target: Scannable = LogIdentifier(),
    constraints: Set[constraints.QueryConstraint] = frozenset(),
) -> AsyncIterator[StoredEvent[str, JsonValue, JsonValue]]

Iterate over the events in the log, a category or a stream.

Parameters:

  • target (Scannable) — The log, category or stream to scan. Defaults to the whole log.
  • constraints (Set[constraints.QueryConstraint]) — Query constraints that each yielded event must satisfy. Adapters may raise for constraint types they do not support.

Returns:

  • AsyncIterator[StoredEvent[str, JsonValue, JsonValue]] — an async iterator over the matching events in serialised form, in ascending sequence number order.
class EventStore(
    adapter: EventStorageAdapter,
    logger: FilteringBoundLogger = _default_logger,
)

The primary interface into the store of events.

An EventStore is backed by a EventStorageAdapter which implements event storage. Typically, events are stored in an immutable append only log, the details of which are storage implementation specific.

The event store is partitioned into streams, a sequence of events relating to the same “thing”, such as an entity, a process or a state machine, and categories, a logical grouping of streams that share some characteristics.

For example, a stream might exist for each order in a commerce system, with the category of such streams being “orders”.

Streams and categories are each identified by a string name. The combination of a category name and a stream name acts as an identifier for a specific stream of events.

Parameters:

  • adapter (EventStorageAdapter) — The storage adapter in which events are stored.
  • logger (FilteringBoundLogger) — The logger to use. Streams, categories and logs obtained from the store use the same logger.
def stream(*, category: str, stream: str) -> EventStream

Get a stream of events from the store.

This method alone doesn’t result in any IO, it instead returns an EventStream for the stream identified by the category and stream names, as part of a fluent interface.

Categories and streams implicitly exist, i.e., calling this method for a category or stream that has never been written to will not result in an error.

Parameters:

  • category (str) — The name of the category of the stream.
  • stream (str) — The name of the stream.

Returns:

  • EventStream — an EventStream for the specified stream.
def category(*, category: str) -> EventCategory

Get a category of events from the store.

This method alone doesn’t result in any IO, it instead returns an EventCategory for the category identified by the category name, as part of a fluent interface.

Categories implicitly exist, i.e., calling this method for a category that has never been written to will not result in an error.

Parameters:

  • category (str) — The name of the category.

Returns:

def log() -> EventLog

Get an event log from the store.

This method alone doesn’t result in any IO, it instead returns an event log, as part of a fluent interface.

Returns:

  • EventLog — an EventLog over all events in the store.
class EventStoreEventSourceFactory(adapter: EventStorageAdapter)

Bases: EventSourceFactory[StoredEvent]

Constructs event store sources backed by a storage adapter.

Out of the box, constructs an EventLog for a LogIdentifier, an EventCategory for a CategoryIdentifier and an EventStream for a StreamIdentifier. Further identifier types can be supported with register_constructor.

Parameters:

property storage_adapter: EventStorageAdapter

The storage adapter used by constructed sources.

def register_constructor[I: EventSourceIdentifier](
    identifier_type: type[I],
    constructor: EventSourceConstructor[I],
) -> Self

Register a constructor for an identifier type.

Replaces any constructor already registered for the type. Lookup is by exact type, so subclasses must be registered separately.

Parameters:

  • identifier_type (type[I]) — The identifier type to construct sources for.
  • constructor (EventSourceConstructor[I]) — A callable taking the identifier and the storage adapter and returning an event source.

Returns:

  • Self — this factory, to allow chaining.
def construct[I: EventSourceIdentifier](
    identifier: I,
) -> EventSource[I, StoredEvent]

Construct an event source for an identifier.

Parameters:

  • identifier (I) — The identifier of the event source to construct.

Returns:

Raises:

  • KeyError — If no constructor is registered for the identifier’s type.
class EventStream(
    adapter: EventStorageAdapter,
    stream: StreamIdentifier,
    logger: FilteringBoundLogger = _default_logger,
)

Bases: EventSource[StreamIdentifier, StoredEvent]

A class for interacting with a specific stream of events.

Events can be published into the stream using the publish method, and the stream can be read using the read or iterate methods. Streams are also async iterable, supporting aiter and async for.

Typically obtained via EventStore.stream or EventCategory.stream rather than constructed directly.

Parameters:

  • adapter (EventStorageAdapter) — The storage adapter backing the stream.
  • stream (StreamIdentifier) — The identifier of the stream.
  • logger (FilteringBoundLogger) — The logger to use.
property identifier: StreamIdentifier

The identifier of the stream.

async def latest() -> StoredEvent | None

Get the latest event in the stream.

Returns:

  • StoredEvent | None — the event at the highest position in the stream, or None if the stream is empty.
async def publish[Name: StringPersistable, Payload: JsonPersistable, Metadata: JsonPersistable](
    *,
    events: Sequence[NewEvent[Name, Payload, Metadata]],
    condition: WriteCondition = NoCondition(),
) -> Sequence[StoredEvent[Name, Payload, Metadata]]

Publish a sequence of events into the stream.

Parameters:

  • events (Sequence[NewEvent[Name, Payload, Metadata]]) — The events to publish, in order.
  • condition (WriteCondition) — A write condition that must be met for the events to be written. Defaults to no condition.

Returns:

  • Sequence[StoredEvent[Name, Payload, Metadata]] — the stored events, in the order they were published.

Raises:

def iterate(
    *,
    constraints: Set[constraints.QueryConstraint] = frozenset(),
) -> AsyncIterator[StoredEvent]

Iterate over the events in the stream.

Parameters:

  • constraints (Set[constraints.QueryConstraint]) — A set of query constraints defining which events to include in the iteration.

Returns:

  • AsyncIterator[StoredEvent] — an async iterator over the events in the stream, in position order.
class ignore_on_error

Bases: event_store_transaction[None], ABC

Abstract decorator that suppresses a given exception type.

Subclasses set the exception class variable to the exception type to suppress. If the handler raises exception, the decorated function returns None. Other exceptions propagate.

exception: type[Exception]
async def wrap_handler[R](handler: Callable[[], Awaitable[R]]) -> R | None
class ignore_on_unmet_condition_error

Bases: ignore_on_error

Decorator that suppresses UnmetWriteConditionError.

The decorated function returns None if a write condition is not met.

exception = UnmetWriteConditionError
class InMemoryEventStorageAdapter(
    *,
    serialisation_guarantee: EventSerialisationGuarantee[CategoryIdentifier | StreamIdentifier | LogIdentifier] = EventSerialisationGuarantee.LOG,
    constraint_converter: Converter[constraints.QueryConstraint, constraints.QueryConstraintCheck[StoredEvent]] | None = None,
    condition_converter: Converter[WriteCondition, WriteConditionEnforcer] | None = None,
)

Bases: EventStorageAdapter

An event storage adapter that holds events in process memory.

Intended for tests and local development: events are lost when the adapter is discarded and are not shared between processes. Writes are locked according to the serialisation guarantee. Reads operate on a snapshot of the events taken when the read starts, so events saved during a scan are not yielded by it.

Parameters:

@overload
async def save[Name: StringPersistable, Payload: JsonPersistable, Metadata: JsonPersistable](
    *,
    target: StreamIdentifier,
    events: Sequence[NewEvent[Name, Payload, Metadata]],
    condition: WriteCondition = NoCondition(),
) -> Sequence[StoredEvent[Name, Payload, Metadata]]
@overload
async def save[Name: StringPersistable, Payload: JsonPersistable, Metadata: JsonPersistable](
    *,
    target: CategoryIdentifier,
    streams: Mapping[str, StreamPublishDefinition[Name, Payload, Metadata]],
) -> Mapping[str, Sequence[StoredEvent[Name, Payload, Metadata]]]
async def latest(
    *,
    target: Latestable,
) -> StoredEvent[str, JsonValue, JsonValue] | None
async def scan(
    *,
    target: Scannable = LogIdentifier(),
    constraints: Set[constraints.QueryConstraint] = frozenset(),
) -> AsyncIterator[StoredEvent[str, JsonValue, JsonValue]]
class InMemoryStoredEventSource[I: EventSourceIdentifier, E: StoredEvent = StoredEvent](
    events: Sequence[E],
    identifier: I,
    constraint_converter: Converter[QueryConstraint, QueryConstraintCheck[E]] | None = None,
)

Bases: InMemoryEventSource[I, E]

An in-memory event source of stored events.

By default, supports the query constraints understood by the in-memory storage adapter, such as SequenceNumberAfterConstraint.

Parameters:

  • events (Sequence[E]) — The stored events in the source, in order.
  • identifier (I) — The identifier of the source.
  • constraint_converter (Converter[QueryConstraint, QueryConstraintCheck[E]] | None) — Converts query constraints into predicates over events. Defaults to the in-memory adapter’s converter.
class PostgresEventStorageAdapter(
    *,
    connection_source: ConnectionSource,
    serialisation_guarantee: AnyEventSerialisationGuarantee = EventSerialisationGuarantee.LOG,
    query_settings: QuerySettings = QuerySettings(),
    table_settings: TableSettings = TableSettings(table_name='events'),
    constraint_converter: Converter[source_constraints.QueryConstraint, QueryApplier] | None = None,
    condition_converter: Converter[WriteCondition, WriteConditionEnforcer] | None = None,
    max_insert_batch_size: int = 1000,
)

Bases: EventStorageAdapter

An event storage adapter backed by a PostgreSQL table.

Writes take transaction-scoped advisory locks according to the serialisation guarantee before checking write conditions and inserting events. Scans are paginated by sequence number, fetching query_settings.scan_query_page_size events per query, so a long-running scan may yield events saved after it started.

When given ConnectionSettings, the adapter creates and owns a connection pool, which must be opened with open before use and closed with close afterwards. When given a pool, the caller manages its lifecycle and open and close do nothing.

Parameters:

  • connection_source (ConnectionSource) — ConnectionSettings to create a pool from, or an existing AsyncConnectionPool.
  • serialisation_guarantee (AnyEventSerialisationGuarantee) — The scope within which writes are serialised. Defaults to EventSerialisationGuarantee.LOG.
  • query_settings (QuerySettings) — Settings for the queries issued by the adapter.
  • table_settings (TableSettings) — Settings for the events table. Defaults to a table named events.
  • constraint_converter (Converter[source_constraints.QueryConstraint, QueryApplier] | None) — Converts query constraints into query appliers. Defaults to a converter supporting SequenceNumberAfterConstraint.
  • condition_converter (Converter[WriteCondition, WriteConditionEnforcer] | None) — Converts write conditions into enforcers. Defaults to a converter supporting all built-in conditions.
  • max_insert_batch_size (int) — Currently unused.
connection_pool
serialisation_guarantee
query_settings
table_settings
constraint_converter
condition_converter
max_insert_batch_size
async def open() -> None

Open the connection pool, if owned by the adapter.

async def close() -> None

Close the connection pool, if owned by the adapter.

@overload
async def save[Name: StringPersistable, Payload: JsonPersistable, Metadata: JsonPersistable](
    *,
    target: StreamIdentifier,
    events: Sequence[NewEvent[Name, Payload, Metadata]],
    condition: WriteCondition = NoCondition(),
) -> Sequence[StoredEvent[Name, Payload, Metadata]]
@overload
async def save[Name: StringPersistable, Payload: JsonPersistable, Metadata: JsonPersistable](
    *,
    target: CategoryIdentifier,
    streams: Mapping[str, StreamPublishDefinition[Name, Payload, Metadata]],
) -> Mapping[str, Sequence[StoredEvent[Name, Payload, Metadata]]]
async def latest(
    *,
    target: Latestable,
) -> StoredEvent[str, JsonValue, JsonValue] | None
async def scan(
    *,
    target: Scannable = LogIdentifier(),
    constraints: Set[source_constraints.QueryConstraint] = frozenset(),
) -> AsyncIterator[StoredEvent[str, JsonValue, JsonValue]]
class retry_on_error(tries: int)

Bases: event_store_transaction, ABC

Abstract decorator that retries the handler on a given exception type.

Subclasses set the exception class variable to the exception type to retry on. The handler is called at most tries times (always at least once); if every attempt raises exception, the exception from the final attempt propagates. Other exceptions propagate immediately.

Parameters:

  • tries (int) — The maximum number of attempts.
tries: Final[int]
exception: type[Exception]
async def wrap_handler[R](handler: Callable[[], Awaitable[R]]) -> R
class retry_on_unmet_condition_error(tries: int)

Bases: retry_on_error

Decorator that retries the handler on UnmetWriteConditionError.

Useful for optimistic concurrency, where the handler re-reads the stream and publishes with an updated write condition on each attempt.

Parameters:

  • tries (int) — The maximum number of attempts.
exception = UnmetWriteConditionError
def stream_publish_definition[Name: StringPersistable = str, Payload: JsonPersistable = JsonValue, Metadata: JsonPersistable = JsonValue](
    *,
    events: Sequence[NewEvent[Name, Payload, Metadata]],
    condition: WriteCondition | None = None,
) -> StreamPublishDefinition[Name, Payload, Metadata]

Create a StreamPublishDefinition.

Parameters:

  • events (Sequence[NewEvent[Name, Payload, Metadata]]) — The events to publish to the stream, in order.
  • condition (WriteCondition | None) — The write condition for the stream. If None, the condition key is omitted and the stream is written unconditionally.

Returns:

class StreamPublishDefinition[Name: StringPersistable = str, Payload: JsonPersistable = JsonValue, Metadata: JsonPersistable = JsonValue]

Bases: TypedDict

The events to publish to a single stream and an optional condition.

Used as the per-stream value when publishing to multiple streams of a category at once.

Attributes:

  • events (Sequence[NewEvent[Name, Payload, Metadata]]) — The events to publish to the stream, in order.
  • condition (NotRequired[WriteCondition]) — The write condition for the stream. If absent, the stream is written unconditionally.
events: Sequence[NewEvent[Name, Payload, Metadata]]
condition: NotRequired[WriteCondition]
class UnmetWriteConditionError(message: str)

Bases: Exception

Raised when a write condition is not met at the time of a write.

When raised, none of the events in the write have been stored.

Parameters:

  • message (str) — A description of the unmet condition.
message
class EventSerialisationGuarantee[Identifier: EventSourceIdentifier]

Bases: ABC

The scope within which a storage adapter serialises writes.

Writes that share a lock name are serialised with respect to each other; writes with different lock names may proceed concurrently. Use one of the provided instances:

  • LOG: all writes to the store are serialised.
  • CATEGORY: writes to the same category are serialised.
  • STREAM: writes to the same stream are serialised.

Narrower scopes allow more write concurrency. With CATEGORY or STREAM, events are not necessarily committed in sequence number order across categories or streams respectively, so a reader scanning the log may observe a later sequence number before an earlier one is committed.

LOG: LogEventSerialisationGuarantee
CATEGORY: CategoryEventSerialisationGuarantee
STREAM: StreamEventSerialisationGuarantee
def lock_name(namespace: str, target: Identifier) -> str

Determine the name of the lock to hold when writing to a target.

Parameters:

  • namespace (str) — A namespace for the lock name, such as a table name.
  • target (Identifier) — The identifier being written to.

Returns:

  • str — the lock name.
type AnyEventSerialisationGuarantee = LogEventSerialisationGuarantee | CategoryEventSerialisationGuarantee | StreamEventSerialisationGuarantee
class PostgresQuerySettings(*, scan_query_page_size: int = 100)

Settings controlling the queries issued by the Postgres adapter.

Parameters:

  • scan_query_page_size (int) — The number of events fetched per query when scanning. Defaults to 100.
scan_query_page_size: int
type InMemoryQueryConstraintCheck[E: StoredEvent = StoredEvent] = constraints.QueryConstraintCheck[E]
class InMemoryTypeRegistryConstraintConverter(
    registry: Mapping[type[I], Converter[Any, R]] | None = None,
)

Bases: TypeRegistryConverter[constraints.QueryConstraint, InMemoryQueryConstraintCheck]

Converts query constraints into in-memory predicates by type.

Register a converter for each supported constraint type, or call with_default_constraint_converters to register the built-in ones.

def register[QC: constraints.QueryConstraint](
    item_type: type[QC],
    converter: Converter[QC, InMemoryQueryConstraintCheck],
) -> Self
def with_default_constraint_converters() -> Self

Register converters for the built-in query constraints.

Returns:

  • Self — this converter, to allow chaining.
class MultiLock(locks: Sequence[Lock])

Async context manager that holds several locks at once.

Locks are acquired in the order given and released in reverse order. Callers should supply locks in a consistent order to avoid deadlock.

Parameters:

  • locks (Sequence[Lock]) — The locks to acquire.
async def __aenter__() -> Any
async def __aexit__(
    exc_type: type[BaseException] | None,
    exc_val: BaseException | None,
    exc_tb: TracebackType | None,
) -> None

Write conditions for conditional (optimistic concurrency) publishing.

A write condition is evaluated against the current state of a stream at the time of a write, under the storage adapter’s write lock. If the condition is not met, the write is rejected with UnmetWriteConditionError and no events are stored.

Conditions can be combined with & (all must be met) and | (at least one must be met), e.g. position_is(3) | stream_is_empty().

class WriteCondition

Bases: ABC

Base class for conditions that must hold for a write to succeed.

Conditions are immutable and support combination with & and |. Combining with a condition of the same compound type flattens the result, so a & b & c is a single AndCondition of three conditions.

def __and__(other: WriteCondition) -> WriteCondition

Combine with another condition such that both must be met.

Returns:

def __or__(other: WriteCondition) -> WriteCondition

Combine with another condition such that either must be met.

Returns:

class AndCondition(conditions: frozenset[WriteCondition])

Bases: WriteCondition

Condition met when all of its constituent conditions are met.

Typically created with the & operator rather than directly.

Attributes:

  • conditions (frozenset[WriteCondition]) — The conditions that must all be met.
conditions: frozenset[WriteCondition]
@classmethod
def construct(*conditions: WriteCondition) -> AndCondition

Create an AndCondition from the given conditions.

Parameters:

  • *conditions (WriteCondition) — The conditions that must all be met.

Returns:

class OrCondition(conditions: frozenset[WriteCondition])

Bases: WriteCondition

Condition met when at least one of its constituent conditions is met.

Typically created with the | operator rather than directly.

Attributes:

  • conditions (frozenset[WriteCondition]) — The conditions of which at least one must be met.
conditions: frozenset[WriteCondition]
@classmethod
def construct(*conditions: WriteCondition) -> OrCondition

Create an OrCondition from the given conditions.

Parameters:

  • *conditions (WriteCondition) — The conditions of which at least one must be met.

Returns:

class NoCondition

Bases: WriteCondition

Condition that is always met. The default for unconditional writes.

class PositionIsCondition(position: int | None)

Bases: WriteCondition

Condition met when the stream’s latest event is at a given position.

Stream positions are zero-based, so the first event in a stream has position 0. A position of None is met only when the stream is empty.

Attributes:

  • position (int | None) — The expected position of the latest event in the stream.
position: int | None
class EmptyStreamCondition

Bases: WriteCondition

Condition met when the stream contains no events.

def position_is(position: int | None) -> WriteCondition

Create a condition that the stream’s latest event is at a position.

Parameters:

  • position (int | None) — The expected zero-based position of the latest event, or None to expect an empty stream.

Returns:

def stream_is_empty() -> WriteCondition

Create a condition that the stream contains no events.

Returns: