Merge put-serve bound: a put the server could never serve is refused, and refusals say why

CultMesh document servers (Rust, TS, Python) refuse a put whose served snapshot reply
could never fit the response bound, before storing it. Refusals carry fixed text per
variant, acknowledge nothing, go unreliable and unordered, and never echo peer input or
OS text; publishers and the snapshot client report a refusal instead of timing out. Send
failures follow Cut D; a reply the queue cannot take is answered, not dropped; a failed
send's goodbye names a fixed error code in every runtime. Python validates options as
Rust does and survives any unstorable put or malformed TCP message.

Soul passes 1-4 plus merge verdict; the final batch closes it. Verified on Yggdrasil at
8b8f8436 (main merged): every CultNet/CultMesh suite in Rust, TS, Python and C#, interop 27/27.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-09-30 23:40:50 +02:00
commit 9dcb3aa154
21 changed files with 3417 additions and 247 deletions

View file

@ -24,7 +24,7 @@ from .node import (
CultMeshReactiveDocumentReconciliation,
create_node,
)
from .server import CultMeshLocalServer
from .server import CULTMESH_RUDP_DEFAULT_MAX_FRAGMENT_BYTES, CultMeshLocalServer
from .session import (
CultMeshGameSession,
CultMeshGameSessionOptions,
@ -79,6 +79,7 @@ __all__ = [
"CultMeshReactiveDocumentReconciliation",
"CultMeshGameSession",
"CultMeshGameSessionOptions",
"CULTMESH_RUDP_DEFAULT_MAX_FRAGMENT_BYTES",
"CultMeshLocalServer",
"CultMeshPeerCard",
"CultMeshPeerCatalog",

View file

@ -24,10 +24,18 @@ from cultnet_py.cultmesh_contracts import (
READY_SCHEMA_VERSION = "cultmesh.daemon_ready.v0"
def _port(value: str) -> int:
"""A TCP/UDP port: 0 (any free port) through 65535."""
port = int(value)
if not 0 <= port <= 65535:
raise argparse.ArgumentTypeError("port must be between 0 and 65535")
return port
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(prog="cultmesh-py-daemon")
parser.add_argument("--host", default="127.0.0.1")
parser.add_argument("--port", type=int, default=3075)
parser.add_argument("--port", type=_port, default=3075)
parser.add_argument("--runtime-id", default="python-runtime")
parser.add_argument("--display-name")
parser.add_argument("--cache-file")
@ -50,7 +58,7 @@ def main(argv: list[str] | None = None) -> int:
stop = threading.Event()
install_signal_handlers(stop)
server = start_server(args)
server = start_server(args, parser)
try:
ready = daemon_ready_document(server)
publish_ready(ready, ready_file=args.ready_file)
@ -61,7 +69,7 @@ def main(argv: list[str] | None = None) -> int:
return 0
def start_server(args: argparse.Namespace) -> CultMeshLocalServer:
def start_server(args: argparse.Namespace, parser: argparse.ArgumentParser) -> CultMeshLocalServer:
node = CultMesh.create_node(
args.cache_file,
runtime_id=args.runtime_id,
@ -98,17 +106,21 @@ def start_server(args: argparse.Namespace) -> CultMeshLocalServer:
quorum_ratio=args.simulation_quorum_ratio,
)
)
server = CultMesh.serve_node(
node,
verse_catalog=verse_catalog,
peer_catalog=peer_catalog,
observation_hub=observation_hub,
host=args.host,
port=args.port,
display_name=args.display_name,
max_snapshot_documents=args.max_snapshot_documents,
max_snapshot_bytes=args.max_snapshot_bytes,
)
try:
server = CultMesh.serve_node(
node,
verse_catalog=verse_catalog,
peer_catalog=peer_catalog,
observation_hub=observation_hub,
host=args.host,
port=args.port,
display_name=args.display_name,
max_snapshot_documents=args.max_snapshot_documents,
max_snapshot_bytes=args.max_snapshot_bytes,
)
except ValueError as error:
# The server owns its option rules; a limit it refuses is a usage error, not a crash.
parser.error(str(error))
advertise_self(server, verse_catalog, peer_catalog, args)
return server

View file

@ -32,7 +32,7 @@ from .node import (
CultMeshPublicationDocumentBinding,
create_node,
)
from .server import CultMeshLocalServer
from .server import CULTMESH_RUDP_DEFAULT_MAX_FRAGMENT_BYTES, CultMeshLocalServer
from .session import CultMeshGameSession, CultMeshGameSessionOptions
from .simulation import CultMeshSimulationFactCommitter
from cultnet_py.cultmesh_contracts import (
@ -408,6 +408,8 @@ class CultMesh:
enable_rudp: bool = True,
rudp_connection_id: int = 0x43554C54,
rudp_resend_delay_ms: int = 25,
rudp_max_fragment_bytes: int = CULTMESH_RUDP_DEFAULT_MAX_FRAGMENT_BYTES,
rudp_max_pending_reliable_packets: int | None = None,
) -> CultMeshLocalServer:
return CultMeshLocalServer(
node=node,
@ -422,6 +424,8 @@ class CultMesh:
enable_rudp=enable_rudp,
rudp_connection_id=rudp_connection_id,
rudp_resend_delay_ms=rudp_resend_delay_ms,
rudp_max_fragment_bytes=rudp_max_fragment_bytes,
rudp_max_pending_reliable_packets=rudp_max_pending_reliable_packets,
).start()
@staticmethod

View file

@ -651,6 +651,38 @@ class CultMeshDatabase:
return message
def apply_raw_put_message(self, message: dict[str, Any]) -> CultMeshDatabaseChange | None:
prepared = self._raw_put_envelope(message)
if prepared is None:
return None
document, envelope = prepared
record_key = envelope.key
previous = self.cache.get(document, record_key)
value = self.cache.put_envelope(document, envelope)
change_kind = "added" if previous is None else "updated"
change = self._publish_local_change(document, record_key, change_kind, value, previous)
self._append_shard_log_put(CultNetMessage(
"cultnet.document_put_raw.v0",
{key: value for key, value in message.items() if key != "schemaVersion"},
), change_kind)
return change
def raw_put_served_alone(self, message: dict[str, Any], *, message_id: str) -> dict[str, Any] | None:
"""The snapshot response that would serve this put's document alone, as a wire map.
It is built from the envelope the put would store, exactly as a snapshot builds it, so a
server can judge a put by the size it would be served at. None when the put would not apply.
"""
prepared = self._raw_put_envelope(message)
if prepared is None:
return None
return CultNetRawSnapshotResponse(
message_id=message_id,
documents=(self._served_record(prepared[1]),),
).to_wire()
def _raw_put_envelope(
self, message: dict[str, Any]
) -> tuple[DocumentDefinition[Any], CultCacheEnvelope] | None:
document_record = message.get("document")
if not isinstance(document_record, dict):
return None
@ -664,24 +696,24 @@ class CultMeshDatabase:
)
except KeyError:
return None
record_key = str(document_record["recordKey"])
previous = self.cache.get(document, record_key)
envelope = CultCacheEnvelope(
key=record_key,
return document, CultCacheEnvelope(
key=str(document_record["recordKey"]),
type=document.type,
schema_id=resolved_schema_id,
payload=bytes(document_record["payload"]),
stored_at=str(document_record.get("storedAt") or ""),
catalog_entry=document.catalog_entry(),
)
value = self.cache.put_envelope(document, envelope)
change_kind = "added" if previous is None else "updated"
change = self._publish_local_change(document, record_key, change_kind, value, previous)
self._append_shard_log_put(CultNetMessage(
"cultnet.document_put_raw.v0",
{key: value for key, value in message.items() if key != "schemaVersion"},
), change_kind)
return change
@staticmethod
def _served_record(envelope: CultCacheEnvelope) -> CultNetRawDocumentRecord:
return CultNetRawDocumentRecord(
schema_id=envelope.schema_id or envelope.type,
record_key=envelope.key,
stored_at=envelope.stored_at,
payload_encoding="messagepack",
payload=envelope.payload,
)
def apply_raw_delete_message(self, message: dict[str, Any]) -> CultMeshDatabaseChange | None:
schema_id = str(message.get("schemaId") or "")
@ -774,13 +806,7 @@ class CultMeshDatabase:
continue
if shard_record_keys is not None and (schema_id, envelope.key) not in shard_record_keys:
continue
documents.append(CultNetRawDocumentRecord(
schema_id=schema_id,
record_key=envelope.key,
stored_at=envelope.stored_at,
payload_encoding="messagepack",
payload=envelope.payload,
))
documents.append(self._served_record(envelope))
return CultNetRawSnapshotResponse(
message_id=message_id,

View file

@ -4,12 +4,13 @@ import logging
import socket
import threading
import time
from dataclasses import dataclass, field
from dataclasses import dataclass, field, replace
from typing import Any
import msgpack
from cultnet_py import (
CultNetRawSnapshotResponse,
CultNetSimulationObservationHub,
CultNetRudpPacket,
CultNetRudpPacketType,
@ -26,6 +27,20 @@ from cultnet_py import (
)
from .node import CultMeshNode
# 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,
@ -36,6 +51,15 @@ from cultnet_py.cultmesh_contracts import (
_LOGGER = logging.getLogger(__name__)
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
@ -72,6 +96,12 @@ class CultMeshLocalServer:
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)
@ -89,10 +119,40 @@ class CultMeshLocalServer:
return self._rudp_send_failures
def __post_init__(self) -> None:
if self.max_snapshot_documents is not None and self.max_snapshot_documents < 0:
raise ValueError("max_snapshot_documents must be non-negative")
if self.max_snapshot_bytes is not None and self.max_snapshot_bytes < 0:
raise ValueError("max_snapshot_bytes must be non-negative")
# 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:
@ -210,7 +270,22 @@ class CultMeshLocalServer:
return
if not isinstance(message, dict):
continue
responses = self._handle_connection_message(message, subscriptions)
try:
responses = self._handle_connection_message(message, subscriptions)
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))
@ -250,6 +325,7 @@ class CultMeshLocalServer:
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,
)
)
)
@ -291,7 +367,7 @@ class CultMeshLocalServer:
continue
if not isinstance(message, dict):
continue
responses = self._handle_connection_message(message, peer.subscriptions)
responses = self._handle_connection_message(message, peer.subscriptions, over_rudp=True)
for response in responses:
if unsendable is None:
unsendable = self._send_rudp_schema_frame(
@ -299,6 +375,7 @@ class CultMeshLocalServer:
remote_addr,
peer.session,
msgpack.packb(response, use_bin_type=True),
message_id=str(response.get("messageId") or ""),
)
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.
@ -310,7 +387,14 @@ class CultMeshLocalServer:
"CultMesh RUDP server could not handle a peer's message (%s); that peer's session ended.",
type(error).__name__,
)
self._end_refused_peer(rudp_socket, peers, remote_addr)
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
@ -342,12 +426,21 @@ class CultMeshLocalServer:
remote_addr: tuple[str, int],
session: CultNetRudpSession,
payload: bytes,
*,
message_id: str = "",
) -> OSError | None:
for packet in session.send_many(
"schema",
payload,
CultNetRudpSendOptions(reliable=True, ordered=True, now_ms=_now_ms()),
):
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
@ -377,11 +470,36 @@ class CultMeshLocalServer:
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)
# The goodbye is built after the reset, or its ack field would acknowledge the
# very frame the session refused.
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)
@ -403,6 +521,8 @@ class CultMeshLocalServer:
self,
message: dict[str, Any],
subscriptions: dict[str, _DatabaseSubscription],
*,
over_rudp: bool = False,
) -> list[dict[str, Any]]:
schema_version = message.get("schemaVersion")
if schema_version == "cultnet.database_subscribe.v0":
@ -426,7 +546,7 @@ class CultMeshLocalServer:
subscriptions.pop(str(message.get("subscriptionId") or ""), None)
return []
if schema_version == "cultnet.document_put_raw.v0":
return self._handle_raw_put(message, subscriptions)
return self._handle_raw_put(message, subscriptions, over_rudp=over_rudp)
if schema_version == "cultnet.document_delete.v0":
return self._handle_raw_delete(message, subscriptions)
if schema_version == "cultnet.simulation_observation.v0":
@ -438,6 +558,8 @@ class CultMeshLocalServer:
self,
message: dict[str, Any],
subscriptions: dict[str, _DatabaseSubscription],
*,
over_rudp: bool = False,
) -> list[dict[str, Any]]:
document_record = message.get("document")
if not isinstance(document_record, dict):
@ -446,7 +568,22 @@ class CultMeshLocalServer:
message_id=str(message.get("messageId") or ""),
code="malformed_document_put",
)]
change = self.node.database.apply_raw_put_message(message)
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._error_response(
"Raw put document could not be stored.",
message_id=str(message.get("messageId") or ""),
code="malformed_document_put",
)]
if change is None:
return [self._error_response(
"Raw put message did not apply to a registered document.",
@ -648,7 +785,7 @@ class CultMeshLocalServer:
details={"documentCount": document_count, "maxSnapshotDocuments": self.max_snapshot_documents},
)
if self.max_snapshot_bytes is not None:
response_bytes = len(msgpack.packb(response, use_bin_type=True))
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}.",
@ -658,6 +795,51 @@ class CultMeshLocalServer:
)
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._error_response(
"Raw put documents must carry a string recordKey and a binary payload.",
message_id=str(message.get("messageId") or ""),
code="malformed_document_put",
)
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,
@ -812,3 +994,8 @@ def _infer_schema_name(schema_id: str) -> str | None:
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))

View file

