Skip to content

AsyncSubscriptionBuilder

Bases: AsyncPositionPhase, AsyncFilterPhase, AsyncBuildPhase

Async counterpart of SubscriptionBuilder. Fluent builder for async event subscriptions.

Source code in event_sourcery/_event_store/_async/subscription.py
@dataclass(repr=False)
class AsyncSubscriptionBuilder(AsyncPositionPhase, AsyncFilterPhase, AsyncBuildPhase):
    """
    Async counterpart of `SubscriptionBuilder`. Fluent builder for async
    event subscriptions.
    """

    _serde: AsyncSerde
    _strategy: AsyncSubscriptionStrategy
    _position: Position = field(init=False, default=sys.maxsize)
    _build: Callable[..., AsyncIterator[list[RecordedRaw]]] = field(init=False)

    def __post_init__(self) -> None:
        self._build = partial(self._strategy.subscribe_to_all)

    def start_from(self, position: Position) -> AsyncFilterPhase:
        self._build = partial(self._build, start_from=position)
        self._position = position
        return self

    def to_category(self, category: StreamCategory) -> AsyncBuildPhase:
        self._build = partial(
            self._strategy.subscribe_to_category,
            start_from=self._position,
            category=category,
        )
        return self

    def to_events(self, events: list[type[Event]]) -> AsyncBuildPhase:
        self._build = partial(
            self._strategy.subscribe_to_events,
            start_from=self._position,
            events=[self._serde.registry.name_for_type(event) for event in events],
        )
        return self

    def build_iter(
        self,
        timelimit: Seconds | timedelta,
    ) -> AsyncIterator[Recorded | None]:
        timelimit = to_timedelta(timelimit)
        return self._single_event_unpack(self._build(batch_size=1, timelimit=timelimit))

    async def _single_event_unpack(
        self,
        subscription: AsyncIterator[list[RecordedRaw]],
    ) -> AsyncIterator[Recorded | None]:
        while True:
            batch = await anext(subscription)
            yield await self._serde.deserialize_record(batch[0]) if batch else None

    def build_batch(
        self,
        size: int,
        timelimit: Seconds | timedelta,
    ) -> AsyncIterator[list[Recorded]]:
        seconds = to_timedelta(timelimit)
        subscription = self._build(batch_size=size, timelimit=seconds)
        return self._batch_unpack(subscription)

    async def _batch_unpack(
        self,
        subscription: AsyncIterator[list[RecordedRaw]],
    ) -> AsyncIterator[list[Recorded]]:
        async for (
            batch
        ) in subscription:  # pragma: no cover  # subscriptions are infinite
            yield [await self._serde.deserialize_record(e) for e in batch]