콘텐츠로 이동

spakky-rabbitmq

RabbitMQ 통합 — 이벤트 전송/수신

메인

Plugin initialization for RabbitMQ integration.

Registers event consumers, transports, and post-processors for automatic event handler registration in RabbitMQ-enabled applications.

initialize(app)

Initialize the RabbitMQ plugin.

Registers event consumers, transports, and the post-processor for automatic event handler registration. This function is called automatically by the Spakky framework during plugin loading.

Parameters:

Name Type Description Default
app SpakkyApplication

The Spakky application instance.

required
Source code in plugins/spakky-rabbitmq/src/spakky/plugins/rabbitmq/main.py
def initialize(app: SpakkyApplication) -> None:
    """Initialize the RabbitMQ plugin.

    Registers event consumers, transports, and the post-processor for automatic
    event handler registration. This function is called automatically by the
    Spakky framework during plugin loading.

    Args:
        app: The Spakky application instance.
    """
    app.add(RabbitMQConnectionConfig)

    app.add(RabbitMQPostProcessor)

    app.add(RabbitMQEventConsumer)
    app.add(RabbitMQEventTransport)

    app.add(AsyncRabbitMQEventConsumer)
    app.add(AsyncRabbitMQEventTransport)

이벤트 Transport

RabbitMQ event transports for integration events.

Provides synchronous and asynchronous event transports that send integration events to RabbitMQ queues with optional exchange routing.

RabbitMQEventTransport(config)

Bases: IEventTransport

Synchronous RabbitMQ event transport.

Sends pre-serialized event payloads to RabbitMQ queues using blocking connections. Optionally routes through an exchange for pub/sub patterns.

Attributes:

Name Type Description
connection_string str

AMQP connection string.

exchange_name str | None

Optional exchange name for routing.

declare_default_queue bool

Whether the queue named after the event is declared (and bound) before publishing.

Initialize the synchronous RabbitMQ event transport.

Parameters:

Name Type Description Default
config RabbitMQConnectionConfig

RabbitMQ connection configuration.

required
Source code in plugins/spakky-rabbitmq/src/spakky/plugins/rabbitmq/event/transport.py
def __init__(self, config: RabbitMQConnectionConfig) -> None:
    """Initialize the synchronous RabbitMQ event transport.

    Args:
        config: RabbitMQ connection configuration.
    """
    self.connection_string = config.connection_string
    self.exchange_name = config.exchange_name
    self.declare_default_queue = config.declare_default_queue

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

Send a pre-serialized event payload to RabbitMQ.

Creates a new connection, publishes the payload with the event name as routing key, and closes the connection. Unless declare_default_queue is turned off, the queue of the unnamed subscriber is declared first so that the message is kept even before a consumer has started.

Parameters:

Name Type Description Default
event_name str

Routing key / queue name for the event.

required
payload bytes

Pre-serialized JSON bytes.

required
headers dict[str, str]

Metadata headers for trace propagation.

required
partition_key str | None

Accepted for transport interface parity and not used for routing — RabbitMQ has no partitions and a single queue is already FIFO ordered, so there is nothing to pin the payload to.

None
Source code in plugins/spakky-rabbitmq/src/spakky/plugins/rabbitmq/event/transport.py
@override
def send(
    self,
    event_name: str,
    payload: bytes,
    headers: dict[str, str],
    partition_key: str | None = None,
) -> None:
    """Send a pre-serialized event payload to RabbitMQ.

    Creates a new connection, publishes the payload with the event name as
    routing key, and closes the connection. Unless `declare_default_queue`
    is turned off, the queue of the unnamed subscriber is declared first so
    that the message is kept even before a consumer has started.

    Args:
        event_name: Routing key / queue name for the event.
        payload: Pre-serialized JSON bytes.
        headers: Metadata headers for trace propagation.
        partition_key: Accepted for transport interface parity and not used
            for routing — RabbitMQ has no partitions and a single queue is
            already FIFO ordered, so there is nothing to pin the payload to.
    """
    connection = BlockingConnection(URLParameters(self.connection_string))
    channel = connection.channel()
    if self.exchange_name is not None:
        channel.exchange_declare(self.exchange_name)
    if self.declare_default_queue:
        channel.queue_declare(event_name, durable=True)
        if self.exchange_name is not None:
            channel.queue_bind(event_name, self.exchange_name, event_name)
    channel.basic_publish(
        self.exchange_name if self.exchange_name is not None else "",
        event_name,
        payload,
        properties=BasicProperties(headers=headers),
    )
    channel.close()
    connection.close()

flush()

Return immediately: send() publishes and closes its own connection.

Source code in plugins/spakky-rabbitmq/src/spakky/plugins/rabbitmq/event/transport.py
@override
def flush(self) -> None:
    """Return immediately: send() publishes and closes its own connection."""

AsyncRabbitMQEventTransport(config)

Bases: IAsyncEventTransport

Asynchronous RabbitMQ event transport.

Sends pre-serialized event payloads to RabbitMQ queues using async connections. Optionally routes through an exchange for pub/sub patterns.

Attributes:

Name Type Description
connection_string str

AMQP connection string.

exchange_name str | None

Optional exchange name for routing.

declare_default_queue bool

Whether the queue named after the event is declared (and bound) before publishing.

Initialize the asynchronous RabbitMQ event transport.

Parameters:

Name Type Description Default
config RabbitMQConnectionConfig

RabbitMQ connection configuration.

required
Source code in plugins/spakky-rabbitmq/src/spakky/plugins/rabbitmq/event/transport.py
def __init__(self, config: RabbitMQConnectionConfig) -> None:
    """Initialize the asynchronous RabbitMQ event transport.

    Args:
        config: RabbitMQ connection configuration.
    """
    self.connection_string = config.connection_string
    self.exchange_name = config.exchange_name
    self.declare_default_queue = config.declare_default_queue

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

