From 719ea7950a84957a2e0e39f79dc9ccc89009ceac Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 27 Jun 2026 23:23:50 +0100 Subject: [PATCH] Add Python typed document subscriptions --- packages/cultcache-py/README.md | 8 ++ .../cultcache-py/src/cultmesh_py/__init__.py | 2 + .../cultcache-py/src/cultmesh_py/client.py | 104 +++++++++++++++++- .../cultcache-py/src/cultmesh_py/facade.py | 23 +++- packages/cultcache-py/tests/test_cultcache.py | 65 +++++++++++ 5 files changed, 200 insertions(+), 2 deletions(-) diff --git a/packages/cultcache-py/README.md b/packages/cultcache-py/README.md index b4dcbf98..48c023ba 100644 --- a/packages/cultcache-py/README.md +++ b/packages/cultcache-py/README.md @@ -408,6 +408,14 @@ synced_stock = CultMesh.sync_document( station_stock_ui_doc, "station:starbridge:stock", ) +with CultMesh.subscribe_document( + node, + raw_client, + station_stock_ui_doc, + "station:starbridge:stock", +) as stock_subscription: + stock = stock_subscription.sync_initial() + next_change = stock_subscription.read_next_change() node.database.sync_shard_log(raw_client, shard_id="interop", shard_epoch=1) replicator = CultNetShardReplicator( node.database, diff --git a/packages/cultcache-py/src/cultmesh_py/__init__.py b/packages/cultcache-py/src/cultmesh_py/__init__.py index 72f649ba..faf39479 100644 --- a/packages/cultcache-py/src/cultmesh_py/__init__.py +++ b/packages/cultcache-py/src/cultmesh_py/__init__.py @@ -1,5 +1,6 @@ from .client import ( CultMeshDiscoveryClient, + CultMeshDocumentSubscription, CultMeshPeerExchangeClient, CultMeshPeerHealth, CultMeshPeerHealthMonitor, @@ -72,6 +73,7 @@ __all__ = [ "CultMeshHmacAuthorityLeaseVerifier", "AuthorityLeaseVerifier", "CultMeshDiscoveryClient", + "CultMeshDocumentSubscription", "CultMeshPeerExchangeClient", "CultMeshPeerHealth", "CultMeshPeerHealthMonitor", diff --git a/packages/cultcache-py/src/cultmesh_py/client.py b/packages/cultcache-py/src/cultmesh_py/client.py index e4e9ad6d..e69e0403 100644 --- a/packages/cultcache-py/src/cultmesh_py/client.py +++ b/packages/cultcache-py/src/cultmesh_py/client.py @@ -7,7 +7,7 @@ from typing import Any, Callable from urllib.parse import urlparse from cultcache_py.documents import DocumentDefinition -from cultnet_py import CultNetRawClient, CultNetRawSnapshotResponse, hello +from cultnet_py import CultNetDatabaseSubscription, CultNetRawClient, CultNetRawSnapshotResponse, hello from .wire import ( PEER_EXCHANGE_RESPONSE, @@ -315,6 +315,26 @@ class CultMeshDiscoveryClient: for document, key in documents ] + def subscribe_document( + self, + database: Any, + document: DocumentDefinition[Any], + key: str, + *, + subscription_id: str | None = None, + message_id: str = "cultmesh-python-document-subscribe", + include_snapshot: bool = True, + ) -> "CultMeshDocumentSubscription": + return CultMeshDocumentSubscription( + client=CultNetRawClient(self.host, self.port, self.timeout_seconds), + database=database, + document=document, + key=key, + subscription_id=subscription_id, + message_id=message_id, + include_snapshot=include_snapshot, + ) + def _fanout_endpoints( self, catalog: CultMeshPeerCatalog, @@ -389,6 +409,88 @@ class CultMeshPeerExchangeClient(CultMeshDiscoveryClient): return self.fanout_peer_catalog(catalog, verse_id=verse_id, roles=roles, limit=limit) +@dataclass +class CultMeshDocumentSubscription: + client: CultNetRawClient + database: Any + document: DocumentDefinition[Any] + key: str + subscription_id: str | None = None + message_id: str = "cultmesh-python-document-subscribe" + include_snapshot: bool = True + _subscription: CultNetDatabaseSubscription | None = field(default=None, init=False, repr=False) + + def __enter__(self) -> "CultMeshDocumentSubscription": + if not self.key: + raise ValueError("key must be non-empty") + registered = self.database._resolve_document_alias(self.document) + self._subscription = self.client.subscribe_database( + subscription_id=self.subscription_id or f"{registered.type}:{self.key}", + message_id=self.message_id, + schema_ids=[registered.catalog_entry().schema_id], + record_keys=[self.key], + include_snapshot=self.include_snapshot, + ) + self._subscription.__enter__() + return self + + def __exit__(self, exc_type: Any, exc: Any, traceback: Any) -> None: + if self._subscription is not None: + self._subscription.__exit__(exc_type, exc, traceback) + self._subscription = None + + def sync_initial(self) -> Any: + self._require_subscription() + changes = self._capture_changes(lambda: self.database.apply_snapshot_response( + self._subscription.read_next_snapshot_response() # type: ignore[union-attr] + )) + if changes: + return changes[-1].value + return self.database.get_required(self.document, self.key) + + def send(self, message: Any) -> None: + self._require_subscription() + self._subscription.send(message) # type: ignore[union-attr] + + def read_next_change(self) -> Any: + self._require_subscription() + remote_change = self._subscription.read_next_change() # type: ignore[union-attr] + + def apply_remote_change() -> None: + if remote_change.raw_document is not None: + self.database.apply_raw_put_message({ + "schemaVersion": "cultnet.document_put_raw.v0", + "messageId": remote_change.message_id, + "document": remote_change.raw_document.to_wire(), + }) + return + if remote_change.change_kind == "removed": + self.database.apply_raw_delete_message({ + "schemaVersion": "cultnet.document_delete.v0", + "messageId": remote_change.message_id, + "schemaId": remote_change.schema_id, + "recordKey": remote_change.record_key, + }) + + changes = self._capture_changes(apply_remote_change) + if not changes: + raise RuntimeError("CultMesh document subscription change did not apply to the local database") + return changes[-1] + + def _capture_changes(self, action: Callable[[], Any]) -> list[Any]: + changes: list[Any] = [] + unsubscribe = self.database.watch_record(self.document, self.key, changes.append) + try: + action() + finally: + unsubscribe() + return changes + + def _require_subscription(self) -> None: + if self._subscription is None: + raise RuntimeError("CultMesh document subscription is not open") + + @dataclass class CultMeshSimulationObservationFanout: client: CultMeshDiscoveryClient diff --git a/packages/cultcache-py/src/cultmesh_py/facade.py b/packages/cultcache-py/src/cultmesh_py/facade.py index 42ba8859..849d8a7a 100644 --- a/packages/cultcache-py/src/cultmesh_py/facade.py +++ b/packages/cultcache-py/src/cultmesh_py/facade.py @@ -21,7 +21,7 @@ from cultnet_py import ( wire_message_schema_catalog, ) -from .client import CultMeshPeerExchangeClient, CultMeshVerseDiscoveryClient +from .client import CultMeshDocumentSubscription, CultMeshPeerExchangeClient, CultMeshVerseDiscoveryClient from .node import CultMeshNode, CultMeshNodeOptions, create_node from .server import CultMeshLocalServer from .session import CultMeshGameSession, CultMeshGameSessionOptions @@ -292,6 +292,27 @@ class CultMesh: shard_epoch=shard_epoch, ) + @staticmethod + def subscribe_document( + node: CultMeshNode, + client: CultNetRawClient, + document: DocumentDefinition[Any], + key: str, + *, + subscription_id: str | None = None, + message_id: str = "cultmesh-python-document-subscribe", + include_snapshot: bool = True, + ) -> CultMeshDocumentSubscription: + return CultMeshDocumentSubscription( + client=client, + database=node.database, + document=document, + key=key, + subscription_id=subscription_id, + message_id=message_id, + include_snapshot=include_snapshot, + ) + @staticmethod def create_game_session( node: CultMeshNode, diff --git a/packages/cultcache-py/tests/test_cultcache.py b/packages/cultcache-py/tests/test_cultcache.py index 1630d05f..fb8b2b2b 100644 --- a/packages/cultcache-py/tests/test_cultcache.py +++ b/packages/cultcache-py/tests/test_cultcache.py @@ -4476,6 +4476,71 @@ class CultCacheTests(unittest.TestCase): self.assertEqual(target.database.get_required(document, "note:alias").body, "from-source") self.assertIsInstance(target.database.get_required(alias, "note:alias"), UiNote) + def test_cultmesh_document_subscription_syncs_alias_snapshot_and_changes(self) -> None: + @dataclass + class CanonicalNote: + body: str + + @dataclass + class UiNote: + body: str + + document = define_database_entry_type( + "mesh.subscription_alias_note", + [("body", 0)], + cls=CanonicalNote, + schema_id="mesh.subscription_alias_note.v1", + schema_name="mesh.subscription_alias_note", + schema_version="mesh.subscription_alias_note.v1", + ) + alias = define_database_entry_type( + "mesh.subscription_alias_note.ui", + [("body", 0)], + cls=UiNote, + schema_id="mesh.subscription_alias_note.v1", + schema_name="mesh.subscription_alias_note", + schema_version="mesh.subscription_alias_note.v1", + ) + source = CultMesh.create_node(runtime_id="subscription-alias-source") + source.database.register_document(document) + source.database.put_raw_message(document, "note:live", CanonicalNote("initial")) + target = CultMesh.create_node(runtime_id="subscription-alias-target") + target.database.register_document(document) + server = CultMesh.serve_node(source) + try: + raw_client = CultMesh.create_client("127.0.0.1", server.port, timeout_seconds=2.0) + with CultMesh.subscribe_document(target, raw_client, alias, "note:live") as subscription: + initial = subscription.sync_initial() + subscription.send(document_put_raw( + message_id="subscription-alias-put", + key="note:live", + schema_id="mesh.subscription_alias_note.v1", + stored_at="2026-06-14T00:00:00Z", + payload=document.encode_payload(CanonicalNote("updated")), + )) + updated = subscription.read_next_change() + subscription.send(document_delete( + message_id="subscription-alias-delete", + schema_id="mesh.subscription_alias_note.v1", + record_key="note:live", + )) + removed = subscription.read_next_change() + finally: + server.stop() + + self.assertIsInstance(initial, UiNote) + self.assertEqual(initial.body, "initial") + self.assertEqual(updated.change_kind, "updated") + self.assertIsInstance(updated.value, UiNote) + self.assertEqual(updated.value.body, "updated") + self.assertIsInstance(updated.previous_value, UiNote) + self.assertEqual(updated.previous_value.body, "initial") + self.assertEqual(removed.change_kind, "removed") + self.assertIsNone(removed.value) + self.assertIsInstance(removed.previous_value, UiNote) + self.assertEqual(removed.previous_value.body, "updated") + self.assertIsNone(target.database.get(alias, "note:live")) + def test_cultmesh_snapshot_fanout_syncs_once_and_reports_applied_records(self) -> None: document = define_database_entry_type( "mesh.snapshot_loop_note",