Skip to content

Enrich event context

A context enricher adds a typed component immediately before an event is serialized. Configure enrichers on the backend before accessing its event store. The original event context is not mutated.

class RequestContext(ContextComponent):
    __context_name__: ClassVar[str] = "application.request"

    request_id: str

class RequestContextEnricher:
    component_type: type[ContextComponent] = RequestContext

    def enrich(
        self,
        context: Context,
        *,
        event: WrappedEvent,
        stream_id: StreamId,
    ) -> RequestContext:
        return RequestContext(request_id="request-123")

class InvoicePaid(Event):
    invoice_number: str

backend = InMemoryBackend().with_context_enrichers(RequestContextEnricher())
event_store = backend.event_store
stream_id = StreamId(name="invoices/1003")

event_store.append(InvoicePaid(invoice_number="1003"), stream_id=stream_id)

recorded = event_store.load_stream(stream_id)[0]
assert recorded.context.get(RequestContext) == RequestContext(
    request_id="request-123"
)

Pass multiple enrichers to with_context_enrichers() in their execution order. Each enricher may return None when it has no component to add for an event. If two enrichers declare the same component, with_context_enrichers() raises ConflictingContextComponent. A component explicitly supplied with the event takes precedence over enricher output.