콘텐츠로 이동

spakky-event

spakky-event는 이벤트 계약, 발행, provider 검증, handler stereotype을 제공하는 core 패키지입니다.

제공자 중립 이벤트 시스템 — EventBus, EventTransport 및 consumer/dispatcher 계약

플러그인 진입점

initialize(app)

Initialize the spakky-event plugin.

Registers publishing contracts and validates declared handler providers.

Source code in core/spakky-event/src/spakky/event/main.py
def initialize(app: SpakkyApplication) -> None:
    """Initialize the spakky-event plugin.

    Registers publishing contracts and validates declared handler providers.
    """
    app.add(AsyncTransactionalEventPublishingAspect)
    app.add(TransactionalEventPublishingAspect)
    app.add(AsyncIdempotentAspect)
    app.add(IdempotentAspect)

    app.add(EventPublisher)
    app.add(AsyncEventPublisher)
    app.add(AuthContextSnapshotHeaderInjector)
    app.add(DirectEventBus)
    app.add(AsyncDirectEventBus)

    app.add(EventHandlerProviderValidationPostProcessor)

Publisher 인터페이스

Event publishing and transport interfaces.

Provides publisher, bus, and transport abstractions for event routing: - IEventPublisher: Routes events by type (domain vs integration). - IEventBus: Serializes and sends integration events via transport. - IEventTransport: Low-level transport for serialized event payloads.

IEventPublisher

Bases: ABC

Publishes events by routing to dispatcher or bus based on event type.

publish(event) abstractmethod

Publish an event (domain → dispatcher, integration → bus).

Source code in core/spakky-event/src/spakky/event/event_publisher.py
@abstractmethod
def publish(self, event: AbstractEvent) -> None:
    """Publish an event (domain → dispatcher, integration → bus)."""
    ...

IAsyncEventPublisher

Bases: ABC

Async counterpart of IEventPublisher.

publish(event) abstractmethod async

Publish an event asynchronously.

Source code in core/spakky-event/src/spakky/event/event_publisher.py
@abstractmethod
async def publish(self, event: AbstractEvent) -> None:
    """Publish an event asynchronously."""
    ...

IEventBus

Bases: ABC

Synchronous event bus for sending integration events.

send(event) abstractmethod

Serialize and send an integration event via transport.

Source code in core/spakky-event/src/spakky/event/event_publisher.py
@abstractmethod
def send(self, event: AbstractIntegrationEvent) -> None:
    """Serialize and send an integration event via transport."""
    ...

IAsyncEventBus

Bases: ABC

Asynchronous event bus for sending integration events.

send(event) abstractmethod async

Serialize and send an integration event via transport.

Source code in core/spakky-event/src/spakky/event/event_publisher.py
@abstractmethod
async def send(self, event: AbstractIntegrationEvent) -> None:
    """Serialize and send an integration event via transport."""
    ...

IEventTransport

Bases: ABC

Low-level synchronous transport for pre-serialized event payloads.

The caller owns the publish batch boundary: hand one or more payloads to send() and call flush() once at the end of the batch. Transports may buffer payloads until flush() so that broker round trips are batched.

send(event_name, payload, headers, partition_key=None) abstractmethod

Hand a serialized event payload to the broker client for delivery.

A permanent rejection attributable to this record must be reported as EventDeliveryRejectedError. A connection, timeout, queue, or other transport-wide failure keeps the client exception's original type so a caller does not spend this record's retry budget.

Parameters:

Name Type Description Default
event_name str

Destination topic / routing key.

required
payload bytes

Pre-serialized event bytes.

required
headers dict[str, str]

Metadata headers for trace and auth propagation.

required
partition_key str | None

Key pinning the payload to one broker partition. None spreads payloads round-robin.

None

Raises:

Type Description
EventDeliveryRejectedError

When the transport permanently rejects this specific record.

EventTransportNotRunningError

When the transport's broker client is not open, which happens outside the application lifecycle.

Source code in core/spakky-event/src/spakky/event/event_publisher.py
@abstractmethod
def send(
    self,
    event_name: str,
    payload: bytes,
    headers: dict[str, str],
    partition_key: str | None = None,
) -> None:
    """Hand a serialized event payload to the broker client for delivery.

    A permanent rejection attributable to this record must be reported as
    `EventDeliveryRejectedError`. A connection, timeout, queue, or other
    transport-wide failure keeps the client exception's original type so a
    caller does not spend this record's retry budget.

    Args:
        event_name: Destination topic / routing key.
        payload: Pre-serialized event bytes.
        headers: Metadata headers for trace and auth propagation.
        partition_key: Key pinning the payload to one broker partition.
            None spreads payloads round-robin.

    Raises:
        EventDeliveryRejectedError: When the transport permanently rejects
            this specific record.
        EventTransportNotRunningError: When the transport's broker client is
            not open, which happens outside the application lifecycle.
    """
    ...

flush() abstractmethod

Block until the broker client has finished sending what send() handed over.

A successful return means every record this caller handed over reached the broker. An implementation that learns of a rejection only through a delivery callback collects it and raises here — a caller that batches records has no other moment to learn that the batch did not arrive, and would otherwise record undelivered events as published.

Implementations must preserve the same failure taxonomy as send(): only a permanent record-specific rejection becomes EventDeliveryRejectedError; transport-wide failures retain the broker client's original exception type.

Raises:

Type Description
EventDeliveryRejectedError

When one or more records are permanently rejected for a record-specific cause.

Source code in core/spakky-event/src/spakky/event/event_publisher.py
@abstractmethod
def flush(self) -> None:
    """Block until the broker client has finished sending what send() handed over.

    A successful return means every record this caller handed over reached
    the broker. An implementation that learns of a rejection only through a
    delivery callback collects it and raises here — a caller that batches
    records has no other moment to learn that the batch did not arrive, and
    would otherwise record undelivered events as published.

    Implementations must preserve the same failure taxonomy as send(): only
    a permanent record-specific rejection becomes
    `EventDeliveryRejectedError`; transport-wide failures retain the broker
    client's original exception type.

    Raises:
        EventDeliveryRejectedError: When one or more records are permanently
            rejected for a record-specific cause.
    """
    ...

IAsyncEventTransport

Bases: ABC

Low-level asynchronous transport for pre-serialized event payloads.

The caller owns the publish batch boundary: hand one or more payloads to send() and call flush() once at the end of the batch. Transports may buffer payloads until flush() so that broker round trips are batched. Publishers share one transport, so a batch's send() and flush() belong to the same execution context and flush() reports only that publisher's payloads.

send(event_name, payload, headers, partition_key=None) abstractmethod async

Hand a serialized event payload to the broker client for delivery.

A permanent rejection attributable to this record must be reported as EventDeliveryRejectedError. A connection, timeout, queue, or other transport-wide failure keeps the client exception's original type so a caller does not spend this record's retry budget.

Parameters:

Name Type Description Default
event_name str

Destination topic / routing key.

required
payload bytes

Pre-serialized event bytes.

required
headers dict[str, str]

Metadata headers for trace and auth propagation.

required
partition_key str | None

Key pinning the payload to one broker partition. None spreads payloads round-robin.

None

Raises:

Type Description
EventDeliveryRejectedError

When the transport permanently rejects this specific record.

EventTransportNotRunningError

When the transport's broker client is not open, which happens outside the application lifecycle.

Source code in core/spakky-event/src/spakky/event/event_publisher.py
@abstractmethod
async def send(
    self,
    event_name: str,
    payload: bytes,
    headers: dict[str, str],
    partition_key: str | None = None,
) -> None:
    """Hand a serialized event payload to the broker client for delivery.

    A permanent rejection attributable to this record must be reported as
    `EventDeliveryRejectedError`. A connection, timeout, queue, or other
    transport-wide failure keeps the client exception's original type so a
    caller does not spend this record's retry budget.

    Args:
        event_name: Destination topic / routing key.
        payload: Pre-serialized event bytes.
        headers: Metadata headers for trace and auth propagation.
        partition_key: Key pinning the payload to one broker partition.
            None spreads payloads round-robin.

    Raises:
        EventDeliveryRejectedError: When the transport permanently rejects
            this specific record.
        EventTransportNotRunningError: When the transport's broker client is
            not open, which happens outside the application lifecycle.
    """
    ...

flush() abstractmethod async

Block until the broker client has finished sending what send() handed over.

A successful return means every record this caller handed over reached the broker. An implementation that learns of a rejection only through a delivery callback collects it and raises here — a caller that batches records has no other moment to learn that the batch did not arrive, and would otherwise record undelivered events as published.

Implementations must preserve the same failure taxonomy as send(): only a permanent record-specific rejection becomes EventDeliveryRejectedError; transport-wide failures retain the broker client's original exception type.

Raises:

Type Description
EventDeliveryRejectedError

When one or more records are permanently rejected for a record-specific cause.

Source code in core/spakky-event/src/spakky/event/event_publisher.py
@abstractmethod
async def flush(self) -> None:
    """Block until the broker client has finished sending what send() handed over.

    A successful return means every record this caller handed over reached
    the broker. An implementation that learns of a rejection only through a
    delivery callback collects it and raises here — a caller that batches
    records has no other moment to learn that the batch did not arrive, and
    would otherwise record undelivered events as published.

    Implementations must preserve the same failure taxonomy as send(): only
    a permanent record-specific rejection becomes
    `EventDeliveryRejectedError`; transport-wide failures retain the broker
    client's original exception type.

    Raises:
        EventDeliveryRejectedError: When one or more records are permanently
            rejected for a record-specific cause.
    """
    ...

Consumer 인터페이스

Event consumer interfaces for registering event handlers.

EventHandlerCallback = Callable[[EventT_contra], None]

Synchronous event handler callback type.

AsyncEventHandlerCallback = Callable[[EventT_contra], Awaitable[None]]

Asynchronous event handler callback type.

IEventConsumer

Bases: ABC

Synchronous event consumer interface for registering event handlers.

register(event, handler) abstractmethod

Register a handler callback for the given event type.

Source code in core/spakky-event/src/spakky/event/event_consumer.py
@abstractmethod
def register[EventT_contra: AbstractEvent](
    self,
    event: type[EventT_contra],
    handler: EventHandlerCallback[EventT_contra],
) -> None:
    """Register a handler callback for the given event type."""
    ...

IAsyncEventConsumer

Bases: ABC

Asynchronous event consumer interface for registering event handlers.

register(event, handler) abstractmethod

Register an async handler callback for the given event type.

Source code in core/spakky-event/src/spakky/event/event_consumer.py
@abstractmethod
def register[EventT_contra: AbstractEvent](
    self,
    event: type[EventT_contra],
    handler: AsyncEventHandlerCallback[EventT_contra],
) -> None:
    """Register an async handler callback for the given event type."""
    ...

IDomainEventConsumer

Bases: IEventConsumer, ABC

Synchronous provider that registers in-process domain event handlers.

IAsyncDomainEventConsumer

Bases: IAsyncEventConsumer, ABC

Asynchronous provider that registers in-process domain event handlers.

IIntegrationEventConsumer

Bases: IEventConsumer, ABC

Synchronous provider that registers external integration event handlers.

Every implementation follows the delivery contract in spakky.event.delivery: subscribers read independently, every handler of a subscriber runs even when another fails, failed handlers are retried under the subscriber's RetryPolicy, and exhausted messages move to the subscriber's own dead-letter destination.

register(event, handler, *, subscriber=None, handler_name=None, retry=None) abstractmethod

Register a handler in the subscription of subscriber for event.

Parameters:

Name Type Description Default
event type[EventT_contra]

Integration event type the handler receives.

required
handler EventHandlerCallback[EventT_contra]

Callback invoked with the deserialized event.

required
subscriber SubscriberName | None

Independent subscriber the handler belongs to. None is the unnamed subscriber that reads through the consumer's base broker identity.

None
handler_name HandlerName | None

Name unique within the subscription; it is recorded in dead-letter metadata and in the idempotency key.

None
retry RetryPolicy | None

Retry the handler's class declared for its subscriber. Only the fields it sets explicitly override the consumer-wide policy; None follows what the subscriber's other classes declared.

None

Raises:

Type Description
ConflictingSubscriberRetryPolicyError

Another handler class of the subscriber declared a different retry.

Source code in core/spakky-event/src/spakky/event/event_consumer.py
@abstractmethod
@override
def register[EventT_contra: AbstractEvent](
    self,
    event: type[EventT_contra],
    handler: EventHandlerCallback[EventT_contra],
    *,
    subscriber: SubscriberName | None = None,
    handler_name: HandlerName | None = None,
    retry: RetryPolicy | None = None,
) -> None:
    """Register a handler in the subscription of `subscriber` for `event`.

    Args:
        event: Integration event type the handler receives.
        handler: Callback invoked with the deserialized event.
        subscriber: Independent subscriber the handler belongs to. None is
            the unnamed subscriber that reads through the consumer's base
            broker identity.
        handler_name: Name unique within the subscription; it is recorded in
            dead-letter metadata and in the idempotency key.
        retry: Retry the handler's class declared for its subscriber. Only
            the fields it sets explicitly override the consumer-wide policy;
            None follows what the subscriber's other classes declared.

    Raises:
        ConflictingSubscriberRetryPolicyError: Another handler class of the
            subscriber declared a different retry.
    """
    ...

IAsyncIntegrationEventConsumer

Bases: IAsyncEventConsumer, ABC

Asynchronous provider that registers external integration event handlers.