@ -15,6 +15,8 @@ from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from pathlib import Path
from typing import Any, Callable
import msgpack
from cultcache_py import (
CultCache,
SingleFileMessagePackBackingStore,
@ -49,17 +51,23 @@ from cultnet_py import (
CultNetSimulationObservation,
CultNetSimulationObservationHub,
CultNetRudpPacketType,
CultNetRudpSendOptions,
CultNetRudpSession,
CultNetRudpSessionOptions,
CultNetRudpSocketMode,
CultNetRudpSocketTransportConnection,
CultNetRudpSocketTransportOptions,
apply_shard_log_response,
create_rudp_schema_transport,
decode_rudp_packet,
document_delete,
document_put_raw,
encode_rudp_packet,
hello,
simulation_observation,
snapshot_request,
)
from cultnet_py.cultmesh_contracts import VERSE_CATALOG_REQUEST
from cultmesh_py import create_node
from cultmesh_py import (
CultMesh,
@ -3751,7 +3759,11 @@ class CultMeshTests(unittest.TestCase):
finally:
self._terminate_process(process)
def test_cultmesh_daemon_enforces_snapshot_document_limit_as_peer_error(self) -> None:
def test_cultmesh_daemon_refuses_a_snapshot_document_limit_of_zero_at_startup(self) -> None:
# A limit of zero is a server that could answer no snapshot, which the Rust document
# server's options also refuse; the daemon passes the flag to the server, and exits with
# a usage error naming the rule instead of serving. The limit's enforcement as a peer error is pinned
# in process by test_cultmesh_local_server_rejects_oversized_snapshot_responses.
with tempfile.TemporaryDirectory() as temp:
ready_path = Path(temp) / "ready.json"
package_src = Path(__file__).resolve().parents[1] / "src"
@ -3762,7 +3774,7 @@ class CultMeshTests(unittest.TestCase):
if not existing_pythonpath
else f"{package_src}{os.pathsep}{existing_pythonpath}"
)
process = subprocess.Popen(
completed = subprocess.run(
[
sys.executable,
"-m",
@ -3777,25 +3789,27 @@ class CultMeshTests(unittest.TestCase):
"--ready-file",
str(ready_path),
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
capture_output=True,
text=True,
env=env,
timeout=30,
)
try:
ready = self._wait_for_ready_file(process, ready_path)
self.assertEqual(ready["snapshotLimits"], {"maxSnapshotBytes": None, "maxSnapshotDocuments": 0})
client = CultMesh.create_client("127.0.0.1", int(ready["port"]), timeout_seconds=2.0)
with self.assertRaisesRegex(CultNetPeerError, "Snapshot document limit exceeded") as raised:
client.fetch_snapshot_response(schema_ids=["cultcache.interop-note"])
self.assertEqual(raised.exception.response["schemaVersion"], "cultnet.error.v0")
self.assertEqual(raised.exception.response["code"], "snapshot_document_limit_exceeded")
self.assertEqual(raised.exception.response["details"]["documentCount"], 1)
self.assertEqual(raised.exception.response["details"]["maxSnapshotDocuments"], 0)
finally:
self._terminate_process(process)
# A usage error from argparse: exit status 2, the rule named, no traceback.
self.assertEqual(completed.returncode, 2, completed.stderr)
self.assertIn("error: max_snapshot_documents must be greater than zero", completed.stderr)
self.assertNotIn("Traceback", completed.stderr)
self.assertFalse(ready_path.exists())
# A port no socket can bind is a usage error too.
completed = subprocess.run(
[sys.executable, "-m", "cultmesh_py.daemon", "--port", "99999"],
capture_output=True,
text=True,
env=env,
timeout=30,
)
self.assertEqual(completed.returncode, 2, completed.stderr)
self.assertIn("port must be between 0 and 65535", completed.stderr)
self.assertNotIn("Traceback", completed.stderr)
def test_cultmesh_daemon_serves_opt_in_simulation_observations(self) -> None:
with tempfile.TemporaryDirectory() as temp:
@ -4327,6 +4341,638 @@ class CultMeshTests(unittest.TestCase):
self.assertEqual(error["details"]["documentCount"], 2)
self.assertEqual(error["details"]["maxSnapshotDocuments"], 1)
def test_cultmesh_local_server_refuses_a_put_it_could_never_serve(self) -> None:
# A put is admitted only if some snapshot request could return it. The put arrives under a
# long foreign schema alias and is stored and served under the shorter local schema id, so
# the size that decides is the served one, not the put's own.
document = define_database_entry_type(
"mesh.served_bound_note",
[("schema_version", 0), ("body", 1)],
schema_id="sha256:mesh-served-bound",
schema_name="mesh.served_bound_note",
schema_version="mesh.served_bound_note.v1",
)
def put(message_id: str, key: str, body_length: int) -> dict[str, Any]:
return document_put_raw(
message_id=message_id,
key=key,
schema_id="runtime.generated.mesh.served_bound_note.ui.99",
stored_at="2026-09-30T00:00:00Z",
payload=document.encode_payload({
"schema_version": "mesh.served_bound_note.v1",
"body": "x" * body_length,
}),
).to_wire()
def exchange(server: Any, *messages: dict[str, Any]) -> tuple[dict[str, Any], bytes]:
client = CultMesh.create_client("127.0.0.1", server.port, timeout_seconds=2.0)
with client.open_transport() as transport:
for message in messages:
transport.send("schema", msgpack.packb(message, use_bin_type=True))
payload = transport.receive().payload
return msgpack.unpackb(payload, raw=False), payload
empty_id_snapshot = snapshot_request(message_id="").to_wire()
# The bound is what the server actually serves for the at-bound document alone, under the
# shortest message id it answers (an empty one), measured on an unbounded server.
def served_alone_bytes(key: str, body_length: int) -> int:
node = CultMesh.create_node(runtime_id="mesh-served-bound-probe")
node.database.register_document(document)
server = CultMesh.serve_node(node, enable_rudp=False)
try:
response, payload = exchange(server, put("probe", key, body_length), empty_id_snapshot)
finally:
server.stop()
self.assertEqual(response["schemaVersion"], "cultnet.snapshot_response_raw.v0")
self.assertEqual(len(response["documents"]), 1)
return len(payload)
limit = served_alone_bytes("note:fits", 100)
self.assertEqual(served_alone_bytes("note:over", 101), limit + 1, "fixture: the documents must straddle the bound by one byte")
node = CultMesh.create_node(runtime_id="mesh-served-bound")
node.database.register_document(document)
server = CultMesh.serve_node(node, max_snapshot_bytes=limit, enable_rudp=False)
try:
refused, _ = exchange(server, put("put-over", "note:over", 101))
stored_after_refusal = node.database.get(document, "note:over")
served, served_payload = exchange(server, put("put-at", "note:fits", 100), empty_id_snapshot)
finally:
server.stop()
self.assertEqual(refused["schemaVersion"], "cultnet.error.v0")
self.assertEqual(refused["messageId"], "put-over")
self.assertEqual(refused["code"], "document_unservable")
self.assertEqual(refused["details"], {"responseBytes": limit + 1, "maxSnapshotBytes": limit})
self.assertIn(str(limit + 1), refused["error"])
self.assertIn(str(limit), refused["error"])
self.assertIsNone(stored_after_refusal)
self.assertEqual(served["schemaVersion"], "cultnet.snapshot_response_raw.v0")
self.assertEqual([record["recordKey"] for record in served["documents"]], ["note:fits"])
self.assertEqual(served["documents"][0]["schemaId"], document.catalog_entry().schema_id)
self.assertEqual(len(served_payload), limit)
def _rudp_bound_note(self) -> Any:
return define_database_entry_type(
"mesh.rudp_bound_note",
[("schema_version", 0), ("body", 1)],
schema_id="sha256:mesh-rudp-bound",
schema_name="mesh.rudp_bound_note",
schema_version="mesh.rudp_bound_note.v1",
)
@staticmethod
def _rudp_note_put(document: Any, message_id: str, key: str, body_length: int) -> dict[str, Any]:
return document_put_raw(
message_id=message_id,
key=key,
schema_id=document.catalog_entry().schema_id,
stored_at="2026-09-30T00:00:00Z",
payload=document.encode_payload({"schema_version": "mesh.rudp_bound_note.v1", "body": "x" * body_length}),
).to_wire()
@staticmethod
def _rudp_exchange(server: Any, *messages: dict[str, Any]) -> tuple[dict[str, Any], bytes]:
"""Sends each message over RUDP in 1200-byte fragments; returns the first reply."""
transport = create_rudp_schema_transport(
host="127.0.0.1",
port=server.port,
connection_id=server.rudp_connection_id,
timeout_seconds=4.0,
max_fragment_bytes=1200,
)
try:
for message in messages:
transport.send("schema", msgpack.packb(message, use_bin_type=True))
payload = transport.receive(timeout_seconds=4.0).payload
finally:
transport.close()
return msgpack.unpackb(payload, raw=False), payload
def test_cultmesh_local_server_serves_a_100_kb_put_over_rudp_in_fragments(self) -> None:
# The reply is larger than any one UDP datagram: it arrives only because it is sent
# in fragments, and the RUDP thread serves on afterwards.
document = self._rudp_bound_note()
node = CultMesh.create_node(runtime_id="mesh-rudp-large")
node.database.register_document(document)
server = CultMesh.serve_node(node)
try:
served, payload = self._rudp_exchange(
server,
self._rudp_note_put(document, "put-large", "note:large", 100_000),
snapshot_request(message_id="large").to_wire(),
)
again, _ = self._rudp_exchange(server, snapshot_request(message_id="again").to_wire())
alive = server._rudp_thread is not None and server._rudp_thread.is_alive()
finally:
server.stop()
self.assertEqual(served["schemaVersion"], "cultnet.snapshot_response_raw.v0")
self.assertEqual([record["recordKey"] for record in served["documents"]], ["note:large"])
self.assertGreater(len(served["documents"][0]["payload"]), 100_000)
self.assertGreater(len(payload), 65_507, "fixture: the reply cannot be one UDP datagram")
self.assertEqual(again["messageId"], "again")
self.assertTrue(alive)
self.assertEqual(server.rudp_send_failures, 0)
def _rudp_body_for(self, document: Any, key: str) -> Callable[[int], int]:
"""The body length whose document, keyed `key`, is served alone under the empty message
id in exactly the given bytes, measured on an unbounded server: what a snapshot sends."""
def served_alone_bytes(body_length: int) -> int:
node = CultMesh.create_node(runtime_id="mesh-rudp-bound-probe")
node.database.register_document(document)
server = CultMesh.serve_node(node)
try:
_, payload = self._rudp_exchange(
server, self._rudp_note_put(document, "probe", key, body_length),
snapshot_request(message_id="").to_wire(),
)
finally:
server.stop()
return len(payload)
probe = served_alone_bytes(500)
def body_for(served_bytes: int) -> int:
body_length = 500 + served_bytes - probe
self.assertEqual(served_alone_bytes(body_length), served_bytes, "fixture: served size is linear in the body")
return body_length
return body_for
def test_cultmesh_local_server_refuses_a_rudp_put_whose_reply_would_overflow_the_reliable_queue(self) -> None:
# Replies go in fragments of 100 bytes and a peer's reliable queue holds 8: a put over RUDP
# whose served reply takes 8 fragments is admitted and served, 9 or 20 are refused. A
# snapshot of two such documents needs 16 and cannot be queued: the peer is answered with a
# small cultnet.error.v0 rather than left to time out, its session ends, and the thread
# serves on.
document = self._rudp_bound_note()
body_for = self._rudp_body_for(document, "note:q")
node = CultMesh.create_node(runtime_id="mesh-rudp-bound")
node.database.register_document(document)
server = CultMesh.serve_node(node, rudp_max_fragment_bytes=100, rudp_max_pending_reliable_packets=8)
try:
refusals = [
self._rudp_exchange(server, self._rudp_note_put(document, f"put-{served}", "note:q", body_for(served)))[0]
for served in (2000, 801)
]
stored_after_refusals = node.database.get(document, "note:q")
served, served_payload = self._rudp_exchange(
server,
self._rudp_note_put(document, "put-at", "note:q", body_for(800)),
snapshot_request(message_id="").to_wire(),
)
unqueueable, _ = self._rudp_exchange(
server,
self._rudp_note_put(document, "put-r", "note:r", body_for(800)),
snapshot_request(message_id="both").to_wire(),
)
failures_after = server.rudp_send_failures
# An empty snapshot fits the small queue; a hello reply would not.
after_reply, _ = self._rudp_exchange(
server, snapshot_request(message_id="after-queue", record_keys=["note:none"]).to_wire()
)
alive = server._rudp_thread is not None and server._rudp_thread.is_alive()
finally:
server.stop()
for refusal, (served_bytes, fragments) in zip(refusals, ((2000, 20), (801, 9))):
self.assertEqual(refusal["schemaVersion"], "cultnet.error.v0")
self.assertEqual(refusal["messageId"], f"put-{served_bytes}")
self.assertEqual(refusal["code"], "document_unservable")
self.assertEqual(refusal["details"], {
"responseBytes": served_bytes,
"maxSnapshotBytes": None,
"fragmentCount": fragments,
"maxFragmentCount": 8,
})
self.assertIn(f"{served_bytes} bytes; it takes {fragments} fragments", refusal["error"])
self.assertNotIn("note:q", refusal["error"])
self.assertIsNone(stored_after_refusals)
self.assertEqual(served["schemaVersion"], "cultnet.snapshot_response_raw.v0")
self.assertEqual([record["recordKey"] for record in served["documents"]], ["note:q"])
self.assertEqual(len(served_payload), 800)
self.assertEqual(unqueueable["schemaVersion"], "cultnet.error.v0")
self.assertEqual(unqueueable["messageId"], "both")
self.assertEqual(unqueueable["code"], "response_unqueueable")
self.assertEqual(failures_after, 0)
self.assertEqual(after_reply["messageId"], "after-queue")
self.assertTrue(alive)
class _RawPeer:
"""A peer driven packet by packet, so a test decides what it acknowledges: nothing."""
def __init__(self, server: Any) -> None:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.bind(("127.0.0.1", 0))
self.sock.settimeout(0.05)
self.address = self.sock.getsockname()[:2]
self.target = ("127.0.0.1", server.port)
self.session = CultNetRudpSession(
CultNetRudpSessionOptions(
connection_id=server.rudp_connection_id, initial_sequence=100, resend_delay_ms=100_000
)
)
self.sock.sendto(encode_rudp_packet(self.session.create_connect(0)), self.target)
accept = self.receive(1.0)
assert accept is not None and accept.packet_type == CultNetRudpPacketType.ACCEPT, accept
self.session.receive(accept, 1)
def receive(self, timeout: float = 0.3) -> Any:
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
wire, _ = self.sock.recvfrom(65535)
except (TimeoutError, socket.timeout):
continue
return decode_rudp_packet(wire)
return None
def drain(self, timeout: float = 0.5) -> list[Any]:
# Bounded overall: the server resends what the peer never acknowledges.
packets = []
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
packet = self.receive(0.05)
if packet is not None:
packets.append(packet)
return packets
def send(self, message: dict[str, Any]) -> list[int]:
packets = self.session.send_many(
"schema",
msgpack.packb(message, use_bin_type=True),
CultNetRudpSendOptions(reliable=True, ordered=True, now_ms=2),
max_fragment_bytes=1200,
)
for packet in packets:
self.sock.sendto(encode_rudp_packet(packet), self.target)
return [packet.sequence for packet in packets]
def close(self) -> None:
self.sock.close()
@staticmethod
def _acknowledges(packet: Any, sequence: int) -> bool:
return packet.ack == sequence or any(
packet.ack_mask & (1 << bit) and packet.ack > bit and packet.ack - bit - 1 == sequence
for bit in range(32)
)
def _brim_server(self) -> tuple[Any, Any]:
"""A server whose peer's reliable queue (8) is filled exactly by an 8-fragment reply the
peer never acknowledges, and the peer."""
document = self._rudp_bound_note()
node = CultMesh.create_node(runtime_id="mesh-rudp-brim")
node.database.register_document(document)
server = CultMesh.serve_node(node, rudp_max_fragment_bytes=100, rudp_max_pending_reliable_packets=8)
def served(body: int) -> int:
put = self._rudp_note_put(document, "p", "note:q", body)
return len(msgpack.packb(node.database.raw_put_served_alone(put, message_id=""), use_bin_type=True))
body = 400 + 800 - served(400)
self.assertEqual(served(body), 800, "fixture: served size is linear in the body")
node.database.apply_raw_put_message(self._rudp_note_put(document, "p", "note:q", body))
peer = self._RawPeer(server)
peer.send(snapshot_request(message_id="", record_keys=["note:q"]).to_wire())
first = {p.sequence for p in peer.drain(0.3) if p.packet_type == CultNetRudpPacketType.DATA}
self.assertEqual(len(first), 8, "fixture: the first reply fills the queue exactly")
return server, peer
def test_cultmesh_local_server_answers_a_peer_whose_queue_is_full_to_the_brim(self) -> None:
# The next reply cannot be queued. The peer is answered with a cultnet.error.v0 that takes
# no room in the full queue and acknowledges nothing the peer sent, then its session ends.
server, peer = self._brim_server()
try:
refused = peer.send(snapshot_request(message_id="b", record_keys=["note:none"]).to_wire())
packets = peer.drain(0.5)
alive = server._rudp_thread is not None and server._rudp_thread.is_alive()
finally:
peer.close()
server.stop()
parts = sorted(
(
p for p in packets
if p.packet_type == CultNetRudpPacketType.DATA and p.channel_id == "schema" and not p.reliable
),
key=lambda p: p.fragment_index,
)
self.assertTrue(parts, "the refusal reaches the peer")
for part in parts:
self.assertFalse(
any(self._acknowledges(part, sequence) for sequence in refused),
f"the refusal acknowledges the refused request: ack={part.ack} mask={part.ack_mask:#x}",
)
refusal = msgpack.unpackb(b"".join(bytes(p.payload) for p in parts), raw=False)
self.assertEqual(refusal["schemaVersion"], "cultnet.error.v0")
self.assertEqual(refusal["messageId"], "b")
self.assertEqual(refusal["code"], "response_unqueueable")
goodbyes = [bytes(p.payload) for p in packets if p.packet_type == CultNetRudpPacketType.DISCONNECT]
self.assertEqual(goodbyes, [b"session refused a packet"], "then the session ends")
self.assertTrue(alive)
def test_cultmesh_local_server_names_a_refusal_that_can_never_be_sent_in_the_goodbye(self) -> None:
# The refusal's own fragment fails permanently: the failure is not dropped, the goodbye
# names it by its fixed code, never the error's text.
import errno
server, peer = self._brim_server()
original_sendto = socket.socket.sendto
def sendto(sock: socket.socket, data: bytes, *args: Any) -> int:
packet = decode_rudp_packet(data)
if (
args and tuple(args[-1]) == tuple(peer.address)
and packet.packet_type == CultNetRudpPacketType.DATA and not packet.reliable
):
raise OSError(errno.EMSGSIZE, "Message too long CANARY-7f3a")
return original_sendto(sock, data, *args)
try:
with patch.object(socket.socket, "sendto", sendto):
peer.send(snapshot_request(message_id="b", record_keys=["note:none"]).to_wire())
packets = peer.drain(0.5)
alive = server._rudp_thread is not None and server._rudp_thread.is_alive()
finally:
peer.close()
server.stop()
self.assertFalse(
[p for p in packets if p.packet_type == CultNetRudpPacketType.DATA and not p.reliable],
"the refusal could not be sent",
)
goodbyes = [bytes(p.payload) for p in packets if p.packet_type == CultNetRudpPacketType.DISCONNECT]
self.assertEqual(goodbyes, [b"packet could not be sent: EMSGSIZE"])
self.assertTrue(alive)
def test_cultmesh_local_server_refuses_a_tcp_message_it_cannot_handle_and_serves_on(self) -> None:
# Messages whose handling raises: the TCP peer is refused with fixed text, the log names
# the error type only, and the connection's thread serves its next message.
shapes = [
{"schemaVersion": "cultnet.snapshot_request.v0", "messageId": "snapshot", "recordKeys": 5},
{"schemaVersion": "cultnet.shard_log_request.v0", "messageId": "shard-log", "shardId": "a", "afterSequence": "CANARY-7f3a"},
{"schemaVersion": "cultnet.database_subscribe.v0", "messageId": "subscribe", "subscriptionId": "s", "schemaIds": 5},
{"schemaVersion": "cultnet.schema_catalog_request.v0", "messageId": "catalog", "schemaIds": 5},
{"schemaVersion": VERSE_CATALOG_REQUEST, "messageId": "verse", "verseIds": 5},
]
deaths: list[str] = []
original_hook = threading.excepthook
threading.excepthook = lambda args: deaths.append(f"{args.exc_type.__name__}")
server = CultMesh.serve_node(CultMesh.create_node(runtime_id="mesh-tcp-shapes"))
try:
with self.assertLogs("cultmesh_py.server", level="WARNING") as logs:
with CultMesh.create_client("127.0.0.1", server.port, timeout_seconds=4.0).open_transport() as transport:
refusals = []
for shape in shapes:
transport.send("schema", msgpack.packb(shape, use_bin_type=True))
refusals.append((shape["messageId"], msgpack.unpackb(transport.receive().payload, raw=False)))
transport.send("schema", msgpack.packb(hello(runtime_id="same-connection").to_wire(), use_bin_type=True))
after = msgpack.unpackb(transport.receive().payload, raw=False)
finally:
server.stop()
threading.excepthook = original_hook
for message_id, refusal in refusals:
self.assertEqual(refusal["schemaVersion"], "cultnet.error.v0", message_id)
self.assertEqual(refusal["messageId"], message_id)
self.assertEqual(refusal["code"], "message_unhandled", message_id)
self.assertEqual(refusal["error"], "The message could not be handled.", message_id)
self.assertEqual(after["schemaVersion"], "cultnet.hello.v0")
self.assertEqual(deaths, [])
self.assertEqual(len(logs.output), len(shapes))
self.assertFalse([line for line in logs.output if "CANARY" in line])
def test_cultmesh_local_server_refuses_a_rudp_put_whose_reply_needs_more_than_65535_fragments(self) -> None:
# One message carries at most 65535 fragments, however deep the queue: with one-byte
# fragments a put served in 65536 bytes is refused, one served in 65535 is stored.
document = self._rudp_bound_note()
body_for = self._rudp_body_for(document, "note:w")
node = CultMesh.create_node(runtime_id="mesh-rudp-wide")
node.database.register_document(document)
server = CultMesh.serve_node(node, rudp_max_fragment_bytes=1)
try:
transport = create_rudp_schema_transport(
host="127.0.0.1", port=server.port, connection_id=server.rudp_connection_id,
timeout_seconds=4.0, max_fragment_bytes=1200,
)
try:
transport.send("schema", msgpack.packb(self._rudp_note_put(document, "put-over", "note:w", body_for(65_536)), use_bin_type=True))
refusal = msgpack.unpackb(transport.receive(timeout_seconds=8.0).payload, raw=False)
transport.send("schema", msgpack.packb(self._rudp_note_put(document, "put-at", "note:w", body_for(65_535)), use_bin_type=True))
deadline = time.monotonic() + 4.0
while node.database.get(document, "note:w") is None and time.monotonic() < deadline:
transport.receive_once()
time.sleep(0.005)
finally:
transport.close()
stored = node.database.get(document, "note:w")
finally:
server.stop()
self.assertEqual(refusal["code"], "document_unservable")
self.assertEqual(refusal["details"]["fragmentCount"], 65_536)
self.assertEqual(refusal["details"]["maxFragmentCount"], 65_535)
self.assertIsNotNone(stored)
def test_cultmesh_local_server_rudp_thread_survives_a_datagram_that_cannot_leave(self) -> None:
# Fragments larger than any UDP datagram: the reply's one packet can never be sent as
# built. That is a permanent failure: it ends that peer's session and is not counted as
# a lost datagram; the thread serves the next peer.
document = self._rudp_bound_note()
node = CultMesh.create_node(runtime_id="mesh-rudp-emsgsize")
node.database.register_document(document)
server = CultMesh.serve_node(node, rudp_max_fragment_bytes=200_000)
try:
transport = create_rudp_schema_transport(
host="127.0.0.1", port=server.port, connection_id=server.rudp_connection_id,
timeout_seconds=4.0, max_fragment_bytes=1200,
)
try:
transport.send("schema", msgpack.packb(self._rudp_note_put(document, "put-large", "note:big", 80_000), use_bin_type=True))
transport.send("schema", msgpack.packb(snapshot_request(message_id="big").to_wire(), use_bin_type=True))
deadline = time.monotonic() + 1.0
while time.monotonic() < deadline:
try:
transport.receive_once()
except ConnectionError:
break
time.sleep(0.005)
finally:
transport.close()
failures = server.rudp_send_failures
hello_reply, _ = self._rudp_exchange(server, hello(runtime_id="after").to_wire())
alive = server._rudp_thread is not None and server._rudp_thread.is_alive()
finally:
server.stop()
self.assertEqual(failures, 0)
self.assertEqual(hello_reply["schemaVersion"], "cultnet.hello.v0")
self.assertTrue(alive)
def test_cultmesh_local_server_refuses_a_malformed_put_over_rudp_and_serves_on(self) -> None:
# A put whose document has no string recordKey or no binary payload could never be stored
# or served: it is refused as malformed before any sizing reads it, and the RUDP thread
# serves the next peer.
document = self._rudp_bound_note()
node = CultMesh.create_node(runtime_id="mesh-rudp-malformed")
node.database.register_document(document)
server = CultMesh.serve_node(node)
try:
refusals = []
for field_name, value in (
("recordKey", None),
("recordKey", 5),
("payload", None),
("payload", "not binary"),
):
put = self._rudp_note_put(document, f"bad-{field_name}-{value}", "note:bad", 10)
if value is None:
del put["document"][field_name]
else:
put["document"][field_name] = value
refusal, _ = self._rudp_exchange(server, put)
refusals.append((put["messageId"], refusal))
after, _ = self._rudp_exchange(server, snapshot_request(message_id="after").to_wire())
alive = server._rudp_thread is not None and server._rudp_thread.is_alive()
finally:
server.stop()
for message_id, refusal in refusals:
self.assertEqual(refusal["schemaVersion"], "cultnet.error.v0", message_id)
self.assertEqual(refusal["messageId"], message_id)
self.assertEqual(refusal["code"], "malformed_document_put", message_id)
self.assertEqual(after["messageId"], "after")
self.assertEqual(after["documents"], [])
self.assertTrue(alive)
def test_cultmesh_local_server_refuses_a_put_its_store_cannot_take_and_serves_on(self) -> None:
# Well-formed puts the store refuses: a blank key, a payload that is not MessagePack, a
# payload its schema cannot decode, a global document under another key. Each is refused
# to the peer that sent it, over RUDP and over TCP; the RUDP thread lives, the TCP
# connection serves its next message, and other peers are served.
document = self._rudp_bound_note()
global_document = define_database_entry_type(
"mesh.rudp_global_note",
[("schema_version", 0), ("body", 1)],
schema_id="sha256:mesh-rudp-global",
schema_name="mesh.rudp_global_note",
schema_version="mesh.rudp_global_note.v1",
global_document=True,
)
def cases() -> list[dict[str, Any]]:
puts = []
for name, field_name, value in (
("empty-key", "recordKey", ""),
("blank-key", "recordKey", " "),
("garbage-payload", "payload", bytes([0xC1])),
("int-payload", "payload", msgpack.packb(5)),
):
put = self._rudp_note_put(document, name, "note:ok", 10)
put["document"][field_name] = value
puts.append(put)
puts.append(self._rudp_note_put(global_document, "global-wrong-key", "not-global", 10))
return puts
node = CultMesh.create_node(runtime_id="mesh-unstorable-put")
node.database.register_document(document)
node.database.register_document(global_document)
server = CultMesh.serve_node(node)
try:
rudp_refusals = [(put["messageId"], self._rudp_exchange(server, put)[0]) for put in cases()]
rudp_after, _ = self._rudp_exchange(server, hello(runtime_id="rudp-after").to_wire())
rudp_alive = server._rudp_thread is not None and server._rudp_thread.is_alive()
tcp_refusals = []
with CultMesh.create_client("127.0.0.1", server.port, timeout_seconds=4.0).open_transport() as transport:
for put in cases():
transport.send("schema", msgpack.packb(put, use_bin_type=True))
tcp_refusals.append((put["messageId"], msgpack.unpackb(transport.receive().payload, raw=False)))
transport.send("schema", msgpack.packb(hello(runtime_id="same-connection").to_wire(), use_bin_type=True))
same_connection = msgpack.unpackb(transport.receive().payload, raw=False)
other_connection = CultMesh.create_client("127.0.0.1", server.port, timeout_seconds=4.0).request(
hello(runtime_id="other-connection").to_wire(), expected_schema_version="cultnet.hello.v0"
)
finally:
server.stop()
self.assertEqual(len(rudp_refusals), 5)
for message_id, refusal in rudp_refusals + tcp_refusals:
self.assertEqual(refusal["schemaVersion"], "cultnet.error.v0", message_id)
self.assertEqual(refusal["messageId"], message_id)
self.assertEqual(refusal["code"], "malformed_document_put", message_id)
self.assertNotIn("note:ok", refusal["error"], message_id)
self.assertEqual(len(tcp_refusals), 5)
self.assertEqual(rudp_after["schemaVersion"], "cultnet.hello.v0")
self.assertTrue(rudp_alive)
self.assertEqual(same_connection["schemaVersion"], "cultnet.hello.v0")
self.assertEqual(other_connection["schemaVersion"], "cultnet.hello.v0")
self.assertIsNone(node.database.get(document, "note:ok"))
def test_cultmesh_local_server_refuses_options_that_could_answer_nothing(self) -> None:
# The Rust document server's option rules: every limit is greater than zero, and the limits
# leave room for an empty snapshot, the smallest response the server sends. One-byte
# fragments and a queue of 16 could never carry one, so no reply would ever be sent.
node = CultMesh.create_node(runtime_id="mesh-rudp-options")
probe = CultMesh.serve_node(node)
try:
_, empty_payload = self._rudp_exchange(probe, snapshot_request(message_id="").to_wire())
finally:
probe.stop()
empty = len(empty_payload)
self.assertGreater(empty, 16, "fixture: an empty snapshot takes more than 16 one-byte fragments")
self.assertNotEqual(empty % (empty - 1), 0, "fixture: empty - 1 byte fragments leave a remainder")
def refused(**options: Any) -> str:
server = None
try:
with self.assertRaises(ValueError, msg=str(options)) as raised:
server = CultMesh.serve_node(node, **options)
finally:
if server is not None:
server.stop()
return str(raised.exception)
def accepted(**options: Any) -> None:
CultMesh.serve_node(node, **options).stop()
carry = "cannot carry an empty snapshot response"
self.assertIn(carry, refused(rudp_max_fragment_bytes=1, rudp_max_pending_reliable_packets=16))
self.assertIn(carry, refused(rudp_max_fragment_bytes=1, rudp_max_pending_reliable_packets=empty - 1))
accepted(rudp_max_fragment_bytes=1, rudp_max_pending_reliable_packets=empty)
# Fragments are counted rounding up: empty - 1 bytes a fragment takes two.
self.assertIn(carry, refused(rudp_max_fragment_bytes=empty - 1, rudp_max_pending_reliable_packets=1))
accepted(rudp_max_fragment_bytes=empty - 1, rudp_max_pending_reliable_packets=2)
self.assertIn("cannot hold an empty snapshot response", refused(max_snapshot_bytes=empty - 1))
accepted(max_snapshot_bytes=empty)
self.assertIn("greater than zero", refused(max_snapshot_bytes=0))
self.assertIn("greater than zero", refused(max_snapshot_documents=0))
accepted(max_snapshot_documents=1)
self.assertIn("greater than zero", refused(rudp_resend_delay_ms=0))
accepted(rudp_resend_delay_ms=1)
self.assertIn("greater than zero", refused(rudp_max_fragment_bytes=0))
self.assertIn("greater than zero", refused(rudp_max_pending_reliable_packets=0))
# The RUDP options configure only the RUDP server: without one, none of them is checked.
accepted(enable_rudp=False, rudp_max_fragment_bytes=1, rudp_max_pending_reliable_packets=16)
accepted(
enable_rudp=False,
rudp_max_fragment_bytes=0,
rudp_max_pending_reliable_packets=0,
rudp_resend_delay_ms=0,
)
self.assertIn("greater than zero", refused(enable_rudp=False, max_snapshot_documents=0))
self.assertIn("cannot hold an empty snapshot response", refused(enable_rudp=False, max_snapshot_bytes=empty - 1))
# The configuration at the bound does answer: an empty snapshot in one-byte fragments,
# exactly as many as the queue holds.
server = CultMesh.serve_node(node, rudp_max_fragment_bytes=1, rudp_max_pending_reliable_packets=empty)
try:
served, payload = self._rudp_exchange(server, snapshot_request(message_id="").to_wire())
finally:
server.stop()
self.assertEqual(served["documents"], [])
self.assertEqual(len(payload), empty)
self.assertEqual(server.rudp_send_failures, 0)
def test_cultmesh_local_server_returns_errors_for_bad_requests(self) -> None:
document = define_database_entry_type(
"mesh.error_note",

View file

@ -48,7 +48,8 @@ class RudpServerGenerationTests(unittest.TestCase):
def setUp(self) -> None:
node = create_node(runtime_id="rudp-generation")
node.database.register_document(NOTE)
self.server = CultMeshLocalServer(node=node, rudp_connection_id=CONNECTION_ID)
# Replies stay whole datagrams here, so each server packet the pump reads is one message.
self.server = CultMeshLocalServer(node=node, rudp_connection_id=CONNECTION_ID, rudp_max_fragment_bytes=60_000)
self.server.start()
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.bind(("127.0.0.1", 0))

View file

@ -822,7 +822,11 @@ pub fn request_raw_snapshot_from_rudp_catalog(
}
cultnet_rs::CultNetMessage::Error { error, .. } => {
let _ = client.disconnect(b"snapshot-error".to_vec());
anyhow::bail!("CultMesh RUDP snapshot failed: {error}");
anyhow::bail!(
"CultMesh RUDP catalog {} refused the snapshot{}",
options.target,
recognised_refusal(error)
);
}
_ => {}
}
@ -856,6 +860,17 @@ pub fn request_raw_snapshot_from_rudp_catalog(
)
}
/// A catalog's refusal text, quoted (`": text"`) only when it is one of the
/// fixed refusals a CultMesh catalog sends; any other text could carry
/// anything, so it is left out.
fn recognised_refusal(text: &str) -> String {
if REFUSAL_TEXTS.contains(&text) {
format!(": {text}")
} else {
String::new()
}
}
fn unix_millis() -> u128 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
@ -866,7 +881,12 @@ fn unix_millis() -> u128 {
/// Publish one raw CultNet schema message to a RUDP catalog.
///
/// Each call owns a fresh connection epoch and returns only after the catalog
/// acknowledges reliable application admission.
/// acknowledges reliable application admission. Against a Rust CultMesh
/// catalog, which never acknowledges a message it refuses, a refusal is
/// returned as an error, naming the refusal when it is one of the fixed texts
/// such a catalog sends. A catalog that acknowledges a message on receipt and
/// refuses it afterwards (the TypeScript document server does) is reported as
/// having admitted it: the acknowledgement arrives first.
pub fn publish_cultnet_message_to_rudp_catalog(
message: &cultnet_rs::CultNetMessage,
options: CultMeshRudpDocumentPublishOptions,
@ -887,7 +907,23 @@ pub fn publish_cultnet_message_to_rudp_catalog(
let receipt = client.send_reliable("schema", payload)?;
let flush_deadline = Instant::now() + options.flush_timeout;
while Instant::now() < flush_deadline {
let _ = client.receive_once()?;
if let Some(frame) = client.receive_once()? {
if frame.channel_id == "schema" {
if let Ok(cultnet_rs::CultNetMessage::Error { error, .. }) =
decode_cultnet_message_from_slice(
&frame.payload,
CultNetWireContract::CultNetSchemaV0,
)
{
let _ = client.disconnect(b"document-refused".to_vec());
anyhow::bail!(
"CultMesh RUDP catalog {} refused the put{}",
options.target,
recognised_refusal(&error)
);
}
}
}
match client.reliable_send_status(&receipt) {
cultnet_rs::CultNetRudpReliableSendStatus::Acknowledged => {
let _ = client.disconnect(b"document-acknowledged".to_vec());
@ -1280,7 +1316,7 @@ mod tests {
}
#[test]
fn document_publish_requires_application_acknowledgement() -> Result<()> {
fn a_refused_publish_fails_with_the_catalogs_reason_not_a_timeout() -> Result<()> {
let temp = tempfile::tempdir()?;
let node = CultMesh::create_node(
temp.path().join("cultmesh.cc"),
@ -1295,7 +1331,7 @@ mod tests {
let mut server = CultMeshRudpDocumentServer::new(
socket,
|_receipt: CultMeshRudpRawDocumentReceipt| {
anyhow::bail!("injected durable sink failure")
anyhow::bail!("injected durable sink failure CANARY-7f3a")
},
|_query: &CultMeshRudpSnapshotQuery| Ok(Vec::new()),
CultMeshSystemClock::default(),
@ -1308,6 +1344,7 @@ mod tests {
Ok(())
});
let started = Instant::now();
let error = node
.publish_document_to_rudp_catalog(
"note",
@ -1317,16 +1354,164 @@ mod tests {
CultMeshRudpDocumentPublishOptions {
target,
connect_timeout: Duration::from_millis(100),
flush_timeout: Duration::from_millis(50),
flush_timeout: Duration::from_secs(10),
poll_interval: Duration::from_millis(2),
resend_delay_ms: 5,
..CultMeshRudpDocumentPublishOptions::default()
},
)
.expect_err("unacknowledged document must fail closed");
.expect_err("a refused document must fail closed");
let waited = started.elapsed();
stop.store(true, std::sync::atomic::Ordering::SeqCst);
server.join().expect("server thread should not panic")?;
assert!(error.to_string().contains("reliable acknowledgement"));
// The publisher hears the refusal and its reason, long before its flush
// deadline: a refusal is not mistaken for loss.
assert!(
error
.to_string()
.ends_with("refused the put: the catalog refused the document"),
"{error:#}"
);
assert!(!error.to_string().contains("CANARY"), "{error:#}");
assert!(waited < Duration::from_secs(5), "waited {waited:?}");
Ok(())
}
/// A catalog that answers every message with a refusal of its own wording,
/// never acknowledging it. Stops when the flag is set.
fn refusing_catalog(
text: &'static str,
) -> Result<(
SocketAddr,
std::sync::Arc<std::sync::atomic::AtomicBool>,
thread::JoinHandle<Result<()>>,
)> {
use cultnet_rs::{
CultNetRudpPacketType, CultNetRudpSendOptions, CultNetRudpSession,
CultNetRudpSessionOptions, decode_rudp_packet, encode_rudp_packet,
};
let socket = UdpSocket::bind("127.0.0.1:0")?;
socket.set_read_timeout(Some(Duration::from_millis(5)))?;
let target = socket.local_addr()?;
let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let catalog_stop = stop.clone();
let catalog = thread::spawn(move || -> Result<()> {
let mut session: Option<CultNetRudpSession> = None;
let mut wire = vec![0_u8; 65_535];
while !catalog_stop.load(std::sync::atomic::Ordering::SeqCst) {
let Ok((bytes, peer)) = socket.recv_from(&mut wire) else {
continue;
};
let Ok(packet) = decode_rudp_packet(&wire[..bytes]) else {
continue;
};
if packet.packet_type == CultNetRudpPacketType::Connect {
let mut accepted = CultNetRudpSession::new(CultNetRudpSessionOptions {
connection_id: packet.connection_id,
initial_sequence: None,
resend_delay_ms: 10_000,
max_pending_reliable_packets: Some(64),
});
let accept = accepted.accept_connect(&packet, 0, Vec::new())?;
socket.send_to(&encode_rudp_packet(&accept)?, peer)?;
session = Some(accepted);
continue;
}
let Some(session) = session.as_mut() else {
continue;
};
let Ok(received) = session.receive(&packet, 1) else {
continue;
};
for _message in received.delivered {
let refusal = encode_cultnet_message_to_vec(
&cultnet_rs::CultNetMessage::Error {
error: text.into(),
code: None,
details: None,
},
CultNetWireContract::CultNetSchemaV0,
)?;
let options = CultNetRudpSendOptions {
reliable: false,
ordered: false,
sequenced: false,
now_ms: 2,
reliable_expire_after_ms: None,
};
for packet in session.send_many("schema", refusal, options, Some(1200))? {
socket.send_to(&encode_rudp_packet(&packet)?, peer)?;
}
}
}
Ok(())
});
Ok((target, stop, catalog))
}
/// A catalog's refusal text is quoted only when it is one of the fixed
/// refusals a CultMesh catalog sends. Any other text, which could carry
/// anything, stays out of the publisher's error.
#[test]
fn a_publisher_never_quotes_a_refusal_it_does_not_recognise() -> Result<()> {
let temp = tempfile::tempdir()?;
let node = CultMesh::create_node(
temp.path().join("cultmesh.cc"),
TestDocuments,
Default::default(),
)?;
let (target, stop, catalog) = refusing_catalog("no such tenant: CANARY-7f3a")?;
let error = node
.publish_document_to_rudp_catalog(
"note",
&Note {
body: "refused by a stranger".into(),
},
CultMeshRudpDocumentPublishOptions {
target,
connect_timeout: Duration::from_secs(2),
flush_timeout: Duration::from_secs(10),
poll_interval: Duration::from_millis(2),
resend_delay_ms: 5,
..CultMeshRudpDocumentPublishOptions::default()
},
)
.expect_err("a refused document must fail closed");
stop.store(true, std::sync::atomic::Ordering::SeqCst);
catalog.join().expect("catalog thread should not panic")?;
assert_eq!(
error.to_string(),
format!("CultMesh RUDP catalog {target} refused the put")
);
Ok(())
}
/// The snapshot client filters a catalog's refusal the same way: a fixed
/// refusal is named, any other text is left out.
#[test]
fn a_snapshot_client_quotes_only_a_refusal_it_recognises() -> Result<()> {
for (text, expected) in [
("no such tenant: CANARY-7f3a", ""),
("the snapshot source failed", ": the snapshot source failed"),
] {
let (target, stop, catalog) = refusing_catalog(text)?;
let error = request_raw_snapshot_from_rudp_catalog(CultMeshRudpSnapshotOptions {
target,
message_id: "refused".into(),
connect_timeout: Duration::from_secs(2),
response_timeout: Duration::from_secs(10),
poll_interval: Duration::from_millis(2),
resend_delay_ms: 5,
..CultMeshRudpSnapshotOptions::default()
})
.expect_err("a refused snapshot must fail");
stop.store(true, std::sync::atomic::Ordering::SeqCst);
catalog.join().expect("catalog thread should not panic")?;
assert_eq!(
error.to_string(),
format!("CultMesh RUDP catalog {target} refused the snapshot{expected}")
);
}
Ok(())
}

View file

@ -3,7 +3,7 @@ use cultnet_rs::{
CultNetMessage, CultNetRawDocumentRecord, CultNetRudpPacket, CultNetRudpPacketType,
CultNetRudpSendOptions, CultNetRudpSession, CultNetRudpSessionOptions, CultNetWireContract,
decode_cultnet_message_from_slice, decode_rudp_packet, encode_cultnet_message_to_vec,
encode_rudp_packet, is_permanent_send_error,
encode_rudp_packet, is_permanent_send_error, send_error_code,
};
use std::collections::BTreeMap;
#[cfg(test)]
@ -13,6 +13,11 @@ use std::net::{SocketAddr, UdpSocket};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
const MAX_UDP_DATAGRAM_BYTES: usize = 65_535;
/// The most fragments one RUDP message can carry: its fragment count is a u16.
const MAX_FRAGMENTS_PER_MESSAGE: usize = u16::MAX as usize;
/// The shortest message id CultNet encodes: one character. A snapshot request
/// can carry no shorter id, so no response to it can be smaller.
const SHORTEST_MESSAGE_ID: &str = "0";
/// The transport identity of one remote CultNet RUDP session.
///
@ -72,6 +77,20 @@ pub trait CultMeshRudpSnapshotSource {
&mut self,
query: &CultMeshRudpSnapshotQuery,
) -> Result<Vec<CultNetRawDocumentRecord>>;
/// The record this source would serve for a received put's `document`.
///
/// The server admits a put only if a snapshot response carrying this record
/// alone fits its limits, so a source that serves a different shape than it
/// receives (dropping provenance, or adding its own) overrides this to keep
/// admission exact. The default serves the record as received. An error
/// refuses the put as `SnapshotSourceFailed`.
fn served_record(
&mut self,
document: &CultNetRawDocumentRecord,
) -> Result<CultNetRawDocumentRecord> {
Ok(document.clone())
}
}
impl<F> CultMeshRudpSnapshotSource for F
@ -140,6 +159,10 @@ pub struct CultMeshRudpDocumentServerOptions {
/// finite without duplicating its fragment/ordering machinery here.
pub max_admitted_payload_bytes: usize,
pub max_admitted_payload_bytes_per_session: usize,
/// The largest encoded snapshot response the server sends. It also bounds
/// puts: a document whose snapshot response alone would exceed it, or would
/// take more fragments than one message or the reliable queue can hold, is
/// refused with `DocumentUnservable`, since no request could return it.
pub max_snapshot_response_bytes: usize,
pub max_snapshot_documents: usize,
pub resend_delay: Duration,
@ -176,12 +199,129 @@ pub enum CultMeshRudpApplicationOperation {
SnapshotRequest,
}
/// Why the server refused an application message.
///
/// `Display` gives the operator-facing sentence; match on the variant to act on
/// the cause.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CultMeshRudpRejectionReason {
/// The caller's sink refused the document. Carries the sink's error text.
SinkRefused(String),
/// The document could never be served: a snapshot response carrying it
/// alone, as the snapshot source would serve it (`served_record`) and under
/// the shortest message id CultNet allows, would
/// exceed `max_snapshot_response_bytes`, or would take more than
/// `max_fragment_count` fragments of `max_fragment_bytes`: the lesser of
/// 65535 and `max_pending_reliable_packets_per_session`. It was not offered
/// to the sink.
DocumentUnservable {
response_bytes: usize,
max_snapshot_response_bytes: usize,
fragment_count: usize,
max_fragment_count: usize,
},
/// The caller's snapshot source failed. Carries its error text.
SnapshotSourceFailed(String),
SnapshotTooManyDocuments {
documents: usize,
max_snapshot_documents: usize,
},
SnapshotResponseTooLarge {
response_bytes: usize,
max_snapshot_response_bytes: usize,
},
/// A snapshot response could not be encoded. Carries the encoder's error text.
ResponseEncodingFailed(String),
/// The server's retained payload budget cannot hold the response.
PayloadBudgetFull,
/// The session could not queue the response. Carries the session's error text.
ResponseQueueFailed(String),
/// A packet of the response can never be sent to the peer as built
/// (`is_permanent_send_error`). Carries the failure's fixed name
/// (`send_error_code`). The session has ended with a goodbye carrying the
/// same name, and no refusal: the server knows the peer cannot be reached.
ResponseSendFailed(&'static str),
}
impl std::fmt::Display for CultMeshRudpRejectionReason {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::SinkRefused(error) | Self::SnapshotSourceFailed(error) => f.write_str(error),
Self::DocumentUnservable {
response_bytes,
max_snapshot_response_bytes,
fragment_count,
max_fragment_count,
} => write!(
f,
"document can never be served: its snapshot response is {response_bytes} bytes in {fragment_count} fragments; limits are {max_snapshot_response_bytes} bytes and {max_fragment_count} fragments"
),
Self::SnapshotTooManyDocuments {
documents,
max_snapshot_documents,
} => write!(
f,
"snapshot returned {documents} documents; limit is {max_snapshot_documents}"
),
Self::SnapshotResponseTooLarge {
response_bytes,
max_snapshot_response_bytes,
} => write!(
f,
"snapshot response is {response_bytes} bytes; limit is {max_snapshot_response_bytes}"
),
Self::ResponseEncodingFailed(error) => {
write!(f, "snapshot response could not be encoded: {error}")
}
Self::PayloadBudgetFull => f.write_str("retained payload budget is full"),
Self::ResponseQueueFailed(error) => {
write!(f, "snapshot response could not be queued: {error}")
}
Self::ResponseSendFailed(code) => {
write!(f, "snapshot response could not be sent: {code}")
}
}
}
}
/// The texts a refused peer is sent, one per rejection variant. They are fixed:
/// a sink's or source's error text can quote what a peer sent, so it stays with
/// the caller that receives the rejection and never reaches the wire.
pub(crate) const REFUSAL_TEXTS: [&str; 9] = [
"the catalog refused the document",
"the document can never be served",
"the snapshot source failed",
"the snapshot has too many documents",
"the snapshot response is too large",
"the snapshot response could not be encoded",
"the retained payload budget is full",
"the snapshot response could not be queued",
"the snapshot response could not be sent",
];
impl CultMeshRudpRejectionReason {
/// The fixed text the refused peer is sent for this variant.
fn refusal_text(&self) -> &'static str {
REFUSAL_TEXTS[match self {
Self::SinkRefused(_) => 0,
Self::DocumentUnservable { .. } => 1,
Self::SnapshotSourceFailed(_) => 2,
Self::SnapshotTooManyDocuments { .. } => 3,
Self::SnapshotResponseTooLarge { .. } => 4,
Self::ResponseEncodingFailed(_) => 5,
Self::PayloadBudgetFull => 6,
Self::ResponseQueueFailed(_) => 7,
Self::ResponseSendFailed(_) => 8,
}]
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CultMeshRudpApplicationRejection {
pub session: CultMeshRudpSessionKey,
pub operation: CultMeshRudpApplicationOperation,
pub message_id: String,
pub reason: String,
pub reason: CultMeshRudpRejectionReason,
}
#[derive(Clone, Debug, PartialEq, Eq)]
@ -191,6 +331,16 @@ pub enum CultMeshRudpPollOutcome {
ApplicationRejected(CultMeshRudpApplicationRejection),
}
/// Why a session ends before its peer is done with it.
enum SessionEnd {
/// The session refused a packet.
Refused,
/// The server rejected a peer's message; the peer is sent this fixed text.
Rejected(&'static str),
/// The session owes its peer a packet that can never be sent as built.
Unsendable(std::io::Error),
}
struct SessionEntry {
session: CultNetRudpSession,
created_at_monotonic_millis: u64,
@ -285,8 +435,12 @@ where
/// Poll transport maintenance and receive at most one UDP datagram.
///
/// Application rejection invalidates only the responsible peer session and
/// is returned as data so a daemon can log it and keep serving. Local
/// socket and server-state failures remain errors.
/// is returned as data so a daemon can log it and keep serving. The peer is
/// sent the refusal as a `cultnet.error.v0` carrying fixed text for the
/// rejection's variant, then a goodbye; neither acknowledges the refused
/// message. The rejection's own detail, which can quote a sink's or
/// source's error, stays with the caller. Local socket and server-state
/// failures remain errors.
pub fn poll_once(&mut self) -> Result<CultMeshRudpPollOutcome> {
self.maintain()?;
let mut wire = vec![0_u8; MAX_UDP_DATAGRAM_BYTES];
@ -359,7 +513,7 @@ where
let result = match result {
Ok(result) => result,
Err(_) => {
self.end_refused_session(key)?;
self.end_session(key, SessionEnd::Refused)?;
self.packets_dropped += 1;
return Ok(CultMeshRudpPollOutcome::Handled);
}
@ -393,7 +547,16 @@ where
now_unix,
now_monotonic,
)? {
self.sessions.remove(&key);
// The only reply `receive` returns is a Pong, which delivers no
// frame, so no earlier send of this poll can precede a rejection.
// A response that could not be sent ended its session where the
// send failed, over the real error.
if !matches!(
rejection.reason,
CultMeshRudpRejectionReason::ResponseSendFailed(_)
) {
self.end_session(key, SessionEnd::Rejected(rejection.reason.refusal_text()))?;
}
return Ok(CultMeshRudpPollOutcome::ApplicationRejected(rejection));
}
}
@ -408,7 +571,7 @@ where
unsendable = self.send_packet(key.remote_addr, &ack)?;
}
if let Some(error) = unsendable {
self.end_unsendable_session(key, &error)?;
self.end_session(key, SessionEnd::Unsendable(error))?;
}
Ok(CultMeshRudpPollOutcome::Handled)
}
@ -437,7 +600,7 @@ where
continue;
}
if let Some(error) = self.send_packet(key.remote_addr, packet)? {
self.end_unsendable_session(*key, &error)?;
self.end_session(*key, SessionEnd::Unsendable(error))?;
}
}
Ok(CultMeshRudpMaintenance {
@ -470,7 +633,7 @@ where
match entry.session.accept_connect(packet, now, Vec::new()) {
Ok(reply) => reply,
Err(_) => {
self.end_refused_session(key)?;
self.end_session(key, SessionEnd::Refused)?;
return Ok(false);
}
}
@ -501,7 +664,7 @@ where
}
};
if let Some(error) = self.send_packet(key.remote_addr, &reply)? {
self.end_unsendable_session(key, &error)?;
self.end_session(key, SessionEnd::Unsendable(error))?;
return Ok(false);
}
Ok(true)
@ -520,6 +683,49 @@ where
message_id,
document,
} => {
let reject = |reason| {
Ok(Some(CultMeshRudpApplicationRejection {
session: key,
operation: CultMeshRudpApplicationOperation::DocumentPutRaw,
message_id: message_id.clone(),
reason,
}))
};
// Admit only what some snapshot request can return: the smallest
// response that could carry this document is the record the snapshot
// source would serve for it, alone, under the shortest message id
// CultNet encodes, sized by the snapshot path's encoder and fragmented
// as the snapshot path sends it.
let served = match self.snapshot_source.served_record(&document) {
Ok(served) => served,
Err(error) => {
return reject(CultMeshRudpRejectionReason::SnapshotSourceFailed(
format!("{error:#}"),
));
}
};
let alone = CultNetMessage::SnapshotResponseRaw {
message_id: SHORTEST_MESSAGE_ID.into(),
documents: vec![served],
};
let response_bytes = match encode_snapshot_response(&alone) {
Ok(payload) => payload.len(),
Err(error) => {
return reject(CultMeshRudpRejectionReason::ResponseEncodingFailed(error));
}
};
let fragment_count = self.fragments_for(response_bytes);
let max_fragment_count = self.max_fragments_per_response();
if response_bytes > self.options.max_snapshot_response_bytes
|| fragment_count > max_fragment_count
{
return reject(CultMeshRudpRejectionReason::DocumentUnservable {
response_bytes,
max_snapshot_response_bytes: self.options.max_snapshot_response_bytes,
fragment_count,
max_fragment_count,
});
}
let receipt = CultMeshRudpRawDocumentReceipt {
session: key,
message_id: message_id.clone(),
@ -528,12 +734,9 @@ where
document,
};
if let Err(error) = self.sink.accept_raw_document(receipt) {
return Ok(Some(CultMeshRudpApplicationRejection {
session: key,
operation: CultMeshRudpApplicationOperation::DocumentPutRaw,
message_id,
reason: format!("{error:#}"),
}));
return reject(CultMeshRudpRejectionReason::SinkRefused(format!(
"{error:#}"
)));
}
}
CultNetMessage::SnapshotRequest {
@ -555,7 +758,9 @@ where
session: key,
operation: CultMeshRudpApplicationOperation::SnapshotRequest,
message_id,
reason: format!("{error:#}"),
reason: CultMeshRudpRejectionReason::SnapshotSourceFailed(format!(
"{error:#}"
)),
}));
}
};
@ -564,28 +769,24 @@ where
session: key,
operation: CultMeshRudpApplicationOperation::SnapshotRequest,
message_id,
reason: format!(
"snapshot returned {} documents; limit is {}",
documents.len(),
self.options.max_snapshot_documents
),
reason: CultMeshRudpRejectionReason::SnapshotTooManyDocuments {
documents: documents.len(),
max_snapshot_documents: self.options.max_snapshot_documents,
},
}));
}
let response = CultNetMessage::SnapshotResponseRaw {
message_id: message_id.clone(),
documents,
};
let payload = match encode_cultnet_message_to_vec(
&response,
CultNetWireContract::CultNetSchemaV0,
) {
let payload = match encode_snapshot_response(&response) {
Ok(payload) => payload,
Err(error) => {
return Ok(Some(CultMeshRudpApplicationRejection {
session: key,
operation: CultMeshRudpApplicationOperation::SnapshotRequest,
message_id,
reason: format!("snapshot response could not be encoded: {error:#}"),
reason: CultMeshRudpRejectionReason::ResponseEncodingFailed(error),
}));
}
};
@ -594,11 +795,10 @@ where
session: key,
operation: CultMeshRudpApplicationOperation::SnapshotRequest,
message_id,
reason: format!(
"snapshot response is {} bytes; limit is {}",
payload.len(),
self.options.max_snapshot_response_bytes
),
reason: CultMeshRudpRejectionReason::SnapshotResponseTooLarge {
response_bytes: payload.len(),
max_snapshot_response_bytes: self.options.max_snapshot_response_bytes,
},
}));
}
if !self.payload_budget_allows(key, payload.len()) {
@ -606,7 +806,7 @@ where
session: key,
operation: CultMeshRudpApplicationOperation::SnapshotRequest,
message_id,
reason: "retained payload budget is full".into(),
reason: CultMeshRudpRejectionReason::PayloadBudgetFull,
}));
}
let payload_bytes = payload.len();
@ -632,7 +832,9 @@ where
session: key,
operation: CultMeshRudpApplicationOperation::SnapshotRequest,
message_id,
reason: format!("snapshot response could not be queued: {error:#}"),
reason: CultMeshRudpRejectionReason::ResponseQueueFailed(format!(
"{error:#}"
)),
}));
}
};
@ -640,11 +842,13 @@ where
entry.admitted_payload_bytes.saturating_add(payload_bytes);
for packet in &packets {
if let Some(error) = self.send_packet(key.remote_addr, packet)? {
let code = send_error_code(&error);
self.end_session(key, SessionEnd::Unsendable(error))?;
return Ok(Some(CultMeshRudpApplicationRejection {
session: key,
operation: CultMeshRudpApplicationOperation::SnapshotRequest,
message_id,
reason: format!("snapshot response could not be sent: {error}"),
reason: CultMeshRudpRejectionReason::ResponseSendFailed(code),
}));
}
}
@ -654,30 +858,84 @@ where
Ok(None)
}
/// The session refused a packet: it ends, and the client is told so it does
/// not wait on a session the server no longer holds.
fn end_refused_session(&mut self, key: CultMeshRudpSessionKey) -> Result<()> {
/// Ends a session before its peer is done with it, and says goodbye. It is
/// the one way a session ends early: every end removes the session, sends
/// what the peer is owed, then the goodbye.
///
/// A rejected message's refusal goes first, unreliable and unordered: the
/// session ends with it, so it is never resent, and a gap in what the peer
/// has received must not hold it back. It is built before the reset and
/// carries acknowledgement fields built after it, which acknowledge
/// nothing: a publisher reads an acknowledgement as admission. A refusal
/// that can never be sent as built is not dropped: the goodbye names its
/// error instead. A refusal that cannot be encoded is not sent.
fn end_session(&mut self, key: CultMeshRudpSessionKey, end: SessionEnd) -> Result<()> {
let Some(mut entry) = self.sessions.remove(&key) else {
return Ok(());
};
let goodbye = entry.session.end_refused_session();
let (refusal, mut unsendable) = match end {
SessionEnd::Refused => (Vec::new(), None),
SessionEnd::Rejected(text) => (self.refusal_packets(&mut entry.session, text), None),
SessionEnd::Unsendable(error) => (Vec::new(), Some(error)),
};
entry.session.reset_peer_state();
let nothing = entry.session.create_ack();
for mut packet in refusal {
packet.ack = nothing.ack;
packet.ack_mask = nothing.ack_mask;
if let Some(error) = self.send_packet(key.remote_addr, &packet)? {
unsendable = Some(error);
break;
}
}
let goodbye = match &unsendable {
Some(error) => entry.session.end_unsendable_session(error),
None => entry.session.end_refused_session(),
};
// The goodbye is the session's last datagram. If it too can never be
// sent, nobody is left to tell.
self.send_packet(key.remote_addr, &goodbye)?;
Ok(())
}
/// The session owes its peer a packet that can never be sent as built. The
/// session ends, never the poll, and the goodbye names the error.
fn end_unsendable_session(
&mut self,
key: CultMeshRudpSessionKey,
error: &std::io::Error,
) -> Result<()> {
let Some(mut entry) = self.sessions.remove(&key) else {
return Ok(());
/// The refusal a rejected peer is sent, as unreliable, unordered packets.
fn refusal_packets(
&self,
session: &mut CultNetRudpSession,
text: &str,
) -> Vec<CultNetRudpPacket> {
let refusal = CultNetMessage::Error {
error: text.into(),
code: None,
details: None,
};
let goodbye = entry.session.end_unsendable_session(error);
self.send_packet(key.remote_addr, &goodbye)?;
Ok(())
encode_cultnet_message_to_vec(&refusal, CultNetWireContract::CultNetSchemaV0)
.and_then(|payload| {
session.send_many(
"schema",
payload,
CultNetRudpSendOptions {
reliable: false,
ordered: false,
sequenced: false,
now_ms: self.clock.now_monotonic_millis(),
reliable_expire_after_ms: None,
},
Some(self.options.max_fragment_bytes),
)
})
.unwrap_or_default()
}
/// The fragments `send_many` splits a response of `bytes` into.
fn fragments_for(&self, bytes: usize) -> usize {
bytes.div_ceil(self.options.max_fragment_bytes).max(1)
}
/// The most fragments one response can take: one message's fragment count,
/// and the reliable queue it must fit into whole.
fn max_fragments_per_response(&self) -> usize {
MAX_FRAGMENTS_PER_MESSAGE.min(self.options.max_pending_reliable_packets_per_session)
}
fn payload_budget_allows(&self, key: CultMeshRudpSessionKey, bytes: usize) -> bool {
@ -788,9 +1046,37 @@ fn validate_options(options: &CultMeshRudpDocumentServerOptions) -> Result<()> {
if options.max_fragment_bytes == 0 {
return Err(anyhow!("max_fragment_bytes must be greater than zero"));
}
// The limits must leave room for the smallest response the server sends, an
// empty snapshot: a server that could answer nothing is misconfigured.
let empty = encode_snapshot_response(&CultNetMessage::SnapshotResponseRaw {
message_id: SHORTEST_MESSAGE_ID.into(),
documents: Vec::new(),
})
.map_err(|error| anyhow!(error))?
.len();
if empty > options.max_snapshot_response_bytes {
return Err(anyhow!(
"max_snapshot_response_bytes cannot hold an empty snapshot response"
));
}
let max_fragments =
MAX_FRAGMENTS_PER_MESSAGE.min(options.max_pending_reliable_packets_per_session);
if empty.div_ceil(options.max_fragment_bytes) > max_fragments {
return Err(anyhow!(
"max_fragment_bytes and max_pending_reliable_packets_per_session cannot carry an empty snapshot response"
));
}
Ok(())
}
/// The one encoder for a snapshot response, shared by the snapshot path and by
/// put admission so the size a put is judged by is the size it would be served at.
fn encode_snapshot_response(response: &CultNetMessage) -> std::result::Result<Vec<u8>, String> {
encode_cultnet_message_to_vec(response, CultNetWireContract::CultNetSchemaV0)
.map_err(|error| format!("{error:#}"))
}
fn duration_millis(duration: Duration) -> u64 {
duration.as_millis().try_into().unwrap_or(u64::MAX)
}

View file

@ -265,7 +265,7 @@ fn a_permanent_failure_acknowledging_a_document_ends_the_session_after_the_docum
}
#[test]
fn a_permanent_failure_sending_a_snapshot_response_rejects_it_naming_the_error() {
fn a_permanent_failure_sending_a_snapshot_response_rejects_it_and_sends_no_refusal() {
let (mut server, _clock, _received, (mut x, x_addr), (_y, _)) = two_peers();
server.unsendable_after.insert(x_addr, 0);
send(&mut x, &snapshot("x-snapshot"));
@ -280,15 +280,34 @@ fn a_permanent_failure_sending_a_snapshot_response_rejects_it_naming_the_error()
let rejection = rejection.expect("the response can never be sent");
assert_eq!(rejection.operation, CultMeshRudpApplicationOperation::SnapshotRequest);
assert_eq!(rejection.message_id, "x-snapshot");
assert!(
rejection
.reason
.starts_with("snapshot response could not be sent: ")
&& rejection.reason.len() > "snapshot response could not be sent: ".len(),
"{}",
rejection.reason
assert_eq!(
rejection.reason,
CultMeshRudpRejectionReason::ResponseSendFailed("EINVAL")
);
assert_eq!(server.session_count(), 1);
// The server knows X cannot be reached: X is sent no refusal, only the
// goodbye naming the error, which carries no text of the peer's.
let mut frames = Vec::new();
let mut reason = None;
for _ in 0..50 {
if let Some(frame) = x.receive_once().unwrap() {
frames.push(frame);
}
if let Some(found) = x.disconnect_reason() {
reason = Some(found.to_vec());
break;
}
thread::sleep(Duration::from_millis(2));
}
assert!(
frames.is_empty(),
"no refusal is sent to an unreachable peer: {frames:?}"
);
// The goodbye names the failure by its fixed name, never the error's text.
assert_eq!(
reason.expect("the client was told the session ended"),
b"packet could not be sent: EINVAL"
);
}
#[test]
@ -444,3 +463,40 @@ fn a_reset_reported_by_a_receive_is_idle_not_an_error() {
}
assert_eq!(received.lock().unwrap().as_slice(), ["y-put"]);
}
#[test]
fn a_refusal_that_can_never_be_sent_ends_the_session_naming_the_error() {
let (mut server, _clock, received, (mut x, x_addr), (mut y, _)) = two_peers();
// Any document is now unservable, so X's put is refused; the refusal is
// the first datagram X is owed, and it can never be sent as built.
server.options.max_snapshot_response_bytes = 16;
server.unsendable_after.insert(x_addr, 0);
send(&mut x, &put("x-put"));
let mut rejected = false;
for _ in 0..10 {
rejected |= matches!(
server.poll_once().unwrap(),
CultMeshRudpPollOutcome::ApplicationRejected(_)
);
}
assert!(rejected);
assert!(received.lock().unwrap().is_empty());
assert_eq!(server.session_count(), 1);
// The failure is not dropped: the goodbye names it, where a refusal's
// goodbye would say the session refused a packet.
assert!(is_unsendable_reason(&goodbye_reason(&mut x)));
assert_eq!(server.send_failures(), 0);
server.options.max_snapshot_response_bytes =
CultMeshRudpDocumentServerOptions::default().max_snapshot_response_bytes;
send(&mut y, &snapshot("y-snapshot"));
let mut served = false;
for _ in 0..50 {
server.poll_once().unwrap();
if y.receive_once().unwrap().is_some() {
served = true;
break;
}
thread::sleep(Duration::from_millis(1));
}
assert!(served, "the other peer is still served");
}

File diff suppressed because it is too large Load diff

View file

@ -4284,6 +4284,30 @@ export interface CultMeshRudpDocumentReceipt<TDefinition extends AnyCultCacheDoc
tags?: string[];
}
/**
* Options for `CultMesh.createRudpDocumentServer`.
*
* The server fragments its replies by `maxFragmentBytes` (default
* `CULTMESH_RUDP_DOCUMENT_SERVER_DEFAULT_MAX_FRAGMENT_BYTES`) and sends no
* reply larger than `maxPayloadBytes`. A put is judged by what serving it
* would send, not by the size of its own frame: a put whose snapshot reply
* could never be sent within those limits, 65535 fragments and
* `maxPendingReliablePackets`, is refused before `onDocumentPutRaw` sees it:
* `onError` receives a `CultMeshRudpUnservableDocumentError` and the peer a
* `cultnet.error.v0`.
*
* The snapshot reply is sized from the record `documents` would store for the
* put, serving it alone. The judgement is exact only for an application whose
* `onDocumentPutRaw` stores the put through that registry
* (`applyRawDocumentPutMessage`) and whose `getCache` serves that store; a
* handler that stores another record is judged by the registry's record, not
* its own. A receipt is not part of the judgement: whether one is sent is the
* handler's to decide after it stores the put.
*
* A reply that cannot be sent all the same, such as a receipt larger than
* `maxPayloadBytes`, reaches `onError`, and the peer receives a
* `cultnet.error.v0` in its place.
*/
export interface CultMeshRudpDocumentServerOptions extends CultMeshRudpSocketOptions {
documents: CultNetDocumentRegistry;
getCache?: () => Promise<CultCache> | CultCache;
@ -4301,6 +4325,39 @@ export interface CultMeshRudpDocumentServerOptions extends CultMeshRudpSocketOpt
sessionTimeoutMs?: number;
}
/** Replies larger than one fragment are split into fragments of at most this many bytes. */
export const CULTMESH_RUDP_DOCUMENT_SERVER_DEFAULT_MAX_FRAGMENT_BYTES = 1200;
const RUDP_MAX_FRAGMENTS_PER_MESSAGE = 0xffff;
/** CultNet parses no message id shorter than one character, so no reply is smaller. */
const SHORTEST_MESSAGE_ID = "0";
/**
* A put the document server refused because it could never serve the document:
* the snapshot reply carrying it alone (`responseBytes`) would exceed the
* server's reply limits.
*/
export class CultMeshRudpUnservableDocumentError extends Error {
constructor(
readonly messageId: string,
readonly recordKey: string,
readonly responseBytes: number,
readonly maxPayloadBytes: number | undefined,
readonly fragmentCount: number,
readonly maxFragmentCount: number,
) {
// The sentence names sizes only: it is sent to the peer, and a record key of
// any length would make the refusal itself too large to send.
super(
`Document can never be served: its reply is ${responseBytes} bytes in `
+ `${fragmentCount} fragments; limits are ${maxPayloadBytes ?? "unbounded"} bytes and `
+ `${maxFragmentCount} fragments.`,
);
this.name = "CultMeshRudpUnservableDocumentError";
}
}
export interface CultMeshRudpServerSession {
readonly sessionId: string;
readonly remote: { address: string; family: string; port: number };
@ -5792,6 +5849,17 @@ export class CultMesh {
const resendPollMs = Math.max(10, options.resendPollMs ?? 25);
const sessionTimeoutMs = Math.max(1_000, options.sessionTimeoutMs ?? 30_000);
const wireContract = options.wireContract ?? "cultnet.schema.v0";
const maxFragmentBytes = options.maxFragmentBytes ?? CULTMESH_RUDP_DOCUMENT_SERVER_DEFAULT_MAX_FRAGMENT_BYTES;
if (!(maxFragmentBytes > 0)) {
throw new Error("CultMesh RUDP document server maxFragmentBytes must be greater than zero.");
}
const maxPayloadBytes = options.maxPayloadBytes;
// The most fragments one reply can take: the wire's fragment count, and the
// reliable queue a reply must fit into whole.
const maxReplyFragments = Math.min(
RUDP_MAX_FRAGMENTS_PER_MESSAGE,
options.maxPendingReliablePackets ?? RUDP_MAX_FRAGMENTS_PER_MESSAGE,
);
let resendTimer: NodeJS.Timeout | undefined;
function reportError(error: unknown): void {
@ -5897,14 +5965,25 @@ export class CultMesh {
});
return;
}
let reply: CultNetMessage;
try {
const cache = await options.getCache();
sendSchemaMessage(record, options.documents.createRawSnapshotResponse(cache, message.messageId, message));
reply = options.documents.createRawSnapshotResponse(cache, message.messageId, message);
} catch (error) {
sendSchemaMessage(record, {
schemaVersion: "cultnet.error.v0",
error: error instanceof Error ? error.message : String(error),
});
reportError(error);
refuse(record, "the snapshot source failed");
return;
}
try {
sendSchemaMessage(record, reply);
} catch (error) {
reportError(error);
refuse(
record,
maxPayloadBytes !== undefined && encodeSchemaMessage(reply).byteLength > maxPayloadBytes
? "the snapshot response is too large"
: "the snapshot response could not be queued",
);
}
return;
}
@ -5913,17 +5992,24 @@ export class CultMesh {
return;
case "cultnet.document_put_raw.v0":
if (options.onDocumentPutRaw) {
const unservable = unservablePut(message);
if (unservable) {
reportError(unservable);
sendSchemaMessage(record, { schemaVersion: "cultnet.error.v0", error: unservable.message });
return;
}
const receipt = await options.onDocumentPutRaw(normalizeRudpDocumentPut(message, record.remote));
if (receipt) {
sendSchemaMessage(record, options.documents.createRawDocumentPutMessage(
receipt.binding, receipt.messageId ?? message.messageId, receipt.recordKey, receipt.value,
{
sourceRuntimeId: receipt.sourceRuntimeId ?? runtimeId,
sourceAgentId: receipt.sourceAgentId,
sourceRole: receipt.sourceRole ?? "provider",
tags: receipt.tags ?? ["receipt"],
},
));
try {
sendSchemaMessage(record, receiptMessage(receipt, message.messageId));
} catch (error) {
// The put is stored: the peer must hear that its receipt is not coming.
reportError(error);
sendSchemaMessage(record, {
schemaVersion: "cultnet.error.v0",
error: `CultMesh RUDP document server stored a put but could not send its receipt.`,
});
}
}
}
return;
@ -6012,16 +6098,96 @@ export class CultMesh {
message: CultNetMessage,
): void {
if (record.closed) throw new Error(`CultMesh RUDP session ${record.sessionId} is closed.`);
const payload = encode(encodeCultNetMessageForWire(message, wireContract));
const payload = encodeSchemaMessage(message);
if (maxPayloadBytes !== undefined && payload.byteLength > maxPayloadBytes) {
throw new Error(
`CultMesh RUDP reply ${message.schemaVersion} is ${payload.byteLength} bytes; `
+ `maxPayloadBytes is ${maxPayloadBytes}.`,
);
}
for (const packet of record.session.sendMany("schema", payload, {
reliable: true,
ordered: true,
nowMs: Date.now(),
maxFragmentBytes,
})) {
sendPacket(record, packet);
}
}
/**
* Answers a request the server cannot serve with fixed text, never an error's message,
* which can quote what a peer or the application supplied. The answer is unreliable and
* unordered, so it needs no room in a reliable queue that may just have refused the reply,
* and its acknowledgement fields acknowledge nothing, as every runtime's refusal does.
*/
function refuse(record: SessionRecord, text: string): void {
if (record.closed) return;
const payload = encodeSchemaMessage({ schemaVersion: "cultnet.error.v0", error: text });
for (const packet of record.session.sendMany("schema", payload, {
reliable: false,
ordered: false,
nowMs: Date.now(),
maxFragmentBytes,
})) {
sendPacket(record, { ...packet, ack: 0, ackMask: 0 });
}
}
/** The one reply encoder, shared by sends and by put admission. */
function encodeSchemaMessage(message: CultNetMessage): Uint8Array {
return encode(encodeCultNetMessageForWire(message, wireContract));
}
/** Builds the receipt `onDocumentPutRaw` returned, under the put's message id by default. */
function receiptMessage(receipt: CultMeshRudpDocumentReceipt, putMessageId: string): CultNetMessage {
return options.documents.createRawDocumentPutMessage(
receipt.binding, receipt.messageId ?? putMessageId, receipt.recordKey, receipt.value,
{
sourceRuntimeId: receipt.sourceRuntimeId ?? runtimeId,
sourceAgentId: receipt.sourceAgentId,
sourceRole: receipt.sourceRole ?? "provider",
tags: receipt.tags ?? ["receipt"],
},
);
}
/**
* Refuse a put whose document could never be served: the snapshot reply
* carrying it alone, under the shortest message id CultNet parses, sized as
* `sendSchemaMessage` would send it. It is built from the record the
* registry would store, which is exact only when the application stores
* through the registry; a document the registry has no binding for is
* sized as received.
*/
function unservablePut(message: CultNetMessage): CultMeshRudpUnservableDocumentError | undefined {
if (message.schemaVersion !== "cultnet.document_put_raw.v0") return undefined;
let reply: CultNetMessage;
try {
reply = options.documents.createRawSnapshotResponseForPut(message, SHORTEST_MESSAGE_ID);
} catch {
reply = {
schemaVersion: "cultnet.snapshot_response_raw.v0",
messageId: SHORTEST_MESSAGE_ID,
documents: [message.document],
};
}
const responseBytes = encodeSchemaMessage(reply).byteLength;
const fragmentCount = Math.max(1, Math.ceil(responseBytes / maxFragmentBytes));
if ((maxPayloadBytes === undefined || responseBytes <= maxPayloadBytes)
&& fragmentCount <= maxReplyFragments) {
return undefined;
}
return new CultMeshRudpUnservableDocumentError(
message.messageId,
message.document.recordKey,
responseBytes,
maxPayloadBytes,
fragmentCount,
maxReplyFragments,
);
}
return {
bind,
get sendFailures() {

View file

@ -1,18 +1,26 @@
import { createSocket } from "node:dgram";
import { mkdtemp } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
import assert from "node:assert/strict";
import { encode } from "@msgpack/msgpack";
import { decode, encode } from "@msgpack/msgpack";
import { z } from "zod";
import { defineDocumentType } from "@gamecult/cultcache-ts";
import {
CultNetDocumentRegistry,
CultNetPeer,
CultNetRudpSession,
cultNetBuiltinSchemaRegistry,
decodeRudpPacket,
defineCultNetDocumentBinding,
encodeRudpPacket,
type CultNetDocumentPutRawMessage,
type CultNetRudpPacket,
type CultNetMessage,
type CultNetSnapshotResponseRawMessage,
} from "cultnet-ts";
import { CultMesh } from "../src/index";
import { CultMesh, CultMeshRudpUnservableDocumentError } from "../src/index";
const noteDocument = defineDocumentType({
type: "cultmesh.note",
@ -3261,6 +3269,493 @@ test("CultMesh TS negotiates streaming frame body transports explicitly", () =>
assert.deepEqual(frameUpdates, [42n]);
});
// A put the RUDP document server admits must be one it can serve. The server
// fragments its replies as its puts are reassembled, and refuses a put whose
// snapshot reply, carrying the document alone under the shortest message id,
// could never be sent within its limits.
type ServedBoundRig = {
server: ReturnType<typeof CultMesh.createRudpDocumentServer>;
peer: CultNetPeer;
admitted: string[];
errors: Error[];
messages: CultNetMessage[];
/** Why each frame the peer could not parse was refused. */
unparsed: Error[];
};
const servedBoundRegistry = () =>
new CultNetDocumentRegistry([defineCultNetDocumentBinding({ definition: noteDocument })]);
/**
* A put's own storedAt, kept by the served record and replaced in the receipt by the server's
* 24-character clock. `SERVED_STORED_AT` is long, so an echoed receipt is smaller than the served
* reply; `RECEIPT_STORED_AT` is short, so an echoed receipt is the larger reply, which shows that
* admission sizes only the served reply.
*/
const SERVED_STORED_AT = `2026-09-30T00:00:00.000Z${"~".repeat(200)}`;
const RECEIPT_STORED_AT = "2026-09-30T00:00:00.000Z";
const SERVED_BOUND_SERVER = "cultmesh-ts-served-bound-server";
function notePut(
messageId: string,
recordKey: string,
bodyLength: number,
sourceRuntimeId?: string,
storedAt = SERVED_STORED_AT,
): CultNetDocumentPutRawMessage {
return {
schemaVersion: "cultnet.document_put_raw.v0",
messageId,
document: {
schemaId: "cultmesh.note.v0",
recordKey,
storedAt,
payloadEncoding: "messagepack",
payload: encode({ noteId: recordKey, body: "x".repeat(bodyLength) }),
...(sourceRuntimeId ? { sourceRuntimeId } : {}),
},
};
}
/**
* The encoded size of the reply that would serve this put's document alone,
* under the shortest message id: the record as a snapshot serves it, which
* keeps no source fields.
*/
function servedAloneBytes(put: CultNetDocumentPutRawMessage): number {
const { schemaId, recordKey, storedAt, payloadEncoding, payload } = put.document;
return encode({
schemaVersion: "cultnet.snapshot_response_raw.v0",
messageId: "0",
documents: [{ schemaId, recordKey, storedAt, payloadEncoding, payload }],
}).byteLength;
}
/**
* The encoded size of the receipt that would acknowledge this put by echoing its value: the
* put's message id, the server's clock and its default provenance. Spelled out here rather than
* asked of the server, so a server that sized another receipt is caught.
*/
function echoReceiptBytes(put: CultNetDocumentPutRawMessage): number {
return encode({
schemaVersion: "cultnet.document_put_raw.v0",
messageId: put.messageId,
document: {
schemaId: "cultmesh.note.v0",
recordKey: put.document.recordKey,
storedAt: new Date().toISOString(),
payloadEncoding: "messagepack",
payload: encode(decode(put.document.payload)),
sourceRuntimeId: SERVED_BOUND_SERVER,
sourceAgentId: undefined,
sourceRole: "provider",
tags: ["receipt"],
},
}).byteLength;
}
/** The body length whose served-alone reply is exactly `bytes`. */
function bodyLengthForReplyBytes(recordKey: string, bytes: number): number {
const probe = 8_000;
const length = probe + bytes - servedAloneBytes(notePut("p", recordKey, probe));
const put = notePut("p", recordKey, length);
assert.equal(servedAloneBytes(put), bytes, "fixture: reply size is linear in the body");
return length;
}
async function withServedBoundRig(
connectionId: number,
serverLimits: { maxFragmentBytes?: number; maxPendingReliablePackets?: number; maxPayloadBytes?: number },
body: (rig: ServedBoundRig) => Promise<void>,
handler: { receipt?: "echo" | "oversized" } = {},
): Promise<void> {
const node = await CultMesh.startNode(
join(await mkdtemp(join(tmpdir(), "cultmesh-ts-served-bound-")), "node.ccmp"),
{ documents: [noteDocument] },
);
const registry = servedBoundRegistry();
const admitted: string[] = [];
const errors: Error[] = [];
const messages: CultNetMessage[] = [];
const unparsed: Error[] = [];
const server = CultMesh.createRudpDocumentServer(SERVED_BOUND_SERVER, connectionId, {
documents: registry,
getCache: () => node.cache,
bindHost: "127.0.0.1",
bindPort: 0,
resendDelayMs: 25,
resendPollMs: 5,
...serverLimits,
// Stored as the registry stores a raw put, so the served record is the one it sizes.
onDocumentPutRaw: async (document) => {
admitted.push(document.recordKey);
await registry.applyRawDocumentPutMessage(node.cache, {
schemaVersion: "cultnet.document_put_raw.v0",
messageId: `store:${document.recordKey}`,
document: {
schemaId: document.schemaId,
recordKey: document.recordKey,
storedAt: document.storedAt,
payloadEncoding: "messagepack",
payload: encode(document.payload),
},
});
if (!handler.receipt) return undefined;
// An echo acknowledges the stored value; an oversized receipt carries a tag larger than
// maxPayloadBytes. Admission sizes neither: receipts are the handler's choice.
return {
binding: defineCultNetDocumentBinding({ definition: noteDocument }),
recordKey: document.recordKey,
value: document.payload as { noteId: string; body: string },
...(handler.receipt === "oversized" ? { tags: ["x".repeat(8_000)] } : {}),
};
},
onError: (error) => errors.push(error),
});
let peer: CultNetPeer | undefined;
try {
await server.start();
peer = await CultMesh.createRudpPeer(
"cultmesh-ts-served-bound-client",
connectionId,
`rudp://127.0.0.1:${server.bind.port}`,
{ resendDelayMs: 25, resendPollMs: 5, maxFragmentBytes: 1024, maxPendingReliablePackets: 512, connectTimeoutMs: 1_000 },
);
peer.on("message", (message: CultNetMessage) => messages.push(message));
peer.on("invalidMessage", (error: Error) => unparsed.push(error));
await body({ server, peer, admitted, errors, messages, unparsed });
} finally {
peer?.close();
server.close();
}
}
/** Requests `recordKey` under the shortest message id and waits for the reply. */
async function snapshotUnderShortestId(rig: ServedBoundRig, recordKey: string): Promise<CultNetMessage> {
const before = rig.messages.length;
rig.peer.sendSnapshotRequest({ schemaVersion: "cultnet.snapshot_request.v0", messageId: "0", recordKeys: [recordKey] });
const startedAt = Date.now();
while (Date.now() - startedAt < 3_000) {
const reply = rig.messages.slice(before).find((message) =>
message.schemaVersion === "cultnet.snapshot_response_raw.v0" && message.messageId === "0");
if (reply) return reply;
await delay(5);
}
throw new Error(`Timed out waiting for the snapshot of ${recordKey}; server errors: ${rig.errors.map(e => e.message).join("; ")}`);
}
function servedBodies(reply: CultNetMessage): Array<[string, number]> {
assert.equal(reply.schemaVersion, "cultnet.snapshot_response_raw.v0");
return (reply as CultNetSnapshotResponseRawMessage).documents.map((document) => [
document.recordKey,
(decode(document.payload) as { body: string }).body.length,
]);
}
async function waitForAdmission(rig: ServedBoundRig, recordKey: string): Promise<void> {
const startedAt = Date.now();
while (!rig.admitted.includes(recordKey) && Date.now() - startedAt < 3_000) await delay(5);
assert.ok(rig.admitted.includes(recordKey), `${recordKey} was not admitted; server errors: ${rig.errors.map(e => e.message).join("; ")}`);
}
async function waitForError(rig: ServedBoundRig, description: string): Promise<Error> {
const startedAt = Date.now();
while (rig.errors.length === 0 && Date.now() - startedAt < 3_000) await delay(5);
assert.ok(rig.errors.length > 0, `no server error for ${description}`);
return rig.errors[0]!;
}
test("CultMesh TS RUDP document server serves an 80 KB note put in 1 KiB fragments", async () => {
await withServedBoundRig(0x10203060, { maxFragmentBytes: 1024, maxPendingReliablePackets: 512 }, async (rig) => {
rig.peer.send(notePut("put-large", "note:large", 80_000));
await waitForAdmission(rig, "note:large");
assert.deepEqual(servedBodies(await snapshotUnderShortestId(rig, "note:large")), [["note:large", 80_000]]);
assert.deepEqual(rig.errors, []);
});
});
test("CultMesh TS RUDP document server refuses a put whose reply would overflow its reliable queue", async () => {
// Eight 1 KiB fragments fit the queue, nine do not.
const atBound = bodyLengthForReplyBytes("note:at", 8 * 1024);
const overBound = bodyLengthForReplyBytes("note:ov", 8 * 1024 + 1);
await withServedBoundRig(0x10203061, { maxFragmentBytes: 1024, maxPendingReliablePackets: 8 }, async (rig) => {
// The puts carry a source the registry does not store, so only the served record is the right size.
rig.peer.send(notePut("put-over", "note:ov", overBound, "cultmesh-ts-served-bound-client"));
const refusal = await waitForError(rig, "the over-bound put");
assert.ok(refusal instanceof CultMeshRudpUnservableDocumentError, refusal.message);
assert.equal(refusal.messageId, "put-over");
assert.equal(refusal.recordKey, "note:ov");
assert.equal(refusal.responseBytes, 8 * 1024 + 1);
assert.equal(refusal.fragmentCount, 9);
assert.equal(refusal.maxFragmentCount, 8);
assert.equal(refusal.maxPayloadBytes, undefined);
assert.match(refusal.message, /8193 bytes in 9 fragments/);
assert.deepEqual(rig.admitted, []);
rig.peer.send(notePut("put-at", "note:at", atBound, "cultmesh-ts-served-bound-client"));
await waitForAdmission(rig, "note:at");
assert.deepEqual(servedBodies(await snapshotUnderShortestId(rig, "note:at")), [["note:at", atBound]]);
assert.equal(rig.errors.length, 1);
});
});
test("CultMesh TS RUDP document server answers a snapshot its reliable queue cannot take", async () => {
// Two documents each served in exactly the eight fragments the queue holds are admitted; a
// snapshot of both needs sixteen and cannot be queued. The peer is answered with a
// cultnet.error.v0, not left to time out, and onError hears why.
const atBound = bodyLengthForReplyBytes("note:q1", 8 * 1024);
await withServedBoundRig(0x10203068, { maxFragmentBytes: 1024, maxPendingReliablePackets: 8 }, async (rig) => {
rig.peer.send(notePut("put-q1", "note:q1", atBound));
rig.peer.send(notePut("put-q2", "note:q2", atBound));
await waitForAdmission(rig, "note:q1");
await waitForAdmission(rig, "note:q2");
assert.deepEqual(rig.errors, []);
rig.peer.sendSnapshotRequest({ schemaVersion: "cultnet.snapshot_request.v0", messageId: "both", recordKeys: ["note:q1", "note:q2"] });
await waitForPeerErrors(rig, 1);
assert.equal(rig.errors.length, 1);
assert.ok(!rig.messages.some((message) => message.schemaVersion === "cultnet.snapshot_response_raw.v0"));
});
});
/**
* A document server over a node that already holds `stored`, and a peer driven packet by packet
* that acknowledges nothing, so a test fills the server's reliable queue at will.
*/
async function withRawPeerRig(
connectionId: number,
serverLimits: { maxFragmentBytes?: number; maxPendingReliablePackets?: number },
stored: CultNetDocumentPutRawMessage[],
getCache: ((cache: unknown) => unknown) | undefined,
body: (rig: {
errors: Error[];
inbox: CultNetRudpPacket[];
request: (messageId: string, recordKeys: string[]) => number[];
}) => Promise<void>,
): Promise<void> {
const node = await CultMesh.startNode(
join(await mkdtemp(join(tmpdir(), "cultmesh-ts-raw-peer-")), "node.ccmp"),
{ documents: [noteDocument] },
);
const registry = servedBoundRegistry();
for (const put of stored) await registry.applyRawDocumentPutMessage(node.cache, put);
const errors: Error[] = [];
const server = CultMesh.createRudpDocumentServer(SERVED_BOUND_SERVER, connectionId, {
documents: registry,
getCache: () => (getCache ? getCache(node.cache) : node.cache) as typeof node.cache,
bindHost: "127.0.0.1",
bindPort: 0,
resendDelayMs: 100_000,
resendPollMs: 5,
...serverLimits,
onError: (error) => errors.push(error),
});
await server.start();
const socket = createSocket("udp4");
try {
await new Promise<void>((resolve) => socket.bind(0, "127.0.0.1", () => resolve()));
const inbox: CultNetRudpPacket[] = [];
socket.on("message", (wire) => inbox.push(decodeRudpPacket(wire)));
const session = new CultNetRudpSession({ connectionId, initialSequence: 100, resendDelayMs: 100_000, maxPendingReliablePackets: 64 });
const send = (packet: CultNetRudpPacket) => socket.send(encodeRudpPacket(packet), server.bind.port, "127.0.0.1");
send(session.createConnect(0));
const startedAt = Date.now();
while (!inbox.some((packet) => packet.packetType === "accept") && Date.now() - startedAt < 2_000) await delay(5);
const accept = inbox.find((packet) => packet.packetType === "accept");
assert.ok(accept, "the server accepts the connect");
session.receive(accept, 1);
inbox.length = 0;
const request = (messageId: string, recordKeys: string[]): number[] => {
const packets = session.sendMany(
"schema",
encode({ schemaVersion: "cultnet.snapshot_request.v0", messageId, recordKeys }),
{ reliable: true, ordered: true, nowMs: 2, maxFragmentBytes: 1200 },
);
packets.forEach(send);
return packets.map((packet) => packet.sequence);
};
await body({ errors, inbox, request });
} finally {
socket.close();
server.close();
}
}
/** The refusal among `packets`: its unreliable fragments, reassembled, and the fragments. */
function refusalIn(packets: CultNetRudpPacket[]): { message: Record<string, unknown>; parts: CultNetRudpPacket[] } | undefined {
const parts = packets
.filter((packet) => packet.packetType === "data" && packet.channelId === "schema" && !packet.reliable)
.sort((a, b) => (a.fragmentIndex ?? 0) - (b.fragmentIndex ?? 0));
if (parts.length === 0) return undefined;
const message = decode(Buffer.concat(parts.map((part) => Buffer.from(part.payload ?? new Uint8Array())))) as Record<string, unknown>;
return { message, parts };
}
function acknowledges(packet: CultNetRudpPacket, sequence: number): boolean {
if (packet.ack === sequence) return true;
for (let bit = 0; bit < 32; bit += 1) {
if ((packet.ackMask & (1 << bit)) !== 0 && packet.ack - bit - 1 === sequence) return true;
}
return false;
}
test("CultMesh TS RUDP document server answers a peer whose reliable queue is full to the brim", async () => {
// An 8-fragment reply the peer never acknowledges fills a queue of 8 exactly. The next reply
// cannot be queued; the peer is still answered, with fixed text that takes no room in that
// queue and acknowledges nothing the peer sent.
const body = bodyLengthForReplyBytes("q1", 800);
await withRawPeerRig(0x10203069, { maxFragmentBytes: 100, maxPendingReliablePackets: 8 }, [notePut("s", "q1", body)], undefined, async (rig) => {
rig.request("0", ["q1"]);
await delay(300);
const first = new Set(rig.inbox.filter((packet) => packet.packetType === "data" && packet.reliable).map((packet) => packet.sequence));
assert.equal(first.size, 8, "fixture: the first reply fills the queue exactly");
rig.inbox.length = 0;
const refused = rig.request("b", ["none"]);
const startedAt = Date.now();
while (!refusalIn(rig.inbox) && Date.now() - startedAt < 3_000) await delay(5);
const refusal = refusalIn(rig.inbox);
assert.ok(refusal, "the refusal reaches the peer");
assert.deepEqual(refusal.message, { schemaVersion: "cultnet.error.v0", error: "the snapshot response could not be queued" });
for (const part of refusal.parts) {
assert.ok(refused.every((sequence) => !acknowledges(part, sequence)), `ack ${part.ack} mask ${part.ackMask}`);
}
assert.equal(rig.errors.length, 1);
});
});
test("CultMesh TS RUDP document server refuses a snapshot with fixed text, never an error's message", async () => {
// The cache the snapshot needs fails with a message a peer must not see: the peer is told
// only that the snapshot source failed; onError keeps the detail.
await withRawPeerRig(0x1020306a, {}, [], () => { throw new Error("no such tenant CANARY-7f3a"); }, async (rig) => {
rig.request("0", ["q1"]);
const startedAt = Date.now();
while (!refusalIn(rig.inbox) && Date.now() - startedAt < 3_000) await delay(5);
const refusal = refusalIn(rig.inbox);
assert.ok(refusal, "the refusal reaches the peer");
assert.deepEqual(refusal.message, { schemaVersion: "cultnet.error.v0", error: "the snapshot source failed" });
assert.match(rig.errors[0]?.message ?? "", /CANARY-7f3a/);
});
});
test("CultMesh TS RUDP document server honours maxPayloadBytes for replies and judges puts by what it would serve", async () => {
const limit = 4_000;
const atBound = bodyLengthForReplyBytes("note:at", limit);
const overBound = bodyLengthForReplyBytes("note:ov", limit + 1);
await withServedBoundRig(0x10203062, { maxFragmentBytes: 1024, maxPayloadBytes: limit }, async (rig) => {
rig.peer.send(notePut("put-over", "note:ov", overBound));
const refusal = await waitForError(rig, "the over-bound put");
assert.ok(refusal instanceof CultMeshRudpUnservableDocumentError, refusal.message);
assert.equal(refusal.responseBytes, limit + 1);
assert.equal(refusal.maxPayloadBytes, limit);
assert.equal(refusal.fragmentCount, 4);
assert.deepEqual(rig.admitted, []);
// The peer is sent the refusal, and it names sizes, never the record.
await waitForPeerErrors(rig, 1);
assert.ok(!refusal.message.includes("note:ov"), refusal.message);
// A put whose own frame is over the limit only by the provenance it carries is served at the
// bound, so it is admitted and served.
const carried = notePut("put-at", "note:at", atBound, `runtime-${"r".repeat(200)}`);
assert.ok(encode(carried).byteLength > limit, "fixture: the put's frame is over the limit");
rig.peer.send(carried);
await waitForAdmission(rig, "note:at");
assert.deepEqual(servedBodies(await snapshotUnderShortestId(rig, "note:at")), [["note:at", atBound]]);
assert.equal(rig.errors.length, 1);
// A record key longer than the limit: the refusal is still small enough to reach the peer.
const longKey = `note:${"k".repeat(2 * limit)}`;
rig.peer.send(notePut("put-long-key", longKey, 10));
await waitForPeerErrors(rig, 2);
assert.ok(rig.errors[1] instanceof CultMeshRudpUnservableDocumentError, rig.errors[1]!.message);
assert.equal(rig.errors.length, 2, "the refusal itself was sent");
assert.deepEqual(rig.admitted, ["note:at"]);
// Two servable documents make a reply over the limit: it is not sent, and onError hears why.
rig.peer.send(notePut("put-a2", "note:a2", atBound));
await waitForAdmission(rig, "note:a2");
rig.peer.sendSnapshotRequest({ schemaVersion: "cultnet.snapshot_request.v0", messageId: "0", recordKeys: ["note:at", "note:a2"] });
const replyStartedAt = Date.now();
while (rig.errors.length < 3 && Date.now() - replyStartedAt < 3_000) await delay(5);
assert.equal(rig.errors.length, 3);
assert.match(rig.errors[2]!.message, /reply cultnet\.snapshot_response_raw\.v0 is \d+ bytes; maxPayloadBytes is 4000/);
});
});
test("CultMesh TS RUDP document server admits a put served at the bound, whatever receipt its handler returns", async () => {
// These puts keep a short storedAt, so the receipt echoing one is larger than its served reply,
// and over the limit. Admission sizes only the served reply: exactly at the limit is admitted
// with or without a receipt, one byte over is refused. An echoed receipt that cannot be sent
// goes the way of any unsendable receipt: the put is stored and the peer is told.
const limit = 4_000;
const put = (messageId: string, recordKey: string, body: number) =>
notePut(messageId, recordKey, body, undefined, RECEIPT_STORED_AT);
const bodyServedAt = (messageId: string, recordKey: string, bytes: number): number => {
const probe = 2_000;
const length = probe + bytes - servedAloneBytes(put(messageId, recordKey, probe));
assert.equal(servedAloneBytes(put(messageId, recordKey, length)), bytes, "fixture: reply size is linear in the body");
assert.ok(echoReceiptBytes(put(messageId, recordKey, length)) > limit, "fixture: the echoed receipt is over the limit");
return length;
};
const atBound = bodyServedAt("put-at", "note:at", limit);
const overBound = bodyServedAt("put-ov", "note:ov", limit + 1);
for (const [connectionId, receipt] of [[0x10203066, undefined], [0x10203067, "echo"]] as const) {
await withServedBoundRig(connectionId, { maxFragmentBytes: 1024, maxPayloadBytes: limit }, async (rig) => {
rig.peer.send(put("put-at", "note:at", atBound));
await waitForAdmission(rig, "note:at");
if (receipt === "echo") {
const failure = await waitForError(rig, "the echoed receipt");
assert.match(failure.message, /reply cultnet\.document_put_raw\.v0 is \d+ bytes; maxPayloadBytes is 4000/);
await waitForPeerErrors(rig, 1);
assert.ok(!rig.messages.some(isDocumentPut));
}
assert.deepEqual(servedBodies(await snapshotUnderShortestId(rig, "note:at")), [["note:at", atBound]]);
const errorsBefore = rig.errors.length;
assert.equal(errorsBefore, receipt === "echo" ? 1 : 0, rig.errors.map((error) => error.message).join("; "));
rig.peer.send(put("put-ov", "note:ov", overBound));
const startedAt = Date.now();
while (rig.errors.length === errorsBefore && Date.now() - startedAt < 3_000) await delay(5);
const refusal = rig.errors[errorsBefore];
assert.ok(refusal instanceof CultMeshRudpUnservableDocumentError, refusal?.message);
assert.equal(refusal.responseBytes, limit + 1);
assert.deepEqual(rig.admitted, ["note:at"]);
}, receipt ? { receipt } : {});
}
});
test("CultMesh TS RUDP document server tells the peer when a stored put's receipt cannot be sent", async () => {
// A handler whose receipt is larger than maxPayloadBytes: admission does not size receipts, so
// the put is stored, the receipt cannot be sent, and the peer hears that it is not coming.
const limit = 4_000;
const small = bodyLengthForReplyBytes("note:small", 1_000);
await withServedBoundRig(0x10203064, { maxFragmentBytes: 1024, maxPayloadBytes: limit }, async (rig) => {
rig.peer.send(notePut("put-small", "note:small", small));
await waitForAdmission(rig, "note:small");
await waitForPeerErrors(rig, 1);
assert.equal(rig.errors.length, 1);
assert.match(rig.errors[0]!.message, /reply cultnet\.document_put_raw\.v0 is \d+ bytes; maxPayloadBytes is 4000/);
assert.ok(!rig.messages.some(isDocumentPut));
assert.deepEqual(servedBodies(await snapshotUnderShortestId(rig, "note:small")), [["note:small", small]]);
}, { receipt: "oversized" });
});
function isDocumentPut(message: CultNetMessage): boolean {
return message.schemaVersion === "cultnet.document_put_raw.v0";
}
/**
* Waits until the peer has been sent `count` cultnet.error.v0 replies. A TypeScript peer cannot
* yet parse the two-key error this server sends (docs/cultnet-error-contract-cut.md:
* "TypeScript cannot parse the errors TypeScript sends"),
* so each arrives as an unparsed cultnet.error.v0 frame; its text is asserted through onError.
*/
async function waitForPeerErrors(rig: ServedBoundRig, count: number): Promise<void> {
const errors = () => rig.unparsed.filter((error) => /cultnet\.error\.v0/.test(error.message)).length
+ rig.messages.filter((message) => message.schemaVersion === "cultnet.error.v0").length;
const startedAt = Date.now();
while (errors() < count && Date.now() - startedAt < 3_000) await delay(5);
assert.equal(errors(), count, `peer errors: ${rig.unparsed.map((error) => error.message).join("; ")}`);
}
function delay(milliseconds: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, milliseconds));
}

View file

@ -124,6 +124,7 @@ from .transport import (
compute_reconnect_delay_ms,
create_reconnect_policy,
is_permanent_send_error,
send_error_code,
create_rudp_transport_profile,
create_tcp_framed_transport_profile,
decode_rudp_packet,
@ -211,6 +212,7 @@ __all__ = [
"CultNetRudpSendOptions",
"CultNetRudpSession",
"is_permanent_send_error",
"send_error_code",
"CultNetRudpSessionOptions",
"CultNetRudpSocketMode",
"CultNetRudpReconnectLoop",

View file

@ -438,18 +438,28 @@ def create_rudp_transport_profile(
UNSENDABLE_PACKET_REASON = "packet could not be sent"
_PERMANENT_SEND_ERRNOS = frozenset(
code
for code in (
errno.EMSGSIZE,
errno.EINVAL,
errno.EAFNOSUPPORT,
getattr(errno, "WSAEMSGSIZE", None),
getattr(errno, "WSAEINVAL", None),
getattr(errno, "WSAEAFNOSUPPORT", None),
# The fixed name of each permanent send failure, keyed by errno, Winsock equivalents included.
_PERMANENT_SEND_ERROR_CODES = {
code: name
for code, name in (
(errno.EMSGSIZE, "EMSGSIZE"),
(errno.EINVAL, "EINVAL"),
(errno.EAFNOSUPPORT, "EAFNOSUPPORT"),
(getattr(errno, "WSAEMSGSIZE", None), "EMSGSIZE"),
(getattr(errno, "WSAEINVAL", None), "EINVAL"),
(getattr(errno, "WSAEAFNOSUPPORT", None), "EAFNOSUPPORT"),
)
if code is not None
)
}
_UNKNOWN_SEND_ERROR = "UNKNOWN"
def send_error_code(error: OSError) -> str:
"""The fixed name of a failed send's cause: EMSGSIZE, EINVAL or EAFNOSUPPORT for a
failure that can never pass (`is_permanent_send_error`), UNKNOWN for anything else. An
unsendable session's goodbye carries this name, never the error's own text, which is the
platform's wording and can quote an address."""
return _PERMANENT_SEND_ERROR_CODES.get(error.errno, _UNKNOWN_SEND_ERROR)
def is_permanent_send_error(error: OSError) -> bool:
@ -459,7 +469,7 @@ def is_permanent_send_error(error: OSError) -> bool:
Winsock equivalents. Everything else (no route, full buffers, firewall drops, a refusal
reported for an earlier datagram, an interrupted call) is a property of the path or the
moment and may pass, so it is a lost datagram, not a reason to end a session."""
return error.errno in _PERMANENT_SEND_ERRNOS
return send_error_code(error) != _UNKNOWN_SEND_ERROR
class CultNetRudpSession:
@ -872,9 +882,10 @@ class CultNetRudpSession:
"""Ends a session that owes its peer a packet that can never be sent as built
(see `is_permanent_send_error`). Resending it would fail forever, and dropping it
would leave a reliable sequence the peer waits on for good, so the session cannot
be kept. Returns the goodbye for the peer; its reason names the error."""
be kept. Returns the goodbye for the peer; its reason names the failure by its fixed
name (`send_error_code`), never the error's text."""
self.reset_peer_state()
return self.create_disconnect(f"{UNSENDABLE_PACKET_REASON}: {error}".encode("utf-8"))
return self.create_disconnect(f"{UNSENDABLE_PACKET_REASON}: {send_error_code(error)}".encode("utf-8"))
def create_disconnect(self, reason: bytes = b"") -> CultNetRudpPacket:
self._end_session()

View file

@ -901,6 +901,18 @@ class CultNetTests(unittest.TestCase):
self.assertFalse(is_permanent_send_error(OSError(code, "transient")), errno.errorcode[code])
self.assertFalse(is_permanent_send_error(OSError("no errno")))
def test_cultnet_rudp_an_unsendable_goodbye_names_the_failure_by_a_fixed_code(self) -> None:
import errno
from cultnet_py import send_error_code
for code, name in ((errno.EMSGSIZE, "EMSGSIZE"), (errno.EINVAL, "EINVAL"), (errno.EAFNOSUPPORT, "EAFNOSUPPORT")):
self.assertEqual(send_error_code(OSError(code, "CANARY-7f3a")), name)
self.assertEqual(send_error_code(OSError(errno.ECONNREFUSED, "CANARY-7f3a")), "UNKNOWN")
session = CultNetRudpSession(CultNetRudpSessionOptions(connection_id=1))
goodbye = session.end_unsendable_session(OSError(errno.EMSGSIZE, "Message too long CANARY-7f3a"))
self.assertEqual(bytes(goodbye.payload), b"packet could not be sent: EMSGSIZE")
# The sender's flow window: a reliable packet goes on the wire only while its sequence is at most 1,023 above
# the lowest unacked one and the payload above that sequence stays within 4 MiB.
FLOW_CONNECTION_ID = 0x464C4F57

View file

@ -472,10 +472,16 @@ impl CultNetRudpSession {
/// built (see `is_permanent_send_error`). Resending it would fail forever,
/// and dropping it would leave a reliable sequence the peer waits on for
/// good, so the session cannot be kept. Returns the goodbye for the peer;
/// its reason names the error.
/// its reason names the failure by its fixed name (`send_error_code`).
pub fn end_unsendable_session(&mut self, error: &std::io::Error) -> CultNetRudpPacket {
self.reset_peer_state();
self.create_disconnect(format!("{RUDP_UNSENDABLE_PACKET_REASON}: {error}").into_bytes())
self.create_disconnect(
format!(
"{RUDP_UNSENDABLE_PACKET_REASON}: {}",
send_error_code(error)
)
.into_bytes(),
)
}
/// Undoes a send that never reached the wire: every packet it created at
@ -2599,7 +2605,7 @@ where
const RUDP_REFUSED_PACKET_REASON: &[u8] = b"session refused a packet";
const SESSION_TIMED_OUT_REASON: &[u8] = b"session timed out";
/// Prefix of the goodbye reason for a session that owed a packet which can
/// never be sent; the error's own description follows it.
/// never be sent; the failure's fixed name (`send_error_code`) follows it.
const RUDP_UNSENDABLE_PACKET_REASON: &str = "packet could not be sent";
/// Whether a failed `send_to` can never succeed for the datagram as built, so
@ -2610,37 +2616,59 @@ const RUDP_UNSENDABLE_PACKET_REASON: &str = "packet could not be sent";
/// call) is a property of the path or the moment and may pass, so it is a lost
/// datagram, not a reason to end a session.
pub fn is_permanent_send_error(error: &std::io::Error) -> bool {
// `EMSGSIZE` and `EAFNOSUPPORT`, or their Winsock equivalents.
#[cfg(any(target_os = "linux", target_os = "android"))]
const PERMANENT_OS_ERRORS: [i32; 2] = [90, 97];
#[cfg(any(
target_os = "macos",
target_os = "ios",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
target_os = "dragonfly"
))]
const PERMANENT_OS_ERRORS: [i32; 2] = [40, 47];
#[cfg(windows)]
const PERMANENT_OS_ERRORS: [i32; 2] = [10040, 10047];
#[cfg(not(any(
target_os = "linux",
target_os = "android",
target_os = "macos",
target_os = "ios",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
target_os = "dragonfly",
windows
)))]
const PERMANENT_OS_ERRORS: [i32; 0] = [];
send_error_code(error) != UNKNOWN_SEND_ERROR
}
const UNKNOWN_SEND_ERROR: &str = "UNKNOWN";
// `EMSGSIZE` and `EAFNOSUPPORT`, or their Winsock equivalents.
#[cfg(any(target_os = "linux", target_os = "android"))]
const PERMANENT_OS_ERRORS: Option<(i32, i32)> = Some((90, 97));
#[cfg(any(
target_os = "macos",
target_os = "ios",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
target_os = "dragonfly"
))]
const PERMANENT_OS_ERRORS: Option<(i32, i32)> = Some((40, 47));
#[cfg(windows)]
const PERMANENT_OS_ERRORS: Option<(i32, i32)> = Some((10040, 10047));
#[cfg(not(any(
target_os = "linux",
target_os = "android",
target_os = "macos",
target_os = "ios",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
target_os = "dragonfly",
windows
)))]
const PERMANENT_OS_ERRORS: Option<(i32, i32)> = None;
/// The fixed name of a failed send's cause: `EMSGSIZE`, `EINVAL` or
/// `EAFNOSUPPORT` for a failure that can never pass
/// (`is_permanent_send_error`), `UNKNOWN` for anything else. An unsendable
/// session's goodbye carries this name, never the error's own text, which is
/// the platform's wording and can differ by the packet that failed.
pub fn send_error_code(error: &std::io::Error) -> &'static str {
if let (Some(code), Some((message_size, address_family))) =
(error.raw_os_error(), PERMANENT_OS_ERRORS)
{
if code == message_size {
return "EMSGSIZE";
}
if code == address_family {
return "EAFNOSUPPORT";
}
}
// `InvalidInput` is `EINVAL` and `WSAEINVAL`.
error.kind() == ErrorKind::InvalidInput
|| error
.raw_os_error()
.is_some_and(|code| PERMANENT_OS_ERRORS.contains(&code))
if error.kind() == ErrorKind::InvalidInput {
return "EINVAL";
}
UNKNOWN_SEND_ERROR
}
/// A session cannot admit a Connect when its sequence space starts exhausted or

