Skip to content

BrokerPort

Message broker interface. Every broker adapter (Inline, Redis Stream, Redis PubSub, or your own) subclasses BrokerPort, which lists the operations Protean calls on every broker. The adapter sets its name, domain and configuration in its own __init__. A broker that declares a capability with its own Port subclasses that Port in place of BrokerPort. Each of these Ports extends BrokerPort:

  • BLOCKING_READ: BlockingReadPort, the blocking reads.
  • DEAD_LETTER_QUEUE: DeadLetterQueuePort, the dead letter queue operations.
  • STREAM_PARTITIONING: PartitioningPort, the partition-per-key operations.
  • STREAM_RETENTION: StreamRetentionPort, stream trimming.

domain.brokers[name] returns a Broker service that wraps the adapter. Application code calls the service, not the adapter.

See Broker Adapters for concrete adapter configuration, and Custom Brokers for writing an adapter.

Bases: Protocol

The operations a broker adapter implements.

An adapter subclasses this Protocol explicitly and sets name, domain and config in its own __init__: BrokerPort.__init__ sets nothing. Each built-in adapter also sets the class attribute broker_type to the name it is known by, such as "inline", "redis" or "redis_pubsub". An adapter that declares a flag listed in CAPABILITY_PORTS subclasses the sub-protocol the flag maps to, such as BlockingReadPort for BrokerCapabilities.BLOCKING_READ. Each sub-protocol extends BrokerPort.

The Broker service in protean.infra.broker wraps the adapter and adds unit-of-work recording, the retry after a connection error, capability checks and synchronous dispatch to subscribers. Code outside the adapter calls these members through the service. The adapter's own methods may call them directly.

Source code in src/protean/port/broker.py
184
185
186
def __init__(
    self, name: str, domain: "Domain", config: Mapping[str, Any]
) -> None: ...

capabilities abstractmethod property

capabilities: BrokerCapabilities

Return the capabilities this broker supports.

ping abstractmethod

ping() -> bool

Return True when the broker responds, False otherwise.

Source code in src/protean/port/broker.py
193
194
195
@abstractmethod
def ping(self) -> bool:
    """Return ``True`` when the broker responds, ``False`` otherwise."""

health abstractmethod

health() -> BrokerHealth

Return the broker's health record.

Reports a failure in the record with healthy=False and does not raise.

Source code in src/protean/port/broker.py
197
198
199
200
201
202
203
@abstractmethod
def health(self) -> BrokerHealth:
    """Return the broker's health record.

    Reports a failure in the record with ``healthy=False`` and does not
    raise.
    """

get_connection abstractmethod

get_connection() -> object

Return the native client the broker holds, or None if it has none.

Source code in src/protean/port/broker.py
205
206
207
@abstractmethod
def get_connection(self) -> object:
    """Return the native client the broker holds, or ``None`` if it has none."""

close

close() -> None

Close the broker and release its connections. No-op by default.

Source code in src/protean/port/broker.py
209
210
211
212
213
def close(self) -> None:
    """Close the broker and release its connections. No-op by default."""
    # A bare return keeps the default concrete: mypy treats a protocol
    # method whose body is only a docstring as abstract.
    return

clear abstractmethod

clear() -> None

Remove every message and consumer group the broker holds.

Meant for tests.

Source code in src/protean/port/broker.py
215
216
217
218
219
220
@abstractmethod
def clear(self) -> None:
    """Remove every message and consumer group the broker holds.

    Meant for tests.
    """

reconnect abstractmethod

reconnect() -> bool

Check the connection and reconnect if it is broken.

RETURNS DESCRIPTION
bool

True when the connection works, False when the broker

bool

cannot reconnect.

Source code in src/protean/port/broker.py
222
223
224
225
226
227
228
229
@abstractmethod
def reconnect(self) -> bool:
    """Check the connection and reconnect if it is broken.

    Returns:
        ``True`` when the connection works, ``False`` when the broker
        cannot reconnect.
    """

publish abstractmethod

publish(stream: str, message: dict[str, Any]) -> str

Send message to stream and return its identifier.

Every broker returns a non-empty identifier. Its format is broker-specific.

Source code in src/protean/port/broker.py
231
232
233
234
235
236
237
@abstractmethod
def publish(self, stream: str, message: dict[str, Any]) -> str:
    """Send ``message`` to ``stream`` and return its identifier.

    Every broker returns a non-empty identifier. Its format is
    broker-specific.
    """

read abstractmethod

read(
    stream: str,
    consumer_group: str,
    limit: int,
    *,
    new_messages: bool = False,
) -> list[BrokerMessage]

Read up to limit messages from stream for consumer_group.

Creates the consumer group if it does not exist. With new_messages=True, skips messages that are pending in the group (delivered and not acknowledged), and returns an empty list when only pending messages remain. A broker that redelivers a nacked message by putting it back on the stream returns it as a new message.

Source code in src/protean/port/broker.py
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
@abstractmethod
def read(
    self,
    stream: str,
    consumer_group: str,
    limit: int,
    *,
    new_messages: bool = False,
) -> list[BrokerMessage]:
    """Read up to ``limit`` messages from ``stream`` for ``consumer_group``.

    Creates the consumer group if it does not exist. With
    ``new_messages=True``, skips messages that are pending in the group
    (delivered and not acknowledged), and returns an empty list when only
    pending messages remain. A broker that redelivers a nacked message by
    putting it back on the stream returns it as a new message.
    """

ack abstractmethod

ack(
    stream: str, message_id: str, consumer_group: str
) -> bool

Acknowledge a message the group processed.

RETURNS DESCRIPTION
bool

True when the message was acknowledged, False otherwise.

Source code in src/protean/port/broker.py
257
258
259
260
261
262
263
@abstractmethod
def ack(self, stream: str, message_id: str, consumer_group: str) -> bool:
    """Acknowledge a message the group processed.

    Returns:
        ``True`` when the message was acknowledged, ``False`` otherwise.
    """

nack abstractmethod

nack(
    stream: str, message_id: str, consumer_group: str
) -> bool

Mark a message the group failed to process for redelivery.