Follows the same delivery contract as IIntegrationEventConsumer.

register(event, handler, *, subscriber=None, handler_name=None, retry=None) abstractmethod

Register an async handler in the subscription of subscriber for event.

Parameters:

Name Type Description Default
event type[EventT_contra]

Integration event type the handler receives.

required
handler AsyncEventHandlerCallback[EventT_contra]

Callback awaited with the deserialized event.

required
subscriber SubscriberName | None

Independent subscriber the handler belongs to. None is the unnamed subscriber that reads through the consumer's base broker identity.

None
handler_name HandlerName | None

Name unique within the subscription; it is recorded in dead-letter metadata and in the idempotency key.

None
retry RetryPolicy | None

Retry the handler's class declared for its subscriber. Only the fields it sets explicitly override the consumer-wide policy; None follows what the subscriber's other classes declared.

None

Raises:

Type Description
ConflictingSubscriberRetryPolicyError

Another handler class of the subscriber declared a different retry.

Source code in core/spakky-event/src/spakky/event/event_consumer.py
@abstractmethod
@override
def register[EventT_contra: AbstractEvent](
    self,
    event: type[EventT_contra],
    handler: AsyncEventHandlerCallback[EventT_contra],
    *,
    subscriber: SubscriberName | None = None,
    handler_name: HandlerName | None = None,
    retry: RetryPolicy | None = None,
) -> None:
    """Register an async handler in the subscription of `subscriber` for `event`.

    Args:
        event: Integration event type the handler receives.
        handler: Callback awaited with the deserialized event.
        subscriber: Independent subscriber the handler belongs to. None is
            the unnamed subscriber that reads through the consumer's base
            broker identity.
        handler_name: Name unique within the subscription; it is recorded in
            dead-letter metadata and in the idempotency key.
        retry: Retry the handler's class declared for its subscriber. Only
            the fields it sets explicitly override the consumer-wide policy;
            None follows what the subscriber's other classes declared.

    Raises:
        ConflictingSubscriberRetryPolicyError: Another handler class of the
            subscriber declared a different retry.
    """
    ...

Dispatcher 인터페이스

Event dispatcher interfaces for dispatching events to registered handlers.

This module provides unified dispatcher interfaces that handle all event types. Dispatchers are responsible for delivering events to registered handlers, while Consumers are responsible for handler registration. These interfaces are combined in Mediator implementations.

IEventDispatcher

Bases: ABC

Synchronous event dispatcher interface.

dispatch(event) abstractmethod

Dispatch an event to all registered handlers.

Source code in core/spakky-event/src/spakky/event/event_dispatcher.py
@abstractmethod
def dispatch(self, event: AbstractEvent) -> None:
    """Dispatch an event to all registered handlers."""
    ...

IAsyncEventDispatcher

Bases: ABC

Asynchronous event dispatcher interface.

dispatch(event) abstractmethod async

Dispatch an event to all registered async handlers.

Source code in core/spakky-event/src/spakky/event/event_dispatcher.py
@abstractmethod
async def dispatch(self, event: AbstractEvent) -> None:
    """Dispatch an event to all registered async handlers."""
    ...

EventBus

Default EventBus implementations that delegate to EventTransport.

DirectEventBus(transport, propagator, auth_snapshot_headers=None)

Bases: IEventBus

Synchronous event bus that serializes and delegates to IEventTransport.

Initialize with the given transport and trace propagator.

Source code in core/spakky-event/src/spakky/event/bus/transport_event_bus.py
def __init__(
    self,
    transport: IEventTransport | None,
    propagator: ITracePropagator,
    auth_snapshot_headers: AuthContextSnapshotHeaderInjector | None = None,
) -> None:
    """Initialize with the given transport and trace propagator."""
    self._transport = transport
    self._propagator = propagator
    self._auth_snapshot_headers = (
        auth_snapshot_headers or AuthContextSnapshotHeaderInjector()
    )
    self._adapters = {}

send(event)

Serialize and send an integration event via transport.

A direct publish is a batch of one, so the transport is flushed before returning and the caller gets the same delivery guarantee as before.

Source code in core/spakky-event/src/spakky/event/bus/transport_event_bus.py
@override
def send(self, event: AbstractIntegrationEvent) -> None:
    """Serialize and send an integration event via transport.

    A direct publish is a batch of one, so the transport is flushed before
    returning and the caller gets the same delivery guarantee as before.
    """
    if self._transport is None:
        raise IntegrationEventTransportUnavailableError()
    event_type = type(event)
    if event_type not in self._adapters:
        self._adapters[event_type] = TypeAdapter(event_type)
    adapter = self._adapters[event_type]
    headers: dict[str, str] = {}
    self._propagator.inject(headers)
    self._auth_snapshot_headers.inject(headers)
    self._transport.send(
        event.event_name,
        adapter.dump_json(event),
        headers,
        event.partition_key,
    )
    self._transport.flush()

AsyncDirectEventBus(transport, propagator, auth_snapshot_headers=None)

Bases: IAsyncEventBus

Asynchronous event bus that serializes and delegates to IAsyncEventTransport.

Initialize with the given async transport and trace propagator.

Source code in core/spakky-event/src/spakky/event/bus/transport_event_bus.py
def __init__(
    self,
    transport: IAsyncEventTransport | None,
    propagator: ITracePropagator,
    auth_snapshot_headers: AuthContextSnapshotHeaderInjector | None = None,
) -> None:
    """Initialize with the given async transport and trace propagator."""
    self._transport = transport
    self._propagator = propagator
    self._auth_snapshot_headers = (
        auth_snapshot_headers or AuthContextSnapshotHeaderInjector()
    )
    self._adapters = {}

send(event) async

Serialize and send an integration event via async transport.

A direct publish is a batch of one, so the transport is flushed before returning and the caller gets the same delivery guarantee as before.

Source code in core/spakky-event/src/spakky/event/bus/transport_event_bus.py
@override
async def send(self, event: AbstractIntegrationEvent) -> None:
    """Serialize and send an integration event via async transport.

    A direct publish is a batch of one, so the transport is flushed before
    returning and the caller gets the same delivery guarantee as before.
    """
    if self._transport is None:
        raise IntegrationEventTransportUnavailableError()
    event_type = type(event)
    if event_type not in self._adapters:
        self._adapters[event_type] = TypeAdapter(event_type)
    adapter = self._adapters[event_type]
    headers: dict[str, str] = {}
    self._propagator.inject(headers)
    self._auth_snapshot_headers.inject(headers)
    await self._transport.send(
        event.event_name,
        adapter.dump_json(event),
        headers,
        event.partition_key,
    )
    await self._transport.flush()

Auth Propagation

Auth snapshot metadata propagation for outbound integration events.

AuthContextSnapshotHeaderInjector(auth_snapshot_signer=None, auth_snapshot_propagation_configs=())

Bases: IApplicationContextAware

Inject signed AuthContextSnapshot metadata into outbound event headers.

Source code in core/spakky-event/src/spakky/event/auth_propagation.py
def __init__(
    self,
    auth_snapshot_signer: IAuthContextSnapshotSigner | None = None,
    auth_snapshot_propagation_configs: tuple[
        AuthSnapshotPropagationConfig, ...
    ] = (),
) -> None:
    self._auth_snapshot_signer = auth_snapshot_signer
    self._auth_snapshot_propagation_config = (
        effective_auth_snapshot_propagation_config(
            auth_snapshot_propagation_configs
        )
    )
    self._application_context = None

set_application_context(application_context)

Inject the application context used to read request-scoped auth state.

Source code in core/spakky-event/src/spakky/event/auth_propagation.py
@override
def set_application_context(self, application_context: IApplicationContext) -> None:
    """Inject the application context used to read request-scoped auth state."""
    self._application_context = application_context

inject(headers)

Add signed snapshot metadata when outbound propagation is enabled.

Source code in core/spakky-event/src/spakky/event/auth_propagation.py
def inject(self, headers: dict[str, str]) -> None:
    """Add signed snapshot metadata when outbound propagation is enabled."""
    self._remove_raw_bearer_headers(headers)
    if not self._auth_snapshot_propagation_config.enabled:
        return
    auth_context = self._current_auth_context()
    if auth_context is None:
        return
    snapshot = self._required_signer().sign_snapshot(
        SnapshotSignRequest(auth_context=auth_context)
    )
    headers[AUTH_CONTEXT_SNAPSHOT_METADATA_KEY] = (
        snapshot.base64url_canonical_json()
    )

로컬 제공자

로컬 구현은 별도 spakky-mediator 플러그인이 소유합니다.

Publisher

Event publisher implementations.

This module provides event publishers that route events by type: - AbstractDomainEvent → EventMediator (in-process dispatch) - AbstractIntegrationEvent → IEventBus (external transport)

EventPublisher(dispatcher, bus)

Bases: IEventPublisher

Routes events by type: domain events to dispatcher, integration events to bus.

Initialize with dispatcher and bus dependencies.

Source code in core/spakky-event/src/spakky/event/publisher/domain_event_publisher.py
def __init__(
    self,
    dispatcher: IEventDispatcher | None,
    bus: IEventBus,
) -> None:
    """Initialize with dispatcher and bus dependencies."""
    self._dispatcher = dispatcher
    self._bus = bus

publish(event)

Route an event to the appropriate handler based on its type.

Source code in core/spakky-event/src/spakky/event/publisher/domain_event_publisher.py
@override
def publish(self, event: AbstractEvent) -> None:
    """Route an event to the appropriate handler based on its type."""
    match event:
        case AbstractDomainEvent():
            if self._dispatcher is None:
                raise DomainEventDispatcherUnavailableError()
            self._dispatcher.dispatch(event)
        case AbstractIntegrationEvent():
            self._bus.send(event)
        case _:  # pragma: no cover - 방어적 분기 (정상 흐름 불가)
            raise UnknownEventTypeError(type(event))

AsyncEventPublisher(dispatcher, bus)

Bases: IAsyncEventPublisher

Async counterpart that routes events by type.

Initialize with async dispatcher and bus dependencies.

Source code in core/spakky-event/src/spakky/event/publisher/domain_event_publisher.py
def __init__(
    self,
    dispatcher: IAsyncEventDispatcher | None,
    bus: IAsyncEventBus,
) -> None:
    """Initialize with async dispatcher and bus dependencies."""
    self._dispatcher = dispatcher
    self._bus = bus

publish(event) async

Route an event to the appropriate async handler based on its type.

Source code in core/spakky-event/src/spakky/event/publisher/domain_event_publisher.py
@override
async def publish(self, event: AbstractEvent) -> None:
    """Route an event to the appropriate async handler based on its type."""
    match event:
        case AbstractDomainEvent():
            if self._dispatcher is None:
                raise DomainEventDispatcherUnavailableError()
            await self._dispatcher.dispatch(event)
        case AbstractIntegrationEvent():
            await self._bus.send(event)
        case _:  # pragma: no cover - 방어적 분기 (정상 흐름 불가)
            raise UnknownEventTypeError(type(event))

Aspect

Transactional event publishing aspect for automatic domain event publishing.

AsyncTransactionalEventPublishingAspect(collector, publisher)

Bases: IAsyncAspect

Source code in core/spakky-event/src/spakky/event/aspects/transactional_event_publishing.py
def __init__(
    self,
    collector: AggregateCollector,
    publisher: IAsyncEventPublisher,
) -> None:
    self._collector = collector
    self._publisher = publisher

after_returning_async(result) async

Publish domain events of the transactions this call committed.

A call that joined an outer transaction committed nothing, so it publishes nothing; its events go out once the outermost call commits.

Source code in core/spakky-event/src/spakky/event/aspects/transactional_event_publishing.py
@AfterReturning(lambda x: Transactional.exists(x) and iscoroutinefunction(x))
@override
async def after_returning_async(self, result: Any) -> None:
    """Publish domain events of the transactions this call committed.

    A call that joined an outer transaction committed nothing, so it
    publishes nothing; its events go out once the outermost call commits.
    """
    aggregates = self._collector.drain_committed()
    events = {
        event.event_id: event
        for aggregate in aggregates
        for event in aggregate.events
    }
    for aggregate in aggregates:
        aggregate.clear_events()
    for event in events.values():
        await self._publisher.publish(event)

TransactionalEventPublishingAspect(collector, publisher)

Bases: IAspect

Source code in core/spakky-event/src/spakky/event/aspects/transactional_event_publishing.py
def __init__(
    self,
    collector: AggregateCollector,
    publisher: IEventPublisher,
) -> None:
    self._collector = collector
    self._publisher = publisher

after_returning(result)

Publish domain events of the transactions this call committed.

A call that joined an outer transaction committed nothing, so it publishes nothing; its events go out once the outermost call commits.

Source code in core/spakky-event/src/spakky/event/aspects/transactional_event_publishing.py
@AfterReturning(lambda x: Transactional.exists(x) and not iscoroutinefunction(x))
@override
def after_returning(self, result: Any) -> None:
    """Publish domain events of the transactions this call committed.

    A call that joined an outer transaction committed nothing, so it
    publishes nothing; its events go out once the outermost call commits.
    """
    aggregates = self._collector.drain_committed()
    events = {
        event.event_id: event
        for aggregate in aggregates
        for event in aggregate.events
    }
    for aggregate in aggregates:
        aggregate.clear_events()
    for event in events.values():
        self._publisher.publish(event)

전달 계약

통합 이벤트 소비자가 공통으로 따르는 구독자·재시도·dead-letter 계약입니다. 사용법은 이벤트 시스템 가이드를 참고하세요.

