Skip to content

KurrentDBBackend

Bases: Backend

KurrentDB integration backend for Event Sourcery.

Source code in event_sourcery_kurrentdb/__init__.py
class KurrentDBBackend(Backend):
    """
    KurrentDB integration backend for Event Sourcery.
    """

    def __init__(self) -> None:
        super().__init__()
        self[KurrentDBClient] = not_configured(
            "Configure backend with `.configure(kurrentdb_client, config)`",
        )
        self[KurrentDBConfig] = not_configured(
            "Configure backend with `.configure(kurrentdb_client, config)`",
        )
        self[StorageStrategy] = lambda c: KurrentDBStorageStrategy(
            c[KurrentDBClient],
            c[KurrentDBConfig].timeout,
        ).scoped_for_tenant(c[TenantId])
        self[SubscriptionStrategy] = lambda c: KurrentDBSubscriptionStrategy(
            c[KurrentDBClient],
        )

    def configure(
        self, client: KurrentDBClient, config: KurrentDBConfig | None = None
    ) -> Self:
        """
        Sets the backend configuration for KurrentDB client and outbox behavior.

        Allows you to provide a KurrentDBClient instance and an optional SQLAlchemyConfig.
        If no config is provided, the default configuration is used.
        This method must be called before using the backend in production
        to ensure correct event publishing and subscription reliability.

        Args:
            client (KurrentDBClient):
                The KurrentDB client instance to use for backend operations.
            config (KurrentDBConfig | None):
                Optional custom configuration. If None, uses default SQLAlchemyConfig().

        Returns:
            Self: The configured backend instance (for chaining).
        """
        self[KurrentDBClient] = client
        self[KurrentDBConfig] = config or KurrentDBConfig()
        return self

    def with_outbox(self, filterer: OutboxFiltererStrategy = no_filter) -> Self:
        self[OutboxFiltererStrategy] = filterer  # type: ignore[type-abstract]
        self[KurrentDBOutboxStorageStrategy] = lambda c: KurrentDBOutboxStorageStrategy(
            c[KurrentDBClient],
            c[OutboxFiltererStrategy],  # type: ignore[type-abstract]
            c[KurrentDBConfig].outbox_name,
            c[KurrentDBConfig].outbox_attempts,
            c[KurrentDBConfig].timeout,
        )
        self[OutboxStorageStrategy] = lambda c: c[KurrentDBOutboxStorageStrategy]
        self[KurrentDBOutboxStorageStrategy].create_subscription()
        return self

configure(client, config=None)

Sets the backend configuration for KurrentDB client and outbox behavior.

Allows you to provide a KurrentDBClient instance and an optional SQLAlchemyConfig. If no config is provided, the default configuration is used. This method must be called before using the backend in production to ensure correct event publishing and subscription reliability.

Parameters:

Name Type Description Default
client KurrentDBClient

The KurrentDB client instance to use for backend operations.

required
config KurrentDBConfig | None

Optional custom configuration. If None, uses default SQLAlchemyConfig().

None

Returns:

Name Type Description
Self Self

The configured backend instance (for chaining).

Source code in event_sourcery_kurrentdb/__init__.py
def configure(
    self, client: KurrentDBClient, config: KurrentDBConfig | None = None
) -> Self:
    """
    Sets the backend configuration for KurrentDB client and outbox behavior.

    Allows you to provide a KurrentDBClient instance and an optional SQLAlchemyConfig.
    If no config is provided, the default configuration is used.
    This method must be called before using the backend in production
    to ensure correct event publishing and subscription reliability.

    Args:
        client (KurrentDBClient):
            The KurrentDB client instance to use for backend operations.
        config (KurrentDBConfig | None):
            Optional custom configuration. If None, uses default SQLAlchemyConfig().

    Returns:
        Self: The configured backend instance (for chaining).
    """
    self[KurrentDBClient] = client
    self[KurrentDBConfig] = config or KurrentDBConfig()
    return self

