Skip to content

AsyncEventStore

Async API for working with events.

Async counterpart of EventStore. All operations are coroutines and must be awaited.

Source code in event_sourcery/_event_store/_async/event_store.py
class AsyncEventStore:
    """
    Async API for working with events.

    Async counterpart of `EventStore`. All operations are coroutines and
    must be awaited.
    """

    def __init__(
        self,
        storage_strategy: AsyncStorageStrategy,
        serde: AsyncSerde,
        context_enrichers: tuple[EventContextEnricher, ...] = (),
    ) -> None:
        self._storage_strategy = storage_strategy
        self._serde = serde
        self._context_enrichers = context_enrichers

    async def load_stream(
        self,
        stream_id: StreamId,
        start: int | None = None,
        stop: int | None = None,
    ) -> Sequence[WrappedEvent]:
        """Loads events from a given stream.

        Args:
            stream_id: The stream identifier to load events from.
            start: The stream version to start loading from (including).
            stop: The stream version to stop loading at (excluding).

        Returns:
            A sequence of events or empty list if the stream doesn't exist.
        """
        events = await self._storage_strategy.fetch_events(
            stream_id, start=start, stop=stop
        )
        return [await self._serde.deserialize(event) for event in events]

    @singledispatchmethod
    async def append(
        self,
        first: WrappedEvent,
        *events: WrappedEvent,
        stream_id: StreamId,
        expected_version: int | Versioning = 0,
    ) -> None:
        """Appends events to a stream with a given ID.

        Implements optimistic locking to ensure stream wasn't modified since last read.
        To use it, pass the expected version of the stream.

        Args:
            first: The first event to append (WrappedEvent or Event).
            *events: The rest of the events to append (same type as first argument).
            stream_id: The stream identifier to append events to.
            expected_version: The expected version of the stream

        Returns:
            None
        """
        await self._append(
            stream_id=stream_id,
            events=(first, *events),
            expected_version=expected_version,
        )

    @append.register
    async def _append_events(
        self,
        *events: Event,
        stream_id: StreamId,
        expected_version: int | Versioning = 0,
    ) -> None:
        wrapped_events = self._wrap_events(expected_version, events)
        await self.append(
            *wrapped_events,
            stream_id=stream_id,
            expected_version=expected_version,
        )

    @singledispatchmethod
    def _wrap_events(
        self,
        expected_version: int,
        events: Sequence[Event],
    ) -> Sequence[WrappedEvent]:
        return [
            WrappedEvent.wrap(event=event, version=version)
            for version, event in enumerate(events, start=expected_version + 1)
        ]

    @_wrap_events.register
    def _wrap_events_versioning(
        self, expected_version: Versioning, events: Sequence[Event]
    ) -> Sequence[WrappedEvent]:
        return [WrappedEvent.wrap(event=event, version=None) for event in events]

    async def _append(
        self,
        stream_id: StreamId,
        events: Sequence[WrappedEvent],
        expected_version: int | Versioning,
    ) -> None:
        new_version = events[-1].version
        versioning: Versioning
        if expected_version is not NO_VERSIONING:
            versioning = ExplicitVersioning(
                expected_version=cast(int, expected_version),
                initial_version=cast(int, new_version),
            )
        else:
            versioning = NO_VERSIONING

        await self._storage_strategy.insert_events(
            stream_id=stream_id,
            versioning=versioning,
            events=[
                await self._serde.serialize(
                    enrich_event(event, stream_id, self._context_enrichers),
                    stream_id,
                )
                for event in events
            ],
        )

    async def delete_stream(self, stream_id: StreamId) -> None:
        """Deletes a stream with a given ID.

        If a stream does not exist, this method does nothing.

        Args:
            stream_id: The stream identifier to delete.

        Returns:
            None
        """
        await self._storage_strategy.delete_stream(stream_id)

    async def save_snapshot(self, stream_id: StreamId, snapshot: WrappedEvent) -> None:
        """Saves a snapshot of the stream.

        Args:
            stream_id: The stream identifier to save the snapshot.
            snapshot: The snapshot to save.

        Returns:
            None
        """
        serialized = await self._serde.serialize(event=snapshot, stream_id=stream_id)
        await self._storage_strategy.save_snapshot(serialized)

    async def position(self) -> Position | None:
        """Returns the current position of the event store.

        Unlike its synchronous counterpart, this is a coroutine (not a property),
        as fetching the position performs I/O in real backends.
        """
        return await self._storage_strategy.current_position()