Send a pre-serialized event payload to RabbitMQ asynchronously.

Creates a new robust connection, publishes the payload with the event name as routing key, and closes the connection. Unless declare_default_queue is turned off, the queue of the unnamed subscriber is declared first so that the message is kept even before a consumer has started.

Parameters:

Name Type Description Default
event_name str

Routing key / queue name for the event.

required
payload bytes

Pre-serialized JSON bytes.

required
headers dict[str, str]

Metadata headers for trace propagation.

required
partition_key str | None

Accepted for transport interface parity and not used for routing — RabbitMQ has no partitions and a single queue is already FIFO ordered, so there is nothing to pin the payload to.

None
Source code in plugins/spakky-rabbitmq/src/spakky/plugins/rabbitmq/event/transport.py
@override
async def send(
    self,
    event_name: str,
    payload: bytes,
    headers: dict[str, str],
    partition_key: str | None = None,
) -> None:
    """Send a pre-serialized event payload to RabbitMQ asynchronously.

    Creates a new robust connection, publishes the payload with the event
    name as routing key, and closes the connection. Unless
    `declare_default_queue` is turned off, the queue of the unnamed
    subscriber is declared first so that the message is kept even before a
    consumer has started.

    Args:
        event_name: Routing key / queue name for the event.
        payload: Pre-serialized JSON bytes.
        headers: Metadata headers for trace propagation.
        partition_key: Accepted for transport interface parity and not used
            for routing — RabbitMQ has no partitions and a single queue is
            already FIFO ordered, so there is nothing to pin the payload to.
    """
    async with await connect_robust(self.connection_string) as connection:
        channel = await connection.channel()
        exchange = (
            await channel.declare_exchange(self.exchange_name)
            if self.exchange_name is not None
            else channel.default_exchange
        )
        if self.declare_default_queue:
            queue = await channel.declare_queue(event_name, durable=True)
            if self.exchange_name is not None:
                await queue.bind(exchange, event_name)
        await exchange.publish(
            Message(body=payload, headers=dict(headers)),
            routing_key=event_name,
        )
        await channel.close()

flush() async

Return immediately: send() publishes and closes its own connection.

Source code in plugins/spakky-rabbitmq/src/spakky/plugins/rabbitmq/event/transport.py
@override
async def flush(self) -> None:
    """Return immediately: send() publishes and closes its own connection."""

이벤트 Consumer

RabbitMQ event consumers for integration events.

Provides synchronous and asynchronous event consumers that run as background services. Each subscriber owns a queue of its own, and every message is handed to the broker-neutral delivery contract of spakky.event.delivery, which decides whether the message is acknowledged, retried or dead-lettered.

RabbitMQAuthSettlement(drop=False) dataclass

What the auth failure policy asked for while one message was delivered.

drop = False class-attribute instance-attribute

A nack_drop policy applied; the message is rejected instead of acked.

RabbitMQEventConsumer(config)

Bases: IIntegrationEventConsumer, IEventRedriver, AbstractBackgroundService

Synchronous RabbitMQ event consumer.

Runs as a background service that consumes one durable queue per subscriber and delivers each message to that subscriber's synchronous handlers under the delivery contract: failed handlers are retried by RetryPolicy, and a message the subscriber gives up on moves to the subscriber's own dead-letter queue.

Attributes:

Name Type Description
connection_string str

AMQP connection string.

exchange_name str | None

Exchange subscriber queues are bound to, if configured.

connection BlockingConnection

Blocking RabbitMQ connection.

channel BlockingChannel

Blocking channel for message consumption.

publish_channel BlockingChannel

Confirm-mode channel for retry and dead-letter copies.

Initialize the synchronous RabbitMQ event consumer.

Parameters:

Name Type Description Default
config RabbitMQConnectionConfig

RabbitMQ connection configuration.

required
Source code in plugins/spakky-rabbitmq/src/spakky/plugins/rabbitmq/event/consumer.py
def __init__(self, config: RabbitMQConnectionConfig) -> None:
    """Initialize the synchronous RabbitMQ event consumer.

    Args:
        config: RabbitMQ connection configuration.
    """
    super().__init__()
    self.connection_string = config.connection_string
    self.exchange_name = config.exchange_name
    self._retry = config.retry
    self._subscriptions = EventSubscriptions(config.retry)
    self._adapters = {}
    self._propagator = None
    self._auth_challenge_action = config.auth_challenge_action
    self._auth_deny_action = config.auth_deny_action
    self._auth_error_action = config.auth_error_action

set_propagator(propagator)

Set the trace propagator for extracting trace context from messages.

Parameters:

Name Type Description Default
propagator ITracePropagator

The trace propagator instance.

required
Source code in plugins/spakky-rabbitmq/src/spakky/plugins/rabbitmq/event/consumer.py
def set_propagator(self, propagator: ITracePropagator) -> None:
    """Set the trace propagator for extracting trace context from messages.

    Args:
        propagator: The trace propagator instance.
    """
    self._propagator = propagator

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

Register a handler in the subscription of subscriber for event.

Parameters:

Name Type Description Default
event type[EventT_contra]

The event type to handle.

required
handler EventHandlerCallback[EventT_contra]

The callback function to handle the event.

required
subscriber SubscriberName | None

Independent subscriber the handler belongs to; None is the unnamed subscriber consuming the queue named after the event.

None
handler_name HandlerName | None

Name unique within the subscription.

None
retry RetryPolicy | None