Subscriber identity shared by every integration event consumer.

A subscriber is one independent reader of an event stream. Each subscriber owns its consume position, retry state and dead-letter destination, so one subscriber failing or falling behind never affects another.

DEFAULT_SUBSCRIBER_KEY = '' module-attribute

Idempotency-key value recorded for handlers that declare no subscriber.

SUBSCRIBER_NAME_PATTERN = compile_pattern('^[A-Za-z0-9][A-Za-z0-9_-]{0,62}$') module-attribute

Names must stay valid inside Kafka group/topic names and RabbitMQ queue names.

A dot is excluded on purpose: brokers derive <event>.<subscriber>.<suffix> resource names, and a dot inside the name would make them ambiguous.

RESERVED_SUBSCRIBER_NAMES = frozenset({'dlq', 'dlt', 'retry', 'redrive'}) module-attribute

Names brokers append to derive dead-letter, retry and redrive resources.

A subscriber with one of these names would share a resource with the unnamed subscriber, e.g. its queue <event>.dlq is that subscriber's dead-letter queue.

SubscriberName = str

Name of one independent subscriber; broker resources are derived from it.

HandlerName = str

Stable name of one handler inside a subscriber; part of the idempotency key.

InvalidSubscriberNameError(subscriber)

Bases: AbstractSpakkyEventError

Raised when a subscriber name cannot be mapped onto broker resources.

Source code in core/spakky-event/src/spakky/event/subscription.py
def __init__(self, subscriber: SubscriberName) -> None:
    self.subscriber = subscriber
    super().__init__()

DuplicateEventHandlerNameError(subscriber, handler_name)

Bases: AbstractSpakkyEventError

Raised when two handlers of one subscription share a handler name.

Source code in core/spakky-event/src/spakky/event/subscription.py
def __init__(
    self, subscriber: SubscriberName | None, handler_name: HandlerName
) -> None:
    self.subscriber = subscriber
    self.handler_name = handler_name
    super().__init__()

MixedSubscriptionModeError(subscriber, event_type)

Bases: AbstractSpakkyEventError

Raised when one subscription mixes sync and async handlers.

Sync and async handlers are served by two separate consumers. Both would read the same broker subscription and split its messages between them, so each handler would silently miss part of the stream.

Source code in core/spakky-event/src/spakky/event/subscription.py
def __init__(self, subscriber: SubscriberName | None, event_type: type) -> None:
    self.subscriber = subscriber
    self.event_type = event_type
    super().__init__()

ConflictingSubscriberRetryPolicyError(subscriber)

Bases: AbstractSpakkyEventError

Raised when handler classes of one subscriber declare different retries.

One worker serves every event of a subscriber, so the subscriber has one retry policy. Classes that declare none follow the declared one; two classes that declare different ones leave no single policy to apply.

Source code in core/spakky-event/src/spakky/event/subscription.py
def __init__(self, subscriber: SubscriberName | None) -> None:
    self.subscriber = subscriber
    super().__init__()

SubscriberNames

Validation and key mapping for subscriber names.

validate(subscriber) staticmethod

Reject names that cannot be turned into broker resource names.

Parameters:

Name Type Description Default
subscriber SubscriberName | None

Declared name, or None for the unnamed subscriber.

required

Returns:

Type Description
SubscriberName | None

The same value once it is known to be usable.

Raises:

Type Description
InvalidSubscriberNameError

The name has unsupported characters or is reserved for derived broker resources.

Source code in core/spakky-event/src/spakky/event/subscription.py
@staticmethod
def validate(subscriber: SubscriberName | None) -> SubscriberName | None:
    """Reject names that cannot be turned into broker resource names.

    Args:
        subscriber: Declared name, or None for the unnamed subscriber.

    Returns:
        The same value once it is known to be usable.

    Raises:
        InvalidSubscriberNameError: The name has unsupported characters or is
            reserved for derived broker resources.
    """
    if subscriber is None:
        return None
    if (
        SUBSCRIBER_NAME_PATTERN.fullmatch(subscriber) is None
        or subscriber.lower() in RESERVED_SUBSCRIBER_NAMES
    ):
        raise InvalidSubscriberNameError(subscriber)
    return subscriber

key(subscriber) staticmethod

Return the value stored for a subscriber in records and headers.

Source code in core/spakky-event/src/spakky/event/subscription.py
@staticmethod
def key(subscriber: SubscriberName | None) -> SubscriberName:
    """Return the value stored for a subscriber in records and headers."""
    return DEFAULT_SUBSCRIBER_KEY if subscriber is None else subscriber

Broker-neutral delivery contract every integration event consumer implements.

The contract fixes what running the handlers of one subscriber means, so Kafka, RabbitMQ and the in-memory broker behave the same way:

  • every handler of the subscriber runs even when an earlier one fails;
  • a delivery is retried while a failed handler remains, and a retry runs only the handlers that have not succeeded yet; a pending handler that is no longer registered counts as a non-retryable failure, never as done;
  • retries are limited by RetryPolicy; a message that exhausts them, or that has a failure retrying cannot fix, moves to the subscriber's dead-letter destination together with DeadLetter metadata;
  • a handler asking to wait (EventDeferredError) makes the delivery wait without counting an attempt, unless another handler failed for good;
  • a dead letter is redriven to the subscriber it failed for, and to no other;
  • an unavailable auth provider is no verdict about the message: the error leaves deliver, and the adapter must keep the message unacknowledged.

A broker adapter maps the returned DeliveryOutcome onto its own mechanics (offset commit, ack, pause, retry destination, dead-letter destination).

RetryPolicyResolver = Callable[[SubscriberName | None, RetryPolicy | None], RetryPolicy]

Turns a subscriber and the retry its handlers declared into the policy it uses.

The declared retry is None when no handler class of the subscriber declared one.

DeliveryHeaders = Mapping[str, str]

String-valued message headers as every broker adapter exposes them.

DeliveryOutcome = DeliveryCompleted | DeliveryRetry | DeliveryDeferred | DeliveryDeadLettered

What one delivery attempt settled; adapters map it onto broker mechanics.

DeliveryHeader

Bases: StrEnum

Headers that carry retry state with a message set aside for a retry.

DeadLetterHeader

Bases: StrEnum

Headers every dead-lettered message carries, on every broker.

DeliveryState

Bases: BaseModel

Where one message stands in its retry sequence for one subscriber.

attempt = Field(default=1, ge=1) class-attribute instance-attribute

1-based number of the attempt about to run.

pending = None class-attribute instance-attribute

Handlers still to run; None means every handler (first delivery).

to_headers()

Encode the state so it can travel with a message set aside for retry.

Source code in core/spakky-event/src/spakky/event/delivery.py
def to_headers(self) -> dict[str, str]:
    """Encode the state so it can travel with a message set aside for retry."""
    headers = {DeliveryHeader.ATTEMPT.value: str(self.attempt)}
    if self.pending is not None:
        headers[DeliveryHeader.PENDING_HANDLERS.value] = (
            self._PENDING_ADAPTER.dump_json(self.pending).decode()
        )
    return headers

from_headers(headers) classmethod

Decode the state of a message; absent headers mean a first delivery.

Raises:

Type Description
InvalidDeliveryHeaderError

A present header cannot be decoded.

Source code in core/spakky-event/src/spakky/event/delivery.py
@classmethod
def from_headers(cls, headers: DeliveryHeaders) -> Self:
    """Decode the state of a message; absent headers mean a first delivery.

    Raises:
        InvalidDeliveryHeaderError: A present header cannot be decoded.
    """
    pending = headers.get(DeliveryHeader.PENDING_HANDLERS.value)
    try:
        return cls(
            attempt=int(headers.get(DeliveryHeader.ATTEMPT.value, "1")),
            pending=(
                None
                if pending is None
                else cls._PENDING_ADAPTER.validate_json(pending)
            ),
        )
    except (ValueError, ValidationError) as error:
        raise InvalidDeliveryHeaderError() from error

HandlerFailure

Bases: BaseModel

Why one handler did not complete in the last attempt.

DeadLetter

Bases: BaseModel

Metadata stored with a message a subscriber gave up on.

event_name instance-attribute

Destination (topic, routing key) the message was originally published to.

subscriber instance-attribute

Subscriber the message failed for; None is the unnamed subscriber.

failures instance-attribute

Handlers that had not succeeded when the subscriber gave up.

attempts instance-attribute

Number of delivery attempts made before giving up.

failed_at instance-attribute

When the last attempt ended.

pending property

Handlers a redrive has to run.

to_headers()

Encode the metadata as dead-letter message headers.

Source code in core/spakky-event/src/spakky/event/delivery.py
def to_headers(self) -> dict[str, str]:
    """Encode the metadata as dead-letter message headers."""
    return {
        DeadLetterHeader.ORIGINAL_DESTINATION.value: self.event_name,
        DeadLetterHeader.SUBSCRIBER.value: SubscriberNames.key(self.subscriber),
        DeadLetterHeader.FAILURES.value: self._FAILURES_ADAPTER.dump_json(
            self.failures
        ).decode(),
        DeadLetterHeader.ATTEMPTS.value: str(self.attempts),
        DeadLetterHeader.FAILED_AT.value: self.failed_at.isoformat(),
    }

from_headers(headers) classmethod

Decode dead-letter metadata from message headers.

Raises:

Type Description
InvalidDeliveryHeaderError

A header is absent or cannot be decoded.

Source code in core/spakky-event/src/spakky/event/delivery.py
@classmethod
def from_headers(cls, headers: DeliveryHeaders) -> Self:
    """Decode dead-letter metadata from message headers.

    Raises:
        InvalidDeliveryHeaderError: A header is absent or cannot be decoded.
    """
    try:
        subscriber = headers[DeadLetterHeader.SUBSCRIBER.value]
        return cls(
            event_name=headers[DeadLetterHeader.ORIGINAL_DESTINATION.value],
            subscriber=subscriber or None,
            failures=cls._FAILURES_ADAPTER.validate_json(
                headers[DeadLetterHeader.FAILURES.value]
            ),
            attempts=int(headers[DeadLetterHeader.ATTEMPTS.value]),
            failed_at=datetime.fromisoformat(
                headers[DeadLetterHeader.FAILED_AT.value]
            ),
        )
    except (KeyError, ValueError, ValidationError) as error:
        raise InvalidDeliveryHeaderError() from error

DeliveryCompleted

Bases: BaseModel

Every handler is done; the adapter acknowledges the message.

DeliveryRetry

Bases: BaseModel

A handler failed and attempts remain; deliver again after delay.

DeliveryDeferred

Bases: BaseModel

A handler asked to wait; deliver again without counting an attempt.

DeliveryDeadLettered

Bases: BaseModel

The subscriber gave up; the adapter stores the message as a dead letter.

EventDeliveryContext

Bases: BaseModel

Identity of the handler call a consumer is making right now.

Set around every handler invocation so that cross-cutting code, such as the idempotency aspect, can key its records without the handler passing it on.

subscriber instance-attribute

Subscriber key; the unnamed subscriber is the empty string.

activate()

Mark this delivery as the one in progress until deactivate.

Source code in core/spakky-event/src/spakky/event/delivery.py
def activate(self) -> Token["EventDeliveryContext | None"]:
    """Mark this delivery as the one in progress until `deactivate`."""
    return self._CURRENT.set(self)

deactivate(token) classmethod

Restore whatever delivery was in progress before activate.

Source code in core/spakky-event/src/spakky/event/delivery.py
@classmethod
def deactivate(cls, token: Token["EventDeliveryContext | None"]) -> None:
    """Restore whatever delivery was in progress before `activate`."""
    cls._CURRENT.reset(token)

current() classmethod

Return the delivery in progress.

Raises:

Type Description
EventDeliveryContextUnavailableError

No consumer is delivering.

Source code in core/spakky-event/src/spakky/event/delivery.py
@classmethod
def current(cls) -> "EventDeliveryContext":
    """Return the delivery in progress.

    Raises:
        EventDeliveryContextUnavailableError: No consumer is delivering.
    """
    context = cls._CURRENT.get()
    if context is None:
        raise EventDeliveryContextUnavailableError()
    return context

current_or_none() classmethod

Return the delivery in progress, or None outside a consumer call.

Source code in core/spakky-event/src/spakky/event/delivery.py
@classmethod
def current_or_none(cls) -> "EventDeliveryContext | None":
    """Return the delivery in progress, or None outside a consumer call."""
    return cls._CURRENT.get()

RegisteredEventHandler(name, callback) dataclass

One named handler of a subscription.

DeliveryAttempt(event_name, subscriber, policy, state, failures, deferred, retry_after) dataclass

Mutable tally of one delivery attempt, settled into a DeliveryOutcome.

record_failure(handler, error)

Keep a handler failure for the retry decision and dead-letter metadata.

Source code in core/spakky-event/src/spakky/event/delivery.py
def record_failure(self, handler: HandlerName, error: Exception) -> None:
    """Keep a handler failure for the retry decision and dead-letter metadata."""
    self.failures.append(
        HandlerFailure(
            handler=handler,
            exception_type=type(error).__qualname__,
            exception_message=str(error),
            retryable=not isinstance(error, AbstractNonRetryableEventError),
        )
    )

record_deferral(handler, error)

Keep a handler's request to be delivered again later.