AsyncKurrentDBBackend

Bases: AsyncBackend

Async KurrentDB integration backend for Event Sourcery.

Async counterpart of KurrentDBBackend. All event store operations are coroutines exposed via AsyncEventStore, AsyncOutbox and AsyncSubscriptionBuilder resolved from this container.

Source code in event_sourcery_kurrentdb/async_/__init__.py
class AsyncKurrentDBBackend(AsyncBackend):
    """
    Async KurrentDB integration backend for Event Sourcery.

    Async counterpart of `KurrentDBBackend`. All event store operations
    are coroutines exposed via `AsyncEventStore`, `AsyncOutbox` and
    `AsyncSubscriptionBuilder` resolved from this container.
    """

    def __init__(self) -> None:
        super().__init__()
        self[AsyncKurrentDBClient] = not_configured(
            "Configure backend with `.configure(kurrentdb_client, config)`",
        )
        self[KurrentDBConfig] = not_configured(
            "Configure backend with `.configure(kurrentdb_client, config)`",
        )
        self[AsyncStorageStrategy] = lambda c: AsyncKurrentDBStorageStrategy(
            c[AsyncKurrentDBClient],
            c[KurrentDBConfig].timeout,
            _outbox_strategy=c.get(AsyncKurrentDBOutboxStorageStrategy),
        ).scoped_for_tenant(c[TenantId])
        self[AsyncSubscriptionStrategy] = lambda c: AsyncKurrentDBSubscriptionStrategy(
            c[AsyncKurrentDBClient],
        )

    def configure(
        self, client: AsyncKurrentDBClient, config: KurrentDBConfig | None = None
    ) -> Self:
        """
        Sets the backend configuration for the async KurrentDB client.

        Args:
            client (AsyncKurrentDBClient):
                The async KurrentDB client instance to use for backend operations.
            config (KurrentDBConfig | None):
                Optional custom configuration. If None, uses default
                KurrentDBConfig().

        Returns:
            Self: The configured backend instance (for chaining).
        """
        self[AsyncKurrentDBClient] = client
        self[KurrentDBConfig] = config or KurrentDBConfig()
        return self

    def with_outbox(self, filterer: OutboxFiltererStrategy = no_filter) -> Self:
        """
        Enables the outbox for the backend.

        Unlike the synchronous `KurrentDBBackend`, the persistent subscription
        is not created here (a coroutine cannot be awaited from a sync method).
        It is created lazily, before the first append or outbox run that needs
        it — see `AsyncKurrentDBOutboxStorageStrategy.ensure_subscription_created`.
        """
        self[OutboxFiltererStrategy] = filterer  # type: ignore[type-abstract]
        self[AsyncKurrentDBOutboxStorageStrategy] = singleton(
            lambda c: AsyncKurrentDBOutboxStorageStrategy(
                c[AsyncKurrentDBClient],
                c[OutboxFiltererStrategy],  # type: ignore[type-abstract]
                c[KurrentDBConfig].outbox_name,
                c[KurrentDBConfig].outbox_attempts,
                c[KurrentDBConfig].timeout,
            )
        )
        self[AsyncOutboxStorageStrategy] = lambda c: c[
            AsyncKurrentDBOutboxStorageStrategy
        ]
        return self

configure(client, config=None)

Sets the backend configuration for the async KurrentDB client.

Parameters:

Name Type Description Default
client AsyncKurrentDBClient

The async KurrentDB client instance to use for backend operations.

required
config KurrentDBConfig | None

Optional custom configuration. If None, uses default KurrentDBConfig().

None

Returns:

Name Type Description
Self Self

The configured backend instance (for chaining).

