Skip to content

Event Processing

Subscribers consume external broker messages, process managers coordinate multi-step workflows, and upcasters convert stored event data from an older schema version to a newer one.

Guides: Subscribers · Process Managers · Event Upcasting


BaseSubscriber

Bases: Element, OptionsMixin

Base class for subscribers that consume messages from external message brokers and act as an anti-corruption layer at the domain boundary.

Subscribers listen to named broker streams, receive raw dict payloads (not typed domain events), and translate external data into domain operations. Implement the __call__ method to process incoming messages.

Meta Options

Option Type Description
broker str The broker adapter name to consume from (default: "default").
stream str The external stream/topic name to subscribe to. Required.
idempotent bool Record a delivery marker per message so a redelivered message is applied once. The payload must carry metadata.headers.id (default: False).
database str The [databases.*] entry that stores the delivery marker when idempotent is set (default: "default").

__call__ abstractmethod

__call__(payload: dict[str, Any]) -> None

Placeholder method for receiving notifications on event

Source code in src/protean/core/subscriber.py
50
51
52
@abstractmethod
def __call__(self, payload: dict[str, Any]) -> None:
    """Placeholder method for receiving notifications on event"""

handle_error classmethod

handle_error(
    exc: Exception, message: dict[str, Any]
) -> None

Handle an exception raised while the engine processed a broker message.

Override it to add custom error handling, such as logging more detail or cleaning up. The engine logs the failure, calls this method, and then moves on to the next message. The default does nothing. An exception raised here is logged and not propagated, so it does not stop the engine.

PARAMETER DESCRIPTION
exc

The exception raised by the subscriber's __call__, or the InsufficientDataError raised before the call when the subscriber is idempotent and the payload's id is unusable.

TYPE: Exception

message

The message payload being processed when the exception occurred.

TYPE: dict[str, Any]

Source code in src/protean/core/subscriber.py
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
@classmethod
def handle_error(cls, exc: Exception, message: dict[str, Any]) -> None:
    """Handle an exception raised while the engine processed a broker message.

    Override it to add custom error handling, such as logging more detail
    or cleaning up. The engine logs the failure, calls this method, and
    then moves on to the next message. The default does nothing. An
    exception raised here is logged and not propagated, so it does not
    stop the engine.

    Args:
        exc: The exception raised by the subscriber's ``__call__``, or
            the ``InsufficientDataError`` raised before the call when the
            subscriber is idempotent and the payload's id is unusable.
        message: The message payload being processed when the exception
            occurred.
    """

BaseProcessManager

BaseProcessManager(*args: Any, **kwargs: Any)

Bases: Element, BaseModel, HandlerMixin, OptionsMixin

Base class for process managers.

A process manager handles events from several aggregate streams and keeps its own state between them. After each handler method runs, it saves that state as a transition event in the event store. See the Process Managers guide for a walk-through.

Meta Options

Option Type Description
stream_categories list Stream categories to subscribe to.
aggregates list Aggregate classes to listen to (categories derived automatically).
subscription_type str The subscription type to use.
subscription_profile str A predefined configuration profile.
subscription_config dict Dictionary of custom configuration overrides.
sequential_by bool Opt in to per-instance sequential processing (ADR-0028).
Source code in src/protean/core/process_manager.py
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
def __init__(self, *args: Any, **kwargs: Any) -> None:
    if self.meta_.abstract is True:
        raise NotSupportedError(
            f"{self.__class__.__name__} class has been marked abstract"
            f" and cannot be instantiated"
        )

    # Support template dict pattern
    if args:
        merged: dict[str, Any] = {}
        for template in args:
            _ensure_template_dict(template)
            merged.update(template)
        merged.update(kwargs)
        kwargs = merged

    super().__init__(**kwargs)

__track_id_field classmethod

__track_id_field() -> None

Find the field marked identifier=True and record its name.

Source code in src/protean/core/process_manager.py
243
244
245
246
247
248
249
250
251
252
253
254
255
@classmethod
def __track_id_field(cls) -> None:
    """Find the field marked ``identifier=True`` and record its name."""
    id_fld = next(
        (
            field
            for _, field in getattr(cls, _FIELDS, {}).items()
            if getattr(field, "identifier", False)
        ),
        None,
    )
    if id_fld is not None:
        setattr(cls, _ID_FIELD_NAME, id_fld.field_name)

mark_as_complete

mark_as_complete() -> None

Mark this process manager as complete.

Once complete, no further events will be processed for this instance.

Source code in src/protean/core/process_manager.py
278
279
280
281
282
283
def mark_as_complete(self) -> None:
    """Mark this process manager as complete.

    Once complete, no further events will be processed for this instance.
    """
    self._is_complete = True

to_dict

to_dict() -> dict[str, Any]

Return process manager data as a dictionary.

Source code in src/protean/core/process_manager.py
288
289
290
291
292
293
294
295
def to_dict(self) -> dict[str, Any]:
    """Return process manager data as a dictionary."""
    result: dict[str, Any] = {}
    for fname, shim in getattr(self, _FIELDS, {}).items():
        if fname.startswith("_"):
            continue
        result[fname] = shim.as_dict(getattr(self, fname, None))
    return result

BaseUpcaster

Bases: Element, OptionsMixin

Base class for event upcasters.

Subclasses must implement upcast() which receives the raw event payload dict (as stored in the event store) and returns a transformed dict compatible with the target version's schema.

Meta Options

Option Type Description
event_type type The event class this upcaster targets (current version).
from_version int Source version number (e.g. 1).
to_version int Target version number (e.g. 2).

upcast abstractmethod

upcast(data: dict[str, Any]) -> dict[str, Any]

Transform event data from from_version to to_version.

PARAMETER DESCRIPTION
data

The raw event payload dictionary as stored.

TYPE: dict[str, Any]

RETURNS DESCRIPTION
dict[str, Any]

The transformed payload dictionary compatible with to_version.

Source code in src/protean/core/upcaster.py
56
57
58
59
60
61
62
63
64
65
66
@abstractmethod
def upcast(self, data: dict[str, Any]) -> dict[str, Any]:
    """Transform event data from ``from_version`` to ``to_version``.

    Args:
        data: The raw event payload dictionary as stored.

    Returns:
        The transformed payload dictionary compatible with ``to_version``.
    """
    ...