RETURNS DESCRIPTION
bool

True when the message was marked, False otherwise.

Source code in src/protean/port/broker.py
265
266
267
268
269
270
271
@abstractmethod
def nack(self, stream: str, message_id: str, consumer_group: str) -> bool:
    """Mark a message the group failed to process for redelivery.

    Returns:
        ``True`` when the message was marked, ``False`` otherwise.
    """

create_group abstractmethod

create_group(stream: str, consumer_group: str) -> None

Create consumer_group on stream if it does not exist.

Source code in src/protean/port/broker.py
273
274
275
@abstractmethod
def create_group(self, stream: str, consumer_group: str) -> None:
    """Create ``consumer_group`` on ``stream`` if it does not exist."""

consumer_groups abstractmethod

consumer_groups() -> dict[str, ConsumerGroupInfo]

Return the broker's consumer groups, keyed by group name.

Source code in src/protean/port/broker.py
277
278
279
@abstractmethod
def consumer_groups(self) -> dict[str, ConsumerGroupInfo]:
    """Return the broker's consumer groups, keyed by group name."""

mark_subscription_owned

mark_subscription_owned(
    stream: str, consumer_group: str
) -> None

Record that a Protean subscription owns retries for this group.

The subscription counts handler failures and publishes a message that runs out of retries to {stream}:dlq. A broker that keeps its own limit on nacks stops dead-lettering the group's messages, and holds and redelivers them instead. The default does nothing, which is correct for a broker without such a limit.

Source code in src/protean/port/broker.py
281
282
283
284
285
286
287
288
289
290
291
292
def mark_subscription_owned(self, stream: str, consumer_group: str) -> None:
    """Record that a Protean subscription owns retries for this group.

    The subscription counts handler failures and publishes a message that
    runs out of retries to ``{stream}:dlq``. A broker that keeps its own
    limit on nacks stops dead-lettering the group's messages, and holds and
    redelivers them instead. The default does nothing, which is correct for
    a broker without such a limit.
    """
    # A bare return keeps the default concrete: mypy treats a protocol
    # method whose body is only a docstring as abstract.
    return

remove_stale_consumers

remove_stale_consumers(
    stream: str, consumer_group: str, current_consumer: str
) -> int

Remove consumers an earlier run of this process left in the group.

RETURNS DESCRIPTION
int

The number of consumers removed. The default removes none and

int

returns 0.

Source code in src/protean/port/broker.py
294
295
296
297
298
299
300
301
302
303
def remove_stale_consumers(
    self, stream: str, consumer_group: str, current_consumer: str
) -> int:
    """Remove consumers an earlier run of this process left in the group.

    Returns:
        The number of consumers removed. The default removes none and
        returns ``0``.
    """
    return 0

reclaim_idle_pending

reclaim_idle_pending(
    stream: str,
    consumer_group: str,
    consumer_name: str | None,
    min_idle_ms: int,
) -> dict[str, int]

Move entries other consumers left pending to consumer_name.

Runs when a subscription starts. A broker that keeps a pending list per consumer takes over every entry of the group that has gone unread for at least min_idle_ms milliseconds. The claim does not deliver the entries: the subscription's next read of its own pending entries does.

PARAMETER DESCRIPTION
consumer_name

The consumer to claim into. None means the consumer the broker's own read uses.

TYPE: str | None

RETURNS DESCRIPTION
dict[str, int]

The delivery count of each claimed entry, keyed by entry ID: how

dict[str, int]

many times the group delivered it before the claim. The default

dict[str, int]

claims nothing and returns {}.

Source code in src/protean/port/broker.py
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
def reclaim_idle_pending(
    self,
    stream: str,
    consumer_group: str,
    consumer_name: str | None,
    min_idle_ms: int,
) -> dict[str, int]:
    """Move entries other consumers left pending to ``consumer_name``.

    Runs when a subscription starts. A broker that keeps a pending list per
    consumer takes over every entry of the group that has gone unread for
    at least ``min_idle_ms`` milliseconds. The claim does not deliver the
    entries: the subscription's next read of its own pending entries does.

    Args:
        consumer_name: The consumer to claim into. ``None`` means the
            consumer the broker's own ``read`` uses.

    Returns:
        The delivery count of each claimed entry, keyed by entry ID: how
        many times the group delivered it before the claim. The default
        claims nothing and returns ``{}``.
    """
    return {}

BlockingReadPort

Bases: BrokerPort, Protocol

The blocking reads of a broker that declares BLOCKING_READ.

A broker that declares BrokerCapabilities.BLOCKING_READ subclasses this Protocol and implements both members. The Broker service calls them when the broker declares the flag, and reads each stream once with read when it does not.

Source code in src/protean/port/broker.py
184
185
186
def __init__(
    self, name: str, domain: "Domain", config: Mapping[str, Any]
) -> None: ...

read_blocking abstractmethod

read_blocking(
    stream: str,
    consumer_group: str,
    consumer_name: str,
    timeout_ms: int = 5000,
    limit: int = 1,
) -> list[BrokerMessage]

Read up to limit messages from stream for one consumer.

Waits up to timeout_ms milliseconds for a message. timeout_ms=0 returns at once. Returns an empty list when no message arrives in time.

Source code in src/protean/port/broker.py
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
@abstractmethod
def read_blocking(
    self,
    stream: str,
    consumer_group: str,
    consumer_name: str,
    timeout_ms: int = 5000,
    limit: int = 1,
) -> list[BrokerMessage]:
    """Read up to ``limit`` messages from ``stream`` for one consumer.

    Waits up to ``timeout_ms`` milliseconds for a message.
    ``timeout_ms=0`` returns at once. Returns an empty list when no
    message arrives in time.
    """

read_blocking_streams abstractmethod

read_blocking_streams(
    streams: Sequence[str],
    consumer_group: str,
    consumer_name: str,
    timeout_ms: int = 5000,
    limit: int = 1,
) -> dict[str, list[BrokerMessage]]

Read several streams for one consumer, waiting on all of them at once.

Waits up to timeout_ms milliseconds in total for a message on any of streams. timeout_ms=0 returns at once. limit caps the messages read from each stream.

