Add Python CultNet subscription interop

This commit is contained in:
Meta Vens 2026-06-13 21:54:03 +01:00
commit 3d67576444
5 changed files with 192 additions and 8 deletions

View file

@ -1,6 +1,8 @@
from .framing import decode_frame, encode_frame, read_frame, write_frame
from .messages import (
CultNetMessage,
database_subscribe,
database_unsubscribe,
document_delete,
document_put_raw,
hello,
@ -11,6 +13,8 @@ from .messages import (
__all__ = [
"CultNetMessage",
"database_subscribe",
"database_unsubscribe",
"decode_frame",
"document_delete",
"document_put_raw",

View file

@ -78,6 +78,22 @@ class PeerState:
peer_catalog: CultMeshPeerCatalog
@dataclass
class DatabaseSubscription:
subscription_id: str
schema_ids: set[str]
record_keys: set[str]
def matches(self, document: dict[str, Any]) -> bool:
schema_id = document.get("schemaId")
record_key = document.get("recordKey")
if self.schema_ids and schema_id not in self.schema_ids:
return False
if self.record_keys and record_key not in self.record_keys:
return False
return True
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(prog="cultnet-py-interop")
sub = parser.add_subparsers(dest="mode", required=True)
@ -175,6 +191,7 @@ def accept_loop(server: socket.socket, state: PeerState, stop: threading.Event)
def handle_connection(client: socket.socket, state: PeerState) -> None:
with client:
stream = client.makefile("rwb", buffering=0)
subscriptions: dict[str, DatabaseSubscription] = {}
while True:
try:
payload = read_frame(stream)
@ -183,12 +200,12 @@ def handle_connection(client: socket.socket, state: PeerState) -> None:
message = msgpack.unpackb(payload, raw=False)
if not isinstance(message, dict):
continue
response_messages = handle_server_message(state, message)
response_messages = handle_server_message(state, message, subscriptions)
for response in response_messages:
write_message(stream, response)
def handle_server_message(state: PeerState, message: dict[str, Any]) -> list[dict[str, Any]]:
def handle_server_message(state: PeerState, message: dict[str, Any], subscriptions: dict[str, DatabaseSubscription]) -> list[dict[str, Any]]:
schema_version = message.get("schemaVersion")
if schema_version == "cultnet.hello.v0":
return [hello_message(state)]
@ -196,8 +213,13 @@ def handle_server_message(state: PeerState, message: dict[str, Any]) -> list[dic
return [catalog_response(state, message)]
if schema_version == "cultnet.snapshot_request.v0":
return [raw_snapshot_response(state, message)]
if schema_version == "cultnet.database_subscribe.v0":
return handle_database_subscribe(state, message, subscriptions)
if schema_version == "cultnet.database_unsubscribe.v0":
subscriptions.pop(str(message.get("subscriptionId") or ""), None)
return []
if schema_version == "cultnet.document_put_raw.v0":
return handle_raw_put(state, message)
return handle_raw_put(state, message, subscriptions)
if schema_version == VERSE_CATALOG_REQUEST:
return [state.verse_catalog.create_response(message)]
if schema_version == PEER_EXCHANGE_REQUEST:
@ -205,11 +227,26 @@ def handle_server_message(state: PeerState, message: dict[str, Any]) -> list[dic
return []
def handle_raw_put(state: PeerState, message: dict[str, Any]) -> list[dict[str, Any]]:
def handle_database_subscribe(state: PeerState, message: dict[str, Any], subscriptions: dict[str, DatabaseSubscription]) -> list[dict[str, Any]]:
subscription_id = str(message.get("subscriptionId") or message.get("messageId") or "")
if not subscription_id:
return []
subscriptions[subscription_id] = DatabaseSubscription(
subscription_id=subscription_id,
schema_ids={str(value) for value in message.get("schemaIds") or []},
record_keys={str(value) for value in message.get("recordKeys") or []},
)
if message.get("includeSnapshot", True) is False:
return []
return [raw_snapshot_response(state, message)]
def handle_raw_put(state: PeerState, message: dict[str, Any], subscriptions: dict[str, DatabaseSubscription]) -> list[dict[str, Any]]:
document = message.get("document")
if not isinstance(document, dict):
return []
applied = apply_raw_document_put(state, document)
responses = database_change_notifications(message, document, subscriptions)
schema_id = document.get("schemaId")
if schema_id == INTEROP_MUTATION_INTENT_SCHEMA_ID:
note_binding = state.bindings_by_schema_id[state.note_schema_id]
@ -230,6 +267,7 @@ def handle_raw_put(state: PeerState, message: dict[str, Any]) -> list[dict[str,
"tags": mutated["tags"],
}
return [
*responses,
raw_document_put(state.bindings_by_schema_id[INTEROP_MUTATION_RECEIPT_SCHEMA_ID], f"{state.runtime_id}-mutation-receipt", receipt["intentId"], receipt, state),
raw_document_put(note_binding, f"{state.runtime_id}-mutated-note", mutated["documentId"], mutated, state),
]
@ -244,8 +282,24 @@ def handle_raw_put(state: PeerState, message: dict[str, Any]) -> list[dict[str,
"shotsFired": 1,
"ammoRemaining": 29,
}
return [raw_document_put(state.bindings_by_schema_id[INTEROP_FIRE_RECEIPT_SCHEMA_ID], f"{state.runtime_id}-fire-receipt", receipt["commandId"], receipt, state)]
return []
return [*responses, raw_document_put(state.bindings_by_schema_id[INTEROP_FIRE_RECEIPT_SCHEMA_ID], f"{state.runtime_id}-fire-receipt", receipt["commandId"], receipt, state)]
return responses
def database_change_notifications(message: dict[str, Any], document: dict[str, Any], subscriptions: dict[str, DatabaseSubscription]) -> list[dict[str, Any]]:
notifications = []
for subscription in subscriptions.values():
if not subscription.matches(document):
continue
message_id = message.get("messageId") or document.get("recordKey") or "change"
notifications.append({
"schemaVersion": "cultnet.database_change_raw.v0",
"messageId": f"{message_id}:{subscription.subscription_id}",
"subscriptionId": subscription.subscription_id,
"changeKind": "put",
"document": document,
})
return notifications
def discovery_loop(sock: socket.socket, advertise_host: str, tcp_port: int, state: PeerState, stop: threading.Event) -> None:

View file

@ -50,6 +50,7 @@ def hello(
def document_put_raw(
*,
message_id: str = "",
key: str,
schema_id: str,
stored_at: str,
@ -65,7 +66,7 @@ def document_put_raw(
}
if source_runtime_id:
record["sourceRuntimeId"] = source_runtime_id
return CultNetMessage("cultnet.document_put_raw.v0", {"document": record})
return CultNetMessage("cultnet.document_put_raw.v0", {"messageId": message_id, "document": record})
def document_delete(*, schema_id: str, record_key: str, deleted_at: str) -> CultNetMessage:
@ -87,3 +88,30 @@ def schema_catalog_request(*, message_id: str = "", include_schema_json: bool =
"cultnet.schema_catalog_request.v0",
{"messageId": message_id, "includeSchemaJson": include_schema_json},
)
def database_subscribe(
*,
subscription_id: str,
message_id: str = "",
schema_ids: list[str] | None = None,
record_keys: list[str] | None = None,
include_snapshot: bool = True,
) -> CultNetMessage:
return CultNetMessage(
"cultnet.database_subscribe.v0",
{
"messageId": message_id,
"subscriptionId": subscription_id,
"schemaIds": schema_ids or [],
"recordKeys": record_keys or [],
"includeSnapshot": include_snapshot,
},
)
def database_unsubscribe(*, subscription_id: str, message_id: str = "") -> CultNetMessage:
return CultNetMessage(
"cultnet.database_unsubscribe.v0",
{"messageId": message_id, "subscriptionId": subscription_id},
)

View file

@ -14,7 +14,7 @@ from cultcache_py import (
define_document_type,
)
from cultcache_py.interop import read_note, write_note
from cultnet_py import decode_frame, encode_frame, hello, parse_message
from cultnet_py import database_subscribe, database_unsubscribe, decode_frame, document_put_raw, encode_frame, hello, parse_message
from cultmesh_py import create_node
from cultmesh_py import (
CultMeshPeerCard,
@ -173,6 +173,40 @@ class CultCacheTests(unittest.TestCase):
self.assertEqual(parsed.schema_version, "cultnet.hello.v0")
self.assertEqual(parsed.body["runtimeId"], "python-test")
def test_cultnet_database_subscription_helpers_match_schema_v0_shape(self) -> None:
subscribe = database_subscribe(
message_id="sub-message",
subscription_id="sub-1",
schema_ids=["schema-a"],
record_keys=["record-a"],
include_snapshot=False,
).to_wire()
self.assertEqual(subscribe["schemaVersion"], "cultnet.database_subscribe.v0")
self.assertEqual(subscribe["messageId"], "sub-message")
self.assertEqual(subscribe["subscriptionId"], "sub-1")
self.assertEqual(subscribe["schemaIds"], ["schema-a"])
self.assertEqual(subscribe["recordKeys"], ["record-a"])
self.assertFalse(subscribe["includeSnapshot"])
unsubscribe = database_unsubscribe(message_id="unsub-message", subscription_id="sub-1").to_wire()
self.assertEqual(unsubscribe["schemaVersion"], "cultnet.database_unsubscribe.v0")
self.assertEqual(unsubscribe["messageId"], "unsub-message")
self.assertEqual(unsubscribe["subscriptionId"], "sub-1")
def test_cultnet_raw_put_helper_carries_message_id(self) -> None:
put = document_put_raw(
message_id="put-1",
key="record-a",
schema_id="schema-a",
stored_at="2026-06-13T00:00:00Z",
payload=b"payload",
source_runtime_id="python-test",
).to_wire()
self.assertEqual(put["schemaVersion"], "cultnet.document_put_raw.v0")
self.assertEqual(put["messageId"], "put-1")
self.assertEqual(put["document"]["recordKey"], "record-a")
self.assertEqual(put["document"]["sourceRuntimeId"], "python-test")
def test_cultmesh_node_uses_cultcache_store(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
document = define_database_entry_type("mesh.note", [("body", 0)])

View file

@ -10,6 +10,7 @@ import { test } from "node:test";
import { promisify } from "node:util";
import { decode, encode } from "@msgpack/msgpack";
import { encodeFrame, LengthPrefixedMessageFramer } from "../../src/framing";
import { INTEROP_SCHEMA_VERSION } from "./cultnet-interop-shared";
const execFileAsync = promisify(execFile);
@ -26,6 +27,7 @@ const cultnetRsRoot = existsSync(resolve(cultLibRoot, "packages", "cultnet-rs"))
const tsPeerScript = resolve(cultNetTsRoot, "dist-test", "test", "interop", "cultnet-interop-peer.js");
const interopSchemaPath = resolve(cultNetTsRoot, "integration", "contracts", "cultnet.interop-note.schema.json");
const interopNoteSchemaId = "https://github.com/GameCult/cultnet-ts/integration/contracts/cultnet.interop-note.schema.json";
const csharpProjectPath = resolve(
cultLibRoot,
"tests",
@ -261,6 +263,38 @@ test("CultNet TS/Rust/C#/Python peers discover each other and exchange raw state
assert.equal(pythonPeerExchange.peers[0].peerId, "python-peer");
assert.ok(pythonPeerExchange.peers[0].roles.includes("read-replica"));
const pythonChange = await requestPythonDatabaseChange(pythonPort, {
schemaVersion: "cultnet.database_subscribe.v0",
messageId: "python-subscribe",
subscriptionId: "python-sub",
schemaIds: [interopNoteSchemaId],
recordKeys: ["note:ts-python-sub"],
includeSnapshot: false,
}, {
schemaVersion: "cultnet.document_put_raw.v0",
messageId: "python-sub-put",
document: {
schemaId: interopNoteSchemaId,
recordKey: "note:ts-python-sub",
storedAt: "2026-06-13T00:00:00Z",
payloadEncoding: "messagepack",
payload: encode([
INTEROP_SCHEMA_VERSION,
"note:ts-python-sub",
"ts-python-sub",
"Subscription note",
"Python streamed this raw change through the CultNet database lane.",
["interop", "subscription"],
]),
sourceRuntimeId: "ts-python-sub",
},
});
assert.equal(pythonChange.schemaVersion, "cultnet.database_change_raw.v0");
assert.equal(pythonChange.subscriptionId, "python-sub");
assert.equal(pythonChange.changeKind, "put");
assert.equal(pythonChange.document.schemaId, interopNoteSchemaId);
assert.equal(pythonChange.document.recordKey, "note:ts-python-sub");
const expectedPeers = ["csharp-peer", "python-peer", "rust-peer", "ts-peer"];
await expectProbePeers("ts-probe", process.execPath, [
@ -472,6 +506,36 @@ async function requestCultMeshFromPython(port: number, request: Record<string, u
});
}
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();
await once(socket, "connect");
return await new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
socket.destroy();
reject(new Error("Timed out waiting for Python database change response."));
}, 5000);
socket.on("data", (chunk) => {
for (const frame of framer.push(chunk)) {
const decoded = decode(frame) as any;
if (decoded?.schemaVersion === "cultnet.database_change_raw.v0") {
clearTimeout(timeout);
socket.end();
resolve(decoded);
}
}
});
socket.once("error", (error) => {
clearTimeout(timeout);
reject(error);
});
socket.write(encodeFrame(encode(subscribe)));
socket.write(encodeFrame(encode(put)));
});
}
async function stopProcess(processState: RunningServeProcess): Promise<void> {
if (processState.child.killed || processState.child.exitCode !== null) {
return;