Bases: BaseModel
Event metadata with fixed fields and independently typed components.
New writes may contain root correlation fields and registered component payloads.
Extra root fields in historical events are retained by the deserialization path
for backwards-compatible reads.
Source code in event_sourcery/_event_store/event/dto.py
| class Context(BaseModel, extra="forbid"):
"""Event metadata with fixed fields and independently typed components.
New writes may contain root correlation fields and registered component payloads.
Extra root fields in historical events are retained by the deserialization path
for backwards-compatible reads.
"""
correlation_id: UUID | None = None
causation_id: UUID | None = None
components: dict[str, dict[str, Any]] = Field(default_factory=dict)
_legacy_fields: dict[str, Any] = PrivateAttr(default_factory=dict)
def get(self, component_type: type[TContextComponent]) -> TContextComponent | None:
"""Return a component validated as ``component_type`` when present."""
if component_type is EventCorrelation:
return cast(
TContextComponent,
EventCorrelation(
correlation_id=self.correlation_id,
causation_id=self.causation_id,
),
)
payload = self.components.get(component_type.__context_name__)
return component_type.model_validate(payload) if payload is not None else None
def with_component(self, component: ContextComponent) -> Self:
"""Return a copy with ``component`` added without mutating this context."""
if isinstance(component, EventCorrelation):
return self.model_copy(
update={
"correlation_id": component.correlation_id,
"causation_id": component.causation_id,
}
)
return self.model_copy(
update={
"components": {
**self.components,
component.__context_name__: component.model_dump(mode="json"),
}
}
)
|
get(component_type)
Return a component validated as component_type when present.
Source code in event_sourcery/_event_store/event/dto.py
| def get(self, component_type: type[TContextComponent]) -> TContextComponent | None:
"""Return a component validated as ``component_type`` when present."""
if component_type is EventCorrelation:
return cast(
TContextComponent,
EventCorrelation(
correlation_id=self.correlation_id,
causation_id=self.causation_id,
),
)
payload = self.components.get(component_type.__context_name__)
return component_type.model_validate(payload) if payload is not None else None
|
with_component(component)
Return a copy with component added without mutating this context.
Source code in event_sourcery/_event_store/event/dto.py
| def with_component(self, component: ContextComponent) -> Self:
"""Return a copy with ``component`` added without mutating this context."""
if isinstance(component, EventCorrelation):
return self.model_copy(
update={
"correlation_id": component.correlation_id,
"causation_id": component.causation_id,
}
)
return self.model_copy(
update={
"components": {
**self.components,
component.__context_name__: component.model_dump(mode="json"),
}
}
)
|