RETURNS DESCRIPTION
dict[str, list[BrokerMessage]]

The messages read from each stream, keyed by stream name in the

dict[str, list[BrokerMessage]]

order given. Every requested stream has a key, with an empty list

dict[str, list[BrokerMessage]]

when it returned nothing. An empty streams returns {}.

Source code in src/protean/port/broker.py
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
@abstractmethod
def read_blocking_streams(
    self,
    streams: Sequence[str],
    consumer_group: str,
    consumer_name: str,
    timeout_ms: int = 5000,
    limit: int = 1,
) -> dict[str, list[BrokerMessage]]:
    """Read several streams for one consumer, waiting on all of them at once.

    Waits up to ``timeout_ms`` milliseconds in total for a message on any
    of ``streams``. ``timeout_ms=0`` returns at once. ``limit`` caps the
    messages read from each stream.

    Returns:
        The messages read from each stream, keyed by stream name in the
        order given. Every requested stream has a key, with an empty list
        when it returned nothing. An empty ``streams`` returns ``{}``.
    """

DeadLetterQueuePort

Bases: BrokerPort, Protocol

The dead-letter queue of a broker that declares DEAD_LETTER_QUEUE.

A broker that declares BrokerCapabilities.DEAD_LETTER_QUEUE subclasses this Protocol and implements every member. The Broker service calls them when the broker declares the flag, and returns an empty answer when it does not.

A dead-letter queue stream is named {stream}:dlq. Each entry carries a _dlq_metadata record that says where the message came from and why it failed.

Source code in src/protean/port/broker.py
184
185
186
def __init__(
    self, name: str, domain: "Domain", config: Mapping[str, Any]
) -> None: ...

dlq_list abstractmethod

dlq_list(
    dlq_streams: list[str], limit: int = 100
) -> list[DLQEntry]

Return up to limit entries from dlq_streams, newest failure first.

An entry without a usable failed_at comes after every entry that has one. A stream that does not exist adds no entries.

Source code in src/protean/port/broker.py
662
663
664
665
666
667
668
@abstractmethod
def dlq_list(self, dlq_streams: list[str], limit: int = 100) -> list[DLQEntry]:
    """Return up to ``limit`` entries from ``dlq_streams``, newest failure first.

    An entry without a usable ``failed_at`` comes after every entry that
    has one. A stream that does not exist adds no entries.
    """

dlq_get abstractmethod

dlq_get(dlq_stream: str, dlq_id: str) -> DLQEntry | None

Return the entry dlq_id in dlq_stream, or None if there is none.

Source code in src/protean/port/broker.py
670
671
672
@abstractmethod
def dlq_get(self, dlq_stream: str, dlq_id: str) -> DLQEntry | None:
    """Return the entry ``dlq_id`` in ``dlq_stream``, or ``None`` if there is none."""

dlq_replay abstractmethod

dlq_replay(
    dlq_stream: str, dlq_id: str, target_stream: str
) -> bool

Publish the entry dlq_id to target_stream and remove it.

RETURNS DESCRIPTION
bool

True when the entry was replayed, False when there is no

bool

such entry.

Source code in src/protean/port/broker.py
674
675
676
677
678
679
680
681
@abstractmethod
def dlq_replay(self, dlq_stream: str, dlq_id: str, target_stream: str) -> bool:
    """Publish the entry ``dlq_id`` to ``target_stream`` and remove it.

    Returns:
        ``True`` when the entry was replayed, ``False`` when there is no
        such entry.
    """

dlq_replay_all abstractmethod

dlq_replay_all(dlq_stream: str, target_stream: str) -> int

Publish every entry in dlq_stream to target_stream and remove it.

RETURNS DESCRIPTION
int

The number of entries replayed.

Source code in src/protean/port/broker.py
683
684
685
686
687
688
689
@abstractmethod
def dlq_replay_all(self, dlq_stream: str, target_stream: str) -> int:
    """Publish every entry in ``dlq_stream`` to ``target_stream`` and remove it.

    Returns:
        The number of entries replayed.
    """

dlq_purge abstractmethod

dlq_purge(dlq_stream: str) -> int

Remove every entry in dlq_stream.

RETURNS DESCRIPTION
int

The number of entries removed.

Source code in src/protean/port/broker.py
691
692
693
694
695
696
697
@abstractmethod
def dlq_purge(self, dlq_stream: str) -> int:
    """Remove every entry in ``dlq_stream``.

    Returns:
        The number of entries removed.
    """

dlq_trim abstractmethod

dlq_trim(dlq_stream: str, older_than: datetime) -> int

Remove the entries in dlq_stream that failed before older_than.

RAISES DESCRIPTION
TypeError

older_than is not a datetime.

ValueError

older_than has no time zone.

RETURNS DESCRIPTION
int

The number of entries removed.

Source code in src/protean/port/broker.py
699
700
701
702
703
704
705
706
707
708
709
@abstractmethod
def dlq_trim(self, dlq_stream: str, older_than: datetime) -> int:
    """Remove the entries in ``dlq_stream`` that failed before ``older_than``.

    Raises:
        TypeError: ``older_than`` is not a ``datetime``.
        ValueError: ``older_than`` has no time zone.

    Returns:
        The number of entries removed.
    """

dlq_depth abstractmethod

dlq_depth(dlq_stream: str) -> int

Return the number of entries in dlq_stream.

A stream that does not exist has 0.

Source code in src/protean/port/broker.py
711
712
713
714
715
716
@abstractmethod
def dlq_depth(self, dlq_stream: str) -> int:
    """Return the number of entries in ``dlq_stream``.

    A stream that does not exist has ``0``.
    """

PartitioningPort

Bases: BrokerPort, Protocol

The partition-per-key operations of a broker that declares STREAM_PARTITIONING.

These back the partitioned stream consumer (ADR-0028). A broker that declares BrokerCapabilities.STREAM_PARTITIONING subclasses this Protocol and implements every member. The Broker service raises NotSupportedError for each of them on a broker without the flag.