Source code in core/spakky-event/src/spakky/event/delivery.py
def record_deferral(self, handler: HandlerName, error: EventDeferredError) -> None:
    """Keep a handler's request to be delivered again later."""
    self.deferred.append(handler)
    self.retry_after = max(self.retry_after, error.retry_after)
    self.failures.append(
        HandlerFailure(
            handler=handler,
            exception_type=type(error).__qualname__,
            exception_message=str(error),
            retryable=True,
        )
    )

settle()

Turn the tally into the outcome the broker adapter has to act on.

One message gets one outcome, so mixed handler results follow a fixed precedence: a non-retryable failure dead-letters the delivery at once, otherwise a deferral makes the whole delivery wait without counting an attempt, otherwise the failures are retried while attempts remain. In every case the handlers that have not succeeded stay pending together.

Source code in core/spakky-event/src/spakky/event/delivery.py
def settle(self) -> DeliveryOutcome:
    """Turn the tally into the outcome the broker adapter has to act on.

    One message gets one outcome, so mixed handler results follow a fixed
    precedence: a non-retryable failure dead-letters the delivery at once,
    otherwise a deferral makes the whole delivery wait without counting an
    attempt, otherwise the failures are retried while attempts remain. In
    every case the handlers that have not succeeded stay pending together.
    """
    if not self.failures:
        return DeliveryCompleted()
    pending = frozenset(failure.handler for failure in self.failures)
    fatal = any(not failure.retryable for failure in self.failures)
    if self.deferred and not fatal:
        return DeliveryDeferred(
            state=DeliveryState(attempt=self.state.attempt, pending=pending),
            retry_after=self.retry_after,
        )
    if not fatal and self.state.attempt < self.policy.max_attempts:
        return DeliveryRetry(
            state=DeliveryState(attempt=self.state.attempt + 1, pending=pending),
            delay=self.policy.delay_after(self.state.attempt),
            failures=tuple(self.failures),
        )
    return DeliveryDeadLettered(
        dead_letter=DeadLetter(
            event_name=self.event_name,
            subscriber=self.subscriber,
            failures=tuple(self.failures),
            attempts=self.state.attempt,
            failed_at=datetime.now(UTC),
        )
    )

SubscriptionDelivery(event_type, subscriber, policy)

Runs the sync handlers one subscriber registered for one event type.

Source code in core/spakky-event/src/spakky/event/delivery.py
def __init__(
    self,
    event_type: type[AbstractEvent],
    subscriber: SubscriberName | None,
    policy: RetryPolicy,
) -> None:
    self.event_type = event_type
    self.subscriber = SubscriberNames.validate(subscriber)
    self.policy = policy
    self.handlers = []

add(name, callback)

Add a handler under a name unique within this subscription.

Raises:

Type Description
DuplicateEventHandlerNameError

The name is already taken.

Source code in core/spakky-event/src/spakky/event/delivery.py
def add(self, name: HandlerName, callback: EventHandlerCallback[Any]) -> None:
    """Add a handler under a name unique within this subscription.

    Raises:
        DuplicateEventHandlerNameError: The name is already taken.
    """
    if any(handler.name == name for handler in self.handlers):
        raise DuplicateEventHandlerNameError(self.subscriber, name)
    self.handlers.append(RegisteredEventHandler(name=name, callback=callback))

deliver(event, state=None, invoker=None)

Run every pending handler once and settle the attempt.

Parameters:

Name Type Description Default
event AbstractEvent

Deserialized event to hand to the handlers.

required
state DeliveryState | None

Retry state of the message; None means a first delivery.

None
invoker Callable[[RegisteredEventHandler[EventHandlerCallback[Any]], AbstractEvent], None] | None

Adapter hook that calls a handler with adapter-specific arguments; None calls handler.callback(event).

None

Returns:

Type Description
DeliveryOutcome

What the adapter must do with the message.

Raises:

Type Description
AuthVerificationProviderUnavailableError

Snapshot verification is unavailable; the message must stay unacknowledged.

AuthRequirementProviderUnavailableError

Authorization data is unavailable; the message must stay unacknowledged.

Source code in core/spakky-event/src/spakky/event/delivery.py
def deliver(
    self,
    event: AbstractEvent,
    state: DeliveryState | None = None,
    invoker: Callable[
        [RegisteredEventHandler[EventHandlerCallback[Any]], AbstractEvent], None
    ]
    | None = None,
) -> DeliveryOutcome:
    """Run every pending handler once and settle the attempt.

    Args:
        event: Deserialized event to hand to the handlers.
        state: Retry state of the message; None means a first delivery.
        invoker: Adapter hook that calls a handler with adapter-specific
            arguments; None calls `handler.callback(event)`.

    Returns:
        What the adapter must do with the message.

    Raises:
        AuthVerificationProviderUnavailableError: Snapshot verification is
            unavailable; the message must stay unacknowledged.
        AuthRequirementProviderUnavailableError: Authorization data is
            unavailable; the message must stay unacknowledged.
    """
    current = DeliveryState() if state is None else state
    attempt = DeliveryAttempt(
        event_name=event.event_name,
        subscriber=self.subscriber,
        policy=self.policy,
        state=current,
        failures=[],
        deferred=[],
        retry_after=0.0,
    )
    for missing in sorted(
        (current.pending or frozenset())
        - {handler.name for handler in self.handlers}
    ):
        # 이름이 바뀌거나 사라진 처리기를 완료로 치면 메시지가 실행 없이 버려진다.
        attempt.record_failure(missing, EventHandlerNotRegisteredError())
    for handler in self.handlers:
        if current.pending is not None and handler.name not in current.pending:
            continue
        token = EventDeliveryContext(
            subscriber=SubscriberNames.key(self.subscriber),
            handler=handler.name,
            event_id=event.event_id,
            attempt=current.attempt,
        ).activate()
        try:
            if invoker is None:
                handler.callback(event)
            else:
                invoker(handler, event)
        except EventDeferredError as error:
            attempt.record_deferral(handler.name, error)
        except (
            AuthVerificationProviderUnavailableError,
            AuthRequirementProviderUnavailableError,
        ):
            # 인증 기반이 내려간 것은 이 메시지에 대한 판정이 아니다.
            raise
        except (AuthContextNotFoundError, AuthRequirementDeniedError) as error:
            # 인가 거부는 같은 메시지를 다시 보내도 바뀌지 않는 판정이다.
            logger.warning(
                f"Auth boundary refused {event.event_name} for handler "
                f"{handler.name}, skipping it: {error}"
            )
        except Exception as error:
            logger.warning(
                f"Handler {handler.name} failed for {event.event_name} "
                f"(attempt {current.attempt}): {error}"
            )
            attempt.record_failure(handler.name, error)
        finally:
            EventDeliveryContext.deactivate(token)
    return attempt.settle()

AsyncSubscriptionDelivery(event_type, subscriber, policy)

Runs the async handlers one subscriber registered for one event type.

Source code in core/spakky-event/src/spakky/event/delivery.py
def __init__(
    self,
    event_type: type[AbstractEvent],
    subscriber: SubscriberName | None,
    policy: RetryPolicy,
) -> None:
    self.event_type = event_type
    self.subscriber = SubscriberNames.validate(subscriber)
    self.policy = policy
    self.handlers = []

add(name, callback)

Add a handler under a name unique within this subscription.

Raises:

Type Description
DuplicateEventHandlerNameError

The name is already taken.

Source code in core/spakky-event/src/spakky/event/delivery.py
def add(self, name: HandlerName, callback: AsyncEventHandlerCallback[Any]) -> None:
    """Add a handler under a name unique within this subscription.

    Raises:
        DuplicateEventHandlerNameError: The name is already taken.
    """
    if any(handler.name == name for handler in self.handlers):
        raise DuplicateEventHandlerNameError(self.subscriber, name)
    self.handlers.append(RegisteredEventHandler(name=name, callback=callback))

deliver(event, state=None, invoker=None) async

Run every pending handler once and settle the attempt.

Parameters:

Name Type Description Default
event AbstractEvent

Deserialized event to hand to the handlers.

required
state DeliveryState | None

Retry state of the message; None means a first delivery.

None
invoker Callable[[RegisteredEventHandler[AsyncEventHandlerCallback[Any]], AbstractEvent], Awaitable[None]] | None

Adapter hook that calls a handler with adapter-specific arguments; None awaits handler.callback(event).

None

Returns:

Type Description
DeliveryOutcome

What the adapter must do with the message.

Raises:

Type Description
AuthVerificationProviderUnavailableError

Snapshot verification is unavailable; the message must stay unacknowledged.

AuthRequirementProviderUnavailableError

Authorization data is unavailable; the message must stay unacknowledged.

Source code in core/spakky-event/src/spakky/event/delivery.py
async def deliver(
    self,
    event: AbstractEvent,
    state: DeliveryState | None = None,
    invoker: Callable[
        [RegisteredEventHandler[AsyncEventHandlerCallback[Any]], AbstractEvent],
        Awaitable[None],
    ]
    | None = None,
) -> DeliveryOutcome:
    """Run every pending handler once and settle the attempt.

    Args:
        event: Deserialized event to hand to the handlers.
        state: Retry state of the message; None means a first delivery.
        invoker: Adapter hook that calls a handler with adapter-specific
            arguments; None awaits `handler.callback(event)`.

    Returns:
        What the adapter must do with the message.

    Raises:
        AuthVerificationProviderUnavailableError: Snapshot verification is
            unavailable; the message must stay unacknowledged.
        AuthRequirementProviderUnavailableError: Authorization data is
            unavailable; the message must stay unacknowledged.
    """
    current = DeliveryState() if state is None else state
    attempt = DeliveryAttempt(
        event_name=event.event_name,
        subscriber=self.subscriber,
        policy=self.policy,
        state=current,
        failures=[],
        deferred=[],
        retry_after=0.0,
    )
    for missing in sorted(
        (current.pending or frozenset())
        - {handler.name for handler in self.handlers}
    ):
        # 이름이 바뀌거나 사라진 처리기를 완료로 치면 메시지가 실행 없이 버려진다.
        attempt.record_failure(missing, EventHandlerNotRegisteredError())
    for handler in self.handlers:
        if current.pending is not None and handler.name not in current.pending:
            continue
        token = EventDeliveryContext(
            subscriber=SubscriberNames.key(self.subscriber),
            handler=handler.name,
            event_id=event.event_id,
            attempt=current.attempt,
        ).activate()
        try:
            if invoker is None:
                await handler.callback(event)
            else:
                await invoker(handler, event)
        except EventDeferredError as error:
            attempt.record_deferral(handler.name, error)
        except (
            AuthVerificationProviderUnavailableError,
            AuthRequirementProviderUnavailableError,
        ):
            # 인증 기반이 내려간 것은 이 메시지에 대한 판정이 아니다.
            raise
        except (AuthContextNotFoundError, AuthRequirementDeniedError) as error:
            # 인가 거부는 같은 메시지를 다시 보내도 바뀌지 않는 판정이다.
            logger.warning(
                f"Auth boundary refused {event.event_name} for handler "
                f"{handler.name}, skipping it: {error}"
            )
        except Exception as error:
            logger.warning(
                f"Handler {handler.name} failed for {event.event_name} "
                f"(attempt {current.attempt}): {error}"
            )
            attempt.record_failure(handler.name, error)
        finally:
            EventDeliveryContext.deactivate(token)
    return attempt.settle()

EventSubscriptions(policy, resolver=None)

Sync subscriptions of one consumer, keyed by subscriber and event type.

Every subscription of one subscriber shares that subscriber's retry policy, because one worker serves all of its events.

Create an empty registry.

Parameters:

Name Type Description Default
policy RetryPolicy

Consumer-wide retry every subscriber starts from.

required
resolver RetryPolicyResolver | None

Turns a subscriber and its declared retry into the policy it uses. None overlays the declared retry on policy.

None
Source code in core/spakky-event/src/spakky/event/delivery.py
def __init__(
    self, policy: RetryPolicy, resolver: RetryPolicyResolver | None = None
) -> None:
    """Create an empty registry.

    Args:
        policy: Consumer-wide retry every subscriber starts from.
        resolver: Turns a subscriber and its declared retry into the policy
            it uses. None overlays the declared retry on `policy`.
    """
    self.policy = policy
    self._resolver = resolver if resolver is not None else self._overlay_declared
    self._declared = {}
    self._deliveries = {}

policy = policy instance-attribute

Consumer-wide retry every subscriber starts from.

policy_of(subscriber)

Return the retry policy subscriber uses for every event it reads.

Source code in core/spakky-event/src/spakky/event/delivery.py
def policy_of(self, subscriber: SubscriberName | None) -> RetryPolicy:
    """Return the retry policy `subscriber` uses for every event it reads."""
    return self._resolver(subscriber, self._declared.get(subscriber))

register(event, handler, subscriber=None, handler_name=None, retry=None)

Add a handler to the subscription of subscriber for event.

Parameters:

Name Type Description Default
event type[AbstractEvent]

Event type the handler receives.

required
handler EventHandlerCallback[Any]

Callback invoked with the deserialized event.

required
subscriber SubscriberName | None

Subscriber the handler belongs to; None is unnamed.

None
handler_name HandlerName | None

Stable name inside the subscription. None derives a positional name, which is not stable enough for idempotency.

None
retry RetryPolicy | None

Retry the handler's class declared for its subscriber; None follows whatever the subscriber's other classes declared.

None

Returns:

Type Description
SubscriptionDelivery

The subscription the handler was added to.

Raises:

Type Description
InvalidSubscriberNameError

The subscriber name is unusable.