Retry the handler's class declared for its subscriber. Its attempt counts and intervals apply to that subscriber only; its mode must match the consumer's retry.mode.

None

Raises:

Type Description
SubscriberExchangeRequiredError

A named subscriber is registered while no exchange is configured.

ConflictingSubscriberRetryPolicyError

Another handler class of the subscriber declared a different retry.

SubscriberRetryModeUnsupportedError

The subscriber's retry mode differs from the consumer's retry.mode.

Source code in plugins/spakky-rabbitmq/src/spakky/plugins/rabbitmq/event/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 in the subscription of `subscriber` for `event`.

    Args:
        event: The event type to handle.
        handler: The callback function to handle the event.
        subscriber: Independent subscriber the handler belongs to; None is
            the unnamed subscriber consuming the queue named after the event.
        handler_name: Name unique within the subscription.
        retry: Retry the handler's class declared for its subscriber. Its
            attempt counts and intervals apply to that subscriber only; its
            mode must match the consumer's `retry.mode`.

    Raises:
        SubscriberExchangeRequiredError: A named subscriber is registered
            while no exchange is configured.
        ConflictingSubscriberRetryPolicyError: Another handler class of the
            subscriber declared a different retry.
        SubscriberRetryModeUnsupportedError: The subscriber's retry mode
            differs from the consumer's `retry.mode`.
    """
    if subscriber is not None and self.exchange_name is None:
        raise SubscriberExchangeRequiredError(subscriber, event)
    self._subscriptions.register(event, handler, subscriber, handler_name, retry)
    if self._subscriptions.policy_of(subscriber).mode is not self._retry.mode:
        raise SubscriberRetryModeUnsupportedError(subscriber)
    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))

initialize()

Initialize RabbitMQ connection and declare subscriber queues.

Declares, for every subscription, the subscriber queue (bound to the exchange when one is configured), its dead-letter queue and, in delayed retry mode, its wait queue, then starts consuming.

Source code in plugins/spakky-rabbitmq/src/spakky/plugins/rabbitmq/event/consumer.py
@override
def initialize(self) -> None:
    """Initialize RabbitMQ connection and declare subscriber queues.

    Declares, for every subscription, the subscriber queue (bound to the
    exchange when one is configured), its dead-letter queue and, in
    delayed retry mode, its wait queue, then starts consuming.
    """
    self.connection = BlockingConnection(
        parameters=URLParameters(self.connection_string)
    )
    self.channel = self.connection.channel()
    self.publish_channel = self.connection.channel()
    self.publish_channel.confirm_delivery()
    if self._retry.mode is RetryMode.BLOCKING:
        self.channel.basic_qos(prefetch_count=BLOCKING_PREFETCH_COUNT)
    if self.exchange_name is not None:
        self.channel.exchange_declare(self.exchange_name)

    for delivery in self._subscriptions:
        queues = self._queues(delivery)
        self.channel.queue_declare(queues.queue, durable=True)
        if self.exchange_name is not None:
            self.channel.queue_bind(
                queues.queue,
                self.exchange_name,
                EventRouting.name_of(delivery.event_type),
            )
        self.channel.queue_declare(queues.dead_letter_queue, durable=True)
        if self._retry.mode is RetryMode.DELAYED:
            self.channel.queue_declare(
                queues.retry_queue,
                durable=True,
                arguments={  # pyrefly: ignore[bad-argument-type] - pika-stubs mistypes queue arguments as DeclareOk; pika takes a dict
                    DEAD_LETTER_EXCHANGE_ARGUMENT: DEFAULT_EXCHANGE_NAME,
                    DEAD_LETTER_ROUTING_KEY_ARGUMENT: queues.queue,
                },
            )
        self.channel.basic_consume(
            queues.queue,
            partial(self._on_message, delivery, queues),
        )

dispose()

Clean up RabbitMQ resources.

Closes the channel and connection when the service is stopped. Messages still waiting for a blocking retry return to their queue.

Source code in plugins/spakky-rabbitmq/src/spakky/plugins/rabbitmq/event/consumer.py
@override
def dispose(self) -> None:
    """Clean up RabbitMQ resources.

    Closes the channel and connection when the service is stopped.
    Messages still waiting for a blocking retry return to their queue.
    """
    self.channel.close()
    self.connection.close()
    return

run()

Run the event consumer loop.

Starts consuming messages from RabbitMQ queues and blocks until the stop event is set.

Source code in plugins/spakky-rabbitmq/src/spakky/plugins/rabbitmq/event/consumer.py
@override
def run(self) -> None:
    """Run the event consumer loop.

    Starts consuming messages from RabbitMQ queues and blocks until
    the stop event is set.
    """
    self.connection.add_callback_threadsafe(self._check_if_event_set)
    self.channel.start_consuming()

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

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

Opens a connection of its own, so it may be called from any thread while the consumer is running. A dead letter that fails again is held until every stored one was taken, then replaced by a copy whose metadata lists only the handlers that failed again, so a handler that succeeded here is not run by the next redrive. Each dead letter is delivered at most once per call.

Raises:

Type Description
SubscriptionNotFoundError

Nothing is registered for the pair.

Source code in plugins/spakky-rabbitmq/src/spakky/plugins/rabbitmq/event/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.

    Opens a connection of its own, so it may be called from any thread
    while the consumer is running. A dead letter that fails again is held
    until every stored one was taken, then replaced by a copy whose
    metadata lists only the handlers that failed again, so a handler that
    succeeded here is not run by the next redrive. Each dead letter is
    delivered at most once per call.

    Raises:
        SubscriptionNotFoundError: Nothing is registered for the pair.
    """
    delivery = self._subscriptions.get(subscriber, event)
    queues = self._queues(delivery)
    connection = BlockingConnection(
        parameters=URLParameters(self.connection_string)
    )
    try:
        channel = connection.channel()
        publish_channel = connection.channel()
        publish_channel.confirm_delivery()
        channel.queue_declare(queues.dead_letter_queue, durable=True)
        succeeded = 0
        kept: list[tuple[int, bytes, dict[str, str]]] = []
        while limit is None or succeeded + len(kept) < limit:
            method_frame, properties, body = channel.basic_get(
                queues.dead_letter_queue
            )
            if (
                method_frame is None
                or method_frame.delivery_tag is None
                or properties is None
                or body is None
            ):
                # 큐에 더 남은 dead letter가 없다.
                break
            payload: bytes = body  # pyrefly: ignore[bad-assignment] - pika-stubs types the body as str; pika returns bytes
            still_dead = self._redrive(
                delivery, self._to_string_headers(properties.headers), payload
            )
            if still_dead is None:
                channel.basic_ack(method_frame.delivery_tag)
                succeeded += 1
                continue
            # 사본을 바로 넣으면 이 호출이 다시 꺼내게 되므로 끝까지 쥐고 있는다.
            kept.append((method_frame.delivery_tag, payload, still_dead))
        for delivery_tag, payload, headers in kept:
            self._forward(
                channel,
                publish_channel,
                delivery_tag,
                queues.dead_letter_queue,
                payload,
                headers,
                None,
            )
        return RedriveResult(succeeded=succeeded, failed=len(kept))
    finally:
        connection.close()

