Skip to content

Write an Event-Store Adapter

To add an event-store adapter to Protean, you implement EventStorePort, register the adapter and run the event-store conformance suite against it. The worked example is DelegatingEventStore, an adapter that passes every call to the memory event store. Each member forwards its call in one statement, so you can see the shape of the adapter and replace each delegate call with a call to your store's client.


What does the adapter implement?

An event-store adapter implements EventStorePort, a typing.Protocol in protean.port.event_store. Protean's EventStore service, which domain.event_store returns, builds aggregate loading, snapshots and message reads on these members. EventStorePort has no sub-protocols: one class implements every member.

The adapter implements these members:

  • capabilities, a property that returns the guarantees the store makes
  • write_message, which appends one message to a stream and returns its position in the stream
  • the reads by stream, by category and over the whole store: get_stream_messages, get_category_messages and get_all_messages
  • the matching reads of the newest row: get_last_stream_message, get_last_category_message and get_last_message
  • stream_ids, which lists the stream identifiers in a category
  • ping, health and get_connection for connection checks
  • clear, which deletes every message, for test runs only

close, create_schema and drop_schema have defaults that do nothing. When the store holds connections, override close. An adapter that declares SCHEMA_MANAGEMENT overrides create_schema and drop_schema.

The constructor takes (name, domain, config), where config is the [event_store] table from the domain configuration. The Protocol's constructor does not store them, so the adapter sets name, domain and config itself.

The EventStorePort reference lists each member's signature and what it returns or raises.

Declare capabilities

The capabilities property returns an EventStoreCapabilities flag. Each flag is a guarantee, such as EXPECTED_VERSION: a write with a stale expected version raises and writes nothing. Declare only the flags the store keeps. The conformance suite runs the tests a flag gates only when the adapter declares that flag, so a flag the store does not keep fails those tests.

The example's capabilities property, in the next section, returns the memory store's flags, CONSISTENT. What each event store guarantees describes every flag and which built-in store declares it.

Write the adapter

Protean's event-store adapters live in src/protean/adapters/event_store/, one module per store. The class subclasses EventStorePort and sets name, domain and config in its constructor. A store with a client, such as Message DB, opens it in get_connection() on first use. Each member keeps the signature EventStorePort gives it. The example forwards every call to the memory store:

from collections.abc import Mapping
from typing import Any

from protean import Domain
from protean.adapters.event_store.memory import MemoryEventStore
from protean.infra.registry import event_stores
from protean.port.event_store import (
    EventStoreCapabilities,
    EventStoreHealth,
    EventStorePort,
    RawMessage,
)


class DelegatingEventStore(EventStorePort):
    """An event store that hands every operation to the memory event store.

    Replace the delegate calls with calls to your store's client.
    """

    def __init__(self, name: str, domain: "Domain", config: Mapping[str, Any]) -> None:
        self.name = name
        self.domain = domain
        self.config = config
        self._delegate = MemoryEventStore(name, domain, config)

    @property
    def capabilities(self) -> EventStoreCapabilities:
        """Declare only the guarantees the store makes."""
        return self._delegate.capabilities

    # Writing
    def write_message(
        self,
        stream_name: str,
        message_type: str,
        data: Mapping[str, Any],
        metadata: Mapping[str, Any] | None = None,
        expected_version: int | None = None,
    ) -> int:
        return self._delegate.write_message(
            stream_name, message_type, data, metadata, expected_version
        )

    # Reading
    def get_stream_messages(
        self, stream_name: str, position: int = 0, limit: int = 1000
    ) -> list[RawMessage]:
        return self._delegate.get_stream_messages(stream_name, position, limit)

    def get_category_messages(
        self,
        category: str,
        position: int = 0,
        limit: int = 1000,
        *,
        consumer_group_member: int | None = None,
        consumer_group_size: int | None = None,
    ) -> list[RawMessage]:
        return self._delegate.get_category_messages(
            category,
            position,
            limit,
            consumer_group_member=consumer_group_member,
            consumer_group_size=consumer_group_size,
        )

    def get_all_messages(
        self, position: int = 0, limit: int = 1000
    ) -> list[RawMessage]:
        return self._delegate.get_all_messages(position, limit)

    def stream_ids(self, category: str) -> list[str]:
        return self._delegate.stream_ids(category)

    # Last message
    def get_last_stream_message(self, stream_name: str) -> RawMessage | None:
        return self._delegate.get_last_stream_message(stream_name)

    def get_last_category_message(self, category: str) -> RawMessage | None:
        return self._delegate.get_last_category_message(category)

    def get_last_message(self) -> RawMessage | None:
        return self._delegate.get_last_message()

    # Connection and health
    def ping(self) -> bool:
        return self._delegate.ping()

    def health(self) -> EventStoreHealth:
        return self._delegate.health()

    def get_connection(self) -> object:
        # Open your store's client here, on the first call
        return self._delegate.get_connection()

    def close(self) -> None:
        self._delegate.close()

    # Test harness
    def clear(self) -> None:
        self._delegate.clear()

End the module with a typed assignment of the class to EventStorePort, as the built-in stores do. When the class leaves a member abstract, mypy reports an error on this line:

_PORT_CHECK: type[EventStorePort] = DelegatingEventStore

Register it with an entry point

A register() function adds the adapter to the event-store registry, protean.infra.registry.event_stores, under the name a domain configuration uses as provider:

def register() -> None:
    """Register the store as `provider = "delegating_memory"`."""
    event_stores.register("delegating_memory", f"{__name__}.DelegatingEventStore")

Protean calls register() through an entry point in the protean.event_stores group the first time it looks up an event-store name. Add the entry-point line to the [project.entry-points."protean.event_stores"] table in Protean's pyproject.toml:

[project.entry-points."protean.event_stores"]
delegating_memory = "delegating_event_store:register"

After you edit pyproject.toml, run uv sync --all-extras --all-groups. The installed package then lists the new entry point.

The example module also calls register() when it is imported, so a test run can load it with -p delegating_event_store. Leave that call out of your adapter.

When the store needs an optional extra, such as a client library, put register() in src/protean/adapters/event_store/__init__.py, as Message DB does, and point the entry point at it. The registry stores the class's dotted path, so registering the name does not import the client library. Without the extra, looking up the name then fails on the missing module instead of reporting an unknown event store.

Run the conformance suite

The event-store conformance suite checks the adapter against the Port and against each flag it declares. Run it from a source checkout of Protean. The suite is in tests/conformance/event_store/. The wheel that pip install protean fetches does not include the tests/ folder.

protean test test-adapter --port event_store --provider <name>

<name> is the name register() uses. The command prints a row for the tests that need no flag and a row for each flag the adapter declares. Each flag the adapter does not declare shows as SKIP (not declared). When the store needs a connection URI or other settings, pass --uri or --config. The suite deletes every message after each test, so point it only at a test database.

The command finds the adapter through its entry point, so the adapter must be installed. The example is not installed, so its test run puts the example's folder on PYTHONPATH and loads the module as a pytest plugin:

PYTHONPATH=docs_src/guides/write-an-adapter/event-store \
    python -m pytest tests/conformance/event_store -p delegating_event_store \
    --port event_store --adapter delegating_memory

Adapter Conformance Testing lists every option of the command.

Configure it in domain.toml

A domain selects the adapter by its registered name in the [event_store] table:

[event_store]
provider = "delegating_memory"

Protean passes the whole table, provider included, to the adapter's constructor as config. The adapter reads its own settings from it, such as the database_uri the Message DB store reads. Event Store Setup shows the configuration of the built-in stores.