ConflictingSubscriberRetryPolicyError

Another handler class of the subscriber declared a different retry.

Source code in core/spakky-event/src/spakky/event/delivery.py
def register(
    self,
    event: type[AbstractEvent],
    handler: EventHandlerCallback[Any],
    subscriber: SubscriberName | None = None,
    handler_name: HandlerName | None = None,
    retry: RetryPolicy | None = None,
) -> SubscriptionDelivery:
    """Add a handler to the subscription of `subscriber` for `event`.

    Args:
        event: Event type the handler receives.
        handler: Callback invoked with the deserialized event.
        subscriber: Subscriber the handler belongs to; None is unnamed.
        handler_name: Stable name inside the subscription. None derives a
            positional name, which is not stable enough for idempotency.
        retry: Retry the handler's class declared for its subscriber; None
            follows whatever the subscriber's other classes declared.

    Returns:
        The subscription the handler was added to.

    Raises:
        InvalidSubscriberNameError: The subscriber name is unusable.
        ConflictingSubscriberRetryPolicyError: Another handler class of the
            subscriber declared a different retry.
    """
    SubscriberNames.validate(subscriber)
    if retry is not None:
        self._declare(subscriber, retry)
    key = (subscriber, event)
    delivery = self._deliveries.get(key)
    if delivery is None:
        delivery = SubscriptionDelivery(
            event, subscriber, self.policy_of(subscriber)
        )
        self._deliveries[key] = delivery
    delivery.add(
        handler_name
        if handler_name is not None
        else f"{event.__name__}#{len(delivery.handlers)}",
        handler,
    )
    return delivery

get(subscriber, event)

Return the subscription of subscriber for event.

Raises:

Type Description
SubscriptionNotFoundError

Nothing is registered for the pair.

Source code in core/spakky-event/src/spakky/event/delivery.py
def get(
    self, subscriber: SubscriberName | None, event: type[AbstractEvent]
) -> SubscriptionDelivery:
    """Return the subscription of `subscriber` for `event`.

    Raises:
        SubscriptionNotFoundError: Nothing is registered for the pair.
    """
    delivery = self._deliveries.get((subscriber, event))
    if delivery is None:
        raise SubscriptionNotFoundError(subscriber, event)
    return delivery

AsyncEventSubscriptions(policy, resolver=None)

Async subscriptions of one consumer, keyed by subscriber and event type.

Every subscription of one subscriber shares that subscriber's retry policy, because one worker serves all of its events.

Create an empty registry.

Parameters:

Name Type Description Default
policy RetryPolicy

Consumer-wide retry every subscriber starts from.

required
resolver RetryPolicyResolver | None

Turns a subscriber and its declared retry into the policy it uses. None overlays the declared retry on policy.

None
Source code in core/spakky-event/src/spakky/event/delivery.py
def __init__(
    self, policy: RetryPolicy, resolver: RetryPolicyResolver | None = None
) -> None:
    """Create an empty registry.

    Args:
        policy: Consumer-wide retry every subscriber starts from.
        resolver: Turns a subscriber and its declared retry into the policy
            it uses. None overlays the declared retry on `policy`.
    """
    self.policy = policy
    self._resolver = resolver if resolver is not None else self._overlay_declared
    self._declared = {}
    self._deliveries = {}

policy = policy instance-attribute

Consumer-wide retry every subscriber starts from.

policy_of(subscriber)

Return the retry policy subscriber uses for every event it reads.

Source code in core/spakky-event/src/spakky/event/delivery.py
def policy_of(self, subscriber: SubscriberName | None) -> RetryPolicy:
    """Return the retry policy `subscriber` uses for every event it reads."""
    return self._resolver(subscriber, self._declared.get(subscriber))

register(event, handler, subscriber=None, handler_name=None, retry=None)

Add a handler to the subscription of subscriber for event.

Parameters:

Name Type Description Default
event type[AbstractEvent]

Event type the handler receives.

required
handler AsyncEventHandlerCallback[Any]

Callback awaited with the deserialized event.

required
subscriber SubscriberName | None

Subscriber the handler belongs to; None is unnamed.

None
handler_name HandlerName | None

Stable name inside the subscription. None derives a positional name, which is not stable enough for idempotency.

None
retry RetryPolicy | None

Retry the handler's class declared for its subscriber; None follows whatever the subscriber's other classes declared.

None

Returns:

Type Description
AsyncSubscriptionDelivery

The subscription the handler was added to.

Raises:

Type Description
InvalidSubscriberNameError

The subscriber name is unusable.

ConflictingSubscriberRetryPolicyError

Another handler class of the subscriber declared a different retry.

Source code in core/spakky-event/src/spakky/event/delivery.py
def register(
    self,
    event: type[AbstractEvent],
    handler: AsyncEventHandlerCallback[Any],
    subscriber: SubscriberName | None = None,
    handler_name: HandlerName | None = None,
    retry: RetryPolicy | None = None,
) -> AsyncSubscriptionDelivery:
    """Add a handler to the subscription of `subscriber` for `event`.

    Args:
        event: Event type the handler receives.
        handler: Callback awaited with the deserialized event.
        subscriber: Subscriber the handler belongs to; None is unnamed.
        handler_name: Stable name inside the subscription. None derives a
            positional name, which is not stable enough for idempotency.
        retry: Retry the handler's class declared for its subscriber; None
            follows whatever the subscriber's other classes declared.

    Returns:
        The subscription the handler was added to.

    Raises:
        InvalidSubscriberNameError: The subscriber name is unusable.
        ConflictingSubscriberRetryPolicyError: Another handler class of the
            subscriber declared a different retry.
    """
    SubscriberNames.validate(subscriber)
    if retry is not None:
        self._declare(subscriber, retry)
    key = (subscriber, event)
    delivery = self._deliveries.get(key)
    if delivery is None:
        delivery = AsyncSubscriptionDelivery(
            event, subscriber, self.policy_of(subscriber)
        )
        self._deliveries[key] = delivery
    delivery.add(
        handler_name
        if handler_name is not None
        else f"{event.__name__}#{len(delivery.handlers)}",
        handler,
    )
    return delivery

get(subscriber, event)

Return the subscription of subscriber for event.

Raises:

Type Description
SubscriptionNotFoundError

Nothing is registered for the pair.

Source code in core/spakky-event/src/spakky/event/delivery.py
def get(
    self, subscriber: SubscriberName | None, event: type[AbstractEvent]
) -> AsyncSubscriptionDelivery:
    """Return the subscription of `subscriber` for `event`.

    Raises:
        SubscriptionNotFoundError: Nothing is registered for the pair.
    """
    delivery = self._deliveries.get((subscriber, event))
    if delivery is None:
        raise SubscriptionNotFoundError(subscriber, event)
    return delivery

EventRouting

Routing identity of event types shared by publishers and consumers.

name_of(event) staticmethod

Return the destination name an event type is published under.

event_name is an instance property that subclasses may override with a class-static value, so it is read through an uninitialized instance.

Source code in core/spakky-event/src/spakky/event/delivery.py
@staticmethod
def name_of(event: type[AbstractEvent]) -> str:
    """Return the destination name an event type is published under.

    `event_name` is an instance property that subclasses may override with
    a class-static value, so it is read through an uninitialized instance.
    """
    probe = object.__new__(event)
    return probe.event_name

Redrive contract: hand dead letters back to the subscriber they failed for.

RedriveResult

Bases: BaseModel

How many dead letters one redrive call settled.

succeeded instance-attribute

Dead letters whose failed handlers all completed; they are removed.

failed instance-attribute

Dead letters that failed again; they stay in the dead-letter destination.

IEventRedriver

Bases: ABC

Synchronous redrive of one subscriber's dead letters.

A redrive reaches only the subscriber that dead-lettered the message, and runs only the handlers recorded as failed. Other subscribers of the same event never see the message again.

redrive(event, *, subscriber=None, limit=None) abstractmethod

Deliver dead letters of subscriber for event to their failed handlers.

Parameters:

Name Type Description Default
event type[AbstractIntegrationEvent]

Event type whose dead letters are redriven.

required
subscriber SubscriberName | None

Subscriber owning the dead letters; None is unnamed.

None
limit int | None

Most dead letters to take in this call; None takes all currently stored.

None

Returns:

Type Description
RedriveResult

Counts of dead letters that completed and that failed again.

Source code in core/spakky-event/src/spakky/event/redrive.py
@abstractmethod
def redrive(
    self,
    event: type[AbstractIntegrationEvent],
    *,
    subscriber: SubscriberName | None = None,
    limit: int | None = None,
) -> RedriveResult:
    """Deliver dead letters of `subscriber` for `event` to their failed handlers.

    Args:
        event: Event type whose dead letters are redriven.
        subscriber: Subscriber owning the dead letters; None is unnamed.
        limit: Most dead letters to take in this call; None takes all
            currently stored.

    Returns:
        Counts of dead letters that completed and that failed again.
    """
    ...

IAsyncEventRedriver

Bases: ABC

Asynchronous redrive of one subscriber's dead letters.

Follows the same contract as IEventRedriver.

redrive(event, *, subscriber=None, limit=None) abstractmethod async

Deliver dead letters of subscriber for event to their failed handlers.

Parameters:

Name Type Description Default
event type[AbstractIntegrationEvent]

Event type whose dead letters are redriven.

required
subscriber SubscriberName | None

Subscriber owning the dead letters; None is unnamed.

None
limit int | None

Most dead letters to take in this call; None takes all currently stored.

None

Returns:

Type Description
RedriveResult

Counts of dead letters that completed and that failed again.

Source code in core/spakky-event/src/spakky/event/redrive.py
@abstractmethod
async def redrive(
    self,
    event: type[AbstractIntegrationEvent],
    *,
    subscriber: SubscriberName | None = None,
    limit: int | None = None,
) -> RedriveResult:
    """Deliver dead letters of `subscriber` for `event` to their failed handlers.

    Args:
        event: Event type whose dead letters are redriven.
        subscriber: Subscriber owning the dead letters; None is unnamed.
        limit: Most dead letters to take in this call; None takes all
            currently stored.

    Returns:
        Counts of dead letters that completed and that failed again.
    """
    ...

멱등 소비

Idempotent consumption contract for integration event handlers.

Brokers deliver at least once, so a handler can see the same event again after a crash, a rebalance or a retry. @Idempotent() makes a handler skip an event it has already processed. The record is keyed by subscriber, handler and event id, and is written through the handler's own transaction, so the record and the handler's changes commit or roll back together.

ProcessedEventKey

Bases: BaseModel

Identity of one handler having processed one event.

subscriber instance-attribute

Subscriber key; the unnamed subscriber is the empty string.

ProcessedEventStoreUnavailableError

Bases: AbstractSpakkyEventError

Raised when an idempotent handler runs without a processed-event store.

IProcessedEventStore

Bases: ABC

Synchronous store of processed-event records.

record must write through the transaction that is active for the calling handler and must fail when none is active; a record committed apart from the handler's changes would either lose the event or process it twice.

exists(key) abstractmethod

Return whether the handler already processed the event.

Source code in core/spakky-event/src/spakky/event/idempotency.py
@abstractmethod
def exists(self, key: ProcessedEventKey) -> bool:
    """Return whether the handler already processed the event."""
    ...

record(key) abstractmethod

Record the event as processed inside the caller's transaction.

A concurrent duplicate must fail here or at commit, never be accepted twice.

Source code in core/spakky-event/src/spakky/event/idempotency.py
@abstractmethod
def record(self, key: ProcessedEventKey) -> None:
    """Record the event as processed inside the caller's transaction.

    A concurrent duplicate must fail here or at commit, never be accepted
    twice.
    """
    ...

purge(older_than) abstractmethod

Delete records processed before older_than.

Returns:

Type Description
int

Number of records removed.

Source code in core/spakky-event/src/spakky/event/idempotency.py
@abstractmethod
def purge(self, older_than: datetime) -> int:
    """Delete records processed before `older_than`.

    Returns:
        Number of records removed.
    """
    ...

IAsyncProcessedEventStore

Bases: ABC

Asynchronous store of processed-event records.

Follows the same contract as IProcessedEventStore.

exists(key) abstractmethod async

Return whether the handler already processed the event.

Source code in core/spakky-event/src/spakky/event/idempotency.py
@abstractmethod
async def exists(self, key: ProcessedEventKey) -> bool:
    """Return whether the handler already processed the event."""
    ...

record(key) abstractmethod async

Record the event as processed inside the caller's transaction.

A concurrent duplicate must fail here or at commit, never be accepted twice.

Source code in core/spakky-event/src/spakky/event/idempotency.py
@abstractmethod
async def record(self, key: ProcessedEventKey) -> None:
    """Record the event as processed inside the caller's transaction.

    A concurrent duplicate must fail here or at commit, never be accepted
    twice.
    """
    ...

purge(older_than) abstractmethod async

Delete records processed before older_than.

Returns:

Type Description
int

Number of records removed.

Source code in core/spakky-event/src/spakky/event/idempotency.py
@abstractmethod
async def purge(self, older_than: datetime) -> int:
    """Delete records processed before `older_than`.

    Returns:
        Number of records removed.
    """
    ...

Idempotent() dataclass

Bases: FunctionAnnotation

Marks an integration event handler as processing each event once.

Combine it with @Transactional() so the processed record and the handler's changes share one transaction:

@EventHandler(subscriber="billing")
class BillingHandler:
    @on_event(OrderPlaced)
    @Transactional()
    @Idempotent()
    async def charge(self, event: OrderPlaced) -> None: ...