AsyncRabbitMQEventConsumer(config)

Bases: IAsyncIntegrationEventConsumer, IAsyncEventRedriver, AbstractAsyncBackgroundService

Asynchronous RabbitMQ event consumer.

Runs as an async background service that consumes one durable queue per subscriber and delivers each message to that subscriber's asynchronous handlers under the delivery contract: failed handlers are retried by RetryPolicy, and a message the subscriber gives up on moves to the subscriber's own dead-letter queue. Uses a robust connection for automatic reconnection.

Attributes:

Name Type Description
connection_string str

AMQP connection string.

exchange_name str | None

Exchange subscriber queues are bound to, if configured.

connection AbstractRobustConnection

Robust RabbitMQ connection for async operations.

channel AbstractChannel

Channel for message consumption.

publish_channel AbstractChannel

Confirm-mode channel for retry and dead-letter copies.

Initialize the asynchronous RabbitMQ event consumer.

Parameters:

Name Type Description Default
config RabbitMQConnectionConfig

RabbitMQ connection configuration.

required
Source code in plugins/spakky-rabbitmq/src/spakky/plugins/rabbitmq/event/consumer.py
def __init__(self, config: RabbitMQConnectionConfig) -> None:
    """Initialize the asynchronous RabbitMQ event consumer.

    Args:
        config: RabbitMQ connection configuration.
    """
    self.connection_string = config.connection_string
    self.exchange_name = config.exchange_name
    self._retry = config.retry
    self._subscriptions = AsyncEventSubscriptions(config.retry)
    self._adapters = {}
    self._propagator = None
    self._auth_challenge_action = config.auth_challenge_action
    self._auth_deny_action = config.auth_deny_action
    self._auth_error_action = config.auth_error_action

set_propagator(propagator)

Set the trace propagator for extracting trace context from messages.

Parameters:

Name Type Description Default
propagator ITracePropagator

The trace propagator instance.

required
Source code in plugins/spakky-rabbitmq/src/spakky/plugins/rabbitmq/event/consumer.py
def set_propagator(self, propagator: ITracePropagator) -> None:
    """Set the trace propagator for extracting trace context from messages.

    Args:
        propagator: The trace propagator instance.
    """
    self._propagator = propagator

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

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

Parameters:

Name Type Description Default
event type[EventT_contra]

The event type to handle.

required
handler AsyncEventHandlerCallback[EventT_contra]

The async callback function to handle the event.

required
subscriber SubscriberName | None

Independent subscriber the handler belongs to; None is the unnamed subscriber consuming the queue named after the event.

None
handler_name HandlerName | None

Name unique within the subscription.

None
retry RetryPolicy | None

Retry the handler's class declared for its subscriber. Its attempt counts and intervals apply to that subscriber only; its mode must match the consumer's retry.mode.

None

Raises:

Type Description
SubscriberExchangeRequiredError

A named subscriber is registered while no exchange is configured.

ConflictingSubscriberRetryPolicyError

Another handler class of the subscriber declared a different retry.

SubscriberRetryModeUnsupportedError

The subscriber's retry mode differs from the consumer's retry.mode.

