From cb8df9dd9e1665cf52714044601e8cf9243a89ac Mon Sep 17 00:00:00 2001 From: Phil Helm Date: Tue, 3 Nov 2026 15:16:16 +0000 Subject: [PATCH 1/3] Fix incorrect docstrings in event store Categories are async iterable only, stream/category accessors return EventStream/EventCategory, and publish docstrings now describe conditions, return values and UnmetWriteConditionError. --- src/logicblocks/event/store/store.py | 49 +++++++++++++++++++++------- 1 file changed, 38 insertions(+), 11 deletions(-) diff --git a/src/logicblocks/event/store/store.py b/src/logicblocks/event/store/store.py index c17a13f4..d3125563 100644 --- a/src/logicblocks/event/store/store.py +++ b/src/logicblocks/event/store/store.py @@ -63,7 +63,20 @@ async def publish[ events: Sequence[NewEvent[Name, Payload, Metadata]], condition: WriteCondition = NoCondition(), ) -> Sequence[StoredEvent[Name, Payload, Metadata]]: - """Publish a sequence of events into the stream.""" + """Publish a sequence of events into the stream. + + Args: + events: The events to publish, in order. + condition: A write condition that must be met for the events to + be written. Defaults to no condition. + + Returns: + the stored events, in the order they were published. + + Raises: + UnmetWriteConditionError: If the condition is not met, in which + case no events are written. + """ await self._logger.adebug( "event.stream.publishing", category=self._identifier.category, @@ -144,7 +157,7 @@ class EventCategory(EventSource[CategoryIdentifier, StoredEvent]): can be narrowed to a specific stream using the `stream` method. Events in the category can be read using the `read` method. Categories are - also iterable, supporting `iter`. + also async iterable, supporting `aiter` and `async for`. """ def __init__( @@ -172,7 +185,7 @@ def stream(self, *, stream: str) -> EventStream: stream (str): The name of the stream. Returns: - an event store scoped to the specified stream. + an `EventStream` for the specified stream. """ return EventStream( adapter=self._adapter, @@ -213,7 +226,21 @@ async def publish[ str, StreamPublishDefinition[Name, Payload, Metadata] ], ) -> Mapping[str, Sequence[StoredEvent[Name, Payload, Metadata]]]: - """Publish events to multiple streams in the category atomically.""" + """Publish events to multiple streams in the category atomically. + + Args: + streams: A mapping from stream name to the definition of what to + publish to that stream. Each definition holds the events to + publish and, optionally, the write condition for that stream. + Streams without a condition are written unconditionally. + + Returns: + a mapping from stream name to the stored events for that stream. + + Raises: + UnmetWriteConditionError: If any stream's condition is not met, in + which case no events are written to any stream. + """ return await self._adapter.save( target=self._identifier, streams=streams ) @@ -309,9 +336,9 @@ def __init__( def stream(self, *, category: str, stream: str) -> EventStream: """Get a stream of events from the store. - This method alone doesn't result in any IO, it instead returns a scoped - event store for the stream identified by the category and stream names, - as part of a fluent interface. + This method alone doesn't result in any IO, it instead returns an + `EventStream` for the stream identified by the category and stream + names, as part of a fluent interface. Categories and streams implicitly exist, i.e., calling this method for a category or stream that has never been written to will not result in an @@ -322,7 +349,7 @@ def stream(self, *, category: str, stream: str) -> EventStream: stream (str): The name of the stream. Returns: - an event store scoped to the specified stream. + an `EventStream` for the specified stream. """ return EventStream( adapter=self._adapter, @@ -333,8 +360,8 @@ def stream(self, *, category: str, stream: str) -> EventStream: def category(self, *, category: str) -> EventCategory: """Get a category of events from the store. - This method alone doesn't result in any IO, it instead returns a scoped - event store for the category identified by the category name, + This method alone doesn't result in any IO, it instead returns an + `EventCategory` for the category identified by the category name, as part of a fluent interface. Categories implicitly exist, i.e., calling this method for a category @@ -344,7 +371,7 @@ def category(self, *, category: str) -> EventCategory: category (str): The name of the category. Returns: - an event store scoped to the specified category. + an `EventCategory` for the specified category. """ return EventCategory( adapter=self._adapter, From bf63c3f24b495f5b18c6b8dd0d59b213f3210a36 Mon Sep 17 00:00:00 2001 From: Phil Helm Date: Tue, 3 Nov 2026 16:20:21 +0000 Subject: [PATCH 2/3] Correct the finalising state docs Describe what state ProjectionEventProcessor actually passes, replace the 'reserved name' claim with the real handler-name clash behaviour, and link ProfileProjector back to the basic example. --- README.md | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 977779c6..b4b448cc 100644 --- a/README.md +++ b/README.md @@ -102,7 +102,9 @@ asyncio.run(main()) Override `finalise_state` to do work once per projection rather than in every event handler, for example validation or normalisation. Handlers can then make -cheap, unvalidated changes and leave the expensive work to the end: +cheap, unvalidated changes and leave the expensive work to the end. This +example extends the `ProfileProjector` from the +[basic example](#basic-example): ```python class ValidatedProfileProjector(ProfileProjector): @@ -119,9 +121,11 @@ including when the source has no events. Keep in mind that: - with `ProjectionEventProcessor`, which projects one event at a time, it runs once per processed event, so the saving comes from multi-event folds such as rebuilds; -- its output is passed back in as the starting state when a projection is - resumed (via `state=`, and always by `ProjectionEventProcessor`), so it must - not change what later handlers, `update_metadata` or `id_factory` compute. +- its output becomes the starting state when a projection is resumed, either + directly via `state=` or, with `ProjectionEventProcessor`, as the state + reloaded from the projection store (the processor passes `state=None` for + a stream's first event, when nothing is stored yet). So it must not change + what later handlers, `update_metadata` or `id_factory` compute. Validation and recomputing derived fields are fine; lossy normalisation, such as clamping or truncation, isn't; - its output must survive a round trip through the projection store, and it @@ -129,8 +133,12 @@ including when the source has no events. Keep in mind that: stored, otherwise those projections need rebuilding; - `update_metadata` and `apply()` see unfinalised state; - handlers mustn't rely on coercion or defaults that validation would apply; -- `finalise_state` is a reserved name, so no event may be named - `finalise-state`; +- handlers are found by converting the event name to snake case, and nothing + stops that matching a projector method. An event named `finalise-state` is + routed to `finalise_state` as if it were a handler and fails with a + `TypeError`. Other method names clash the same way: `apply` and `project` + also raise a `TypeError`, and `id-factory` silently replaces the state with + the projection id. Avoid event names that convert to projector methods; - subclasses that override `project()` must call `finalise_state` themselves. From 9d087b2da1b8789e1ab195e0d457944eeeab6f37 Mon Sep 17 00:00:00 2001 From: Phil Helm Date: Tue, 3 Nov 2026 16:20:21 +0000 Subject: [PATCH 3/3] Polish the README basic example Print the projected state inside main(), drop the easily misread projection-metadata type argument, explain structlog output and how to quieten it, and tidy formatting. --- README.md | 69 ++++++++++++++++++++++++++++++++----------------------- 1 file changed, 40 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index b4b448cc..705d40a0 100644 --- a/README.md +++ b/README.md @@ -34,30 +34,28 @@ Usage ```python import asyncio -from logicblocks.event.store import EventStore, adapters -from logicblocks.event.types import NewEvent, StreamIdentifier from logicblocks.event.projection import Projector +from logicblocks.event.store import EventStore, adapters +from logicblocks.event.types import JsonValue, NewEvent, StreamIdentifier -class ProfileProjector( - Projector[StreamIdentifier, dict[str, str], dict[str, str]] -): +class ProfileProjector(Projector[StreamIdentifier, dict[str, str]]): def initial_state_factory(self) -> dict[str, str]: return {} - def initial_metadata_factory(self) -> dict[str, str]: + def initial_metadata_factory(self) -> JsonValue: return {} def id_factory(self, state, source: StreamIdentifier) -> str: return source.stream def profile_created(self, state, event): - state['name'] = event.payload['name'] - state['email'] = event.payload['email'] + state["name"] = event.payload["name"] + state["email"] = event.payload["email"] return state def date_of_birth_set(self, state, event): - state['dob'] = event.payload['dob'] + state["dob"] = event.payload["dob"] return state @@ -66,36 +64,49 @@ async def main(): store = EventStore(adapter) stream = store.stream(category="profiles", stream="joe.bloggs") + # metadata is required; pass metadata=None when the event has no metadata - profile_created_event = NewEvent(name="profile-created", - payload={"name": "Joe Bloggs", "email": "joe.bloggs@example.com"}, - metadata=None) - date_of_birth_set_event = NewEvent(name="date-of-birth-set", payload={"dob": "1992-07-10"}, - metadata={"actor": "user-123"}) - - await stream.publish( - events=[ - profile_created_event - ]) - await stream.publish( - events=[ - date_of_birth_set_event - ] + profile_created_event = NewEvent( + name="profile-created", + payload={"name": "Joe Bloggs", "email": "joe.bloggs@example.com"}, + metadata=None, ) + date_of_birth_set_event = NewEvent( + name="date-of-birth-set", + payload={"dob": "1992-07-10"}, + metadata={"actor": "user-123"}, + ) + + await stream.publish(events=[profile_created_event]) + await stream.publish(events=[date_of_birth_set_event]) projector = ProfileProjector() projection = await projector.project(source=stream) - profile = projection.state + + print(projection.state) + # {'name': 'Joe Bloggs', 'email': 'joe.bloggs@example.com', + # 'dob': '1992-07-10'} asyncio.run(main()) +``` + +`Projector` takes the source identifier type, the state type and, optionally, +the type of the projection's own metadata, which defaults to `JsonValue`. The +projection's metadata is separate from the metadata on each event. + +The library logs through [structlog](https://www.structlog.org/), so running +the example also prints debug and info lines for each publish and read. To +show only warnings and above, configure structlog before running it: + +```python +import logging +import structlog -# profile == { -# "name": "Joe Bloggs", -# "email": "joe.bloggs@example.com", -# "dob": "1992-07-10" -# } +structlog.configure( + wrapper_class=structlog.make_filtering_bound_logger(logging.WARNING) +) ``` ### Finalising State