idempotent(func)

Decorator form of Idempotent().

Parameters:

Name Type Description Default
func Callable[P, R]

Event handler method to mark.

required

Returns:

Type Description
Callable[P, R]

The same method carrying the idempotency annotation.

Source code in core/spakky-event/src/spakky/event/idempotency.py
def idempotent[**P, R](func: Callable[P, R]) -> Callable[P, R]:
    """Decorator form of `Idempotent()`.

    Args:
        func: Event handler method to mark.

    Returns:
        The same method carrying the idempotency annotation.
    """
    return Idempotent()(func)

Aspects that skip integration events a handler has already processed.

IDEMPOTENT_ASPECT_ORDER = 2 module-attribute

Runs inside TransactionalAspect (order 1) so the record joins its transaction.

AsyncIdempotentAspect

Bases: IAsyncAspect, IContainerAware

Skips an async handler call for an event that handler already processed.

set_container(container)

Keep the container so the store is resolved only when a handler needs it.

Source code in core/spakky-event/src/spakky/event/aspects/idempotent.py
@override
def set_container(self, container: IContainer) -> None:
    """Keep the container so the store is resolved only when a handler needs it."""
    self._container = container

IdempotentAspect

Bases: IAspect, IContainerAware

Skips a sync handler call for an event that handler already processed.

set_container(container)

Keep the container so the store is resolved only when a handler needs it.

Source code in core/spakky-event/src/spakky/event/aspects/idempotent.py
@override
def set_container(self, container: IContainer) -> None:
    """Keep the container so the store is resolved only when a handler needs it."""
    self._container = container

메모리 구현체

자동으로 등록되지 않습니다. spakky.event.memory.main.initialize(app)로 켭니다.

Opt-in registration of the in-memory integration event broker.

initialize(app)

Register the in-memory broker as the integration event provider.

This is not a plugin entry point and is never loaded automatically: call it explicitly, and do not combine it with a broker plugin in one application.

Parameters:

Name Type Description Default
app SpakkyApplication

Application that should run integration events in memory.

required
Source code in core/spakky-event/src/spakky/event/memory/main.py
def initialize(app: SpakkyApplication) -> None:
    """Register the in-memory broker as the integration event provider.

    This is not a plugin entry point and is never loaded automatically: call it
    explicitly, and do not combine it with a broker plugin in one application.

    Args:
        app: Application that should run integration events in memory.
    """
    app.add(InMemoryEventConfig)
    app.add(InMemoryEventBroker)
    app.add(InMemoryEventTransport)
    app.add(AsyncInMemoryEventTransport)
    app.add(InMemoryEventConsumer)
    app.add(AsyncInMemoryEventConsumer)
    app.add(InMemoryEventPostProcessor)

In-memory broker that fans published events out to subscriber queues.

IN_FLIGHT_POLL_INTERVAL = 0.001 module-attribute

Seconds drain waits between checks on a message another consumer is handling.

SubscriptionKey = tuple[str, SubscriberName | None]

Event name and subscriber identifying one in-memory queue.

InMemoryMessage

Bases: BaseModel

One published event as a subscriber queue holds it.

partition_key = None class-attribute instance-attribute

Recorded for assertions; in-memory queues are not partitioned.

state = DeliveryState() class-attribute instance-attribute

Retry state of this message for the subscriber owning the queue.

not_before = 0.0 class-attribute instance-attribute

Monotonic time before which the message must not be delivered.

InMemoryDeadLetter

Bases: BaseModel

A message a subscriber gave up on, with the reason.

InMemoryEventBroker()

Holds one queue and one dead-letter list per subscriber and event.

Publishing copies the message into the queue of every subscriber bound to the event name, so subscribers consume independently. A message published while no subscriber is bound is kept only in published.

Source code in core/spakky-event/src/spakky/event/memory/broker.py
def __init__(self) -> None:
    self.published = []
    self._lock = RLock()
    self._queues = {}
    self._dead_letters = {}
    self._in_flight = 0
    self._busy = set()
    self._drains = []
    self._async_drains = []

published = [] instance-attribute

Every message ever published, in order, for test assertions.

idle property

Whether no message is queued or being handled.

bind(key)

Create the queue of a subscriber; later publishes are copied into it.

Source code in core/spakky-event/src/spakky/event/memory/broker.py
def bind(self, key: SubscriptionKey) -> None:
    """Create the queue of a subscriber; later publishes are copied into it."""
    with self._lock:
        self._queues.setdefault(key, deque())
        self._dead_letters.setdefault(key, [])

attach(drain)

Let drain reach a sync consumer bound to this broker.

Source code in core/spakky-event/src/spakky/event/memory/broker.py
def attach(self, drain: Callable[[], int]) -> None:
    """Let `drain` reach a sync consumer bound to this broker."""
    self._drains.append(drain)

attach_async(drain)

Let drain_async reach an async consumer bound to this broker.

Source code in core/spakky-event/src/spakky/event/memory/broker.py
def attach_async(self, drain: Callable[[], Awaitable[int]]) -> None:
    """Let `drain_async` reach an async consumer bound to this broker."""
    self._async_drains.append(drain)

publish(message)

Copy a message into the queue of every subscriber of its event name.

Source code in core/spakky-event/src/spakky/event/memory/broker.py
def publish(self, message: InMemoryMessage) -> None:
    """Copy a message into the queue of every subscriber of its event name."""
    with self._lock:
        self.published.append(message)
        for (event_name, _), queue in self._queues.items():
            if event_name == message.event_name:
                queue.append(message)

take(key, now, head_only)

Remove and return the next deliverable message of one queue.

Parameters:

Name Type Description Default
key SubscriptionKey

Queue to read.

required
now float

Current monotonic time.

required
head_only bool

Only the oldest message may be taken, so a waiting retry blocks the messages behind it and order is preserved. The queue then also stays closed to other consumers until done.

required

Returns:

Type Description
InMemoryMessage | None

A due message, counted as in flight until done, or None.

Source code in core/spakky-event/src/spakky/event/memory/broker.py
def take(
    self, key: SubscriptionKey, now: float, head_only: bool
) -> InMemoryMessage | None:
    """Remove and return the next deliverable message of one queue.

    Args:
        key: Queue to read.
        now: Current monotonic time.
        head_only: Only the oldest message may be taken, so a waiting retry
            blocks the messages behind it and order is preserved. The queue
            then also stays closed to other consumers until `done`.

    Returns:
        A due message, counted as in flight until `done`, or None.
    """
    with self._lock:
        if key in self._busy:
            return None
        queue = self._queues[key]
        for index, message in enumerate(queue):
            if message.not_before <= now:
                del queue[index]
                self._in_flight += 1
                if head_only:
                    self._busy.add(key)
                return message
            if head_only:
                return None
        return None

done(key)

Mark a taken message as settled, after any requeue or dead-letter.

Source code in core/spakky-event/src/spakky/event/memory/broker.py
def done(self, key: SubscriptionKey) -> None:
    """Mark a taken message as settled, after any requeue or dead-letter."""
    with self._lock:
        self._in_flight -= 1
        self._busy.discard(key)

requeue_front(key, message)

Put a message back as the oldest one of its queue.

Source code in core/spakky-event/src/spakky/event/memory/broker.py
def requeue_front(self, key: SubscriptionKey, message: InMemoryMessage) -> None:
    """Put a message back as the oldest one of its queue."""
    with self._lock:
        self._queues[key].appendleft(message)

requeue_back(key, message)

Put a message back behind everything already queued.

Source code in core/spakky-event/src/spakky/event/memory/broker.py
def requeue_back(self, key: SubscriptionKey, message: InMemoryMessage) -> None:
    """Put a message back behind everything already queued."""
    with self._lock:
        self._queues[key].append(message)

next_due_in(keys, now, head_only)

Return seconds until a queued message becomes deliverable.

Parameters:

Name Type Description Default
keys list[SubscriptionKey]

Queues to inspect.

required
now float

Current monotonic time.

required
head_only bool

Only the oldest message of each queue can become deliverable, matching take. Queues another consumer is handling are skipped.

required

Returns:

Type Description
float | None

None when the given queues are empty.

Source code in core/spakky-event/src/spakky/event/memory/broker.py
def next_due_in(
    self, keys: list[SubscriptionKey], now: float, head_only: bool
) -> float | None:
    """Return seconds until a queued message becomes deliverable.

    Args:
        keys: Queues to inspect.
        now: Current monotonic time.
        head_only: Only the oldest message of each queue can become
            deliverable, matching `take`. Queues another consumer is
            handling are skipped.

    Returns:
        None when the given queues are empty.
    """
    with self._lock:
        waits = [
            max(message.not_before - now, 0.0)
            for key in keys
            if key not in self._busy
            for message in (
                list(self._queues[key])[:1] if head_only else self._queues[key]
            )
        ]
    return min(waits) if waits else None

add_dead_letter(key, entry)

Store a message a subscriber gave up on.

Source code in core/spakky-event/src/spakky/event/memory/broker.py
def add_dead_letter(self, key: SubscriptionKey, entry: InMemoryDeadLetter) -> None:
    """Store a message a subscriber gave up on."""
    with self._lock:
        self._dead_letters[key].append(entry)

take_dead_letters(key, limit)

Remove and return up to limit oldest dead letters of one subscriber.

Source code in core/spakky-event/src/spakky/event/memory/broker.py
def take_dead_letters(
    self, key: SubscriptionKey, limit: int | None
) -> list[InMemoryDeadLetter]:
    """Remove and return up to `limit` oldest dead letters of one subscriber."""
    with self._lock:
        entries = self._dead_letters[key]
        count = len(entries) if limit is None else min(limit, len(entries))
        taken = entries[:count]
        del entries[:count]
        return taken

dead_letters(event_name, subscriber=None)

Return the dead letters one subscriber holds for an event name.

Source code in core/spakky-event/src/spakky/event/memory/broker.py
def dead_letters(
    self, event_name: str, subscriber: SubscriberName | None = None
) -> list[InMemoryDeadLetter]:
    """Return the dead letters one subscriber holds for an event name."""
    with self._lock:
        return list(self._dead_letters.get((event_name, subscriber), []))

queued(event_name, subscriber=None)

Return the messages still waiting in one subscriber queue.

Source code in core/spakky-event/src/spakky/event/memory/broker.py
def queued(
    self, event_name: str, subscriber: SubscriberName | None = None
) -> list[InMemoryMessage]:
    """Return the messages still waiting in one subscriber queue."""
    with self._lock:
        return list(self._queues.get((event_name, subscriber), []))

drain()

Deliver through the sync consumers until they make no progress.

Messages queued for async subscribers are left for drain_async. A message a background consumer is still handling is waited for, so the effects of every delivery are visible when this returns.

Returns:

Type Description
int

Number of deliveries made by this call.

Source code in core/spakky-event/src/spakky/event/memory/broker.py
def drain(self) -> int:
    """Deliver through the sync consumers until they make no progress.

    Messages queued for async subscribers are left for `drain_async`. A
    message a background consumer is still handling is waited for, so the
    effects of every delivery are visible when this returns.

    Returns:
        Number of deliveries made by this call.
    """
    total = 0
    while True:
        delivered = sum(drain() for drain in self._drains)
        total += delivered
        if delivered:
            continue
        if not self._handling:
            return total
        sleep(IN_FLIGHT_POLL_INTERVAL)

drain_async() async

Deliver through every consumer until the broker makes no progress.

Handlers may publish further events; those are delivered as well. A message a background consumer is still handling is waited for, so the effects of every delivery are visible when this returns.

Returns:

Type Description
int

Number of deliveries made by this call.

Source code in core/spakky-event/src/spakky/event/memory/broker.py
async def drain_async(self) -> int:
    """Deliver through every consumer until the broker makes no progress.

    Handlers may publish further events; those are delivered as well. A
    message a background consumer is still handling is waited for, so the
    effects of every delivery are visible when this returns.

    Returns:
        Number of deliveries made by this call.
    """
    total = 0
    while True:
        delivered = sum(drain() for drain in self._drains)
        for drain_async in self._async_drains:
            delivered += await drain_async()
        total += delivered
        if delivered:
            continue
        if not self._handling:
            return total
        await async_sleep(IN_FLIGHT_POLL_INTERVAL)

Consumers that deliver in-memory broker messages to registered handlers.

InMemorySettlement

Applies a delivery outcome to the in-memory broker.

undeserializable(message, subscriber, handlers, error) staticmethod

Dead-letter a payload no retry can turn into the event type.

Source code in core/spakky-event/src/spakky/event/memory/consumer.py
@staticmethod
def undeserializable(
    message: InMemoryMessage,
    subscriber: SubscriberName | None,
    handlers: list[HandlerName],
    error: ValidationError,
) -> DeliveryDeadLettered:
    """Dead-letter a payload no retry can turn into the event type."""
    return DeliveryDeadLettered(
        dead_letter=DeadLetter(
            event_name=message.event_name,
            subscriber=subscriber,
            failures=tuple(
                HandlerFailure(
                    handler=handler,
                    exception_type=type(error).__qualname__,
                    exception_message=str(error),
                    retryable=False,
                )
                for handler in handlers
            ),
            attempts=message.state.attempt,
            failed_at=datetime.now(UTC),
        )
    )

still_dead(entry, outcome) staticmethod

Keep a redriven dead letter, narrowed to the handlers that failed again.

Handlers that succeeded in this redrive leave the metadata, so the next redrive does not run them a second time.