Source code in plugins/spakky-rabbitmq/src/spakky/plugins/rabbitmq/event/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 in the subscription of `subscriber` for `event`.

    Args:
        event: The event type to handle.
        handler: The async callback function to handle the event.
        subscriber: Independent subscriber the handler belongs to; None is
            the unnamed subscriber consuming the queue named after the event.
        handler_name: Name unique within the subscription.
        retry: Retry the handler's class declared for its subscriber. Its
            attempt counts and intervals apply to that subscriber only; its
            mode must match the consumer's `retry.mode`.

    Raises:
        SubscriberExchangeRequiredError: A named subscriber is registered
            while no exchange is configured.
        ConflictingSubscriberRetryPolicyError: Another handler class of the
            subscriber declared a different retry.
        SubscriberRetryModeUnsupportedError: The subscriber's retry mode
            differs from the consumer's `retry.mode`.
    """
    if subscriber is not None and self.exchange_name is None:
        raise SubscriberExchangeRequiredError(subscriber, event)
    self._subscriptions.register(event, handler, subscriber, handler_name, retry)
    if self._subscriptions.policy_of(subscriber).mode is not self._retry.mode:
        raise SubscriberRetryModeUnsupportedError(subscriber)
    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))

initialize_async() async

Initialize async RabbitMQ connection and declare subscriber queues.

Declares, for every subscription, the subscriber queue (bound to the exchange when one is configured), its dead-letter queue and, in delayed retry mode, its wait queue, then starts consuming.

Source code in plugins/spakky-rabbitmq/src/spakky/plugins/rabbitmq/event/consumer.py
@override
async def initialize_async(self) -> None:
    """Initialize async RabbitMQ connection and declare subscriber queues.

    Declares, for every subscription, the subscriber queue (bound to the
    exchange when one is configured), its dead-letter queue and, in
    delayed retry mode, its wait queue, then starts consuming.
    """
    self.connection = await connect_robust(self.connection_string)
    self.channel = await self.connection.channel()
    self.publish_channel = await self.connection.channel(on_return_raises=True)
    if self._retry.mode is RetryMode.BLOCKING:
        await self.channel.set_qos(prefetch_count=BLOCKING_PREFETCH_COUNT)
    exchange = (
        await self.channel.declare_exchange(self.exchange_name)
        if self.exchange_name is not None
        else None
    )

    for delivery in self._subscriptions:
        queues = self._queues(delivery)
        queue = await self.channel.declare_queue(queues.queue, durable=True)
        if exchange is not None:
            await queue.bind(exchange, EventRouting.name_of(delivery.event_type))
        await self.channel.declare_queue(queues.dead_letter_queue, durable=True)
        if self._retry.mode is RetryMode.DELAYED:
            await self.channel.declare_queue(
                queues.retry_queue,
                durable=True,
                arguments={
                    DEAD_LETTER_EXCHANGE_ARGUMENT: DEFAULT_EXCHANGE_NAME,
                    DEAD_LETTER_ROUTING_KEY_ARGUMENT: queues.queue,
                },
            )
        await queue.consume(partial(self._on_message, delivery, queues))

dispose_async() async

Clean up async RabbitMQ resources.

Closes the channel and connection when the service is stopped.

Source code in plugins/spakky-rabbitmq/src/spakky/plugins/rabbitmq/event/consumer.py
@override
async def dispose_async(self) -> None:
    """Clean up async RabbitMQ resources.

    Closes the channel and connection when the service is stopped.
    """
    await self.channel.close()
    await self.connection.close()
    return

run_async() async

Run the async event consumer loop.

Waits for the stop event to be set while consuming messages from RabbitMQ queues in the background.

Source code in plugins/spakky-rabbitmq/src/spakky/plugins/rabbitmq/event/consumer.py
@override
async def run_async(self) -> None:
    """Run the async event consumer loop.

    Waits for the stop event to be set while consuming messages from
    RabbitMQ queues in the background.
    """
    await self._stop_event.wait()

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

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

Opens a connection of its own. A dead letter that fails again is held until every stored one was taken, then replaced by a copy whose metadata lists only the handlers that failed again, so a handler that succeeded here is not run by the next redrive. Each dead letter is delivered at most once per call.

Raises:

Type Description
SubscriptionNotFoundError

Nothing is registered for the pair.

Source code in plugins/spakky-rabbitmq/src/spakky/plugins/rabbitmq/event/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.

    Opens a connection of its own. A dead letter that fails again is held
    until every stored one was taken, then replaced by a copy whose
    metadata lists only the handlers that failed again, so a handler that
    succeeded here is not run by the next redrive. Each dead letter is
    delivered at most once per call.

    Raises:
        SubscriptionNotFoundError: Nothing is registered for the pair.
    """
    delivery = self._subscriptions.get(subscriber, event)
    queues = self._queues(delivery)
    async with await connect_robust(self.connection_string) as connection:
        channel = await connection.channel()
        publish_channel = await connection.channel(on_return_raises=True)
        queue = await channel.declare_queue(queues.dead_letter_queue, durable=True)
        succeeded = 0
        kept: list[tuple[AbstractIncomingMessage, dict[str, str]]] = []
        while limit is None or succeeded + len(kept) < limit:
            message = await queue.get(fail=False)
            if message is None:
                # 큐에 더 남은 dead letter가 없다.
                break
            still_dead = await self._redrive(
                delivery, self._to_string_headers(message.headers), message.body
            )
            if still_dead is None:
                await message.ack()
                succeeded += 1
                continue
            # 사본을 바로 넣으면 이 호출이 다시 꺼내게 되므로 끝까지 쥐고 있는다.
            kept.append((message, still_dead))
        for message, headers in kept:
            await self._forward(
                publish_channel,
                message,
                queues.dead_letter_queue,
                headers,
                None,
            )
        return RedriveResult(succeeded=succeeded, failed=len(kept))

구독자 큐 이름

Names of the RabbitMQ queues one subscriber owns for one event.

EventName = str

Routing identity of an event; also the routing key it is published with.

QueueName = str

Name of a RabbitMQ queue.

RabbitMQSubscriptionQueues

Bases: BaseModel

Queues that keep one subscriber's messages apart from every other one.

queue instance-attribute

Queue the subscriber consumes; bound to the exchange by the event name.

retry_queue instance-attribute

Wait queue whose expired messages return to queue only.

dead_letter_queue instance-attribute

Queue storing the messages the subscriber gave up on.

of(event_name, subscriber) classmethod

Derive the queue names of subscriber for event_name.

Parameters:

Name Type Description Default
event_name EventName

Routing identity of the event.

required
subscriber SubscriberName | None