View file

@ -500,3 +500,32 @@ fn a_send_refused_at_any_fragment_delivers_nothing_of_it() {
}
}
}
#[test]
fn a_send_failure_is_named_by_a_fixed_code_never_its_text() {
use std::io::{Error, ErrorKind};
let named = |error: Error| (send_error_code(&error), is_permanent_send_error(&error));
assert_eq!(
named(Error::new(ErrorKind::InvalidInput, "CANARY-7f3a")),
("EINVAL", true)
);
assert_eq!(
named(Error::new(ErrorKind::ConnectionRefused, "CANARY-7f3a")),
("UNKNOWN", false)
);
#[cfg(any(target_os = "linux", target_os = "android"))]
{
assert_eq!(named(Error::from_raw_os_error(90)), ("EMSGSIZE", true));
assert_eq!(named(Error::from_raw_os_error(97)), ("EAFNOSUPPORT", true));
assert_eq!(named(Error::from_raw_os_error(111)), ("UNKNOWN", false));
}
let mut session = CultNetRudpSession::new(CultNetRudpSessionOptions {
connection_id: 1,
initial_sequence: None,
resend_delay_ms: 10,
max_pending_reliable_packets: None,
});
let goodbye =
session.end_unsendable_session(&Error::new(ErrorKind::InvalidInput, "CANARY-7f3a"));
assert_eq!(goodbye.payload, b"packet could not be sent: EINVAL");
}