Source code in core/spakky-event/src/spakky/event/memory/consumer.py
@staticmethod
def still_dead(
    entry: InMemoryDeadLetter,
    outcome: DeliveryRetry | DeliveryDeferred | DeliveryDeadLettered,
) -> InMemoryDeadLetter:
    """Keep a redriven dead letter, narrowed to the handlers that failed again.

    Handlers that succeeded in this redrive leave the metadata, so the next
    redrive does not run them a second time.
    """
    match outcome:
        case DeliveryDeadLettered(dead_letter=dead_letter):
            failures = dead_letter.failures
        case DeliveryRetry(failures=retried):
            failures = retried
        case DeliveryDeferred(  # pragma: no branch - exhaustive outcome union
            state=state
        ):
            failures = tuple(
                failure
                for failure in entry.dead_letter.failures
                if state.pending is None or failure.handler in state.pending
            )
    return entry.model_copy(
        update={
            "dead_letter": entry.dead_letter.model_copy(
                update={"failures": failures}
            )
        }
    )

next_due_in(broker, queues, now) staticmethod

Return seconds until a message of any queue becomes deliverable.

Each subscriber has its own retry mode, so a blocking queue only offers its oldest message while a delayed queue offers every message.

Returns:

Type Description
float | None

None when every given queue is empty.

Source code in core/spakky-event/src/spakky/event/memory/consumer.py
@staticmethod
def next_due_in(
    broker: InMemoryEventBroker,
    queues: list[tuple[SubscriptionKey, RetryMode]],
    now: float,
) -> float | None:
    """Return seconds until a message of any queue becomes deliverable.

    Each subscriber has its own retry mode, so a blocking queue only offers
    its oldest message while a delayed queue offers every message.

    Returns:
        None when every given queue is empty.
    """
    waits = [
        wait
        for key, mode in queues
        if (wait := broker.next_due_in([key], now, mode is RetryMode.BLOCKING))
        is not None
    ]
    return min(waits) if waits else None

apply(broker, key, message, outcome, mode) staticmethod

Requeue, dead-letter or drop the message as the outcome requires.

Source code in core/spakky-event/src/spakky/event/memory/consumer.py
@staticmethod
def apply(
    broker: InMemoryEventBroker,
    key: SubscriptionKey,
    message: InMemoryMessage,
    outcome: DeliveryOutcome,
    mode: RetryMode,
) -> None:
    """Requeue, dead-letter or drop the message as the outcome requires."""
    match outcome:
        case DeliveryCompleted():
            return
        case DeliveryRetry(state=state, delay=delay):
            retry = message.model_copy(
                update={"state": state, "not_before": monotonic() + delay}
            )
            if mode is RetryMode.BLOCKING:
                broker.requeue_front(key, retry)
            else:
                broker.requeue_back(key, retry)
        case DeliveryDeferred(state=state, retry_after=retry_after):
            broker.requeue_front(
                key,
                message.model_copy(
                    update={
                        "state": state,
                        "not_before": monotonic() + retry_after,
                    }
                ),
            )
        case DeliveryDeadLettered(  # pragma: no branch - exhaustive DeliveryOutcome
            dead_letter=dead_letter
        ):
            broker.add_dead_letter(
                key, InMemoryDeadLetter(message=message, dead_letter=dead_letter)
            )

InMemoryEventConsumer(broker, config)

Bases: IIntegrationEventConsumer, IEventRedriver, AbstractBackgroundService

Delivers in-memory messages to sync handlers under the delivery contract.

Source code in core/spakky-event/src/spakky/event/memory/consumer.py
def __init__(
    self, broker: InMemoryEventBroker, config: InMemoryEventConfig
) -> None:
    super().__init__()
    self._broker = broker
    self._config = config
    self._subscriptions = EventSubscriptions(config.retry)
    self._adapters = {}
    broker.attach(self.drain)

register(event, handler, *, subscriber=None, handler_name=None, retry=None)

Register a handler and bind its subscriber queue to the event.

Source code in core/spakky-event/src/spakky/event/memory/consumer.py
@override
def register[EventT_contra: AbstractEvent](
    self,
    event: type[EventT_contra],
    handler: EventHandlerCallback[EventT_contra],
    *,
    subscriber: SubscriberName | None = None,
    handler_name: HandlerName | None = None,
    retry: RetryPolicy | None = None,
) -> None:
    """Register a handler and bind its subscriber queue to the event."""
    delivery = self._subscriptions.register(
        event, handler, subscriber, handler_name, retry
    )
    if event not in self._adapters:
        # TypeAdapter is invariant; the registry is keyed by the concrete type.
        self._adapters[event] = cast(TypeAdapter[AbstractEvent], TypeAdapter(event))
    self._broker.bind(self._key(delivery))

drain()

Deliver every queued message, waiting out retry delays.

Returns:

Type Description
int

Number of deliveries made, retries included.

Source code in core/spakky-event/src/spakky/event/memory/consumer.py
def drain(self) -> int:
    """Deliver every queued message, waiting out retry delays.

    Returns:
        Number of deliveries made, retries included.
    """
    return self._drain(self._sleep_through)

initialize()

Nothing to open; queues are bound at registration.

Source code in core/spakky-event/src/spakky/event/memory/consumer.py
@override
def initialize(self) -> None:
    """Nothing to open; queues are bound at registration."""
    return

run()

Deliver messages as they arrive until the service is stopped.

Source code in core/spakky-event/src/spakky/event/memory/consumer.py
@override
def run(self) -> None:
    """Deliver messages as they arrive until the service is stopped."""
    while not self._stop_event.is_set():
        self._drain(self._stop_event.wait)
        self._stop_event.wait(self._config.poll_interval)

dispose()

Nothing to close; queued messages stay inspectable on the broker.

Source code in core/spakky-event/src/spakky/event/memory/consumer.py
@override
def dispose(self) -> None:
    """Nothing to close; queued messages stay inspectable on the broker."""
    return

redrive(event, *, subscriber=None, limit=None)

Run the failed handlers of this subscriber's dead letters again.

Source code in core/spakky-event/src/spakky/event/memory/consumer.py
@override
def redrive(
    self,
    event: type[AbstractIntegrationEvent],
    *,
    subscriber: SubscriberName | None = None,
    limit: int | None = None,
) -> RedriveResult:
    """Run the failed handlers of this subscriber's dead letters again."""
    delivery = self._subscriptions.get(subscriber, event)
    key = self._key(delivery)
    succeeded = 0
    failed = 0
    for entry in self._broker.take_dead_letters(key, limit):
        outcome = self._deliver(
            delivery,
            entry.message.model_copy(
                update={
                    "state": DeliveryState(pending=entry.dead_letter.pending),
                    "not_before": 0.0,
                }
            ),
        )
        if isinstance(outcome, DeliveryCompleted):
            succeeded += 1
            continue
        failed += 1
        self._broker.add_dead_letter(
            key, InMemorySettlement.still_dead(entry, outcome)
        )
    return RedriveResult(succeeded=succeeded, failed=failed)

AsyncInMemoryEventConsumer(broker, config)

Bases: IAsyncIntegrationEventConsumer, IAsyncEventRedriver, AbstractAsyncBackgroundService

Delivers in-memory messages to async handlers under the delivery contract.

Source code in core/spakky-event/src/spakky/event/memory/consumer.py
def __init__(
    self, broker: InMemoryEventBroker, config: InMemoryEventConfig
) -> None:
    super().__init__()
    self._broker = broker
    self._config = config
    self._subscriptions = AsyncEventSubscriptions(config.retry)
    self._adapters = {}
    broker.attach_async(self.drain_async)

register(event, handler, *, subscriber=None, handler_name=None, retry=None)

Register an async handler and bind its subscriber queue to the event.

Source code in core/spakky-event/src/spakky/event/memory/consumer.py
@override
def register[EventT_contra: AbstractEvent](
    self,
    event: type[EventT_contra],
    handler: AsyncEventHandlerCallback[EventT_contra],
    *,
    subscriber: SubscriberName | None = None,
    handler_name: HandlerName | None = None,
    retry: RetryPolicy | None = None,
) -> None:
    """Register an async handler and bind its subscriber queue to the event."""
    delivery = self._subscriptions.register(
        event, handler, subscriber, handler_name, retry
    )
    if event not in self._adapters:
        # TypeAdapter is invariant; the registry is keyed by the concrete type.
        self._adapters[event] = cast(TypeAdapter[AbstractEvent], TypeAdapter(event))
    self._broker.bind(self._key(delivery))

drain_async() async

Deliver every queued message, waiting out retry delays.

Returns:

Type Description
int

Number of deliveries made, retries included.

Source code in core/spakky-event/src/spakky/event/memory/consumer.py
async def drain_async(self) -> int:
    """Deliver every queued message, waiting out retry delays.

    Returns:
        Number of deliveries made, retries included.
    """
    return await self._drain_async(self._sleep_through_async)

initialize_async() async

Nothing to open; queues are bound at registration.

Source code in core/spakky-event/src/spakky/event/memory/consumer.py
@override
async def initialize_async(self) -> None:
    """Nothing to open; queues are bound at registration."""
    return

run_async() async

Deliver messages as they arrive until the service is stopped.

Source code in core/spakky-event/src/spakky/event/memory/consumer.py
@override
async def run_async(self) -> None:
    """Deliver messages as they arrive until the service is stopped."""
    while not self._stop_event.is_set():
        await self._drain_async(self._wait_for_stop_async)
        await self._wait_for_stop_async(self._config.poll_interval)

dispose_async() async

Nothing to close; queued messages stay inspectable on the broker.

Source code in core/spakky-event/src/spakky/event/memory/consumer.py
@override
async def dispose_async(self) -> None:
    """Nothing to close; queued messages stay inspectable on the broker."""
    return

redrive(event, *, subscriber=None, limit=None) async

Run the failed handlers of this subscriber's dead letters again.

Source code in core/spakky-event/src/spakky/event/memory/consumer.py
@override
async def redrive(
    self,
    event: type[AbstractIntegrationEvent],
    *,
    subscriber: SubscriberName | None = None,
    limit: int | None = None,
) -> RedriveResult:
    """Run the failed handlers of this subscriber's dead letters again."""
    delivery = self._subscriptions.get(subscriber, event)
    key = self._key(delivery)
    succeeded = 0
    failed = 0
    for entry in self._broker.take_dead_letters(key, limit):
        outcome = await self._deliver_async(
            delivery,
            entry.message.model_copy(
                update={
                    "state": DeliveryState(pending=entry.dead_letter.pending),
                    "not_before": 0.0,
                }
            ),
        )
        if isinstance(outcome, DeliveryCompleted):
            succeeded += 1
            continue
        failed += 1
        self._broker.add_dead_letter(
            key, InMemorySettlement.still_dead(entry, outcome)
        )
    return RedriveResult(succeeded=succeeded, failed=failed)

Transports that publish serialized integration events into the in-memory broker.

InMemoryEventTransport(broker)

Bases: IEventTransport

Synchronous transport backed by InMemoryEventBroker.

Source code in core/spakky-event/src/spakky/event/memory/transport.py
def __init__(self, broker: InMemoryEventBroker) -> None:
    self._broker = broker

send(event_name, payload, headers, partition_key=None)

Publish the payload to every subscriber queue of event_name.

Source code in core/spakky-event/src/spakky/event/memory/transport.py
@override
def send(
    self,
    event_name: str,
    payload: bytes,
    headers: dict[str, str],
    partition_key: str | None = None,
) -> None:
    """Publish the payload to every subscriber queue of `event_name`."""
    self._broker.publish(
        InMemoryMessage(
            event_name=event_name,
            payload=payload,
            headers=dict(headers),
            partition_key=partition_key,
        )
    )

flush()

Nothing is buffered; send already published.

Source code in core/spakky-event/src/spakky/event/memory/transport.py
@override
def flush(self) -> None:
    """Nothing is buffered; `send` already published."""
    return

AsyncInMemoryEventTransport(broker)

Bases: IAsyncEventTransport

Asynchronous transport backed by InMemoryEventBroker.

Source code in core/spakky-event/src/spakky/event/memory/transport.py
def __init__(self, broker: InMemoryEventBroker) -> None:
    self._broker = broker

send(event_name, payload, headers, partition_key=None) async

Publish the payload to every subscriber queue of event_name.

Source code in core/spakky-event/src/spakky/event/memory/transport.py
@override
async def send(
    self,
    event_name: str,
    payload: bytes,
    headers: dict[str, str],
    partition_key: str | None = None,
) -> None:
    """Publish the payload to every subscriber queue of `event_name`."""
    self._broker.publish(
        InMemoryMessage(
            event_name=event_name,
            payload=payload,
            headers=dict(headers),
            partition_key=partition_key,
        )
    )

flush() async

Nothing is buffered; send already published.

Source code in core/spakky-event/src/spakky/event/memory/transport.py
@override
async def flush(self) -> None:
    """Nothing is buffered; `send` already published."""
    return

Configuration of the in-memory integration event broker.

InMemoryEventConfig()

Bases: BaseSettings

Retry and polling settings of the in-memory broker.

Source code in core/spakky-event/src/spakky/event/memory/config.py
def __init__(self) -> None:
    super().__init__()

retry = RetryPolicy() class-attribute instance-attribute

Retry limits applied to each subscriber independently.

poll_interval = 0.05 class-attribute instance-attribute

Seconds a background consumer waits before looking for new messages.

스테레오타입