Subscriber name; None is the unnamed subscriber, which keeps the queue named after the event alone.

required
Source code in plugins/spakky-rabbitmq/src/spakky/plugins/rabbitmq/event/topology.py
@classmethod
def of(cls, event_name: EventName, subscriber: SubscriberName | None) -> Self:
    """Derive the queue names of `subscriber` for `event_name`.

    Args:
        event_name: Routing identity of the event.
        subscriber: Subscriber name; None is the unnamed subscriber, which
            keeps the queue named after the event alone.
    """
    queue = (
        event_name
        if subscriber is None
        else f"{event_name}{SUBSCRIBER_QUEUE_SEPARATOR}{subscriber}"
    )
    return cls(
        queue=queue,
        retry_queue=f"{queue}{RETRY_QUEUE_SUFFIX}",
        dead_letter_queue=f"{queue}{DEAD_LETTER_QUEUE_SUFFIX}",
    )

에러

Errors raised by the RabbitMQ plugin.

AbstractSpakkyRabbitMQError

Bases: AbstractSpakkyFrameworkError, ABC

Base error for RabbitMQ plugin operations.

SubscriberExchangeRequiredError(subscriber, event_type)

Bases: AbstractSpakkyRabbitMQError

Raised at startup when a named subscriber is used without an exchange.

Every named subscriber owns a queue bound to the configured exchange so that each one receives its own copy of an event. The default exchange can only deliver a message to the single queue named by its routing key.

Source code in plugins/spakky-rabbitmq/src/spakky/plugins/rabbitmq/error.py
def __init__(self, subscriber: SubscriberName, event_type: type) -> None:
    self.subscriber = subscriber
    self.event_type = event_type
    super().__init__()

RabbitMQAuthRequeueError

Bases: AuthRequirementProviderUnavailableError

Raised when the auth failure policy keeps a message unacknowledged.

The delivery contract lets provider-unavailable errors leave the delivery so that the message is not acknowledged. A nack_requeue auth policy asks for exactly that, so it is signalled through the same error family.

SubscriberRetryModeUnsupportedError(subscriber)

Bases: AbstractSpakkyRabbitMQError

Raised at startup when a subscriber needs a retry mode of its own.

A RabbitMQ consumer declares its queues and its prefetch limit for one retry mode. A subscriber whose resolved retry mode differs from the consumer's retry.mode cannot get the order guarantee it declared, so the registration fails instead of silently using the consumer's mode.

Source code in plugins/spakky-rabbitmq/src/spakky/plugins/rabbitmq/error.py
def __init__(self, subscriber: SubscriberName | None) -> None:
    self.subscriber = subscriber
    super().__init__()

인증 Boundary

Auth boundary helpers for RabbitMQ consumer callbacks.

RABBITMQ_AUTH_BOUNDARY = 'rabbitmq' module-attribute

AuthInvocation boundary value used for RabbitMQ consumer handlers.

RABBITMQ_EVENT_NAME_ATTRIBUTE = 'event_name' module-attribute

AuthInvocation attribute carrying the integration event name.

RABBITMQ_SNAPSHOT_ATTRIBUTE = 'auth_context_snapshot' module-attribute

AuthInvocation attribute carrying the signed snapshot envelope.

RabbitMQAuthBoundary(application_context, snapshot_verifier)

Verify signed snapshots and seed AuthContext for RabbitMQ handlers.

Source code in plugins/spakky-rabbitmq/src/spakky/plugins/rabbitmq/auth.py
def __init__(
    self,
    application_context: IApplicationContext,
    snapshot_verifier: IAuthContextSnapshotVerifier | None,
) -> None:
    self._application_context = application_context
    self._snapshot_verifier = snapshot_verifier

seed_auth_context(*, event_type, operation, protected)

Verify the current message snapshot and seed AuthContext when needed.

Source code in plugins/spakky-rabbitmq/src/spakky/plugins/rabbitmq/auth.py
def seed_auth_context(
    self,
    *,
    event_type: type[AbstractEvent],
    operation: str,
    protected: bool,
) -> None:
    """Verify the current message snapshot and seed AuthContext when needed."""
    headers = current_rabbitmq_message_headers()
    snapshot_envelope = self._snapshot_envelope(headers)
    if snapshot_envelope is None:
        if protected:
            raise AuthRequirementDeniedError(MISSING_SNAPSHOT_DECISION)
        return
    verifier = self._snapshot_verifier
    if verifier is None:
        raise AuthRequirementDeniedError(VERIFICATION_PROVIDER_UNAVAILABLE_DECISION)
    try:
        auth_context = verifier.verify_snapshot(
            snapshot_envelope,
            self._invocation(event_type, operation, snapshot_envelope),
        )
    except MissingAuthContextSnapshotError as error:
        raise AuthRequirementDeniedError(MISSING_SNAPSHOT_DECISION) from error
    except InvalidAuthContextSnapshotError as error:
        raise AuthRequirementDeniedError(INVALID_SNAPSHOT_DECISION) from error
    except ExpiredAuthContextSnapshotError as error:
        raise AuthRequirementDeniedError(EXPIRED_SNAPSHOT_DECISION) from error
    except AuthVerificationProviderUnavailableError as error:
        raise AuthRequirementDeniedError(
            VERIFICATION_PROVIDER_UNAVAILABLE_DECISION
        ) from error
    store_auth_context(self._application_context, auth_context)

set_current_rabbitmq_message_headers(headers)

Set the message headers visible to the post-processor endpoint.

