CultLib/packages/cultmesh-py/src/cultmesh_py/server.py
Libby bf81695537
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 5m17s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 52s
cultmesh-py: answer the capped frame reliably and end the session once the answer is acknowledged
The 8th refusal was sent unreliable and unordered with only the first response,
then the goodbye at once, so a lost datagram left the peer without it. All answers
now go the normal reliable path; the session ends when the peer has acknowledged
them (a lost one is resent) or after a 2 s grace, and serves nothing after the
capped frame meanwhile.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 09:54:37 +00:00

1164 lines
54 KiB
Python

from __future__ import annotations
import errno
import logging
import socket
import threading
import time
from dataclasses import dataclass, field, replace
from typing import Any
import msgpack
from cultnet_py import (
error_message,
message_invalid_error,
unsupported_schema_version_error,
CultNetRawSnapshotResponse,
CultNetSimulationObservationHub,
CultNetRudpPacket,
CultNetRudpPacketType,
CultNetRudpSendOptions,
CultNetRudpSession,
CultNetRudpSessionOptions,
TcpFramedTransportConnection,
create_rudp_transport_profile,
create_tcp_framed_transport_profile,
decode_rudp_packet,
encode_rudp_packet,
is_permanent_send_error,
wire_message_schema_descriptors,
)
from .node import CultMeshNode
from .write_authority import (
CultMeshRemoteWriteAuthority,
CultMeshRemoteWriteOperation,
CultMeshRemoteWriteRequest,
CultMeshServerPeer,
)
# The shortest message id this server answers a snapshot request under. It takes a
# request's messageId as given, an empty one included, so no response it sends is smaller.
_SHORTEST_SERVED_MESSAGE_ID = ""
# The most fragments one RUDP message can carry: its fragment count is a u16.
_MAX_FRAGMENTS_PER_MESSAGE = 0xFFFF
# Replies larger than one fragment are split into fragments of at most this many bytes,
# as the Rust and TypeScript document servers do by default.
CULTMESH_RUDP_DEFAULT_MAX_FRAGMENT_BYTES = 1200
# The answer to a request whose reply the peer's reliable queue cannot take. Fixed text: it
# never quotes the reply or the queue's error.
_REPLY_UNQUEUEABLE = "The reply could not be queued for this peer."
# The answer to a message the server could not handle. Fixed text: it never quotes the message.
_MESSAGE_UNHANDLED = "The message could not be handled."
from cultnet_py.cultmesh_contracts import (
PEER_EXCHANGE_REQUEST,
VERSE_CATALOG_REQUEST,
CultMeshPeerCatalog,
CultMeshVerseCatalog,
)
_LOGGER = logging.getLogger(__name__)
# How many consecutive refused frames of one kind a RUDP session may send before it is ended: undecodable
# frames (reset by any frame that decodes) and deletes the write authority refuses (reset by any decoded
# frame that is not a refused delete). Fewer are answered with a typed refusal and the session is kept; the
# frame that reaches this number is answered too, then the session ends. The same number is the cap in every
# runtime.
MAX_CONSECUTIVE_REFUSED_FRAMES = 8
# How long a session whose capped frame was answered waits for the peer to acknowledge the answer before it ends anyway.
_RUDP_CAPPED_ANSWER_GRACE_MS = 2000
_EPHEMERAL_PAIR_ATTEMPTS = 64
class _ReplyUnqueueable(Exception):
"""A reply the peer's reliable queue cannot take. The peer's session ends, and the peer is
answered first with a small cultnet.error.v0 under the request's message id."""
def __init__(self, message_id: str) -> None:
super().__init__("reply could not be queued")
self.message_id = message_id
@dataclass(frozen=True)
class _DatabaseSubscription:
subscription_id: str
schema_ids: set[str]
record_keys: set[str]
def matches(self, document: dict[str, Any]) -> bool:
schema_id = str(document.get("schemaId") or "")
record_key = str(document.get("recordKey") or "")
return (
(not self.schema_ids or schema_id in self.schema_ids)
and (not self.record_keys or record_key in self.record_keys)
)
@dataclass
class _RudpPeerConnection:
session: CultNetRudpSession
subscriptions: dict[str, _DatabaseSubscription] = field(default_factory=dict)
undecodable_frames_in_a_row: int = 0
refused_deletes_in_a_row: int = 0
# Set once the peer's capped frame has been answered: the session ends when the answers are acknowledged.
ending_deadline_ms: int | None = None
@dataclass
class CultMeshLocalServer:
node: CultMeshNode
verse_catalog: CultMeshVerseCatalog = field(default_factory=CultMeshVerseCatalog)
peer_catalog: CultMeshPeerCatalog = field(default_factory=CultMeshPeerCatalog)
observation_hub: CultNetSimulationObservationHub | None = None
# Asked once per peer put and delete. None refuses every one of them (write_not_authorized); a node's own
# writes never come through here.
write_authority: CultMeshRemoteWriteAuthority | None = None
host: str = "127.0.0.1"
port: int = 0
display_name: str | None = None
runtime_kind: str = "python"
max_snapshot_documents: int | None = None
max_snapshot_bytes: int | None = None
enable_rudp: bool = True
rudp_connection_id: int = 0x43554C54
rudp_resend_delay_ms: int = 25
# RUDP replies are fragmented by rudp_max_fragment_bytes, and each peer's reliable queue
# holds at most rudp_max_pending_reliable_packets (None: only the 65535 fragments one
# message can carry). A put arriving over RUDP whose served reply could not fit them is
# refused as document_unservable.
rudp_max_fragment_bytes: int = CULTMESH_RUDP_DEFAULT_MAX_FRAGMENT_BYTES
rudp_max_pending_reliable_packets: int | None = None
_socket: socket.socket | None = field(default=None, init=False, repr=False)
_rudp_socket: socket.socket | None = field(default=None, init=False, repr=False)
_stop: threading.Event = field(default_factory=threading.Event, init=False, repr=False)
_thread: threading.Thread | None = field(default=None, init=False, repr=False)
_rudp_thread: threading.Thread | None = field(default=None, init=False, repr=False)
_rudp_send_failures: int = field(default=0, init=False, repr=False)
@property
def rudp_send_failures(self) -> int:
"""Datagrams that could not be sent to a peer. Each is that peer's lost
datagram: a reliable packet stays pending and is resent, and no other
peer is affected. A datagram that can never be sent as built
(`is_permanent_send_error`) is not counted here: it ends that peer's
session, and the peer's goodbye names the error."""
return self._rudp_send_failures
def __post_init__(self) -> None:
# The Rust document server's option rules (validate_options), for each option this
# server shares with it: every limit is greater than zero, and the limits leave room for
# the smallest response the server sends, an empty snapshot. A server that could answer
# nothing is misconfigured. The RUDP options are checked only when RUDP is served, as
# Rust checks them only for the RUDP server they configure.
if self.max_snapshot_bytes is not None and self.max_snapshot_bytes <= 0:
raise ValueError("max_snapshot_bytes must be greater than zero")
if self.max_snapshot_documents is not None and self.max_snapshot_documents <= 0:
raise ValueError("max_snapshot_documents must be greater than zero")
if self.enable_rudp:
if self.rudp_resend_delay_ms <= 0:
raise ValueError("rudp_resend_delay_ms must be greater than zero")
if self.rudp_max_pending_reliable_packets is not None and self.rudp_max_pending_reliable_packets <= 0:
raise ValueError("rudp_max_pending_reliable_packets must be greater than zero")
if self.rudp_max_fragment_bytes <= 0:
raise ValueError("rudp_max_fragment_bytes must be greater than zero")
empty = _snapshot_response_bytes(
CultNetRawSnapshotResponse(message_id=_SHORTEST_SERVED_MESSAGE_ID, documents=()).to_wire()
)
if self.max_snapshot_bytes is not None and empty > self.max_snapshot_bytes:
raise ValueError("max_snapshot_bytes cannot hold an empty snapshot response")
if self.enable_rudp and -(-empty // self.rudp_max_fragment_bytes) > self._max_rudp_reply_fragments():
raise ValueError(
"rudp_max_fragment_bytes and rudp_max_pending_reliable_packets cannot carry an empty "
"snapshot response"
)
def _max_rudp_reply_fragments(self) -> int:
"""The most fragments one RUDP reply can take: one message's fragment count, and the
peer's reliable queue it must fit into whole."""
return min(
_MAX_FRAGMENTS_PER_MESSAGE,
self.rudp_max_pending_reliable_packets or _MAX_FRAGMENTS_PER_MESSAGE,
)
def start(self) -> "CultMeshLocalServer":
if self._socket is not None:
return self
server, rudp_socket = self._bind_sockets()
server.settimeout(0.2)
self._socket = server
self.port = int(server.getsockname()[1])
self._stop.clear()
self._thread = threading.Thread(target=self._accept_loop, daemon=True)
self._thread.start()
if rudp_socket is not None:
rudp_socket.settimeout(0.02)
self._rudp_socket = rudp_socket
self._rudp_thread = threading.Thread(target=self._rudp_loop, daemon=True)
self._rudp_thread.start()
return self
def _bind_sockets(self) -> tuple[socket.socket, socket.socket | None]:
"""The listening TCP socket and, when RUDP is on, the UDP socket on the same port number.
An explicit port is bound as asked and a failure is the caller's. Port 0 asks for any free port, and the
kernel picks the TCP one without knowing whether another process holds that number for UDP, so a
UDP collision retries with a fresh TCP port instead of failing the start. Both sockets are bound
before any thread starts, so a failed start leaves nothing running or open.
"""
attempts = _EPHEMERAL_PAIR_ATTEMPTS if self.port == 0 and self.enable_rudp else 1
for attempt in range(attempts):
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
rudp_socket = None
try:
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((self.host, self.port))
server.listen()
if self.enable_rudp:
rudp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
rudp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
rudp_socket.bind((self.host, int(server.getsockname()[1])))
return server, rudp_socket
except OSError as error:
server.close()
if rudp_socket is not None:
rudp_socket.close()
if error.errno != errno.EADDRINUSE or attempt == attempts - 1:
raise
raise AssertionError("unreachable")
def stop(self) -> None:
self._stop.set()
if self._rudp_socket is not None:
try:
self._rudp_socket.close()
except OSError:
pass
self._rudp_socket = None
if self._socket is not None:
try:
self._socket.close()
except OSError:
pass
self._socket = None
if self._thread is not None:
self._thread.join(timeout=2.0)
self._thread = None
if self._rudp_thread is not None:
self._rudp_thread.join(timeout=2.0)
self._rudp_thread = None
def __enter__(self) -> "CultMeshLocalServer":
return self.start()
def __exit__(self, exc_type: Any, exc: Any, traceback: Any) -> None:
self.stop()
def handle_message(self, message: dict[str, Any]) -> dict[str, Any] | None:
schema_version = message.get("schemaVersion")
if schema_version == "cultnet.hello.v0":
return self._hello_response()
if schema_version == "cultnet.schema_catalog_request.v0":
return self._schema_catalog_response(message)
if schema_version == "cultnet.snapshot_request.v0":
return self._snapshot_response(message)
if schema_version == "cultnet.shard_catalog_request.v0":
return self._shard_catalog_response(message)
if schema_version == "cultnet.shard_log_request.v0":
return self.node.database.create_shard_log_response(
message_id=str(message.get("messageId") or ""),
shard_id=str(message.get("shardId") or ""),
shard_epoch=message.get("shardEpoch"),
after_sequence=int(message.get("afterSequence") or 0),
limit=message.get("limit"),
)
if schema_version == VERSE_CATALOG_REQUEST:
return self.verse_catalog.create_response(message)
if schema_version == PEER_EXCHANGE_REQUEST:
return self.peer_catalog.create_response(message)
if schema_version == "cultnet.simulation_observation.v0":
candidates = self._candidate_responses(message)
return candidates[0] if candidates else None
return unsupported_schema_version_error(schema_version).to_wire()
def _accept_loop(self) -> None:
while not self._stop.is_set():
server = self._socket
if server is None:
return
try:
client, address = server.accept()
except TimeoutError:
continue
except OSError:
return
peer = CultMeshServerPeer(f"{address[0]}:{address[1]}", "tcp")
threading.Thread(target=self._handle_connection, args=(client, peer), daemon=True).start()
def _handle_connection(self, client: socket.socket, peer: CultMeshServerPeer) -> None:
with client:
stream = client.makefile("rwb")
transport = TcpFramedTransportConnection(
stream,
profile=create_tcp_framed_transport_profile(
self.node.runtime_id,
transport_id="cultmesh-local-tcp",
host=self.host,
port=self.port,
),
)
subscriptions: dict[str, _DatabaseSubscription] = {}
while not self._stop.is_set():
try:
frame = transport.receive()
message = msgpack.unpackb(frame.payload, raw=False)
except EOFError:
return
if not isinstance(message, dict):
continue
try:
responses = self._handle_connection_message(message, subscriptions, peer=peer)
except Exception as error: # noqa: BLE001 - one message never ends the connection
# Whatever a peer's message makes the handling raise is that peer's failure:
# it is refused with fixed text and the connection serves on. The log names
# the error type only, because the error's own message can quote the peer.
_LOGGER.warning(
"CultMesh server could not handle a peer's message (%s); it was refused.",
type(error).__name__,
)
message_id = message.get("messageId")
responses = [self._error_response(
_MESSAGE_UNHANDLED,
message_id=message_id if isinstance(message_id, str) else "",
code="message_unhandled",
)]
for response in responses:
transport.send("schema", msgpack.packb(response, use_bin_type=True))
def _rudp_loop(self) -> None:
rudp_socket = self._rudp_socket
if rudp_socket is None:
return
peers: dict[tuple[str, int], _RudpPeerConnection] = {}
while not self._stop.is_set():
try:
wire, remote_addr = rudp_socket.recvfrom(65535)
except (TimeoutError, ConnectionResetError):
# Windows reports an earlier ICMP port-unreachable, from a peer that
# has gone away, as an error on the next receive. It names no datagram
# of this read, so it is idle, not the end of the thread.
self._poll_rudp_resends(rudp_socket, peers)
continue
except OSError:
return
try:
packet = decode_rudp_packet(wire)
except ValueError:
continue
if packet.connection_id != self.rudp_connection_id:
continue
self._end_answered_peers(rudp_socket, peers)
now_ms = _now_ms()
peer = peers.get(remote_addr)
if packet.packet_type == CultNetRudpPacketType.CONNECT:
# The session decides whether this Connect repeats the one it
# accepted. Any other Connect is a new client session, with new
# subscriptions.
if peer is None or not peer.session.connect_repeats(packet):
peer = _RudpPeerConnection(
CultNetRudpSession(
CultNetRudpSessionOptions(
connection_id=self.rudp_connection_id,
resend_delay_ms=self.rudp_resend_delay_ms,
max_pending_reliable_packets=self.rudp_max_pending_reliable_packets,
)
)
)
peers[remote_addr] = peer
unsendable = self._send_rudp_packet(
rudp_socket,
remote_addr,
peer.session.accept_connect(packet, now_ms, b"cultmesh-local-rudp"),
)
if unsendable is not None:
self._end_unsendable_peer(rudp_socket, peers, remote_addr, unsendable)
continue
if peer is None:
continue
try:
result = peer.session.receive(packet, now_ms)
except ValueError:
# receive() has already recorded the packet's reliable sequence, so the
# session cannot be kept: a retransmit would be acknowledged and the
# frame silently lost. It ends, never the thread, and the peer is told.
self._end_refused_peer(rudp_socket, peers, remote_addr)
continue
unsendable: OSError | None = None
for outgoing in (*([result.reply] if result.reply is not None else []), *result.ready_to_send):
unsendable = self._send_rudp_packet(rudp_socket, remote_addr, outgoing)
if unsendable is not None:
break
if result.disconnected:
peers.pop(remote_addr, None)
continue
try:
for delivered in result.delivered:
if delivered.channel_id != "schema":
continue
if peer.ending_deadline_ms is not None:
# The capped frame was answered; nothing after it is served while the answer is delivered.
break
try:
message = msgpack.unpackb(delivered.payload, raw=False)
except (msgpack.ExtraData, msgpack.FormatError, msgpack.StackError, ValueError):
message = None
if isinstance(message, dict):
peer.undecodable_frames_in_a_row = 0
responses = self._handle_connection_message(
message,
peer.subscriptions,
over_rudp=True,
peer=CultMeshServerPeer(f"{remote_addr[0]}:{remote_addr[1]}", "rudp"),
)
refused_delete = message.get("schemaVersion") == "cultnet.document_delete.v0" and any(
response.get("code") == "write_not_authorized" for response in responses
)
peer.refused_deletes_in_a_row = peer.refused_deletes_in_a_row + 1 if refused_delete else 0
refused, run = refused_delete, peer.refused_deletes_in_a_row
else:
# A frame that is no CultNet message is answered, not dropped, and the session kept.
peer.undecodable_frames_in_a_row += 1
refused, run = True, peer.undecodable_frames_in_a_row
responses = [self._message_invalid({}, "message", "CultMesh RUDP server could not read the message.")]
for response in responses:
if unsendable is None:
unsendable = self._send_rudp_schema_frame(
rudp_socket,
remote_addr,
peer.session,
msgpack.packb(response, use_bin_type=True),
message_id=str(response.get("messageId") or ""),
)
if refused and run >= MAX_CONSECUTIVE_REFUSED_FRAMES:
# The capped frame is answered like any other, reliably. The session ends once the peer
# has acknowledged every answer (or the grace runs out): see _end_answered_peers.
peer.ending_deadline_ms = now_ms + _RUDP_CAPPED_ANSWER_GRACE_MS
break
except Exception as error: # noqa: BLE001 - one peer's message never ends the thread
# Whatever a peer's message makes the handling raise is that peer's failure.
# The session recorded the frame's sequence, so it cannot be kept: a retransmit
# would be acknowledged and never handled. The session ends, never the thread,
# and the peer is told. The log names the error type only, because the error's
# own message can quote what the peer sent.
_LOGGER.warning(
"CultMesh RUDP server could not handle a peer's message (%s); that peer's session ended.",
type(error).__name__,
)
refusal = None
if isinstance(error, _ReplyUnqueueable):
refusal = self._error_response(
_REPLY_UNQUEUEABLE,
message_id=error.message_id,
code="response_unqueueable",
)
self._end_refused_peer(rudp_socket, peers, remote_addr, refusal=refusal)
continue
if unsendable is None and (
packet.reliable or packet.packet_type == CultNetRudpPacketType.DATA or result.delivered
):
unsendable = self._send_rudp_packet(
rudp_socket,
remote_addr,
peer.session.create_ack_for_received(packet.sequence),
)
if unsendable is not None:
self._end_unsendable_peer(rudp_socket, peers, remote_addr, unsendable)
def _end_answered_peers(
self,
rudp_socket: socket.socket,
peers: dict[tuple[str, int], _RudpPeerConnection],
) -> None:
"""Ends each session whose capped frame was answered once the peer has acknowledged every answer (a lost
answer is resent first), or when the grace has run out."""
now_ms = _now_ms()
for remote_addr, peer in list(peers.items()):
if peer.ending_deadline_ms is None:
continue
if peer.session.outstanding_reliable_packet_count == 0 or now_ms >= peer.ending_deadline_ms:
self._end_refused_peer(rudp_socket, peers, remote_addr)
def _poll_rudp_resends(
self,
rudp_socket: socket.socket,
peers: dict[tuple[str, int], _RudpPeerConnection],
) -> None:
self._end_answered_peers(rudp_socket, peers)
now_ms = _now_ms()
for remote_addr, peer in list(peers.items()):
for packet in peer.session.due_resends(now_ms):
unsendable = self._send_rudp_packet(rudp_socket, remote_addr, packet)
if unsendable is not None:
self._end_unsendable_peer(rudp_socket, peers, remote_addr, unsendable)
break
def _send_rudp_schema_frame(
self,
rudp_socket: socket.socket,
remote_addr: tuple[str, int],
session: CultNetRudpSession,
payload: bytes,
*,
message_id: str = "",
) -> OSError | None:
try:
packets = session.send_many(
"schema",
payload,
CultNetRudpSendOptions(reliable=True, ordered=True, now_ms=_now_ms()),
max_fragment_bytes=self.rudp_max_fragment_bytes,
)
except ValueError:
# The peer's reliable queue cannot take this reply. The peer is answered, not left
# to time out, and its session ends: see _end_refused_peer.
raise _ReplyUnqueueable(message_id) from None
for packet in packets:
unsendable = self._send_rudp_packet(rudp_socket, remote_addr, packet)
if unsendable is not None:
return unsendable
return None
def _send_rudp_packet(
self,
rudp_socket: socket.socket,
remote_addr: tuple[str, int],
packet: CultNetRudpPacket,
) -> OSError | None:
# A transient send failure is that peer's lost datagram: counted, never
# raised (raising here ended the RUDP thread for every peer). A permanent
# one (`is_permanent_send_error`) is returned: the datagram can never be
# sent as built, and the caller ends that peer's session.
wire = encode_rudp_packet(packet)
try:
rudp_socket.sendto(wire, remote_addr)
except OSError as error:
if is_permanent_send_error(error):
return error
self._rudp_send_failures += 1
return None
def _end_refused_peer(
self,
rudp_socket: socket.socket,
peers: dict[tuple[str, int], _RudpPeerConnection],
remote_addr: tuple[str, int],
*,
refusal: dict[str, Any] | None = None,
) -> None:
"""Ends a peer's session that refused one of its messages, and says goodbye. A
refusal, when there is one, goes first, unreliable and unordered: the session ends
with it, so it is never resent and needs no room in the reliable queue. It is built
before the reset and carries acknowledgement fields built after it, which acknowledge
nothing, like the goodbye: the ack would otherwise cover the very frame refused. A
refusal fragment that can never be sent is not dropped: the goodbye names its failure."""
peer = peers.pop(remote_addr)
packets: list[CultNetRudpPacket] = []
if refusal is not None:
try:
packets = peer.session.send_many(
"schema",
msgpack.packb(refusal, use_bin_type=True),
CultNetRudpSendOptions(reliable=False, ordered=False, now_ms=_now_ms()),
max_fragment_bytes=self.rudp_max_fragment_bytes,
)
except ValueError:
packets = []
peer.session.reset_peer_state()
nothing = peer.session.create_ack()
for packet in packets:
unsendable = self._send_rudp_packet(
rudp_socket, remote_addr, replace(packet, ack=nothing.ack, ack_mask=nothing.ack_mask)
)
if unsendable is not None:
self._send_rudp_packet(rudp_socket, remote_addr, peer.session.end_unsendable_session(unsendable))
return
goodbye = peer.session.create_disconnect(b"session refused a packet")
self._send_rudp_packet(rudp_socket, remote_addr, goodbye)
def _end_unsendable_peer(
self,
rudp_socket: socket.socket,
peers: dict[tuple[str, int], _RudpPeerConnection],
remote_addr: tuple[str, int],
error: OSError,
) -> None:
"""The session owes its peer a packet that can never be sent as built. It ends,
never the thread, and the peer's goodbye names the error."""
peer = peers.pop(remote_addr, None)
if peer is None:
return
self._send_rudp_packet(rudp_socket, remote_addr, peer.session.end_unsendable_session(error))
def _handle_connection_message(
self,
message: dict[str, Any],
subscriptions: dict[str, _DatabaseSubscription],
*,
over_rudp: bool = False,
peer: CultMeshServerPeer | None = None,
) -> list[dict[str, Any]]:
schema_version = message.get("schemaVersion")
if schema_version == "cultnet.database_subscribe.v0":
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 []
snapshot_request = {
"messageId": str(message.get("messageId") or ""),
"schemaIds": list(subscriptions[subscription_id].schema_ids),
"recordKeys": list(subscriptions[subscription_id].record_keys),
}
return [self._snapshot_response(snapshot_request)]
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 self._handle_raw_put(message, subscriptions, over_rudp=over_rudp, peer=peer)
if schema_version == "cultnet.document_delete.v0":
return self._handle_raw_delete(message, subscriptions, peer=peer)
if schema_version == "cultnet.simulation_observation.v0":
return self._candidate_responses(message)
response = self.handle_message(message)
return [] if response is None else [response]
def _handle_raw_put(
self,
message: dict[str, Any],
subscriptions: dict[str, _DatabaseSubscription],
*,
over_rudp: bool = False,
peer: CultMeshServerPeer | None = None,
) -> list[dict[str, Any]]:
document_record = message.get("document")
if not isinstance(document_record, dict):
return [self._message_invalid(message, "document", "Raw put messages must contain a document map.")]
malformed_shard = self._malformed_shard_fields(message)
if malformed_shard is not None:
return [malformed_shard]
# Refusal precedes every other judgment of the put. The node resolves the schema first, because the
# authority must be asked about the canonical schema id (a payload-inferred alias included), as C#
# does; only a payload of the wire shape is resolved, so nothing of an ungranted peer's is
# allocated. A put the node cannot resolve is asked about under the ids as sent. Residual: the
# refusal is the same either way, but an ungranted peer can still tell registered from unregistered
# schemas by timing.
target = self.node.database.raw_put_target(message) or (
str(document_record.get("schemaId") or ""),
str(document_record.get("recordKey") or ""),
)
refusal = self._refuse_unauthorized_write(peer, CultMeshRemoteWriteOperation.PUT, target, message)
if refusal is not None:
return [refusal]
unservable = self._unservable_put(message, over_rudp=over_rudp)
if unservable is not None:
return [unservable]
try:
change = self.node.database.apply_raw_put_message(message)
except Exception as error: # noqa: BLE001 - a put the store cannot take is that peer's refusal
# The store refused the put: a blank key, a payload its schema cannot decode, a global
# document under another key, or anything a document's own decoder or validator
# raises. It is refused to the peer that sent it; no thread and no other peer is
# affected. Neither the refusal nor the log quotes the error, which can quote the put.
_LOGGER.warning("CultMesh server refused a raw put the store could not take (%s).", type(error).__name__)
return [self._message_invalid(message, "document", "Raw put document could not be stored.")]
if change is None:
return [self._error_response(
"Raw put message did not apply to a registered document.",
message_id=str(message.get("messageId") or ""),
code="unregistered_document_put",
)]
return self._database_change_notifications(
message,
document_record,
change.change_kind,
subscriptions,
resolved_schema_id=change.schema_id,
)
def _handle_raw_delete(
self,
message: dict[str, Any],
subscriptions: dict[str, _DatabaseSubscription],
*,
peer: CultMeshServerPeer | None = None,
) -> list[dict[str, Any]]:
schema_id = str(message.get("schemaId") or "")
record_key = str(message.get("recordKey") or "")
if not schema_id or not record_key:
return [self._message_invalid(
message, "schemaId" if not schema_id else "recordKey", "Raw delete messages must contain schemaId and recordKey.",
)]
malformed_shard = self._malformed_shard_fields(message)
if malformed_shard is not None:
return [malformed_shard]
target = self.node.database.raw_delete_target(message) or (schema_id, record_key)
refusal = self._refuse_unauthorized_write(peer, CultMeshRemoteWriteOperation.DELETE, target, message)
if refusal is not None:
return [refusal]
change = self.node.database.apply_raw_delete_message(message)
if change is None:
return [self._error_response(
"Raw delete message did not apply to a registered document.",
message_id=str(message.get("messageId") or ""),
code="unregistered_document_delete",
)]
return self._database_delete_notifications(message, subscriptions, resolved_schema_id=change.schema_id)
def _message_invalid(self, message: dict[str, Any], field: str, reason: str) -> dict[str, Any]:
"""The typed `message_invalid` refusal naming the request field at fault, under the request's messageId."""
response = message_invalid_error(field, reason).to_wire()
response["messageId"] = str(message.get("messageId") or "")
return response
def _malformed_shard_fields(self, message: dict[str, Any]) -> dict[str, Any] | None:
"""The protocol error for a shardId that is not a string or a shardEpoch that is not an int (a bool is
not), else None. It precedes the gate, so the authority only ever judges a write whose shard it can
read, and the store never files a write under a shard the authority did not see."""
shard_id = message.get("shardId")
shard_epoch = message.get("shardEpoch")
if (shard_id is None or isinstance(shard_id, str)) and (
shard_epoch is None or (isinstance(shard_epoch, int) and not isinstance(shard_epoch, bool))
):
return None
return self._message_invalid(
message,
"shardId" if not (shard_id is None or isinstance(shard_id, str)) else "shardEpoch",
"shardId must be a string and shardEpoch an integer.",
)
def _refuse_unauthorized_write(
self,
peer: CultMeshServerPeer | None,
operation: CultMeshRemoteWriteOperation,
target: tuple[str, str],
message: dict[str, Any],
) -> dict[str, Any] | None:
"""None when the write may proceed, else the typed refusal for the sending peer.
No authority configured refuses; an authority that raises refuses too (fail closed) and is logged.
"""
schema_id, record_key = target
reason: str | None
authority = self.write_authority
if authority is None:
reason = "no remote write authority is configured"
else:
request = CultMeshRemoteWriteRequest(
peer=peer or CultMeshServerPeer("", "unknown"),
operation=operation,
schema_id=schema_id,
record_key=record_key,
shard_id=message.get("shardId"),
shard_epoch=message.get("shardEpoch"),
)
try:
decision = authority.decide(request)
except Exception as error: # noqa: BLE001 - a failing authority refuses
_LOGGER.error("CultMesh remote write authority failed (%s); the write was refused.", type(error).__name__)
decision = None
reason = "the write authority failed"
else:
reason = getattr(decision, "reason", None)
if decision is not None and getattr(decision, "is_granted", False) is True:
return None
_LOGGER.warning("CultMesh %s of %s refused: write not authorized.", operation.value, schema_id)
return error_message(
f"write_not_authorized: {reason}" if reason and reason.strip() else "write_not_authorized",
code="write_not_authorized",
details={"field": "recordKey", "value": record_key},
).to_wire()
def _database_change_notifications(
self,
message: dict[str, Any],
document: dict[str, Any],
change_kind: str,
subscriptions: dict[str, _DatabaseSubscription],
*,
resolved_schema_id: str | None = None,
) -> list[dict[str, Any]]:
notifications = []
for subscription in subscriptions.values():
if not self._subscription_matches_document(
subscription,
document,
resolved_schema_id=resolved_schema_id,
):
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": change_kind,
"document": document,
})
return notifications
def _database_delete_notifications(
self,
message: dict[str, Any],
subscriptions: dict[str, _DatabaseSubscription],
*,
resolved_schema_id: str | None = None,
) -> list[dict[str, Any]]:
schema_id = str(message.get("schemaId") or "")
record_key = str(message.get("recordKey") or "")
notifications = []
document = {"schemaId": schema_id, "recordKey": record_key}
for subscription in subscriptions.values():
if not self._subscription_matches_document(
subscription,
document,
resolved_schema_id=resolved_schema_id,
):
continue
message_id = message.get("messageId") or record_key or "change"
notifications.append({
"schemaVersion": "cultnet.database_change_raw.v0",
"messageId": f"{message_id}:{subscription.subscription_id}",
"subscriptionId": subscription.subscription_id,
"changeKind": "removed",
"schemaId": schema_id,
"recordKey": record_key,
})
return notifications
def _subscription_matches_document(
self,
subscription: _DatabaseSubscription,
document: dict[str, Any],
*,
resolved_schema_id: str | None = None,
) -> bool:
record_key = str(document.get("recordKey") or "")
if subscription.record_keys and record_key not in subscription.record_keys:
return False
if not subscription.schema_ids:
return True
document_schema_id = str(document.get("schemaId") or "")
documents_by_schema_id = _schema_document_map(self.node.documents)
if _schema_matches_request(
document_schema_id,
documents_by_schema_id.get(document_schema_id),
subscription.schema_ids,
):
return True
if resolved_schema_id is None:
return False
return _schema_matches_request(
resolved_schema_id,
documents_by_schema_id.get(resolved_schema_id),
subscription.schema_ids,
)
def _hello_response(self) -> dict[str, Any]:
return {
"schemaVersion": "cultnet.hello.v0",
"runtimeId": self.node.runtime_id,
"runtimeKind": self.runtime_kind,
"displayName": self.display_name or self.node.runtime_id,
"supportedDocumentTypes": [document.type for document in self.node.documents],
"supportedMutationContracts": [
{
"documentType": document.type,
"payloadSchemaVersion": document.catalog_entry().schema_version,
"operations": ["snapshot", "documentPut", "documentDelete", "shardLog"],
"authority": "runtime",
}
for document in self.node.documents
],
"supportedMessageVersions": [
"cultnet.hello.v0",
"cultnet.error.v0",
"cultnet.schema_catalog_request.v0",
"cultnet.snapshot_request.v0",
"cultnet.database_subscribe.v0",
"cultnet.database_unsubscribe.v0",
"cultnet.document_put_raw.v0",
"cultnet.document_delete.v0",
"cultnet.shard_catalog_request.v0",
"cultnet.shard_log_request.v0",
VERSE_CATALOG_REQUEST,
PEER_EXCHANGE_REQUEST,
] + (
[
"cultnet.simulation_observation.v0",
"cultnet.simulation_consensus_candidate.v0",
]
if self.observation_hub is not None
else []
),
"transportProfiles": [
create_tcp_framed_transport_profile(
self.node.runtime_id,
transport_id="cultmesh-local-tcp",
host=self.host,
port=self.port,
),
*(
[
create_rudp_transport_profile(
self.node.runtime_id,
transport_id="cultmesh-local-rudp",
host=self.host,
port=self.port,
)
]
if self.enable_rudp
else []
),
],
"supportsSchemaCatalog": True,
}
def _snapshot_response(self, request: dict[str, Any]) -> dict[str, Any]:
response = self.node.database.create_snapshot_response(
message_id=str(request.get("messageId") or ""),
schema_ids=[str(value) for value in request.get("schemaIds") or []],
record_keys=[str(value) for value in request.get("recordKeys") or []],
shard_id=request.get("shardId"),
shard_epoch=request.get("shardEpoch"),
)
return self._enforce_snapshot_limits(response)
def _enforce_snapshot_limits(self, response: dict[str, Any]) -> dict[str, Any]:
document_count = len(response.get("documents") or [])
if self.max_snapshot_documents is not None and document_count > self.max_snapshot_documents:
return self._error_response(
f"Snapshot document limit exceeded: {document_count} > {self.max_snapshot_documents}.",
message_id=str(response.get("messageId") or ""),
code="snapshot_document_limit_exceeded",
details={"documentCount": document_count, "maxSnapshotDocuments": self.max_snapshot_documents},
)
if self.max_snapshot_bytes is not None:
response_bytes = _snapshot_response_bytes(response)
if response_bytes > self.max_snapshot_bytes:
return self._error_response(
f"Snapshot byte limit exceeded: {response_bytes} > {self.max_snapshot_bytes}.",
message_id=str(response.get("messageId") or ""),
code="snapshot_byte_limit_exceeded",
details={"responseBytes": response_bytes, "maxSnapshotBytes": self.max_snapshot_bytes},
)
return response
def _unservable_put(self, message: dict[str, Any], *, over_rudp: bool) -> dict[str, Any] | None:
"""The refusal for a put this server could never serve, or None. The document alone,
as a snapshot would serve it under the shortest message id, must fit max_snapshot_bytes;
a put arriving over RUDP must also fit, as fragments of rudp_max_fragment_bytes, in one
message and the peer's reliable queue. A put whose document has no string recordKey or
binary payload could never be stored or served, and is refused as malformed."""
document_record = message.get("document")
if not (
isinstance(document_record, dict)
and isinstance(document_record.get("recordKey"), str)
and isinstance(document_record.get("payload"), (bytes, bytearray))
):
return self._message_invalid(message, "document", "Raw put documents must carry a string recordKey and a binary payload.")
if self.max_snapshot_bytes is None and not over_rudp:
return None
alone = self.node.database.raw_put_served_alone(message, message_id=_SHORTEST_SERVED_MESSAGE_ID)
if alone is None:
return None
response_bytes = _snapshot_response_bytes(alone)
details: dict[str, Any] = {"responseBytes": response_bytes, "maxSnapshotBytes": self.max_snapshot_bytes}
fits = self.max_snapshot_bytes is None or response_bytes <= self.max_snapshot_bytes
limits = f"limit is {self.max_snapshot_bytes}"
if over_rudp:
fragment_count = max(1, -(-response_bytes // self.rudp_max_fragment_bytes))
max_fragment_count = self._max_rudp_reply_fragments()
details |= {"fragmentCount": fragment_count, "maxFragmentCount": max_fragment_count}
fits = fits and fragment_count <= max_fragment_count
limits = (
f"it takes {fragment_count} fragments; limits are "
f"{'unbounded' if self.max_snapshot_bytes is None else self.max_snapshot_bytes} bytes "
f"and {max_fragment_count} fragments"
)
if fits:
return None
return self._error_response(
f"Document can never be served: its snapshot response is {response_bytes} bytes; {limits}.",
message_id=str(message.get("messageId") or ""),
code="document_unservable",
details=details,
)
@staticmethod
def _error_response(
error: str,
*,
message_id: str = "",
code: str | None = None,
details: dict[str, Any] | None = None,
) -> dict[str, Any]:
response: dict[str, Any] = {
"schemaVersion": "cultnet.error.v0",
"messageId": message_id,
"error": error,
}
if code is not None:
response["code"] = code
if details is not None:
response["details"] = details
return response
def _candidate_responses(self, message: dict[str, Any]) -> list[dict[str, Any]]:
if self.observation_hub is None:
return [self._error_response(
"Simulation observations are not enabled for this CultMesh server.",
message_id=str(message.get("messageId") or ""),
code="simulation_observations_disabled",
details={"schemaVersion": "cultnet.simulation_observation.v0"},
)]
message_id = str(message.get("messageId") or "")
return [
{
**candidate.to_wire(),
"messageId": message_id,
}
for candidate in self.observation_hub.submit_candidate_objects(message)
]
def _schema_catalog_response(self, request: dict[str, Any]) -> dict[str, Any]:
requested_schema_ids = {str(value) for value in request.get("schemaIds") or []}
requested_kinds = {str(value) for value in request.get("kinds") or []}
include_schema_json = request.get("includeSchemaJson") is True
schemas = []
for descriptor in wire_message_schema_descriptors(include_schema_json):
if requested_schema_ids and descriptor["schemaId"] not in requested_schema_ids:
continue
if requested_kinds and descriptor["kind"] not in requested_kinds:
continue
schemas.append(descriptor)
for document in self.node.documents:
entry = document.catalog_entry()
if requested_schema_ids and entry.schema_id not in requested_schema_ids:
continue
if requested_kinds and "document_payload" not in requested_kinds:
continue
descriptor = {
"schemaId": entry.schema_id,
"kind": "document_payload",
"schemaVersion": entry.schema_version,
"documentType": document.type,
"title": entry.schema_name,
"wireContracts": [
"cultnet.document_put_raw.v0",
"cultnet.document_delete.v0",
"cultnet.snapshot_response_raw.v0",
"cultnet.shard_log_response.v0",
],
"contentHash": entry.content_hash,
}
if include_schema_json:
descriptor["schemaJson"] = entry.canonical_schema_json
schemas.append(descriptor)
return {
"schemaVersion": "cultnet.schema_catalog_response.v0",
"messageId": request.get("messageId", ""),
"schemas": schemas,
}
def _shard_catalog_response(self, request: dict[str, Any]) -> dict[str, Any]:
requested_schema_ids = {str(value) for value in request.get("schemaIds") or []}
document_schema_ids = [document.catalog_entry().schema_id for document in self.node.documents]
documents_by_schema_id = _schema_document_map(self.node.documents)
shard_ids = self.node.database.shard_ids() or ["primary"]
shards = []
for shard_id in shard_ids:
schema_ids = self.node.database.shard_schema_ids(shard_id) or document_schema_ids
if requested_schema_ids:
schema_ids = [
schema_id
for schema_id in schema_ids
if _schema_matches_request(
schema_id,
documents_by_schema_id.get(schema_id),
requested_schema_ids,
)
]
if not schema_ids:
continue
shards.append({
"shardId": shard_id,
"ownerRuntimeId": self.node.runtime_id,
"epoch": self.node.database.shard_epoch(shard_id),
"isPrimary": True,
"schemaIds": schema_ids,
"keyPrefix": "",
"primaryEndpoints": [f"cultnet://{self.host}:{self.port}"],
"replicaEndpoints": [],
"readReplicaEndpoints": [f"cultnet://{self.host}:{self.port}"],
"region": "local",
})
return {
"schemaVersion": "cultnet.shard_catalog_response.v0",
"messageId": request.get("messageId", ""),
"shards": shards,
}
def _now_ms() -> int:
return int(time.time() * 1000)
def _schema_document_map(documents: list[Any]) -> dict[str, Any]:
mapped: dict[str, Any] = {}
for document in documents:
entry = document.catalog_entry()
mapped[entry.schema_id] = document
mapped[entry.schema_name] = document
mapped[entry.schema_version] = document
for compatible_schema_id in entry.compatible_schema_ids:
mapped[compatible_schema_id] = document
return mapped
def _schema_matches_request(
schema_id: str,
document: Any | None,
requested_schema_ids: set[str],
) -> bool:
if not requested_schema_ids or schema_id in requested_schema_ids:
return True
if document is None:
return False
entry = document.catalog_entry()
if entry.schema_id in requested_schema_ids or entry.schema_name in requested_schema_ids:
return True
if any(compatible_schema_id in requested_schema_ids for compatible_schema_id in entry.compatible_schema_ids):
return True
return any(_infer_schema_name(requested_schema_id) == entry.schema_name for requested_schema_id in requested_schema_ids)
def _infer_schema_name(schema_id: str) -> str | None:
marker = schema_id.rfind(".v")
if marker <= 0 or marker + 2 >= len(schema_id):
return None
version = schema_id[marker + 2:]
return schema_id[:marker] if version.isdigit() else None
def _snapshot_response_bytes(response: dict[str, Any]) -> int:
"""The one measure of a snapshot response, shared by the snapshot path and put admission."""
return len(msgpack.packb(response, use_bin_type=True))