Source code in src/protean/port/broker.py
184
185
186
def __init__(
    self, name: str, domain: "Domain", config: Mapping[str, Any]
) -> None: ...

record_partition abstractmethod

record_partition(category: str, key: str) -> None

Record key in the partition index for category.

Called on publish to {category}:{key} so the partitioned consumer can find the partition without scanning the keyspace (ADR-0028 decision 7). Recording the same key twice changes nothing.

Source code in src/protean/port/broker.py
387
388
389
390
391
392
393
394
@abstractmethod
def record_partition(self, category: str, key: str) -> None:
    """Record ``key`` in the partition index for ``category``.

    Called on publish to ``{category}:{key}`` so the partitioned consumer
    can find the partition without scanning the keyspace (ADR-0028
    decision 7). Recording the same key twice changes nothing.
    """

partition_keys abstractmethod

partition_keys(category: str) -> set[str]

Return the live partition keys recorded for category.

Source code in src/protean/port/broker.py
396
397
398
@abstractmethod
def partition_keys(self, category: str) -> set[str]:
    """Return the live partition keys recorded for ``category``."""

reap_partition abstractmethod

reap_partition(
    category: str,
    key: str,
    min_idle_ms: int,
    backfill_suffix: str | None,
) -> bool

Remove a drained, idle partition from the index and delete its streams.

The check and the delete happen in one atomic step. A stream that holds entries passes the check only when it has at least one consumer group, every group on it has read and acknowledged every entry, and its newest entry is at least min_idle_ms old. An empty stream always passes. The partition is reaped only when each of its streams passes. When priority lanes are enabled, backfill_suffix names the backfill lane {category}:{key}:{backfill_suffix}, which is checked and deleted with the main stream, so a backfill lane with unread entries keeps an empty main stream from being reaped. The partition's generation counter is kept, so a partition created again under the same key keeps a rising generation. The partition's current owner calls it once it has drained the partition. See ADR-0028 decision 7.

RETURNS DESCRIPTION
bool

True when the partition was reaped.

Source code in src/protean/port/broker.py
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
@abstractmethod
def reap_partition(
    self,
    category: str,
    key: str,
    min_idle_ms: int,
    backfill_suffix: str | None,
) -> bool:
    """Remove a drained, idle partition from the index and delete its streams.

    The check and the delete happen in one atomic step. A stream that
    holds entries passes the check only when it has at least one consumer
    group, every group on it has read and acknowledged every entry, and
    its newest entry is at least ``min_idle_ms`` old. An empty stream
    always passes. The partition is reaped only when each of its streams
    passes. When priority lanes are enabled, ``backfill_suffix`` names the
    backfill lane ``{category}:{key}:{backfill_suffix}``, which is checked
    and deleted with the main stream, so a backfill lane with unread
    entries keeps an empty main stream from being reaped. The partition's generation counter is
    kept, so a partition created again under the same key keeps a rising
    generation. The partition's current owner calls it once it has
    drained the partition. See ADR-0028 decision 7.

    Returns:
        ``True`` when the partition was reaped.
    """

acquire_partition_lease abstractmethod

acquire_partition_lease(
    lease_key: str,
    generation_key: str,
    owner_id: str,
    ttl_ms: int,
) -> int | None

Acquire the ownership lease for a partition and return its generation.

In one atomic step (ADR-0028 decision 5): when the lease is unheld, increments the durable generation counter, takes the lease at that generation for ttl_ms milliseconds, and returns the generation. Returns None when the lease is already held.

Source code in src/protean/port/broker.py
427
428
429
430
431
432
433
434
435
436
437
@abstractmethod
def acquire_partition_lease(
    self, lease_key: str, generation_key: str, owner_id: str, ttl_ms: int
) -> int | None:
    """Acquire the ownership lease for a partition and return its generation.

    In one atomic step (ADR-0028 decision 5): when the lease is unheld,
    increments the durable generation counter, takes the lease at that
    generation for ``ttl_ms`` milliseconds, and returns the generation.
    Returns ``None`` when the lease is already held.
    """

renew_partition_lease abstractmethod

renew_partition_lease(
    lease_key: str, fence_token: str, ttl_ms: int
) -> bool

Renew a held lease so that it expires ttl_ms milliseconds from now.

fence_token is {owner_id}:{generation}. The renew succeeds only while the lease still holds that exact token, so an owner that lost the lease to expiry or a takeover cannot take it back.

RETURNS DESCRIPTION
bool

False when the lease is lost.

Source code in src/protean/port/broker.py
439
440
441
442
443
444
445
446
447
448
449
450
451
@abstractmethod
def renew_partition_lease(
    self, lease_key: str, fence_token: str, ttl_ms: int
) -> bool:
    """Renew a held lease so that it expires ``ttl_ms`` milliseconds from now.

    ``fence_token`` is ``{owner_id}:{generation}``. The renew succeeds only
    while the lease still holds that exact token, so an owner that lost
    the lease to expiry or a takeover cannot take it back.

    Returns:
        ``False`` when the lease is lost.
    """

release_partition_lease abstractmethod

release_partition_lease(
    lease_key: str, fence_token: str
) -> bool

Release a held lease on graceful shutdown.

RETURNS DESCRIPTION
bool

False when the lease is not held at fence_token.

Source code in src/protean/port/broker.py
453
454
455
456
457
458
459
@abstractmethod
def release_partition_lease(self, lease_key: str, fence_token: str) -> bool:
    """Release a held lease on graceful shutdown.

    Returns:
        ``False`` when the lease is not held at ``fence_token``.
    """

read_partition_fenced abstractmethod

read_partition_fenced(
    stream: str,
    consumer_group: str,
    consumer_name: str,
    lease_key: str,
    fence_token: str,
    limit: int,
    new_messages: bool,
) -> list[BrokerMessage]

Read up to limit messages from a partition stream, fenced by the lease.

The lease check and the read are one atomic step (ADR-0028 decision 5). A caller that no longer holds the lease at fence_token gets LeaseLostError and reads no message. new_messages=True reads undelivered entries, and new_messages=False reads the entries already delivered to this consumer and not acknowledged. Does not wait for messages.