Source code in event_sourcery_kurrentdb/async_/__init__.py
def configure(
    self, client: AsyncKurrentDBClient, config: KurrentDBConfig | None = None
) -> Self:
    """
    Sets the backend configuration for the async KurrentDB client.

    Args:
        client (AsyncKurrentDBClient):
            The async KurrentDB client instance to use for backend operations.
        config (KurrentDBConfig | None):
            Optional custom configuration. If None, uses default
            KurrentDBConfig().

    Returns:
        Self: The configured backend instance (for chaining).
    """
    self[AsyncKurrentDBClient] = client
    self[KurrentDBConfig] = config or KurrentDBConfig()
    return self

with_outbox(filterer=no_filter)

Enables the outbox for the backend.

Unlike the synchronous KurrentDBBackend, the persistent subscription is not created here (a coroutine cannot be awaited from a sync method). It is created lazily, before the first append or outbox run that needs it — see AsyncKurrentDBOutboxStorageStrategy.ensure_subscription_created.

Source code in event_sourcery_kurrentdb/async_/__init__.py
def with_outbox(self, filterer: OutboxFiltererStrategy = no_filter) -> Self:
    """
    Enables the outbox for the backend.

    Unlike the synchronous `KurrentDBBackend`, the persistent subscription
    is not created here (a coroutine cannot be awaited from a sync method).
    It is created lazily, before the first append or outbox run that needs
    it — see `AsyncKurrentDBOutboxStorageStrategy.ensure_subscription_created`.
    """
    self[OutboxFiltererStrategy] = filterer  # type: ignore[type-abstract]
    self[AsyncKurrentDBOutboxStorageStrategy] = singleton(
        lambda c: AsyncKurrentDBOutboxStorageStrategy(
            c[AsyncKurrentDBClient],
            c[OutboxFiltererStrategy],  # type: ignore[type-abstract]
            c[KurrentDBConfig].outbox_name,
            c[KurrentDBConfig].outbox_attempts,
            c[KurrentDBConfig].timeout,
        )
    )
    self[AsyncOutboxStorageStrategy] = lambda c: c[
        AsyncKurrentDBOutboxStorageStrategy
    ]
    return self

KurrentDBConfig

Bases: BaseModel

Configuration for KurrentDBBackend event store integration.

Attributes:

Name Type Description
timeout Seconds | None

Optional timeout (in seconds) for KurrentDB operations. Controls the maximum time allowed for backend requests. If None, the default client timeout is used.

outbox_name str

Name of the outbox stream used for reliable event publishing.

outbox_attempts PositiveInt

Maximum number of outbox delivery attempts per event before giving up.

Source code in event_sourcery_kurrentdb/__init__.py
class KurrentDBConfig(BaseModel):
    """
    Configuration for KurrentDBBackend event store integration.

    Attributes:
        timeout (Seconds | None):
            Optional timeout (in seconds) for KurrentDB operations. Controls the maximum
            time allowed for backend requests.
            If None, the default client timeout is used.
        outbox_name (str):
            Name of the outbox stream used for reliable event publishing.
        outbox_attempts (PositiveInt):
            Maximum number of outbox delivery attempts per event before giving up.
    """

    model_config = ConfigDict(extra="forbid", frozen=True)

    timeout: Seconds | None = None
    outbox_name: str = "pyes-outbox"
    outbox_attempts: PositiveInt = 3

KurrentDBStorageStrategy

Bases: StorageStrategy