Source code in plugins/spakky-rabbitmq/src/spakky/plugins/rabbitmq/auth.py
def set_current_rabbitmq_message_headers(
    headers: Mapping[str, str],
) -> Token[Mapping[str, str] | None]:
    """Set the message headers visible to the post-processor endpoint."""
    return _current_message_headers.set(headers)

reset_current_rabbitmq_message_headers(token)

Restore the previous message header context.

Source code in plugins/spakky-rabbitmq/src/spakky/plugins/rabbitmq/auth.py
def reset_current_rabbitmq_message_headers(
    token: Token[Mapping[str, str] | None],
) -> None:
    """Restore the previous message header context."""
    _current_message_headers.reset(token)

current_rabbitmq_message_headers()

Return the active RabbitMQ message headers for this handler invocation.

Source code in plugins/spakky-rabbitmq/src/spakky/plugins/rabbitmq/auth.py
def current_rabbitmq_message_headers() -> Mapping[str, str]:
    """Return the active RabbitMQ message headers for this handler invocation."""
    headers = _current_message_headers.get()
    if headers is None:
        return {}
    return headers

설정

Configuration for RabbitMQ connections.

Provides configuration dataclass for RabbitMQ connection parameters including host, port, credentials, and exchange settings.

RabbitMQAuthFailureAction

Bases: StrEnum

Ack/nack action used when a protected RabbitMQ handler fails auth.

ACK = 'ack' class-attribute instance-attribute

Acknowledge and drop the message.

NACK_REQUEUE = 'nack_requeue' class-attribute instance-attribute

Negative-acknowledge and requeue the message.

NACK_DROP = 'nack_drop' class-attribute instance-attribute

Negative-acknowledge without requeueing the message.

RabbitMQConnectionConfig()

Bases: BaseSettings

Configuration for RabbitMQ connection.

Stores connection parameters and provides a formatted connection string for establishing RabbitMQ connections.

Attributes:

Name Type Description
host str

RabbitMQ server hostname.

port int

RabbitMQ server port.

user str

Username for authentication.

password str

Password for authentication.

exchange_name str | None

Optional exchange name for pub/sub routing.

declare_default_queue bool

Whether transports declare the unnamed queue.

retry RetryPolicy

Retry policy applied to every subscriber independently.

Source code in plugins/spakky-rabbitmq/src/spakky/plugins/rabbitmq/common/config.py
def __init__(self) -> None:
    super().__init__()

use_ssl instance-attribute

Flag indicating whether to use SSL for the connection.

host instance-attribute

RabbitMQ server hostname or IP address.

port instance-attribute

RabbitMQ server port number.

user instance-attribute

Username for RabbitMQ authentication.

password instance-attribute

Password for RabbitMQ authentication.

exchange_name = None class-attribute instance-attribute

Optional exchange name for pub/sub message routing.

None publishes through the default exchange, which reaches only the queue named after the event. Named subscribers require an exchange.

declare_default_queue = True class-attribute instance-attribute

Whether transports declare (and bind) the queue named after the event.

That queue belongs to the unnamed subscriber. Turn it off when every consumer of the published events is a named subscriber; otherwise the queue would only accumulate messages nobody consumes.

retry = RetryPolicy() class-attribute instance-attribute

Retry limits, spacing and mode applied to each subscriber queue.

auth_challenge_action = RabbitMQAuthFailureAction.ACK class-attribute instance-attribute

Message action for missing, invalid, or expired snapshot decisions.

auth_deny_action = RabbitMQAuthFailureAction.ACK class-attribute instance-attribute

Message action for explicit DENY decisions from protected handlers.

auth_error_action = RabbitMQAuthFailureAction.NACK_REQUEUE class-attribute instance-attribute

Message action for retryable provider ERROR decisions.

protocol property

Determine protocol based on SSL usage.

Returns:

Type Description
str

'amqps' if SSL is enabled, otherwise 'amqp'.

connection_string property

Generate AMQP connection string from configuration.

Returns:

Type Description
str

Formatted AMQP connection string with credentials and host information.

후처리기

Post-processor for registering RabbitMQ event handlers.

Automatically discovers and registers event handlers from @EventHandler decorated classes, connecting them to RabbitMQ consumers with dependency injection.

RabbitMQPostProcessor

Bases: IPostProcessor, IContainerAware, IApplicationContextAware

Post-processor that registers event handlers with RabbitMQ consumers.

Scans @EventHandler decorated classes for @event decorated methods and automatically registers them with the appropriate RabbitMQ consumer (sync or async) with proper dependency injection.

set_container(container)

Set the container for dependency injection.

Parameters:

Name Type Description Default
container IContainer

The IoC container.

required
Source code in plugins/spakky-rabbitmq/src/spakky/plugins/rabbitmq/post_processor.py
@override
def set_container(self, container: IContainer) -> None:
    """Set the container for dependency injection.

    Args:
        container: The IoC container.
    """
    self.__container = container

set_application_context(application_context)

Set the application context.

Parameters:

Name Type Description Default
application_context IApplicationContext

The application context instance.

required
Source code in plugins/spakky-rabbitmq/src/spakky/plugins/rabbitmq/post_processor.py
@override
def set_application_context(self, application_context: IApplicationContext) -> None:
    """Set the application context.

    Args:
        application_context: The application context instance.
    """
    self.__application_context = application_context

post_process(pod)

Register event handlers from event handler classes.

Reads the @on_event methods declared on the event handler class, so that handlers advised by an aspect (whose Pod is an AOP proxy) are registered too, and registers each with the sync or async consumer.

Parameters:

Name Type Description Default
pod object

The Pod to process, potentially an event handler.

required

Returns:

Type Description
object

The Pod, with event handlers registered if it's an event handler.