RAISES DESCRIPTION
LeaseLostError

The caller does not hold the lease at fence_token.

Source code in src/protean/port/broker.py
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
@abstractmethod
def read_partition_fenced(
    self,
    stream: str,
    consumer_group: str,
    consumer_name: str,
    lease_key: str,
    fence_token: str,
    limit: int,
    new_messages: bool,
) -> list[BrokerMessage]:
    """Read up to ``limit`` messages from a partition stream, fenced by the lease.

    The lease check and the read are one atomic step (ADR-0028 decision
    5). A caller that no longer holds the lease at ``fence_token`` gets
    ``LeaseLostError`` and reads no message. ``new_messages=True`` reads undelivered entries, and
    ``new_messages=False`` reads the entries already delivered to this
    consumer and not acknowledged. Does not wait for messages.

    Raises:
        LeaseLostError: The caller does not hold the lease at
            ``fence_token``.
    """

ack_partition_fenced abstractmethod

ack_partition_fenced(
    stream: str,
    message_id: str,
    consumer_group: str,
    lease_key: str,
    fence_token: str,
) -> bool

Acknowledge a partition message, fenced by the lease.

The lease check and the acknowledgement are one atomic step, so an owner whose lease was taken over cannot acknowledge a message the new owner holds.

RETURNS DESCRIPTION
bool

True when the message was acknowledged.

RAISES DESCRIPTION
LeaseLostError

The caller does not hold the lease at fence_token.

Source code in src/protean/port/broker.py
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
@abstractmethod
def ack_partition_fenced(
    self,
    stream: str,
    message_id: str,
    consumer_group: str,
    lease_key: str,
    fence_token: str,
) -> bool:
    """Acknowledge a partition message, fenced by the lease.

    The lease check and the acknowledgement are one atomic step, so an
    owner whose lease was taken over cannot acknowledge a message the new
    owner holds.

    Returns:
        ``True`` when the message was acknowledged.

    Raises:
        LeaseLostError: The caller does not hold the lease at
            ``fence_token``.
    """

reclaim_partition_pending abstractmethod

reclaim_partition_pending(
    stream: str,
    consumer_group: str,
    consumer_name: str,
    min_idle_ms: int,
    limit: int,
) -> list[BrokerMessage]

Move a dead owner's pending entries to consumer_name.

On failover the new owner reclaims the previous owner's unacknowledged entries so none are lost or skipped (ADR-0028 decision 5). Claims entries idle for at least min_idle_ms milliseconds, limit per page, and stops at the end of the pending list or at the first page that claims nothing.

RETURNS DESCRIPTION
list[BrokerMessage]

The reclaimed messages, now pending on consumer_name. A claimed

list[BrokerMessage]

entry whose payload was already trimmed from the stream is left

list[BrokerMessage]

out.

Source code in src/protean/port/broker.py
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
@abstractmethod
def reclaim_partition_pending(
    self,
    stream: str,
    consumer_group: str,
    consumer_name: str,
    min_idle_ms: int,
    limit: int,
) -> list[BrokerMessage]:
    """Move a dead owner's pending entries to ``consumer_name``.

    On failover the new owner reclaims the previous owner's unacknowledged
    entries so none are lost or skipped (ADR-0028 decision 5). Claims
    entries idle for at least ``min_idle_ms`` milliseconds, ``limit`` per
    page, and stops at the end of the pending list or at the first page
    that claims nothing.

    Returns:
        The reclaimed messages, now pending on ``consumer_name``. A claimed
        entry whose payload was already trimmed from the stream is left
        out.
    """

StreamRetentionPort

Bases: BrokerPort, Protocol

Stream trimming for a broker that declares STREAM_RETENTION.

A broker that declares BrokerCapabilities.STREAM_RETENTION subclasses this Protocol and implements trim. The Broker service trims nothing on a broker without the flag.

Source code in src/protean/port/broker.py
184
185
186
def __init__(
    self, name: str, domain: "Domain", config: Mapping[str, Any]
) -> None: ...

trim abstractmethod

trim(stream: str) -> int

Remove the entries of stream that every consumer group has acknowledged.

The stream subscription calls it after each processed batch. The trim removes only entries that every consumer group on stream has read and acknowledged when it runs, so no existing group loses a message it still needs. It need not remove all of them.

RETURNS DESCRIPTION
int

The number of entries removed.

Source code in src/protean/port/broker.py
540
541
542
543
544
545
546
547
548
549
550
551
@abstractmethod
def trim(self, stream: str) -> int:
    """Remove the entries of ``stream`` that every consumer group has acknowledged.

    The stream subscription calls it after each processed batch. The trim
    removes only entries that every consumer group on ``stream`` has read
    and acknowledged when it runs, so no existing group loses a message it
    still needs. It need not remove all of them.

    Returns:
        The number of entries removed.
    """

Records

BrokerMessage

Bases: NamedTuple

One message a broker returns from a read.

Unpacks as (id, payload), like the tuples brokers returned before.

BrokerHealth dataclass

BrokerHealth(
    healthy: bool,
    message_counts: Mapping[str, int] = dict(),
    consumer_groups: Mapping[str, Any] = dict(),
    details: Mapping[str, Any] = dict(),
)

The health record a broker reports.

ATTRIBUTE DESCRIPTION
healthy

False when the broker reports a problem.

TYPE: bool

message_counts

Message counts, such as total_messages and in_flight.

TYPE: Mapping[str, int]

consumer_groups

The consumer groups the broker knows, usually as count and names.

TYPE: Mapping[str, Any]

details

Adapter-specific data, such as server statistics, the broker's configuration, or an error or warning message.

TYPE: Mapping[str, Any]

DLQEntry dataclass

DLQEntry(
    dlq_id: str,
    original_id: str,
    stream: str,
    consumer_group: str,
    payload: dict[str, Any],
    failure_reason: str,
    failed_at: str | None,
    retry_count: int,
    dlq_stream: str,
)

A broker-agnostic view of one dead letter queue message.

ATTRIBUTE DESCRIPTION
dlq_id

Identifier within the DLQ (Redis stream ID or UUID).

TYPE: str

original_id

