Watch Python CultNet database changes

This commit is contained in:
Meta Vens 2026-06-14 00:14:36 +01:00
commit 1d0a700f9e
5 changed files with 238 additions and 1 deletions

View file

@ -175,6 +175,8 @@ subscription = database_subscribe(subscription_id="ui", schema_ids=["cultnet.int
shard_request = shard_catalog_request(message_id="shards", schema_ids=["cultnet.interop-note"])
shard_log = client.fetch_shard_log(shard_id="interop", shard_epoch=1, after_sequence=0)
# log_changes = apply_shard_log_response(cache, [note_doc], shard_log)
with client.subscribe_database(subscription_id="ui", schema_ids=["cultnet.interop-note"]) as live:
initial_snapshot = live.read_next()
claim_hash = compute_simulation_claim_hash("frame:42", "subject:player-1", "hit")
observation = simulation_observation(
message_id="obs-1",

View file

@ -1,4 +1,4 @@
from .client import CultNetRawClient
from .client import CultNetDatabaseSubscription, CultNetRawClient
from .framing import decode_frame, encode_frame, read_frame, write_frame
from .messages import (
CultNetMessage,
@ -28,6 +28,7 @@ from .replication import (
__all__ = [
"CultNetMessage",
"CultNetDatabaseSubscription",
"CultNetRawClient",
"CultNetAppliedRecord",
"apply_raw_document_record",

View file

@ -9,6 +9,8 @@ import msgpack
from .framing import read_frame, write_frame
from .messages import (
CultNetMessage,
database_subscribe,
database_unsubscribe,
schema_catalog_request,
shard_catalog_request,
shard_log_request,
@ -107,3 +109,88 @@ class CultNetRawClient:
expected_schema_version="cultnet.shard_log_response.v0",
)
def subscribe_database(
self,
*,
subscription_id: str,
message_id: str = "cultnet-python-subscribe",
schema_ids: list[str] | None = None,
record_keys: list[str] | None = None,
include_snapshot: bool = True,
) -> "CultNetDatabaseSubscription":
return CultNetDatabaseSubscription(
host=self.host,
port=self.port,
timeout_seconds=self.timeout_seconds,
subscription_id=subscription_id,
message_id=message_id,
schema_ids=schema_ids,
record_keys=record_keys,
include_snapshot=include_snapshot,
)
@dataclass
class CultNetDatabaseSubscription:
host: str
port: int
timeout_seconds: float
subscription_id: str
message_id: str = "cultnet-python-subscribe"
schema_ids: list[str] | None = None
record_keys: list[str] | None = None
include_snapshot: bool = True
_connection: socket.socket | None = None
_stream: Any | None = None
def __enter__(self) -> "CultNetDatabaseSubscription":
self._connection = socket.create_connection((self.host, self.port), timeout=self.timeout_seconds)
self._connection.settimeout(self.timeout_seconds)
self._stream = self._connection.makefile("rwb")
self.send(database_subscribe(
message_id=self.message_id,
subscription_id=self.subscription_id,
schema_ids=self.schema_ids,
record_keys=self.record_keys,
include_snapshot=self.include_snapshot,
))
return self
def __exit__(self, exc_type: Any, exc: Any, traceback: Any) -> None:
try:
if self._stream is not None:
self.send(database_unsubscribe(
message_id=f"{self.message_id}-unsubscribe",
subscription_id=self.subscription_id,
))
finally:
if self._stream is not None:
self._stream.close()
self._stream = None
if self._connection is not None:
self._connection.close()
self._connection = None
def send(self, message: CultNetMessage | dict[str, Any]) -> None:
if self._stream is None:
raise RuntimeError("CultNet database subscription is not open")
wire = message.to_wire() if isinstance(message, CultNetMessage) else message
write_frame(self._stream, msgpack.packb(wire, use_bin_type=True))
self._stream.flush()
def read_next(self) -> dict[str, Any]:
if self._stream is None:
raise RuntimeError("CultNet database subscription is not open")
response = msgpack.unpackb(read_frame(self._stream), raw=False)
if not isinstance(response, dict):
raise ValueError("CultNet subscription response must be a MessagePack map")
schema_version = response.get("schemaVersion")
if schema_version not in {"cultnet.snapshot_response_raw.v0", "cultnet.database_change_raw.v0"}:
raise ValueError(f"Unexpected CultNet subscription message {schema_version!r}")
return response
def iter_messages(self, *, max_messages: int | None = None) -> Any:
received = 0
while max_messages is None or received < max_messages:
yield self.read_next()
received += 1

View file

@ -347,6 +347,94 @@ class CultCacheTests(unittest.TestCase):
"cultnet.shard_log_request.v0",
])
def test_cultnet_database_subscription_reads_snapshot_and_change(self) -> None:
import msgpack # type: ignore
from cultnet_py import read_frame, write_frame
document = define_database_entry_type(
"sub.item",
[
("name", 0),
("category", 1),
("value", 2, 0),
],
cls=Item,
)
schema_id = document.catalog_entry().schema_id
ready = threading.Event()
server_error: list[BaseException] = []
port_holder: list[int] = []
received_versions: list[str] = []
def serve_subscription() -> None:
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(("127.0.0.1", 0))
port_holder.append(server.getsockname()[1])
server.listen(1)
ready.set()
connection, _ = server.accept()
with connection:
stream = connection.makefile("rwb")
subscribe = msgpack.unpackb(read_frame(stream), raw=False)
received_versions.append(subscribe["schemaVersion"])
self.assertEqual(subscribe["subscriptionId"], "sub-1")
snapshot = {
"schemaVersion": "cultnet.snapshot_response_raw.v0",
"messageId": subscribe["messageId"],
"documents": [],
}
write_frame(stream, msgpack.packb(snapshot, use_bin_type=True))
stream.flush()
put = msgpack.unpackb(read_frame(stream), raw=False)
received_versions.append(put["schemaVersion"])
change = {
"schemaVersion": "cultnet.database_change_raw.v0",
"messageId": "change-1",
"subscriptionId": "sub-1",
"changeKind": "added",
"document": put["document"],
}
write_frame(stream, msgpack.packb(change, use_bin_type=True))
stream.flush()
unsubscribe = msgpack.unpackb(read_frame(stream), raw=False)
received_versions.append(unsubscribe["schemaVersion"])
except BaseException as error:
server_error.append(error)
ready.set()
thread = threading.Thread(target=serve_subscription, daemon=True)
thread.start()
self.assertTrue(ready.wait(2.0))
self.assertFalse(server_error)
client = CultNetRawClient("127.0.0.1", port_holder[0], timeout_seconds=2.0)
put = document_put_raw(
message_id="put-sub",
key="item:sub",
schema_id=schema_id,
stored_at="2026-06-14T00:00:00Z",
payload=document.encode_payload(Item("orb", "gear", 8)),
)
with client.subscribe_database(subscription_id="sub-1", schema_ids=[schema_id]) as subscription:
snapshot = subscription.read_next()
subscription.send(put)
change = subscription.read_next()
thread.join(2.0)
self.assertFalse(server_error)
self.assertEqual(snapshot["schemaVersion"], "cultnet.snapshot_response_raw.v0")
self.assertEqual(change["schemaVersion"], "cultnet.database_change_raw.v0")
self.assertEqual(change["document"]["recordKey"], "item:sub")
self.assertEqual(received_versions, [
"cultnet.database_subscribe.v0",
"cultnet.document_put_raw.v0",
"cultnet.database_unsubscribe.v0",
])
def test_cultnet_replication_helpers_apply_raw_snapshot_and_shard_log(self) -> None:
document = define_database_entry_type(
"replica.item",

View file

@ -311,6 +311,11 @@ test("CultNet TS/Rust/C#/Python peers discover each other and exchange raw state
assert.equal(pythonCultMeshNodeEmit.note.authorRuntimeId, "python-node-emit");
assert.equal(pythonCultMeshNodeEmit.note.title, "Python node emitted raw put");
const pythonSubscription = await runPythonCultNetSubscription(pythonPort);
assert.equal(pythonSubscription.changeKind, "added");
assert.equal(pythonSubscription.recordKey, "note:python-sub-client");
assert.equal(pythonSubscription.subscriptionId, "python-public-sub");
const pythonChange = await requestPythonDatabaseChange(pythonPort, {
schemaVersion: "cultnet.database_subscribe.v0",
messageId: "python-subscribe",
@ -872,6 +877,60 @@ async function runPythonCultMeshNodeEmit(port: number): Promise<any> {
return JSON.parse(stdout);
}
async function runPythonCultNetSubscription(port: number): Promise<any> {
const schemaPathJson = JSON.stringify(interopSchemaPath);
const script = [
"import json",
"from pathlib import Path",
"from cultcache_py import define_database_entry_type",
"from cultmesh_py import create_node",
"from cultnet_py import CultNetRawClient",
`schema_json = Path(${schemaPathJson}).read_text(encoding='utf-8')`,
"note_doc = define_database_entry_type(",
" 'cultnet.interop-note',",
" [('schemaVersion', 0), ('documentId', 1), ('authorRuntimeId', 2), ('title', 3), ('body', 4), ('tags', 5, [])],",
` schema_id='${interopNoteSchemaId}',`,
" schema_version='cultnet.interop_note.v0',",
" canonical_schema_json=schema_json,",
")",
"node = create_node(runtime_id='python-sub-client')",
"node.register_document(note_doc)",
"message = node.put_raw_message(",
" note_doc,",
" 'note:python-sub-client',",
" {",
" 'schemaVersion': 'cultnet.interop_note.v0',",
" 'documentId': 'note:python-sub-client',",
" 'authorRuntimeId': 'python-sub-client',",
" 'title': 'Python subscription client emitted raw put',",
" 'body': 'subscription client saw its own live change',",
" 'tags': ['python', 'subscription'],",
" },",
" message_id='python-sub-client-put',",
" shard_id='interop',",
" shard_epoch=1,",
")",
`client = CultNetRawClient('127.0.0.1', ${port}, timeout_seconds=4.0)`,
`with client.subscribe_database(subscription_id='python-public-sub', schema_ids=['${interopNoteSchemaId}'], record_keys=['note:python-sub-client'], include_snapshot=False) as subscription:`,
" subscription.send(message)",
" change = subscription.read_next()",
"print(json.dumps({",
" 'subscriptionId': change.get('subscriptionId'),",
" 'changeKind': change.get('changeKind'),",
" 'recordKey': change.get('document', {}).get('recordKey'),",
"}))",
].join("\n");
const { stdout } = await execFileAsync(pythonCommand, ["-c", script], {
cwd: cultcachePyRoot,
env: {
...process.env,
PYTHONPATH: cultcachePySrc,
},
timeout: 8000,
});
return JSON.parse(stdout);
}
async function requestPythonDatabaseChange(port: number, subscribe: Record<string, unknown>, put: Record<string, unknown>): Promise<any> {
const socket = connectTcp(port, "127.0.0.1");
const framer = new LengthPrefixedMessageFramer();