Source code in event_sourcery_kurrentdb/event_store.py
@dataclass(repr=False)
class KurrentDBStorageStrategy(StorageStrategy):
    _client: KurrentDBClient
    _timeout: float | None
    _tenant_id: TenantId = DEFAULT_TENANT

    def fetch_events(
        self,
        stream_id: StreamId,
        start: int | None = None,
        stop: int | None = None,
    ) -> list[RawEvent]:
        snapshot = None
        name = stream.Name(self._tenant_id, stream_id)
        if start is None and (snapshot := self._read_snapshot(name)) is not None:
            start = cast(int, snapshot.version) + 1

        position, limit = stream.scope(start, stop)
        entries = self._client.read_stream(
            stream_name=str(name),
            stream_position=position,
            limit=limit,
            timeout=self._timeout,
        )
        try:
            events = [dto.raw_event(entry) for entry in entries]
            if snapshot:
                return [snapshot, *events]
            return events
        except NotFoundError:
            return []

    def _read_snapshot(self, name: stream.Name) -> RawEvent | None:
        snapshots = self._client.read_stream(
            name.snapshot,
            limit=1,
            backwards=True,
            timeout=self._timeout,
        )
        try:
            last = next(iter(snapshots))
            return dto.snapshot(last)
        except NotFoundError:
            return None

    def insert_events(
        self, stream_id: StreamId, versioning: Versioning, events: list[RawEvent]
    ) -> None:
        expectation: int | StreamState = StreamState.ANY
        if isinstance(versioning, ExplicitVersioning):
            if versioning.expected_version == 0:
                expectation = StreamState.NO_STREAM
            else:
                expectation = cast(int, versioning.expected_version) - 1

        for sid in {e.stream_id for e in events}:
            stream_name = stream.Name(self._tenant_id, sid)
            stream_events = [e for e in events if e.stream_id == sid]
            self._append_events(
                stream_name, events=stream_events, expectation=expectation
            )

    def _append_events(
        self, name: stream.Name, events: list[RawEvent], expectation: int | StreamState
    ) -> int:
        try:
            return cast(
                int,
                self._client.append_events(
                    str(name),
                    current_version=expectation,
                    events=(dto.new_entry(e) for e in events),
                    timeout=self._timeout,
                ),
            )
        except WrongCurrentVersionError as err:
            raise ConcurrentStreamWriteError from err

    def save_snapshot(self, snapshot: RawEvent) -> None:
        name = stream.Name(self._tenant_id, snapshot.stream_id)
        stream_position = stream.Position.from_version(cast(int, snapshot.version))
        self._client.append_events(
            name.snapshot,
            current_version=StreamState.ANY,
            events=[dto.new_entry(snapshot, stream_position=stream_position)],
            timeout=self._timeout,
        )

    def delete_stream(self, stream_id: StreamId) -> None:
        name = stream.Name(self._tenant_id, stream_id)
        try:
            self._client.delete_stream(
                str(name),
                current_version=StreamState.ANY,
                timeout=self._timeout,
            )
        except NotFoundError:
            pass

    @property
    def current_position(self) -> Position | None:
        return Position(self._client.get_commit_position(timeout=self._timeout))

    def scoped_for_tenant(self, tenant_id: TenantId) -> Self:
        return replace(self, _tenant_id=tenant_id)

AsyncKurrentDBStorageStrategy

Bases: AsyncStorageStrategy

Async counterpart of KurrentDBStorageStrategy.

Stores events in KurrentDB using the AsyncKurrentDBClient.