View file

@ -246,17 +246,46 @@ export class CultNetDocumentRegistry {
cache: CultCache,
message: CultNetDocumentPutRawMessage,
): Promise<unknown> {
const { binding, envelope } = this.#rawPutEnvelope(message);
return cache.putEnvelope(binding.definition, envelope);
}
/**
* The snapshot response that would serve this raw put's document alone: the
* record `applyRawDocumentPutMessage` would store, as `createRawSnapshotResponse`
* would serve it. A server uses it to judge a put by the size it would be
* served at. Throws, as the put would, when no binding accepts the document.
*/
createRawSnapshotResponseForPut(
message: CultNetDocumentPutRawMessage,
messageId: string,
): CultNetSnapshotResponseRawMessage {
const { envelope } = this.#rawPutEnvelope(message);
return {
schemaVersion: "cultnet.snapshot_response_raw.v0",
messageId,
documents: [this.#createRawDocumentRecord(envelope)],
};
}
#rawPutEnvelope(message: CultNetDocumentPutRawMessage): {
binding: CultNetDocumentBinding;
envelope: CultCacheEnvelope;
} {
const resolution = this.#resolveRawDocumentBinding(message.document);
const { binding } = resolution;
return cache.putEnvelope(binding.definition, {
key: message.document.recordKey,
type: binding.definition.type,
schemaId: resolution.preserveIncomingSchemaId
? message.document.schemaId
: schemaIdForBinding(binding),
payload: new Uint8Array(message.document.payload),
storedAt: message.document.storedAt,
});
return {
binding,
envelope: {
key: message.document.recordKey,
type: binding.definition.type,
schemaId: resolution.preserveIncomingSchemaId
? message.document.schemaId
: schemaIdForBinding(binding),
payload: new Uint8Array(message.document.payload),
storedAt: message.document.storedAt,
},
};
}
async applySnapshotResponse(

View file

@ -1490,15 +1490,30 @@ namespace GameCult.Networking
internal const string UnsendablePacketReason = "packet could not be sent";
/// <summary>
/// The fixed name of a failed send's cause: EMSGSIZE, EINVAL or EAFNOSUPPORT for a failure
/// that can never pass (<see cref="IsPermanentSendError"/>), UNKNOWN for anything else, as
/// every runtime's goodbye names it. Never the error's own message, which is the platform's
/// wording.
/// </summary>
internal static string SendErrorCode(SocketException error) => error.SocketErrorCode switch
{
SocketError.MessageSize => "EMSGSIZE",
SocketError.InvalidArgument => "EINVAL",
SocketError.AddressFamilyNotSupported => "EAFNOSUPPORT",
_ => "UNKNOWN",
};
/// <summary>
/// Ends a session that owes its peer a packet that can never be sent as built. Resending it
/// would fail forever, and dropping it would leave a reliable sequence the peer waits on for
/// good, so the session cannot be kept. The goodbye's reason names the error.
/// good, so the session cannot be kept. The goodbye's reason names the failure by its fixed
/// name (<see cref="SendErrorCode"/>).
/// </summary>
internal CultNetRudpPacket EndUnsendable(SocketException error)
{
ResetPeerState();
return CreateDisconnect(Encoding.UTF8.GetBytes(UnsendablePacketReason + ": " + error.Message));
return CreateDisconnect(Encoding.UTF8.GetBytes(UnsendablePacketReason + ": " + SendErrorCode(error)));
}
internal uint NextSequence => _nextSequence;

View file

@ -137,6 +137,18 @@ namespace GameCult.Networking.Tests
// caller-directed send throws it and queues nothing; inside a poll it ends that peer's
// session and never the poll.
[Test]
public void An_unsendable_goodbye_names_the_failure_by_a_fixed_code_never_its_message()
{
var session = new CultNetRudpSession(new CultNetRudpSessionOptions { ConnectionId = 1 });
Assert.That(
Encoding.UTF8.GetString(session.EndUnsendable(new SocketException((int)SocketError.MessageSize)).Payload!),
Is.EqualTo("packet could not be sent: EMSGSIZE"));
Assert.That(CultNetRudpSession.SendErrorCode(new SocketException((int)SocketError.InvalidArgument)), Is.EqualTo("EINVAL"));
Assert.That(CultNetRudpSession.SendErrorCode(new SocketException((int)SocketError.AddressFamilyNotSupported)), Is.EqualTo("EAFNOSUPPORT"));
Assert.That(CultNetRudpSession.SendErrorCode(new SocketException((int)SocketError.ConnectionRefused)), Is.EqualTo("UNKNOWN"));
}
private static bool IsUnsendableReason(byte[]? reason)
{
var text = Encoding.UTF8.GetString(reason ?? Array.Empty<byte>());