append(first, *events, stream_id, expected_version=0) async

Appends events to a stream with a given ID.

Implements optimistic locking to ensure stream wasn't modified since last read. To use it, pass the expected version of the stream.

Parameters:

Name Type Description Default
first WrappedEvent

The first event to append (WrappedEvent or Event).

required
*events WrappedEvent

The rest of the events to append (same type as first argument).

()
stream_id StreamId

The stream identifier to append events to.

required
expected_version int | Versioning

The expected version of the stream

0

Returns:

Type Description
None

None

Source code in event_sourcery/_event_store/_async/event_store.py
@singledispatchmethod
async def append(
    self,
    first: WrappedEvent,
    *events: WrappedEvent,
    stream_id: StreamId,
    expected_version: int | Versioning = 0,
) -> None:
    """Appends events to a stream with a given ID.

    Implements optimistic locking to ensure stream wasn't modified since last read.
    To use it, pass the expected version of the stream.

    Args:
        first: The first event to append (WrappedEvent or Event).
        *events: The rest of the events to append (same type as first argument).
        stream_id: The stream identifier to append events to.
        expected_version: The expected version of the stream

    Returns:
        None
    """
    await self._append(
        stream_id=stream_id,
        events=(first, *events),
        expected_version=expected_version,
    )

delete_stream(stream_id) async

Deletes a stream with a given ID.

If a stream does not exist, this method does nothing.

Parameters:

Name Type Description Default
stream_id StreamId

The stream identifier to delete.

required

Returns:

Type Description
None

None

Source code in event_sourcery/_event_store/_async/event_store.py
async def delete_stream(self, stream_id: StreamId) -> None:
    """Deletes a stream with a given ID.

    If a stream does not exist, this method does nothing.

    Args:
        stream_id: The stream identifier to delete.

    Returns:
        None
    """
    await self._storage_strategy.delete_stream(stream_id)

load_stream(stream_id, start=None, stop=None) async

Loads events from a given stream.

Parameters:

Name Type Description Default
stream_id StreamId

The stream identifier to load events from.

required
start int | None

The stream version to start loading from (including).

None
stop int | None

The stream version to stop loading at (excluding).

None

Returns:

Type Description
Sequence[WrappedEvent]

A sequence of events or empty list if the stream doesn't exist.

Source code in event_sourcery/_event_store/_async/event_store.py
async def load_stream(
    self,
    stream_id: StreamId,
    start: int | None = None,
    stop: int | None = None,
) -> Sequence[WrappedEvent]:
    """Loads events from a given stream.

    Args:
        stream_id: The stream identifier to load events from.
        start: The stream version to start loading from (including).
        stop: The stream version to stop loading at (excluding).

    Returns:
        A sequence of events or empty list if the stream doesn't exist.
    """
    events = await self._storage_strategy.fetch_events(
        stream_id, start=start, stop=stop
    )
    return [await self._serde.deserialize(event) for event in events]

position() async

Returns the current position of the event store.

Unlike its synchronous counterpart, this is a coroutine (not a property), as fetching the position performs I/O in real backends.

Source code in event_sourcery/_event_store/_async/event_store.py
async def position(self) -> Position | None:
    """Returns the current position of the event store.

    Unlike its synchronous counterpart, this is a coroutine (not a property),
    as fetching the position performs I/O in real backends.
    """
    return await self._storage_strategy.current_position()

save_snapshot(stream_id, snapshot) async

Saves a snapshot of the stream.

Parameters:

Name Type Description Default
stream_id StreamId

The stream identifier to save the snapshot.

required
snapshot WrappedEvent

The snapshot to save.

required

Returns:

Type Description
None

None

Source code in event_sourcery/_event_store/_async/event_store.py
async def save_snapshot(self, stream_id: StreamId, snapshot: WrappedEvent) -> None:
    """Saves a snapshot of the stream.

    Args:
        stream_id: The stream identifier to save the snapshot.
        snapshot: The snapshot to save.

    Returns:
        None
    """
    serialized = await self._serde.serialize(event=snapshot, stream_id=stream_id)
    await self._storage_strategy.save_snapshot(serialized)