Original message identifier before it entered DLQ.

TYPE: str

stream

Original stream category the message belonged to.

TYPE: str

consumer_group

Consumer group that failed to process the message.

TYPE: str

payload

Full message payload dict.

TYPE: dict[str, Any]

failure_reason

Why the message was moved to DLQ.

TYPE: str

failed_at

ISO 8601 timestamp of when the message failed.

TYPE: str | None

retry_count

Number of retries attempted before DLQ.

TYPE: int

dlq_stream

Name of the DLQ stream this entry lives in.

TYPE: str

ConsumerGroupInfo

Bases: TypedDict

One consumer group, summed over the streams it reads.

pending is the broker's own count of messages delivered to the group and not yet settled, so it differs between brokers. The inline broker counts messages delivered and not yet acknowledged or nacked. The Redis broker reports the length of the Redis pending list, which keeps a nacked message. A broker without acknowledgement reports 0.

consumer_count counts the consumers the broker tracks. The inline broker tracks none and reports 0.

ConsumerInfo

Bases: TypedDict

One consumer of a consumer group and the messages it has not acknowledged.

Broker service

The framework's view of one broker adapter.

domain.brokers[name] returns this service. It adds to the adapter: recording messages on the current unit of work, one retry after a connection error, capability checks, ping timing, the health envelope and synchronous dispatch to registered subscribers.

RAISES DESCRIPTION
ConfigurationError

When it is built, if the adapter declares a capability flag without subclassing the sub-protocol CAPABILITY_PORTS maps it to.

Source code in src/protean/infra/broker.py
82
83
84
85
86
87
88
89
90
def __init__(self, adapter: BrokerPort) -> None:
    self._adapter = adapter
    self._check_capability_ports()
    self._subscribers: defaultdict[str, set[type[BaseSubscriber]]] = defaultdict(
        set
    )
    self._last_ping_time: float | None = None
    self._last_ping_success: bool | None = None
    self._start_time = time.time()

capabilities property

capabilities: BrokerCapabilities

Return the adapter's capability flags.

publish

publish(stream: str, message: dict[str, Any]) -> str | None

Publish message to stream.

Inside a unit of work, records the message and returns None; the unit of work sends it on commit. Outside one, sends it and returns its identifier, and in synchronous processing hands it to each subscriber registered for stream.

RAISES DESCRIPTION
ValidationError

When message is empty.

Source code in src/protean/infra/broker.py
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
def publish(self, stream: str, message: dict[str, Any]) -> str | None:
    """Publish ``message`` to ``stream``.

    Inside a unit of work, records the message and returns ``None``; the
    unit of work sends it on commit. Outside one, sends it and returns its
    identifier, and in synchronous processing hands it to each subscriber
    registered for ``stream``.

    Raises:
        ValidationError: When ``message`` is empty.
    """
    if not message:
        raise ValidationError({"message": ["Message cannot be empty"]})

    if current_uow:
        logger.debug(f"Recording message {message} in {current_uow} for dispatch")
        current_uow.register_message(stream, message, broker_name=self.name)
        return None

    identifier = self._retry_once(
        "publish", lambda: self._adapter.publish(stream, message)
    )
    self._dispatch_sync(stream, message)
    return identifier

read

read(
    stream: str, consumer_group: str, limit: int
) -> list[BrokerMessage]

Read up to limit messages from stream for consumer_group.

Returns an empty list when the broker lacks CONSUMER_GROUPS.

Source code in src/protean/infra/broker.py
172
173
174
175
176
177
178
179
180
181
182
183
def read(self, stream: str, consumer_group: str, limit: int) -> list[BrokerMessage]:
    """Read up to ``limit`` messages from ``stream`` for ``consumer_group``.

    Returns an empty list when the broker lacks ``CONSUMER_GROUPS``.
    """
    if BrokerCapabilities.CONSUMER_GROUPS not in self.capabilities:
        logger.warning(f"Broker {self.name} does not support consumer groups")
        return []

    return self._retry_once(
        "read", lambda: self._adapter.read(stream, consumer_group, limit)
    )

read_blocking

read_blocking(
    stream: str,
    consumer_group: str,
    consumer_name: str,
    timeout_ms: int = 5000,
    limit: int = 1,
) -> list[BrokerMessage]

Read up to limit messages from stream for one consumer.

A broker with BLOCKING_READ waits up to timeout_ms milliseconds for a message. A broker without it reads stream once with read and does not wait. Either read runs again once after a connection error.

Source code in src/protean/infra/broker.py
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
def read_blocking(
    self,
    stream: str,
    consumer_group: str,
    consumer_name: str,
    timeout_ms: int = 5000,
    limit: int = 1,
) -> list[BrokerMessage]:
    """Read up to ``limit`` messages from ``stream`` for one consumer.

    A broker with ``BLOCKING_READ`` waits up to ``timeout_ms`` milliseconds
    for a message. A broker without it reads ``stream`` once with ``read``
    and does not wait. Either read runs again once after a connection
    error.
    """
    if BrokerCapabilities.BLOCKING_READ not in self.capabilities:
        return self._retry_once(
            "read_blocking",
            lambda: self._adapter.read(stream, consumer_group, limit),
        )

    adapter = cast(BlockingReadPort, self._adapter)
    return self._retry_once(
        "read_blocking",
        lambda: adapter.read_blocking(
            stream,
            consumer_group,
            consumer_name,
            timeout_ms=timeout_ms,
            limit=limit,
        ),
    )

read_blocking_streams

read_blocking_streams(
    streams: Sequence[str],
    consumer_group: str,
    consumer_name: str,
    timeout_ms: int = 5000,
    limit: int = 1,
) -> dict[str, list[BrokerMessage]]

Read several streams for one consumer in one call.

The result has one key per requested stream, in the order given, with an empty list for a stream that returned nothing. An empty streams returns {} without reading. A broker with BLOCKING_READ waits up to timeout_ms milliseconds in total. A broker without it reads each stream once with read and does not wait. limit caps the messages read from each stream. The read runs again once after a connection error.