Source code in plugins/spakky-rabbitmq/src/spakky/plugins/rabbitmq/post_processor.py
@override
def post_process(self, pod: object) -> object:
    """Register event handlers from event handler classes.

    Reads the @on_event methods declared on the event handler class, so
    that handlers advised by an aspect (whose Pod is an AOP proxy) are
    registered too, and registers each with the sync or async consumer.

    Args:
        pod: The Pod to process, potentially an event handler.

    Returns:
        The Pod, with event handlers registered if it's an event handler.
    """
    if not EventHandler.exists(pod):
        return pod
    handler: EventHandler = EventHandler.get(pod)
    consumer = self.__container.get(RabbitMQEventConsumer)
    async_consumer = self.__container.get(AsyncRabbitMQEventConsumer)
    auth_boundary = RabbitMQAuthBoundary(
        self.__application_context,
        self.__container.get_or_none(IAuthContextSnapshotVerifier),
    )
    propagator = self.__application_context.get_or_none(ITracePropagator)
    if propagator is not None:
        # 프레임워크 내부: consumer 인터페이스가 선택적 propagator를 지원하는지 확인
        if hasattr(consumer, "set_propagator"):  # optional tracing bridge injection
            consumer.set_propagator(propagator)
        # 프레임워크 내부: consumer 인터페이스가 선택적 propagator를 지원하는지 확인
        if hasattr(  # optional tracing bridge injection
            async_consumer, "set_propagator"
        ):
            async_consumer.set_propagator(propagator)
    for declared in handler.routes():
        route = declared.route
        name = declared.method_name
        if not issubclass(route.event_type, AbstractIntegrationEvent):
            continue
        # 프레임워크 내부: 선언된 핸들러 함수의 메타데이터 조회. Pod 인스턴스는
        # AOP proxy일 수 있어 클래스에서 읽는다.
        method = getattr(  # declared handler function lookup
            handler.type_, name
        )
        auth_metadata = get_effective_auth_metadata(
            method,
            owner_type=handler.type_,
        )

        handler_name = declared.handler_name

        # pylint: disable=line-too-long
        logger.info(
            f"[{type(self).__name__}] {route.event_type.__name__} -> {method.__qualname__} (subscriber {handler.subscriber!r})"
        )

        if declared.asynchronous:

            @wraps(method)
            async def async_endpoint(
                *args: Any,
                method_name: str = name,
                controller_type: type[object] = handler.type_,
                event_type: type[AbstractEvent] = route.event_type,
                protected: bool = auth_metadata.protected,
                context: IContainer = self.__container,
                **kwargs: Any,
            ) -> Any:
                # Each message is handled in isolation, so clear the
                # application context to avoid reusing dependency state.
                self.__application_context.clear_context()
                auth_boundary.seed_auth_context(
                    event_type=event_type,
                    operation=f"{controller_type.__module__}.{controller_type.__qualname__}.{method_name}",
                    protected=protected,
                )
                controller_instance = context.get(controller_type)
                # 프레임워크 내부: 컨트롤러 메서드 동적 디스패치
                method_to_call = getattr(  # event handler method lookup
                    controller_instance, method_name
                )
                return await method_to_call(*args, **kwargs)

            async_consumer.register(
                route.event_type,
                async_endpoint,
                subscriber=handler.subscriber,
                handler_name=handler_name,
                retry=handler.retry,
            )
            continue

        @wraps(method)
        def endpoint(
            *args: Any,
            method_name: str = name,
            controller_type: type[object] = handler.type_,
            event_type: type[AbstractEvent] = route.event_type,
            protected: bool = auth_metadata.protected,
            context: IContainer = self.__container,
            **kwargs: Any,
        ) -> Any:
            # Synchronous consumers share threads, so drop any lingering
            # scoped data before invoking the handler.
            self.__application_context.clear_context()
            auth_boundary.seed_auth_context(
                event_type=event_type,
                operation=f"{controller_type.__module__}.{controller_type.__qualname__}.{method_name}",
                protected=protected,
            )
            controller_instance = context.get(controller_type)
            # 프레임워크 내부: 컨트롤러 메서드 동적 디스패치
            method_to_call = getattr(  # async event handler method lookup
                controller_instance, method_name
            )
            return method_to_call(*args, **kwargs)

        consumer.register(
            route.event_type,
            endpoint,
            subscriber=handler.subscriber,
            handler_name=handler_name,
            retry=handler.retry,
        )
    return pod

추가 모듈

SUBSCRIBER_QUEUE_SEPARATOR = '.' module-attribute

Separator between an event name and the subscriber that owns the queue.

RETRY_QUEUE_SUFFIX = '.retry' module-attribute

Suffix of the wait queue that holds a subscriber's delayed retries.

DEAD_LETTER_QUEUE_SUFFIX = '.dlq' module-attribute

Suffix of the queue that stores a subscriber's dead letters.

DEFAULT_EXCHANGE_NAME = '' module-attribute

AMQP default exchange: routes a message to the queue named by its routing key.

DEAD_LETTER_EXCHANGE_ARGUMENT = 'x-dead-letter-exchange' module-attribute

Queue argument naming the exchange expired messages are republished to.

DEAD_LETTER_ROUTING_KEY_ARGUMENT = 'x-dead-letter-routing-key' module-attribute

Queue argument naming the routing key expired messages are republished with.

BLOCKING_PREFETCH_COUNT = 1 module-attribute

Unacknowledged messages allowed per queue while retries block the queue.

PERSISTENT_DELIVERY_MODE = 2 module-attribute

AMQP delivery mode that survives a broker restart in a durable queue.

MILLISECONDS_PER_SECOND = 1000 module-attribute

Factor between RetryPolicy seconds and AMQP expiration milliseconds.