콘텐츠로 이동

spakky-outbox

spakky-outbox는 Integration Event를 비즈니스 데이터와 같은 transaction에 원자적으로 기록하고 별도 Relay로 전송하기 위한 계약을 제공합니다. 브로커가 수락 가능한 레코드는 확인될 때까지 재전송되지만, 영구적인 레코드 귀속 거부는 retry 소진 후 성공 전달 없이 abandoned 처리될 수 있습니다.

Outbox 패턴 — 원자적 기록과 Relay 상태 계약

플러그인 진입점

Plugin initialization entry point.

initialize(app)

Initialize the Outbox plugin.

Parameters:

Name Type Description Default
app SpakkyApplication

The Spakky application instance.

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

    Args:
        app: The Spakky application instance.
    """
    app.add(OutboxConfig)
    app.add(OutboxRelayWakeup)
    app.add(OutboxEventBus)
    app.add(AsyncOutboxEventBus)
    app.add(OutboxRelayBackgroundService)
    app.add(AsyncOutboxRelayBackgroundService)

EventBus

Outbox Event Bus — sync and async implementations replacing IEventBus/IAsyncEventBus via @Primary.

OutboxEventBus(storage, propagator, synchronization, wakeup, auth_snapshot_headers=None)

Bases: IEventBus

Intercepts integration events and stores them in the Outbox table (sync).

Replaces the default DirectEventBus so that events are persisted atomically within the same database transaction as the business data.

Source code in core/spakky-outbox/src/spakky/outbox/bus/outbox_event_bus.py
def __init__(
    self,
    storage: IOutboxStorage,
    propagator: ITracePropagator,
    synchronization: TransactionSynchronization,
    wakeup: OutboxRelayWakeup,
    auth_snapshot_headers: AuthContextSnapshotHeaderInjector | None = None,
) -> None:
    self._storage = storage
    self._propagator = propagator
    self._synchronization = synchronization
    self._wakeup = wakeup
    self._auth_snapshot_headers = (
        auth_snapshot_headers or AuthContextSnapshotHeaderInjector()
    )

__wake_relay_after_commit()

Have the relays send this message as soon as its transaction commits.

Outside a @Transactional call there is no commit to wait for; the message is then sent by the relay's next poll.

Source code in core/spakky-outbox/src/spakky/outbox/bus/outbox_event_bus.py
def __wake_relay_after_commit(self) -> None:
    """Have the relays send this message as soon as its transaction commits.

    Outside a `@Transactional` call there is no commit to wait for; the
    message is then sent by the relay's next poll.
    """
    if not self._synchronization.is_active:
        return
    self._synchronization.register_after_commit(self._wakeup.notify)

AsyncOutboxEventBus(storage, propagator, synchronization, wakeup, auth_snapshot_headers=None)

Bases: IAsyncEventBus

Intercepts integration events and stores them in the Outbox table (async).

Replaces the default AsyncDirectEventBus so that events are persisted atomically within the same database transaction as the business data.

Source code in core/spakky-outbox/src/spakky/outbox/bus/outbox_event_bus.py
def __init__(
    self,
    storage: IAsyncOutboxStorage,
    propagator: ITracePropagator,
    synchronization: TransactionSynchronization,
    wakeup: OutboxRelayWakeup,
    auth_snapshot_headers: AuthContextSnapshotHeaderInjector | None = None,
) -> None:
    self._storage = storage
    self._propagator = propagator
    self._synchronization = synchronization
    self._wakeup = wakeup
    self._auth_snapshot_headers = (
        auth_snapshot_headers or AuthContextSnapshotHeaderInjector()
    )

__wake_relay_after_commit()

Have the relays send this message as soon as its transaction commits.

Outside a @Transactional call there is no commit to wait for; the message is then sent by the relay's next poll.

Source code in core/spakky-outbox/src/spakky/outbox/bus/outbox_event_bus.py
def __wake_relay_after_commit(self) -> None:
    """Have the relays send this message as soon as its transaction commits.

    Outside a `@Transactional` call there is no commit to wait for; the
    message is then sent by the relay's next poll.
    """
    if not self._synchronization.is_active:
        return
    self._synchronization.register_after_commit(self._wakeup.notify)

포트

Outbox storage port.

IOutboxStorage

Bases: ABC

Synchronous outbox message storage abstraction.

save(message) abstractmethod

Save message within the current transaction.

Source code in core/spakky-outbox/src/spakky/outbox/ports/storage.py
@abstractmethod
def save(self, message: OutboxMessage) -> None:
    """Save message within the current transaction."""

fetch_pending(limit, max_retry) abstractmethod

Claim unpublished messages for this relay instance (with lock).

A partition key must be claimed whole: an implementation may only hand out messages of a key when it also claims that key's oldest message that is neither published nor abandoned. Otherwise two relay instances publish one key in parallel and lose the ordering the key exists to provide. Messages without a partition key carry no such constraint.

Source code in core/spakky-outbox/src/spakky/outbox/ports/storage.py
@abstractmethod
def fetch_pending(self, limit: int, max_retry: int) -> list[OutboxMessage]:
    """Claim unpublished messages for this relay instance (with lock).

    A partition key must be claimed whole: an implementation may only hand
    out messages of a key when it also claims that key's oldest message that
    is neither published nor abandoned. Otherwise two relay instances
    publish one key in parallel and lose the ordering the key exists to
    provide. Messages without a partition key carry no such constraint.
    """

mark_published(message_id) abstractmethod

Mark a message as published.

Source code in core/spakky-outbox/src/spakky/outbox/ports/storage.py
@abstractmethod
def mark_published(self, message_id: UUID) -> None:
    """Mark a message as published."""

increment_retry(message_id) abstractmethod

Increment the retry count of a message.

Source code in core/spakky-outbox/src/spakky/outbox/ports/storage.py
@abstractmethod
def increment_retry(self, message_id: UUID) -> None:
    """Increment the retry count of a message."""

mark_abandoned(message_id) abstractmethod

Record that the relay gave up on a message after exhausting retries.

The message leaves the pending queue without being published, so a partition key never waits forever on a message that will not be retried again. An implementation must keep the record and the reason readable — the operator has to be able to find what was dropped.

Source code in core/spakky-outbox/src/spakky/outbox/ports/storage.py
@abstractmethod
def mark_abandoned(self, message_id: UUID) -> None:
    """Record that the relay gave up on a message after exhausting retries.

    The message leaves the pending queue without being published, so a
    partition key never waits forever on a message that will not be retried
    again. An implementation must keep the record and the reason readable —
    the operator has to be able to find what was dropped.
    """

release_claim(message) abstractmethod

Give up this relay's claim on a message it did not publish.

Called when sending the message failed, so the next read can hand it out again instead of waiting for claim_timeout_seconds to expire. Only the claim is cleared: the retry count, a published message and an abandoned message stay as they are.

The claim is released only while it is still the one fetch_pending handed out, identified by message.claimed_at. A relay that stalled past claim_timeout_seconds may find the message claimed again by another instance; clearing that newer claim would let a third read send it in parallel and break the partition key ordering.

Parameters:

Name Type Description Default
message OutboxMessage

The message as returned by fetch_pending.

required
Source code in core/spakky-outbox/src/spakky/outbox/ports/storage.py
@abstractmethod
def release_claim(self, message: OutboxMessage) -> None:
    """Give up this relay's claim on a message it did not publish.

    Called when sending the message failed, so the next read can hand it
    out again instead of waiting for `claim_timeout_seconds` to expire.
    Only the claim is cleared: the retry count, a published message and an
    abandoned message stay as they are.

    The claim is released only while it is still the one `fetch_pending`
    handed out, identified by `message.claimed_at`. A relay that stalled
    past `claim_timeout_seconds` may find the message claimed again by
    another instance; clearing that newer claim would let a third read
    send it in parallel and break the partition key ordering.

    Args:
        message: The message as returned by `fetch_pending`.
    """

purge_published(older_than) abstractmethod

Delete messages published before older_than and return how many.

Only published messages are removed. A message still awaiting delivery and a message the relay abandoned both stay, whatever their age: the first is still owed to the broker and the second is the operator's record of what was dropped.

Parameters:

Name Type Description Default
older_than datetime

Messages whose published_at is earlier than this are deleted. Use a timezone-aware datetime.

required

Returns:

Type Description
int

Number of deleted messages.

Source code in core/spakky-outbox/src/spakky/outbox/ports/storage.py
@abstractmethod
def purge_published(self, older_than: datetime) -> int:
    """Delete messages published before `older_than` and return how many.

    Only published messages are removed. A message still awaiting delivery
    and a message the relay abandoned both stay, whatever their age: the
    first is still owed to the broker and the second is the operator's
    record of what was dropped.

    Args:
        older_than: Messages whose `published_at` is earlier than this are
            deleted. Use a timezone-aware datetime.

    Returns:
        Number of deleted messages.
    """

IAsyncOutboxStorage

Bases: ABC

Asynchronous outbox message storage abstraction.

save(message) abstractmethod async

Save message within the current transaction.

Source code in core/spakky-outbox/src/spakky/outbox/ports/storage.py
@abstractmethod
async def save(self, message: OutboxMessage) -> None:
    """Save message within the current transaction."""

fetch_pending(limit, max_retry) abstractmethod async

Claim unpublished messages for this relay instance (with lock).

A partition key must be claimed whole: an implementation may only hand out messages of a key when it also claims that key's oldest message that is neither published nor abandoned. Otherwise two relay instances publish one key in parallel and lose the ordering the key exists to provide. Messages without a partition key carry no such constraint.

Source code in core/spakky-outbox/src/spakky/outbox/ports/storage.py
@abstractmethod
async def fetch_pending(self, limit: int, max_retry: int) -> list[OutboxMessage]:
    """Claim unpublished messages for this relay instance (with lock).

    A partition key must be claimed whole: an implementation may only hand
    out messages of a key when it also claims that key's oldest message that
    is neither published nor abandoned. Otherwise two relay instances
    publish one key in parallel and lose the ordering the key exists to
    provide. Messages without a partition key carry no such constraint.
    """

mark_published(message_id) abstractmethod async

Mark a message as published.

Source code in core/spakky-outbox/src/spakky/outbox/ports/storage.py
@abstractmethod
async def mark_published(self, message_id: UUID) -> None:
    """Mark a message as published."""

increment_retry(message_id) abstractmethod async

Increment the retry count of a message.

Source code in core/spakky-outbox/src/spakky/outbox/ports/storage.py
@abstractmethod
async def increment_retry(self, message_id: UUID) -> None:
    """Increment the retry count of a message."""

mark_abandoned(message_id) abstractmethod async

Record that the relay gave up on a message after exhausting retries.

The message leaves the pending queue without being published, so a partition key never waits forever on a message that will not be retried again. An implementation must keep the record and the reason readable — the operator has to be able to find what was dropped.

Source code in core/spakky-outbox/src/spakky/outbox/ports/storage.py
@abstractmethod
async def mark_abandoned(self, message_id: UUID) -> None:
    """Record that the relay gave up on a message after exhausting retries.

    The message leaves the pending queue without being published, so a
    partition key never waits forever on a message that will not be retried
    again. An implementation must keep the record and the reason readable —
    the operator has to be able to find what was dropped.
    """

release_claim(message) abstractmethod async

Give up this relay's claim on a message it did not publish.

Called when sending the message failed, so the next read can hand it out again instead of waiting for claim_timeout_seconds to expire. Only the claim is cleared: the retry count, a published message and an abandoned message stay as they are.

The claim is released only while it is still the one fetch_pending handed out, identified by message.claimed_at. A relay that stalled past claim_timeout_seconds may find the message claimed again by another instance; clearing that newer claim would let a third read send it in parallel and break the partition key ordering.

Parameters:

Name Type Description Default
message OutboxMessage

The message as returned by fetch_pending.

required
Source code in core/spakky-outbox/src/spakky/outbox/ports/storage.py
@abstractmethod
async def release_claim(self, message: OutboxMessage) -> None:
    """Give up this relay's claim on a message it did not publish.

    Called when sending the message failed, so the next read can hand it
    out again instead of waiting for `claim_timeout_seconds` to expire.
    Only the claim is cleared: the retry count, a published message and an
    abandoned message stay as they are.

    The claim is released only while it is still the one `fetch_pending`
    handed out, identified by `message.claimed_at`. A relay that stalled
    past `claim_timeout_seconds` may find the message claimed again by
    another instance; clearing that newer claim would let a third read
    send it in parallel and break the partition key ordering.

    Args:
        message: The message as returned by `fetch_pending`.
    """

purge_published(older_than) abstractmethod async

Delete messages published before older_than and return how many.

Only published messages are removed. A message still awaiting delivery and a message the relay abandoned both stay, whatever their age: the first is still owed to the broker and the second is the operator's record of what was dropped.

Parameters:

Name Type Description Default
older_than datetime

Messages whose published_at is earlier than this are deleted. Use a timezone-aware datetime.

required

Returns:

Type Description
int

Number of deleted messages.

Source code in core/spakky-outbox/src/spakky/outbox/ports/storage.py
@abstractmethod
async def purge_published(self, older_than: datetime) -> int:
    """Delete messages published before `older_than` and return how many.

    Only published messages are removed. A message still awaiting delivery
    and a message the relay abandoned both stay, whatever their age: the
    first is still owed to the broker and the second is the operator's
    record of what was dropped.

    Args:
        older_than: Messages whose `published_at` is earlier than this are
            deleted. Use a timezone-aware datetime.

    Returns:
        Number of deleted messages.
    """

Relay

Outbox relay module.

Outbox Relay Background Services (sync and async).

OutboxRelayBackgroundService(storage, transport, config, wakeup)

Bases: AbstractBackgroundService

Relays pending Outbox messages to the transport (sync).

The relay reads the outbox as soon as a transaction that stored messages commits, and every polling_interval_seconds to recover what an earlier read could not send.

Initialize with storage, transport, config, and wakeup dependencies.

Source code in core/spakky-outbox/src/spakky/outbox/relay/relay.py
def __init__(
    self,
    storage: IOutboxStorage,
    transport: IEventTransport,
    config: OutboxConfig,
    wakeup: OutboxRelayWakeup,
) -> None:
    """Initialize with storage, transport, config, and wakeup dependencies."""
    self._storage = storage
    self._transport = transport
    self._config = config
    self._wakeup = wakeup
    self._wake_event = Event()

initialize()

Start listening for commits that stored outbox messages.

Source code in core/spakky-outbox/src/spakky/outbox/relay/relay.py
@override
def initialize(self) -> None:
    """Start listening for commits that stored outbox messages."""
    self._wakeup.subscribe(self.wake)

dispose()

Stop listening for commits.

Source code in core/spakky-outbox/src/spakky/outbox/relay/relay.py
@override
def dispose(self) -> None:
    """Stop listening for commits."""
    self._wakeup.unsubscribe(self.wake)

stop()

Stop the relay without waiting for the current polling interval.

Source code in core/spakky-outbox/src/spakky/outbox/relay/relay.py
@override
def stop(self) -> None:
    """Stop the relay without waiting for the current polling interval."""
    self._stop_event.set()
    self._wake_event.set()
    super().stop()

wake()

Read the outbox now instead of at the next poll. Thread-safe.

Source code in core/spakky-outbox/src/spakky/outbox/relay/relay.py
def wake(self) -> None:
    """Read the outbox now instead of at the next poll. Thread-safe."""
    self._wake_event.set()

run()

Relay pending messages on every wake-up and poll until stopped.

A failing read is logged and the loop goes on, so one database error does not stop delivery until the service restarts.

Source code in core/spakky-outbox/src/spakky/outbox/relay/relay.py
@override
def run(self) -> None:
    """Relay pending messages on every wake-up and poll until stopped.

    A failing read is logged and the loop goes on, so one database error
    does not stop delivery until the service restarts.
    """
    while True:
        self._wake_event.clear()
        if self._stop_event.is_set():
            return
        try:
            self._relay_batch()
        except Exception:
            logger.exception("Outbox relay batch failed; retrying at next poll")
        self._wake_event.wait(timeout=self._config.polling_interval_seconds)

__register_refusal(message, halted_partition_keys, settled_ids)

Spend one retry on a refused message, or abandon it when none is left.

A message whose budget is spent will never be fetched again, so it is abandoned rather than left behind: that releases its partition key, which would otherwise wait forever on a message nobody will retry, and keeps the record findable. A message that still has budget holds its key back until it is delivered, so nothing of that key overtakes it.

Source code in core/spakky-outbox/src/spakky/outbox/relay/relay.py
def __register_refusal(
    self,
    message: OutboxMessage,
    halted_partition_keys: set[str],
    settled_ids: set[UUID],
) -> None:
    """Spend one retry on a refused message, or abandon it when none is left.

    A message whose budget is spent will never be fetched again, so it is
    abandoned rather than left behind: that releases its partition key,
    which would otherwise wait forever on a message nobody will retry, and
    keeps the record findable. A message that still has budget holds its key
    back until it is delivered, so nothing of that key overtakes it.
    """
    if message.retry_count + 1 >= self._config.max_retry_count:
        self._storage.mark_abandoned(message.id)
        settled_ids.add(message.id)
        return
    self._storage.increment_retry(message.id)
    if message.partition_key is not None:
        halted_partition_keys.add(message.partition_key)

__publish_one_at_a_time(messages, halted_partition_keys, settled_ids)

Replay a batch whose flush failed, confirming one message at a time.

A batch flush reports that the broker refused something but not what, so neither the retry budget nor the partition key hold-back can be aimed without replaying. Confirming one message per flush puts the broker's verdict on the message that earned it: the refused message spends its budget and holds back the rest of its key, while its neighbours publish. Only a refusal counts — a transport that cannot reach the broker at all stops the replay untouched, because an outage is no message's fault. The replay can re-deliver a record the failed flush had already accepted — delivery stays at-least-once, which consumers already assume.

Source code in core/spakky-outbox/src/spakky/outbox/relay/relay.py
def __publish_one_at_a_time(
    self,
    messages: list[OutboxMessage],
    halted_partition_keys: set[str],
    settled_ids: set[UUID],
) -> None:
    """Replay a batch whose flush failed, confirming one message at a time.

    A batch flush reports that the broker refused something but not what, so
    neither the retry budget nor the partition key hold-back can be aimed
    without replaying. Confirming one message per flush puts the broker's
    verdict on the message that earned it: the refused message spends its
    budget and holds back the rest of its key, while its neighbours publish.
    Only a refusal counts — a transport that cannot reach the broker at all
    stops the replay untouched, because an outage is no message's fault.
    The replay can re-deliver a record the failed flush had already accepted
    — delivery stays at-least-once, which consumers already assume.
    """
    for message in messages:
        if message.partition_key in halted_partition_keys:
            continue
        try:
            self._transport.send(
                message.event_name,
                message.payload,
                message.headers,
                message.partition_key,
            )
            self._transport.flush()
        except EventDeliveryRejectedError:
            logger.exception("Broker refused outbox message %s", message.id)
            self.__register_refusal(message, halted_partition_keys, settled_ids)
            continue
        except Exception:
            # The transport itself is failing — a closed client, a lost
            # connection, a timeout. That is no single message's fault, so
            # the rest of the batch is left pending instead of spending
            # budgets that would abandon healthy messages during an outage.
            logger.exception(
                "Transport failed while confirming outbox message %s",
                message.id,
            )
            return
        self._storage.mark_published(message.id)
        settled_ids.add(message.id)

__release_unsettled(messages, settled_ids)

Release the claims of the messages this read did not settle.

A message that was neither published nor abandoned — refused with budget left, held back behind its partition key, or caught in a transport failure — goes back to the queue right away, so the next read sends it again instead of waiting for the claim to time out.

Source code in core/spakky-outbox/src/spakky/outbox/relay/relay.py
def __release_unsettled(
    self,
    messages: list[OutboxMessage],
    settled_ids: set[UUID],
) -> None:
    """Release the claims of the messages this read did not settle.

    A message that was neither published nor abandoned — refused with
    budget left, held back behind its partition key, or caught in a
    transport failure — goes back to the queue right away, so the next
    read sends it again instead of waiting for the claim to time out.
    """
    # A failing release must not hide the error or cancellation that ended
    # the read; the claims it could not clear expire after the timeout.
    try:
        for message in messages:
            if message.id not in settled_ids:
                self._storage.release_claim(message)
    except Exception:
        logger.exception("Failed to release outbox claims; they expire later")

AsyncOutboxRelayBackgroundService(storage, transport, config, wakeup)

Bases: AbstractAsyncBackgroundService

Relays pending Outbox messages to the transport (async).

The relay reads the outbox as soon as a transaction that stored messages commits, and every polling_interval_seconds to recover what an earlier read could not send.

Initialize with async storage, transport, config, and wakeup dependencies.

Source code in core/spakky-outbox/src/spakky/outbox/relay/relay.py
def __init__(
    self,
    storage: IAsyncOutboxStorage,
    transport: IAsyncEventTransport,
    config: OutboxConfig,
    wakeup: OutboxRelayWakeup,
) -> None:
    """Initialize with async storage, transport, config, and wakeup dependencies."""
    self._storage = storage
    self._transport = transport
    self._config = config
    self._wakeup = wakeup
    self._wake_event = AsyncEvent()
    self._loop = None

initialize_async() async

Start listening for commits that stored outbox messages.

Source code in core/spakky-outbox/src/spakky/outbox/relay/relay.py
@override
async def initialize_async(self) -> None:
    """Start listening for commits that stored outbox messages."""
    self._loop = get_running_loop()
    self._wake_event = AsyncEvent()
    self._wakeup.subscribe(self.wake)

dispose_async() async

Stop listening for commits.

Source code in core/spakky-outbox/src/spakky/outbox/relay/relay.py
@override
async def dispose_async(self) -> None:
    """Stop listening for commits."""
    self._wakeup.unsubscribe(self.wake)
    self._loop = None

stop_async() async

Stop the relay without waiting for the current polling interval.

Source code in core/spakky-outbox/src/spakky/outbox/relay/relay.py
@override
async def stop_async(self) -> None:
    """Stop the relay without waiting for the current polling interval."""
    self._stop_event.set()
    self._wake_event.set()
    await super().stop_async()

wake()

Read the outbox now instead of at the next poll.

Safe to call from any thread: a commit in synchronous code running on a worker thread wakes the relay on its own event loop. Before the relay starts there is no loop to wake, and its first read picks the message up.

Source code in core/spakky-outbox/src/spakky/outbox/relay/relay.py
def wake(self) -> None:
    """Read the outbox now instead of at the next poll.

    Safe to call from any thread: a commit in synchronous code running on
    a worker thread wakes the relay on its own event loop. Before the relay
    starts there is no loop to wake, and its first read picks the message up.
    """
    if self._loop is None:
        return
    self._loop.call_soon_threadsafe(self._wake_event.set)

run_async() async

Relay pending messages on every wake-up and poll until stopped.

A failing read is logged and the loop goes on, so one database error does not stop delivery until the service restarts.

Source code in core/spakky-outbox/src/spakky/outbox/relay/relay.py
@override
async def run_async(self) -> None:
    """Relay pending messages on every wake-up and poll until stopped.

    A failing read is logged and the loop goes on, so one database error
    does not stop delivery until the service restarts.
    """
    while True:
        self._wake_event.clear()
        if self._stop_event.is_set():
            return
        try:
            await self._relay_batch()
        except Exception:
            logger.exception("Outbox relay batch failed; retrying at next poll")
        try:
            await wait_for(
                self._wake_event.wait(),
                timeout=self._config.polling_interval_seconds,
            )
        except TimeoutError:
            continue

__register_refusal(message, halted_partition_keys, settled_ids) async

Spend one retry on a refused message, or abandon it when none is left.

A message whose budget is spent will never be fetched again, so it is abandoned rather than left behind: that releases its partition key, which would otherwise wait forever on a message nobody will retry, and keeps the record findable. A message that still has budget holds its key back until it is delivered, so nothing of that key overtakes it.

Source code in core/spakky-outbox/src/spakky/outbox/relay/relay.py
async def __register_refusal(
    self,
    message: OutboxMessage,
    halted_partition_keys: set[str],
    settled_ids: set[UUID],
) -> None:
    """Spend one retry on a refused message, or abandon it when none is left.

    A message whose budget is spent will never be fetched again, so it is
    abandoned rather than left behind: that releases its partition key,
    which would otherwise wait forever on a message nobody will retry, and
    keeps the record findable. A message that still has budget holds its key
    back until it is delivered, so nothing of that key overtakes it.
    """
    if message.retry_count + 1 >= self._config.max_retry_count:
        await self._storage.mark_abandoned(message.id)
        settled_ids.add(message.id)
        return
    await self._storage.increment_retry(message.id)
    if message.partition_key is not None:
        halted_partition_keys.add(message.partition_key)

__publish_one_at_a_time(messages, halted_partition_keys, settled_ids) async

Replay a batch whose flush failed, confirming one message at a time.

A batch flush reports that the broker refused something but not what, so neither the retry budget nor the partition key hold-back can be aimed without replaying. Confirming one message per flush puts the broker's verdict on the message that earned it: the refused message spends its budget and holds back the rest of its key, while its neighbours publish. Only a refusal counts — a transport that cannot reach the broker at all stops the replay untouched, because an outage is no message's fault. The replay can re-deliver a record the failed flush had already accepted — delivery stays at-least-once, which consumers already assume.

Source code in core/spakky-outbox/src/spakky/outbox/relay/relay.py
async def __publish_one_at_a_time(
    self,
    messages: list[OutboxMessage],
    halted_partition_keys: set[str],
    settled_ids: set[UUID],
) -> None:
    """Replay a batch whose flush failed, confirming one message at a time.

    A batch flush reports that the broker refused something but not what, so
    neither the retry budget nor the partition key hold-back can be aimed
    without replaying. Confirming one message per flush puts the broker's
    verdict on the message that earned it: the refused message spends its
    budget and holds back the rest of its key, while its neighbours publish.
    Only a refusal counts — a transport that cannot reach the broker at all
    stops the replay untouched, because an outage is no message's fault.
    The replay can re-deliver a record the failed flush had already accepted
    — delivery stays at-least-once, which consumers already assume.
    """
    for message in messages:
        if message.partition_key in halted_partition_keys:
            continue
        try:
            await self._transport.send(
                message.event_name,
                message.payload,
                message.headers,
                message.partition_key,
            )
            await self._transport.flush()
        except EventDeliveryRejectedError:
            logger.exception("Broker refused outbox message %s", message.id)
            await self.__register_refusal(
                message, halted_partition_keys, settled_ids
            )
            continue
        except Exception:
            # The transport itself is failing — a closed client, a lost
            # connection, a timeout. That is no single message's fault, so
            # the rest of the batch is left pending instead of spending
            # budgets that would abandon healthy messages during an outage.
            logger.exception(
                "Transport failed while confirming outbox message %s",
                message.id,
            )
            return
        await self._storage.mark_published(message.id)
        settled_ids.add(message.id)

__release_unsettled(messages, settled_ids) async

Release the claims of the messages this read did not settle.

A message that was neither published nor abandoned — refused with budget left, held back behind its partition key, or caught in a transport failure — goes back to the queue right away, so the next read sends it again instead of waiting for the claim to time out.

Source code in core/spakky-outbox/src/spakky/outbox/relay/relay.py
async def __release_unsettled(
    self,
    messages: list[OutboxMessage],
    settled_ids: set[UUID],
) -> None:
    """Release the claims of the messages this read did not settle.

    A message that was neither published nor abandoned — refused with
    budget left, held back behind its partition key, or caught in a
    transport failure — goes back to the queue right away, so the next
    read sends it again instead of waiting for the claim to time out.
    """
    # A failing release must not hide the error or cancellation that ended
    # the read; the claims it could not clear expire after the timeout.
    try:
        for message in messages:
            if message.id not in settled_ids:
                await self._storage.release_claim(message)
    except Exception:
        logger.exception("Failed to release outbox claims; they expire later")

공통

Outbox configuration.

OutboxConfig()

Bases: BaseSettings

Outbox plugin configuration loaded from environment variables.

Load outbox configuration from environment variables.

Source code in core/spakky-outbox/src/spakky/outbox/common/config.py
def __init__(self) -> None:
    """Load outbox configuration from environment variables."""
    super().__init__()

Outbox message model.

OutboxMessage(id, event_name, payload, headers, created_at, published_at=None, retry_count=0, claimed_at=None, partition_key=None, abandoned_at=None) dataclass

Persistence-agnostic Outbox message model.

partition_key = field(default=None) class-attribute instance-attribute

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

abandoned_at = field(default=None) class-attribute instance-attribute

When the relay gave up on this message. None means it is still pending.

에러

Outbox error classes.

AbstractSpakkyOutboxError

Bases: AbstractSpakkyFrameworkError, ABC

Base exception for Spakky Outbox errors.