Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 54 additions & 35 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand All @@ -66,43 +64,58 @@ 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

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):
Expand All @@ -119,18 +132,24 @@ 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
must not change fields `id_factory` uses for projections that are already
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.

Expand Down
49 changes: 38 additions & 11 deletions src/logicblocks/event/store/store.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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__(
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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
)
Expand Down Expand Up @@ -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
Expand All @@ -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,
Expand All @@ -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
Expand All @@ -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,
Expand Down
Loading