Source code in src/protean/infra/broker.py
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
def read_blocking_streams(
    self,
    streams: Sequence[str],
    consumer_group: str,
    consumer_name: str,
    timeout_ms: int = 5000,
    limit: int = 1,
) -> dict[str, list[BrokerMessage]]:
    """Read several streams for one consumer in one call.

    The result has one key per requested stream, in the order given, with
    an empty list for a stream that returned nothing. An empty ``streams``
    returns ``{}`` without reading. A broker with ``BLOCKING_READ`` waits
    up to ``timeout_ms`` milliseconds in total. A broker without it reads
    each stream once with ``read`` and does not wait. ``limit`` caps the
    messages read from each stream. The read runs again once after a
    connection error.
    """
    if not streams:
        return {}

    if BrokerCapabilities.BLOCKING_READ not in self.capabilities:
        return self._retry_once(
            "read_blocking_streams",
            lambda: self._read_each_stream(streams, consumer_group, limit),
        )

    adapter = cast(BlockingReadPort, self._adapter)
    return self._retry_once(
        "read_blocking_streams",
        lambda: adapter.read_blocking_streams(
            streams,
            consumer_group,
            consumer_name,
            timeout_ms=timeout_ms,
            limit=limit,
        ),
    )

get_next

get_next(
    stream: str, consumer_group: str
) -> BrokerMessage | None

Return the next message the adapter reads with new_messages=True.

Skips messages that are pending in the group. Returns None when there is none, or when the broker lacks CONSUMER_GROUPS.

Source code in src/protean/infra/broker.py
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
def get_next(self, stream: str, consumer_group: str) -> BrokerMessage | None:
    """Return the next message the adapter reads with ``new_messages=True``.

    Skips messages that are pending in the group. Returns ``None`` when
    there is none, or when the broker lacks ``CONSUMER_GROUPS``.
    """
    if BrokerCapabilities.CONSUMER_GROUPS not in self.capabilities:
        logger.warning(f"Broker {self.name} does not support consumer groups")
        return None

    messages = self._retry_once(
        "get_next",
        lambda: self._adapter.read(stream, consumer_group, 1, new_messages=True),
    )
    return messages[0] if messages else None

ack

ack(
    stream: str, message_id: str, consumer_group: str
) -> bool

Acknowledge a message consumer_group processed.

Returns False when the broker lacks ACK_NACK.

Source code in src/protean/infra/broker.py
281
282
283
284
285
286
287
288
289
290
291
292
293
294
def ack(self, stream: str, message_id: str, consumer_group: str) -> bool:
    """Acknowledge a message ``consumer_group`` processed.

    Returns ``False`` when the broker lacks ``ACK_NACK``.
    """
    if BrokerCapabilities.ACK_NACK not in self.capabilities:
        logger.warning(
            f"Broker {self.name} does not support message acknowledgment"
        )
        return False

    return self._retry_once(
        "ack", lambda: self._adapter.ack(stream, message_id, consumer_group)
    )

nack

nack(
    stream: str, message_id: str, consumer_group: str
) -> bool

Mark a message consumer_group failed to process for redelivery.

Returns False when the broker lacks ACK_NACK.

Source code in src/protean/infra/broker.py
296
297
298
299
300
301
302
303
304
305
306
307
308
309
def nack(self, stream: str, message_id: str, consumer_group: str) -> bool:
    """Mark a message ``consumer_group`` failed to process for redelivery.

    Returns ``False`` when the broker lacks ``ACK_NACK``.
    """
    if BrokerCapabilities.ACK_NACK not in self.capabilities:
        logger.warning(
            f"Broker {self.name} does not support message negative acknowledgment"
        )
        return False

    return self._retry_once(
        "nack", lambda: self._adapter.nack(stream, message_id, consumer_group)
    )

ping

ping() -> bool

Return True when the broker responds, and record how long it took.

Returns False when the adapter's ping fails or raises.

Source code in src/protean/infra/broker.py
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
def ping(self) -> bool:
    """Return ``True`` when the broker responds, and record how long it took.

    Returns ``False`` when the adapter's ping fails or raises.
    """
    try:
        start_time = time.time()
        result = self._adapter.ping()
        self._last_ping_time = time.time() - start_time
        self._last_ping_success = result
        return result
    except Exception as e:  # noqa: BLE001 - health probe: any adapter fault is "down"
        logger.debug(f"Ping failed for broker {self.name}: {e}")
        self._last_ping_time = None
        self._last_ping_success = False
        return False

health

health() -> dict[str, Any]

Return the broker's health in a status envelope.

The envelope has status (healthy, degraded or unhealthy), connected, last_ping_ms, uptime_seconds and details, the adapter's health record as a dict with its free-form details at the top level. A failure while gathering it is reported as unhealthy and not raised.

Source code in src/protean/infra/broker.py
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
def health(self) -> dict[str, Any]:
    """Return the broker's health in a status envelope.

    The envelope has ``status`` (``healthy``, ``degraded`` or
    ``unhealthy``), ``connected``, ``last_ping_ms``, ``uptime_seconds`` and
    ``details``, the adapter's health record as a dict with its free-form
    details at the top level. A failure while
    gathering it is reported as ``unhealthy`` and not raised.
    """
    try:
        record = self._adapter.health()
        is_connected = self.ping()

        if is_connected and record.healthy:
            status = "healthy"
        elif is_connected:
            status = "degraded"
        else:
            status = "unhealthy"

        return {
            "status": status,
            "connected": is_connected,
            "last_ping_ms": self._last_ping_time * 1000
            if self._last_ping_time is not None
            else None,
            "uptime_seconds": time.time() - self._start_time,
            "details": _health_details(record),
        }
    except Exception as e:  # noqa: BLE001 - health probe: report the fault as unhealthy
        logger.error(f"Error gathering health stats for broker {self.name}: {e}")
        return {
            "status": "unhealthy",
            "connected": False,
            "last_ping_ms": None,
            "uptime_seconds": 0,
            "details": {"error": str(e)},
        }

get_connection

get_connection() -> object

Return the adapter's native client, or None if it has none.