EventHandler stereotype and event routing decorators.

This module provides @EventHandler stereotype and @on_event decorator for organizing event-driven architectures.

EventHandlerMethod = Callable[[Any, EventT_contra], None | Awaitable[None]]

Type alias for event handler callback functions.

EventRoute(event_type, name=None) dataclass

Bases: FunctionAnnotation

Annotation for marking methods as event handlers.

Associates a method with a specific domain event type.

event_type instance-attribute

The domain event type this handler processes.

name = None class-attribute instance-attribute

Explicit handler name; None derives <Class>.<method>.

The name identifies the handler in dead-letter metadata and in the idempotency key, so set it explicitly when the method may be renamed.

handler_name(owner, method_name)

Return the name this handler is registered under.

Parameters:

Name Type Description Default
owner type

Event handler class declaring the method.

required
method_name str

Name of the decorated method.

required
Source code in core/spakky-event/src/spakky/event/stereotype/event_handler.py
def handler_name(self, owner: type, method_name: str) -> HandlerName:
    """Return the name this handler is registered under.

    Args:
        owner: Event handler class declaring the method.
        method_name: Name of the decorated method.
    """
    if self.name is not None:
        return self.name
    return f"{owner.__qualname__}.{method_name}"

__call__(obj)

Apply event route annotation to method.

Parameters:

Name Type Description Default
obj EventHandlerMethod[EventT_contra]

The method to annotate.

required

Returns:

Type Description
EventHandlerMethod[EventT_contra]

The annotated method.

Source code in core/spakky-event/src/spakky/event/stereotype/event_handler.py
def __call__(
    self, obj: EventHandlerMethod[EventT_contra]
) -> EventHandlerMethod[EventT_contra]:
    """Apply event route annotation to method.

    Args:
        obj: The method to annotate.

    Returns:
        The annotated method.
    """
    return super().__call__(obj)

DeclaredEventRoute(method_name, route, asynchronous, handler_name) dataclass

One @on_event method as declared on an event handler class.

method_name instance-attribute

Attribute name to look the bound method up on a handler instance.

EventHandler(*, name='', scope=Scope.SINGLETON, subscriber=None, retry=None) dataclass

Bases: Pod

Stereotype for event handler classes.

EventHandlers contain methods decorated with @on_event that process domain events asynchronously.

Example

@EventHandler(subscriber="billing", retry=RetryPolicy(max_attempts=3)) class BillingHandler: @on_event(OrderPlaced) async def charge(self, event: OrderPlaced) -> None: ...

subscriber = field(kw_only=True, default=None) class-attribute instance-attribute

Independent subscriber the integration handlers of this class belong to.

Each subscriber reads an integration event stream on its own: it has its own consume position, retries and dead-letter destination. None keeps the handlers on the unnamed subscriber of the consumer. Domain events are dispatched in process and ignore this value.

retry = field(kw_only=True, default=None) class-attribute instance-attribute

Retry the subscriber of this class uses; None declares nothing.

Only the fields set explicitly override the consumer-wide policy, so RetryPolicy(mode=RetryMode.DELAYED) keeps the attempt counts and intervals of the deployment settings. The value covers every event of the subscriber: classes of the same subscriber that declare none follow it, and two classes that declare different values fail registration with ConflictingSubscriberRetryPolicyError.

__post_init__()

Reject subscriber names that cannot become broker resource names.

Source code in core/spakky-event/src/spakky/event/stereotype/event_handler.py
def __post_init__(self) -> None:
    """Reject subscriber names that cannot become broker resource names."""
    SubscriberNames.validate(self.subscriber)

routes()

List the @on_event methods declared on the handler class.

Routes are read from the class, not from an instance: an instance may be an AOP proxy whose attributes are plain callables, and scanning it for bound methods would silently miss every advised handler.

Source code in core/spakky-event/src/spakky/event/stereotype/event_handler.py
def routes(self) -> list[DeclaredEventRoute]:
    """List the `@on_event` methods declared on the handler class.

    Routes are read from the class, not from an instance: an instance may be
    an AOP proxy whose attributes are plain callables, and scanning it for
    bound methods would silently miss every advised handler.
    """
    declared: list[DeclaredEventRoute] = []
    for method_name, function in getmembers(self.type_, isfunction):
        route: EventRoute[AbstractEvent] | None = EventRoute[
            AbstractEvent
        ].get_or_none(function)
        if route is None:
            continue
        declared.append(
            DeclaredEventRoute(
                method_name=method_name,
                route=route,
                asynchronous=iscoroutinefunction(function),
                handler_name=route.handler_name(self.type_, method_name),
            )
        )
    return declared

on_event(event_type, *, name=None)

Decorator for marking methods as event handlers.

Parameters:

Name Type Description Default
event_type type[EventT_contra]

The domain event type to handle.

required
name HandlerName | None

Explicit handler name; None derives <Class>.<method>.

None

Returns:

Type Description
Callable[[EventHandlerMethod[EventT_contra]], EventHandlerMethod[EventT_contra]]

Decorator function that applies EventRoute annotation.

Example

@EventHandler() class UserEventHandler: @on_event(UserCreatedEvent) async def handle_user_created(self, event: UserCreatedEvent) -> None: # Handle event pass

Source code in core/spakky-event/src/spakky/event/stereotype/event_handler.py
def on_event[EventT_contra: AbstractEvent](
    event_type: type[EventT_contra],
    *,
    name: HandlerName | None = None,
) -> Callable[
    [EventHandlerMethod[EventT_contra]],
    EventHandlerMethod[EventT_contra],
]:
    """Decorator for marking methods as event handlers.

    Args:
        event_type: The domain event type to handle.
        name: Explicit handler name; None derives `<Class>.<method>`.

    Returns:
        Decorator function that applies EventRoute annotation.

    Example:
        @EventHandler()
        class UserEventHandler:
            @on_event(UserCreatedEvent)
            async def handle_user_created(self, event: UserCreatedEvent) -> None:
                # Handle event
                pass
    """

    def wrapper(
        method: EventHandlerMethod[EventT_contra],
    ) -> EventHandlerMethod[EventT_contra]:
        return EventRoute(event_type, name)(method)

    return wrapper

후처리기

Fail startup when declared handlers lack an explicit consumer provider.

EventHandlerProviderValidationPostProcessor()

Bases: IPostProcessor, IContainerAware

Validate domain/integration and sync/async capabilities without a hidden provider.

Source code in core/spakky-event/src/spakky/event/post_processor.py
def __init__(self) -> None:
    self._subscription_modes = {}

set_container(container)

Receive the provider-neutral registry for startup validation.

Parameters:

Name Type Description Default
container IContainer

Registry containing only explicitly selected providers.

required
Source code in core/spakky-event/src/spakky/event/post_processor.py
@override
def set_container(self, container: IContainer) -> None:
    """Receive the provider-neutral registry for startup validation.

    Args:
        container: Registry containing only explicitly selected providers.
    """
    self._container = container

post_process(pod)

Fail deterministically when a declared handler would remain unregistered.

Parameters:

Name Type Description Default
pod object

Constructed business or infrastructure Pod.

required

Returns:

Type Description
object

The original Pod after validating all declared event routes.

Raises:

Type Description
EventHandlerProviderUnavailableError

No provider supports the handler role.

MixedSubscriptionModeError

One subscription mixes sync and async handlers.

Source code in core/spakky-event/src/spakky/event/post_processor.py
@override
def post_process(self, pod: object) -> object:
    """Fail deterministically when a declared handler would remain unregistered.

    Args:
        pod: Constructed business or infrastructure Pod.

    Returns:
        The original Pod after validating all declared event routes.

    Raises:
        EventHandlerProviderUnavailableError: No provider supports the handler role.
        MixedSubscriptionModeError: One subscription mixes sync and async handlers.
    """
    if not EventHandler.exists(type(pod)):
        return pod
    handler = EventHandler.get(type(pod))
    for declared in handler.routes():
        route = declared.route
        if issubclass(route.event_type, AbstractDomainEvent):
            provider = (
                IAsyncDomainEventConsumer
                if declared.asynchronous
                else IDomainEventConsumer
            )
        elif issubclass(route.event_type, AbstractIntegrationEvent):
            provider = (
                IAsyncIntegrationEventConsumer
                if declared.asynchronous
                else IIntegrationEventConsumer
            )
            subscription = (handler.subscriber, route.event_type)
            known = self._subscription_modes.setdefault(
                subscription, declared.asynchronous
            )
            if known is not declared.asynchronous:
                raise MixedSubscriptionModeError(*subscription)
        else:
            raise UnknownEventTypeError(route.event_type)
        if self._container.get_or_none(provider) is None:
            raise EventHandlerProviderUnavailableError(
                f"{handler.type_.__module__}.{handler.type_.__qualname__}."
                f"{declared.method_name}",
                route.event_type,
                provider,
            )
    return pod

에러

AbstractSpakkyEventError

Bases: AbstractSpakkyFrameworkError, ABC

Base error for event system operations.

InvalidMessageError

Bases: AbstractSpakkyEventError

Raised when a message received is invalid or malformed.

IntegrationEventTransportUnavailableError

Bases: AbstractSpakkyEventError

Raised when integration events are published without a broker transport.

AuthSnapshotPropagationSignerUnavailableError

Bases: AbstractSpakkyEventError

Raised when signed snapshot propagation lacks a signer provider.

AuthSnapshotPropagationContextUnavailableError

Bases: AbstractSpakkyEventError

Raised when signed snapshot propagation cannot read ApplicationContext.

EventTransportNotRunningError

Bases: AbstractSpakkyEventError

Raised when a transport is used outside the application lifecycle.

Transports whose broker client is opened at application start and closed at application stop raise this instead of publishing into a closed client, so that callers can tell a shutdown window apart from a delivery failure.

EventDeliveryRejectedError(reasons)

Bases: AbstractSpakkyEventError

Raised when a transport attributes a permanent rejection to a record.

A client may report the rejection synchronously from send() or later through a delivery callback consumed by flush(). Both paths use this error so callers can distinguish record-specific failure from a transport-wide outage.

Source code in core/spakky-event/src/spakky/event/error.py
def __init__(self, reasons: list[str]) -> None:
    self.reasons = reasons
    super().__init__()

UnknownEventTypeError(event_type)

Bases: AbstractSpakkyEventError

Raised when an event type is neither domain nor integration.

Source code in core/spakky-event/src/spakky/event/error.py
def __init__(self, event_type: type) -> None:
    self.event_type = event_type
    super().__init__()

DomainEventDispatcherUnavailableError

Bases: AbstractSpakkyEventError

Raised when local domain publishing has no configured dispatcher provider.

EventHandlerProviderUnavailableError(handler, event_type, provider_type)

Bases: AbstractSpakkyEventError

Raised at startup when a declared event handler has no matching consumer.

Keep the missing provider and affected handler in startup diagnostics.

Parameters:

Name Type Description Default
handler str

Fully qualified method declaring the unsupported handler.

required
event_type type

Declared domain or integration event type.

required
provider_type type

Required synchronous or asynchronous consumer role.

required
Source code in core/spakky-event/src/spakky/event/error.py
def __init__(self, handler: str, event_type: type, provider_type: type) -> None:
    """Keep the missing provider and affected handler in startup diagnostics.

    Args:
        handler: Fully qualified method declaring the unsupported handler.
        event_type: Declared domain or integration event type.
        provider_type: Required synchronous or asynchronous consumer role.
    """
    self.handler, self.event_type, self.provider_type = (
        handler,
        event_type,
        provider_type,
    )
    super().__init__()

InvalidEventDeferralError

Bases: AbstractSpakkyEventError

Raised when a deferral delay is not finite and strictly positive.

EventDeferredError(retry_after=1.0)

Bases: AbstractSpakkyEventError

Defer delivery without counting a handler failure or acknowledging it.

Raise before effects, or let a transaction roll back before this reaches the consumer. Earlier handlers may run again and must remain idempotent. Broker consumers supporting deferral retry after the delay while continuing to poll. Direct in-process dispatch propagates the error to its caller.

Source code in core/spakky-event/src/spakky/event/error.py
def __init__(self, retry_after: float = 1.0) -> None:
    if not isfinite(retry_after) or retry_after <= 0:
        raise InvalidEventDeferralError()
    self.retry_after = retry_after
    super().__init__()

AbstractNonRetryableEventError

Bases: AbstractSpakkyEventError, ABC

Base for handler failures that another delivery attempt cannot fix.

A consumer skips the remaining retry attempts for such a failure and moves the message to the subscriber's dead-letter destination.

InvalidDeliveryHeaderError

Bases: AbstractSpakkyEventError

Raised when delivery or dead-letter headers cannot be decoded.

EventDeliveryContextUnavailableError

Bases: AbstractSpakkyEventError

Raised when delivery metadata is read outside a consumer-driven handler call.

SubscriptionNotFoundError(subscriber, event_type)

Bases: AbstractSpakkyEventError

Raised when no handler is registered for a subscriber and event type.

Source code in core/spakky-event/src/spakky/event/error.py
def __init__(self, subscriber: str | None, event_type: type) -> None:
    self.subscriber = subscriber
    self.event_type = event_type
    super().__init__()

EventHandlerNotRegisteredError

Bases: AbstractNonRetryableEventError

Recorded when a delivery names a handler its subscription no longer has.

A retry or redrive carries the names of the handlers still to run. If one was renamed or removed, completing the delivery would discard the message without running anything, so it is kept as a failure instead.