Source code in event_sourcery_kurrentdb/async_/event_store.py
@dataclass(repr=False)
class AsyncKurrentDBStorageStrategy(AsyncStorageStrategy):
    """
    Async counterpart of `KurrentDBStorageStrategy`.

    Stores events in KurrentDB using the `AsyncKurrentDBClient`.
    """

    _client: AsyncKurrentDBClient
    _timeout: float | None
    _tenant_id: TenantId = DEFAULT_TENANT
    _outbox_strategy: AsyncKurrentDBOutboxStorageStrategy | None = None

    async def fetch_events(
        self,
        stream_id: StreamId,
        start: int | None = None,
        stop: int | None = None,
    ) -> list[RawEvent]:
        snapshot = None
        name = stream.Name(self._tenant_id, stream_id)
        if start is None and (snapshot := await self._read_snapshot(name)) is not None:
            start = cast(int, snapshot.version) + 1

        position, limit = stream.scope(start, stop)
        entries = await self._client.read_stream(
            stream_name=str(name),
            stream_position=position,
            limit=limit,
            timeout=self._timeout,
        )
        try:
            events = [dto.raw_event(entry) async for entry in entries]
            if snapshot:
                return [snapshot, *events]
            return events
        except NotFoundError:
            return []

    async def _read_snapshot(self, name: stream.Name) -> RawEvent | None:
        snapshots = await self._client.read_stream(
            name.snapshot,
            limit=1,
            backwards=True,
            timeout=self._timeout,
        )
        try:
            last = await anext(snapshots)
            return dto.snapshot(last)
        except NotFoundError:
            return None

    async def insert_events(
        self, stream_id: StreamId, versioning: Versioning, events: list[RawEvent]
    ) -> None:
        expectation: int | StreamState = StreamState.ANY
        if isinstance(versioning, ExplicitVersioning):
            if versioning.expected_version == 0:
                expectation = StreamState.NO_STREAM
            else:
                expectation = cast(int, versioning.expected_version) - 1

        if self._outbox_strategy is not None:
            # the outbox persistent subscription must exist before the first
            # append, otherwise events would never reach the outbox
            await self._outbox_strategy.ensure_subscription_created()

        for sid in {e.stream_id for e in events}:
            stream_name = stream.Name(self._tenant_id, sid)
            stream_events = [e for e in events if e.stream_id == sid]
            await self._append_events(
                stream_name, events=stream_events, expectation=expectation
            )

    async def _append_events(
        self, name: stream.Name, events: list[RawEvent], expectation: int | StreamState
    ) -> int:
        try:
            return cast(
                int,
                await self._client.append_events(
                    str(name),
                    current_version=expectation,
                    events=(dto.new_entry(e) for e in events),
                    timeout=self._timeout,
                ),
            )
        except WrongCurrentVersionError as err:
            raise ConcurrentStreamWriteError from err

    async def save_snapshot(self, snapshot: RawEvent) -> None:
        name = stream.Name(self._tenant_id, snapshot.stream_id)
        stream_position = stream.Position.from_version(cast(int, snapshot.version))
        await self._client.append_events(
            name.snapshot,
            current_version=StreamState.ANY,
            events=[dto.new_entry(snapshot, stream_position=stream_position)],
            timeout=self._timeout,
        )

    async def delete_stream(self, stream_id: StreamId) -> None:
        name = stream.Name(self._tenant_id, stream_id)
        try:
            await self._client.delete_stream(
                str(name),
                current_version=StreamState.ANY,
                timeout=self._timeout,
            )
        except NotFoundError:
            pass

    async def current_position(self) -> Position | None:
        return Position(await self._client.get_commit_position(timeout=self._timeout))

    def scoped_for_tenant(self, tenant_id: TenantId) -> Self:
        return replace(self, _tenant_id=tenant_id)

AsyncKurrentDBOutboxStorageStrategy

Bases: AsyncOutboxStorageStrategy

Async counterpart of KurrentDBOutboxStorageStrategy.

Implements the outbox on top of a KurrentDB persistent subscription to the $all stream. Unlike the sync variant, the persistent subscription is created lazily — before the first append that uses the outbox or before the first outbox run — because the sync with_outbox() configuration method cannot await coroutines.