Source code in src/protean/infra/broker.py
367
368
369
def get_connection(self) -> object:
    """Return the adapter's native client, or ``None`` if it has none."""
    return self._adapter.get_connection()

clear

clear() -> None

Remove every message and consumer group the broker holds.

Source code in src/protean/infra/broker.py
371
372
373
def clear(self) -> None:
    """Remove every message and consumer group the broker holds."""
    self._adapter.clear()

register

register(subscriber_cls: type[BaseSubscriber]) -> None

Register subscriber_cls for synchronous dispatch on its stream.

Source code in src/protean/infra/broker.py
375
376
377
378
379
380
381
def register(self, subscriber_cls: type[BaseSubscriber]) -> None:
    """Register ``subscriber_cls`` for synchronous dispatch on its stream."""
    stream = subscriber_cls.meta_.stream
    self._subscribers[stream].add(subscriber_cls)
    logger.debug(
        f"Broker {self.name}: Registered Subscriber {subscriber_cls.__name__} for stream {stream}"
    )

dlq_list

dlq_list(
    dlq_streams: list[str], limit: int = 100
) -> list[DLQEntry]

Return up to limit entries from dlq_streams, newest failure first.

Returns an empty list when the broker lacks DEAD_LETTER_QUEUE.

Source code in src/protean/infra/broker.py
425
426
427
428
429
430
431
def dlq_list(self, dlq_streams: list[str], limit: int = 100) -> list[DLQEntry]:
    """Return up to ``limit`` entries from ``dlq_streams``, newest failure first.

    Returns an empty list when the broker lacks ``DEAD_LETTER_QUEUE``.
    """
    adapter = self._dlq_port()
    return adapter.dlq_list(dlq_streams, limit) if adapter else []

dlq_get

dlq_get(dlq_stream: str, dlq_id: str) -> DLQEntry | None

Return the entry dlq_id in dlq_stream, or None if there is none.

Returns None when the broker lacks DEAD_LETTER_QUEUE.

Source code in src/protean/infra/broker.py
433
434
435
436
437
438
439
def dlq_get(self, dlq_stream: str, dlq_id: str) -> DLQEntry | None:
    """Return the entry ``dlq_id`` in ``dlq_stream``, or ``None`` if there is none.

    Returns ``None`` when the broker lacks ``DEAD_LETTER_QUEUE``.
    """
    adapter = self._dlq_port()
    return adapter.dlq_get(dlq_stream, dlq_id) if adapter else None

dlq_replay

dlq_replay(
    dlq_stream: str, dlq_id: str, target_stream: str
) -> bool

Publish the entry dlq_id to target_stream and remove it.

Returns False when there is no such entry, or when the broker lacks DEAD_LETTER_QUEUE.

Source code in src/protean/infra/broker.py
441
442
443
444
445
446
447
448
449
450
def dlq_replay(self, dlq_stream: str, dlq_id: str, target_stream: str) -> bool:
    """Publish the entry ``dlq_id`` to ``target_stream`` and remove it.

    Returns ``False`` when there is no such entry, or when the broker lacks
    ``DEAD_LETTER_QUEUE``.
    """
    adapter = self._dlq_port()
    return (
        adapter.dlq_replay(dlq_stream, dlq_id, target_stream) if adapter else False
    )

dlq_replay_all

dlq_replay_all(dlq_stream: str, target_stream: str) -> int

Publish every entry in dlq_stream to target_stream and remove it.

Returns the number replayed, 0 when the broker lacks DEAD_LETTER_QUEUE.

Source code in src/protean/infra/broker.py
452
453
454
455
456
457
458
459
def dlq_replay_all(self, dlq_stream: str, target_stream: str) -> int:
    """Publish every entry in ``dlq_stream`` to ``target_stream`` and remove it.

    Returns the number replayed, ``0`` when the broker lacks
    ``DEAD_LETTER_QUEUE``.
    """
    adapter = self._dlq_port()
    return adapter.dlq_replay_all(dlq_stream, target_stream) if adapter else 0

dlq_purge

dlq_purge(dlq_stream: str) -> int

Remove every entry in dlq_stream.

Returns the number removed, 0 when the broker lacks DEAD_LETTER_QUEUE.

Source code in src/protean/infra/broker.py
461
462
463
464
465
466
467
468
def dlq_purge(self, dlq_stream: str) -> int:
    """Remove every entry in ``dlq_stream``.

    Returns the number removed, ``0`` when the broker lacks
    ``DEAD_LETTER_QUEUE``.
    """
    adapter = self._dlq_port()
    return adapter.dlq_purge(dlq_stream) if adapter else 0

dlq_trim

dlq_trim(dlq_stream: str, older_than: datetime) -> int

Remove the entries in dlq_stream that failed before older_than.

Returns the number removed, 0 when the broker lacks DEAD_LETTER_QUEUE.

RAISES DESCRIPTION
TypeError

older_than is not a datetime.

ValueError

older_than has no time zone.

Source code in src/protean/infra/broker.py
470
471
472
473
474
475
476
477
478
479
480
481
482
def dlq_trim(self, dlq_stream: str, older_than: datetime) -> int:
    """Remove the entries in ``dlq_stream`` that failed before ``older_than``.

    Returns the number removed, ``0`` when the broker lacks
    ``DEAD_LETTER_QUEUE``.

    Raises:
        TypeError: ``older_than`` is not a ``datetime``.
        ValueError: ``older_than`` has no time zone.
    """
    require_aware_cutoff(older_than)
    adapter = self._dlq_port()
    return adapter.dlq_trim(dlq_stream, older_than) if adapter else 0

dlq_depth

dlq_depth(dlq_stream: str) -> int

Return the number of entries in dlq_stream.

Returns 0 when the broker lacks DEAD_LETTER_QUEUE.

Source code in src/protean/infra/broker.py
484
485
486
487
488
489
490
def dlq_depth(self, dlq_stream: str) -> int:
    """Return the number of entries in ``dlq_stream``.

    Returns ``0`` when the broker lacks ``DEAD_LETTER_QUEUE``.
    """
    adapter = self._dlq_port()
    return adapter.dlq_depth(dlq_stream) if adapter else 0