Source code in event_sourcery_kurrentdb/async_/outbox.py
@dataclass(repr=False)
class AsyncKurrentDBOutboxStorageStrategy(AsyncOutboxStorageStrategy):
    """
    Async counterpart of `KurrentDBOutboxStorageStrategy`.

    Implements the outbox on top of a KurrentDB persistent subscription
    to the `$all` stream. Unlike the sync variant, the persistent
    subscription is created lazily — before the first append that uses
    the outbox or before the first outbox run — because the sync
    `with_outbox()` configuration method cannot await coroutines.
    """

    _client: AsyncKurrentDBClient
    _filterer: OutboxFiltererStrategy
    _outbox_name: str
    _max_publish_attempts: int
    _timeout: float | None
    _active_subscription: AbstractAsyncPersistentSubscription = field(init=False)
    _subscription_creation: asyncio.Lock = field(
        init=False, default_factory=asyncio.Lock
    )
    _subscription_created: bool = field(init=False, default=False)

    async def ensure_subscription_created(self) -> None:
        """
        Creates the persistent subscription for the outbox if missing.

        Called lazily: by the storage strategy before the first append (so no
        event can bypass the outbox) and before each outbox run. Idempotent and
        safe to call concurrently.
        """
        if self._subscription_created:
            return
        async with self._subscription_creation:
            if self._subscription_created:
                return
            await self._create_subscription()
            self._subscription_created = True

    async def _create_subscription(self) -> None:
        try:
            await self._client.get_subscription_info(
                self._outbox_name, timeout=self._timeout
            )
        except NotFoundError:
            await self._client.create_subscription_to_all(
                self._outbox_name,
                from_end=True,
                timeout=self._timeout,
            )

    @asynccontextmanager
    async def _context(
        self,
        limit: int | None = None,
    ) -> AsyncIterator[AsyncIterator[RecordedEvent]]:
        self._active_subscription = await self._client.read_subscription_to_all(
            self._outbox_name,
            timeout=self._timeout,
        )
        try:
            yield self._take(self._active_subscription, limit or 100)
        finally:
            await self._active_subscription.stop()
            delattr(self, "_active_subscription")

    @staticmethod
    async def _take(
        subscription: AbstractAsyncPersistentSubscription, limit: int
    ) -> AsyncIterator[RecordedEvent]:
        for _ in range(limit):
            try:
                yield await anext(subscription)
            except StopAsyncIteration:
                return

    @property
    def active_subscription(self) -> AbstractAsyncPersistentSubscription:
        return self._active_subscription

    async def outbox_entries(
        self, limit: int
    ) -> AsyncIterator[AbstractAsyncContextManager[RecordedRaw]]:
        await self.ensure_subscription_created()

        info = await self._client.get_subscription_info(
            self._outbox_name,
            timeout=self._timeout,
        )
        if info.live_buffer_count == 0:
            return

        async with self._context(limit) as subscription:
            try:
                async for entry in subscription:
                    record = dto.raw_record(entry)
                    if self._filterer(record.entry):
                        yield self._publish_context(entry, record)
                    else:
                        await self.active_subscription.ack(entry.id)
            except DeadlineExceededError:
                pass

    @asynccontextmanager
    async def _publish_context(
        self,
        entry: RecordedEvent,
        record: RecordedRaw,
    ) -> AsyncGenerator[RecordedRaw, None]:
        try:
            yield record
        except Exception:
            logger.exception("Failed to publish message #%d", entry.id)
            failure_count = (entry.retry_count or 0) + 1
            if self._reached_max_number_of_attempts(failure_count):
                await self.active_subscription.nack(entry.id, action="park")
            else:
                await self.active_subscription.nack(entry.id, action="retry")
        else:
            await self.active_subscription.ack(entry.id)

    def _reached_max_number_of_attempts(self, failure_count: int) -> bool:
        return failure_count >= self._max_publish_attempts

ensure_subscription_created() async

Creates the persistent subscription for the outbox if missing.

Called lazily: by the storage strategy before the first append (so no event can bypass the outbox) and before each outbox run. Idempotent and safe to call concurrently.

Source code in event_sourcery_kurrentdb/async_/outbox.py
async def ensure_subscription_created(self) -> None:
    """
    Creates the persistent subscription for the outbox if missing.

    Called lazily: by the storage strategy before the first append (so no
    event can bypass the outbox) and before each outbox run. Idempotent and
    safe to call concurrently.
    """
    if self._subscription_created:
        return
    async with self._subscription_creation:
        if self._subscription_created:
            return
        await self._create_subscription()
        self._subscription_created = True