Add Rust CultMesh connected RUDP clients

This commit is contained in:
Meta Vens 2026-06-17 06:04:00 +01:00
commit b72bc7803b
5 changed files with 227 additions and 10 deletions

View file

@ -405,10 +405,12 @@ Current progress:
first peer authorized by the authority lease catalog for a Verse role. The
facade delegates to the existing Rust schema registry, shard catalog, and RUDP
socket transport owners; discovery contact remains separate from trust, which
is still gated by the authority lease catalog. Rust RUDP transports now also
send and receive typed `cultnet.schema.v0` messages on the reliable ordered
`schema` channel, so callers do not have to hand-encode MessagePack payloads
before using the shared RUDP pipe.
is still gated by the authority lease catalog. The facade can now also return
a connected RUDP client from a direct endpoint, peer card, or authorized peer
lookup. Rust RUDP transports now also send and receive typed
`cultnet.schema.v0` messages on the reliable ordered `schema` channel, so
callers do not have to hand-encode MessagePack payloads or hand-roll the
client handshake before using the shared RUDP pipe.
- Rust now also has substrate-shaped shard catalog helpers:
`CultNetShardDescriptor`, `CultNetShardCatalog`, request filtering by schema
id and record key, response creation, response application, and built-in

View file

@ -33,7 +33,7 @@ CultMesh.
| C# | Reference implementation and production game/server substrate | CultCache typed documents and SoA, CultNet schema-v0, LiteNetLib production path with adapter profile, shared transport profiles, shared RUDP socket transport, connected RUDP CultMesh client helpers, RUDP reconnect policy/controller and reconnect-loop helper, LiteNetLib client reconnect-controller adoption, schema-client transport port for service request/response clients, CultMesh node/session/catalog/stream/simulation/RUDP surfaces, authorized peer lookup | No need to abandon LiteNetLib before the CultNet adapter fully owns production service adoption |
| Python | Package runtime, local daemon endpoint, raw interop peer, typed state participant | CultCache/CultNet/CultMesh package surface, branded CultMesh node/schema/shard/Verse/peer/authority/stream/RUDP ergonomics, authorized peer lookup, shard catalogs/logs, schema-transport factory for raw client request/subscription flows, local TCP CultMesh server, session/prediction/simulation fact helpers, RUDP codec/session/socket transport, RUDP reconnect policy/controller and reconnect-loop helper, schema-v0 MessagePack over RUDP evidence, benchmark evidence against C# cache paths | Universal C# throughput, full C# daemon/server stack, and RUDP as the only public service pipe |
| TypeScript | Node/browser-adjacent projection and interop runtime | CultCache parity tests, CultNet schema-v0 peer, advertised schema/shard catalog wire contracts plus request/sync helpers, transport profiles, TCP-framed transport port and peer helper, shared RUDP socket transport, RUDP reconnect policy/controller, RUDP reconnect-loop helper, branded CultMesh node/schema/shard/Verse/peer/authority/stream/RUDP ergonomics, authorized peer lookup | Full C# game session/server stack |
| Rust | Low-level cache/transport/runtime substrate | CultCache/CultNet interop lane, schema and shard catalog helpers, transport profiles, TCP-framed port, shared RUDP codec/session/socket transport, RUDP reconnect policy/controller and reconnect-loop helper, schema-v0 MessagePack over RUDP evidence, small CultMesh facade for schema registry, shard catalog, peer cards, authority leases, authorized peer lookup, RUDP endpoint parsing, and peer-card/authorized-peer RUDP client construction | Full CultMesh game-session/server facade, stream catalog, or production game-session server |
| Rust | Low-level cache/transport/runtime substrate | CultCache/CultNet interop lane, schema and shard catalog helpers, transport profiles, TCP-framed port, shared RUDP codec/session/socket transport, connected RUDP CultMesh client helpers, RUDP reconnect policy/controller and reconnect-loop helper, schema-v0 MessagePack over RUDP evidence, small CultMesh facade for schema registry, shard catalog, peer cards, authority leases, authorized peer lookup, RUDP endpoint parsing, and peer-card/authorized-peer RUDP client construction | Full CultMesh game-session/server facade, stream catalog, or production game-session server |
| Kotlin | JVM/Android client substrate | Typed MessagePack cache, built-in schema catalog advertisement, schema/shard catalogs with shared schema-message transport fetch/sync helpers, authority leases, authorized peer lookup, stream catalog, branded `CultMesh` facade, WebSocket transport profile/connection helper, RUDP client/server sugar, connected RUDP CultMesh client helpers, RUDP reconnect policy/controller and reconnect-loop helper, schema-v0 MessagePack over RUDP evidence | C# SoA store, full C# server daemon, or Unity hot-loop memory layout |
## Evidence Gates

View file

@ -124,8 +124,8 @@ contact and authority ergonomics:
```rust
use cultnet_rs::{
CultMesh, CultMeshAuthorityLease, CultMeshPeerCard, CultMeshRudpSocketOptions, CultNetMessage,
CultNetSchemaKind,
CultMesh, CultMeshAuthorityLease, CultMeshPeerCard, CultMeshRudpClientOptions,
CultMeshRudpSocketOptions, CultNetMessage, CultNetSchemaKind,
};
use chrono::{Duration, Utc};
@ -166,7 +166,7 @@ leases.upsert(CultMeshAuthorityLease {
expires_at: now + Duration::minutes(1),
})?;
let mut client = CultMesh::create_rudp_client_for_authorized_peer(
let mut client = CultMesh::connect_rudp_client_for_authorized_peer(
"rust-client",
0x1020_3040,
&peers,
@ -175,9 +175,12 @@ let mut client = CultMesh::create_rudp_client_for_authorized_peer(
"schema",
None,
now,
CultMeshRudpSocketOptions::default(),
CultMeshRudpClientOptions {
socket_options: CultMeshRudpSocketOptions::default(),
connect_payload: b"join".to_vec(),
..CultMeshRudpClientOptions::default()
},
)?;
client.connect(b"join".to_vec())?;
client.send_schema_message(&CultNetMessage::SchemaCatalogRequest {
message_id: "rust-schema-catalog".to_string(),
include_schema_json: Some(false),
@ -186,6 +189,10 @@ client.send_schema_message(&CultNetMessage::SchemaCatalogRequest {
})?;
```
`create_rudp_client...` remains available when the caller intentionally owns the
handshake and polling loop. `connect_rudp_client...` performs the client
handshake before returning the same schema-message-capable RUDP transport.
For caller-owned reconnect loops, `CultNetRudpReconnectLoop` keeps transport
construction outside the library while sharing the portable retry controller:

View file

@ -6,7 +6,9 @@ use std::collections::BTreeMap;
use std::net::SocketAddr;
use std::net::ToSocketAddrs;
use std::net::UdpSocket;
use std::thread;
use std::time::Duration;
use std::time::Instant;
use crate::CultNetRudpSocketMode;
use crate::CultNetRudpSocketTransportConnection;
@ -263,6 +265,25 @@ impl Default for CultMeshRudpSocketOptions {
}
}
#[derive(Clone, Debug)]
pub struct CultMeshRudpClientOptions {
pub socket_options: CultMeshRudpSocketOptions,
pub connect_payload: Vec<u8>,
pub connect_timeout: Duration,
pub poll_interval: Duration,
}
impl Default for CultMeshRudpClientOptions {
fn default() -> Self {
Self {
socket_options: CultMeshRudpSocketOptions::default(),
connect_payload: Vec::new(),
connect_timeout: Duration::from_secs(1),
poll_interval: Duration::from_millis(5),
}
}
}
pub struct CultMesh;
impl CultMesh {
@ -373,6 +394,76 @@ impl CultMesh {
})?;
Self::create_rudp_client_for_peer(runtime_id, connection_id, &peer, options)
}
pub fn connect_rudp_client(
runtime_id: impl Into<String>,
connection_id: u32,
endpoint: &CultNetRudpEndpoint,
options: CultMeshRudpClientOptions,
) -> Result<CultNetRudpSocketTransportConnection> {
let runtime_id = runtime_id.into();
let mut client = Self::create_rudp_client(
runtime_id.clone(),
connection_id,
endpoint,
options.socket_options,
)?;
client.connect(options.connect_payload)?;
let deadline = Instant::now() + options.connect_timeout;
while Instant::now() < deadline {
let _ = client.receive_once()?;
client.poll_resends()?;
if client.connected() {
return Ok(client);
}
thread::sleep(options.poll_interval);
}
if client.connected() {
return Ok(client);
}
Err(anyhow!(
"Timed out waiting for RUDP client {runtime_id} to connect"
))
}
pub fn connect_rudp_client_for_endpoint(
runtime_id: impl Into<String>,
connection_id: u32,
endpoint: &str,
options: CultMeshRudpClientOptions,
) -> Result<CultNetRudpSocketTransportConnection> {
let endpoint = Self::parse_rudp_endpoint(endpoint)?;
Self::connect_rudp_client(runtime_id, connection_id, &endpoint, options)
}
pub fn connect_rudp_client_for_peer(
runtime_id: impl Into<String>,
connection_id: u32,
peer: &CultMeshPeerCard,
options: CultMeshRudpClientOptions,
) -> Result<CultNetRudpSocketTransportConnection> {
let endpoint = peer.rudp_endpoint()?;
Self::connect_rudp_client(runtime_id, connection_id, &endpoint, options)
}
pub fn connect_rudp_client_for_authorized_peer(
runtime_id: impl Into<String>,
connection_id: u32,
peers: &CultMeshPeerCatalog,
leases: &CultMeshAuthorityLeaseCatalog,
verse_id: &str,
role: &str,
shard_id: Option<&str>,
at: DateTime<Utc>,
options: CultMeshRudpClientOptions,
) -> Result<CultNetRudpSocketTransportConnection> {
let peer = peers
.first_authorized(verse_id, role, leases, shard_id, at)
.ok_or_else(|| {
anyhow!("No authorized RUDP peer for role {role} in Verse {verse_id}")
})?;
Self::connect_rudp_client_for_peer(runtime_id, connection_id, &peer, options)
}
}
pub fn cultnet_rudp_endpoint(endpoint: &str) -> Result<CultNetRudpEndpoint> {

View file

@ -7,6 +7,7 @@ use cultcache_rs::SingleFileMessagePackBackingStore;
use cultnet_rs::CultMesh;
use cultnet_rs::CultMeshAuthorityLease;
use cultnet_rs::CultMeshPeerCard;
use cultnet_rs::CultMeshRudpClientOptions;
use cultnet_rs::CultMeshRudpSocketOptions;
use cultnet_rs::CultNetClientSecurityOptions;
use cultnet_rs::CultNetDocumentBinding;
@ -60,6 +61,8 @@ use pretty_assertions::assert_eq;
use std::cell::RefCell;
use std::net::UdpSocket;
use std::rc::Rc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration as StdDuration;
@ -112,6 +115,26 @@ fn receive_rudp_schema_message(
anyhow::bail!("RUDP schema message was not delivered")
}
fn pump_rudp_server_until_connected(
server: Arc<Mutex<CultNetRudpSocketTransportConnection>>,
done: Arc<AtomicBool>,
) -> thread::JoinHandle<Result<()>> {
thread::spawn(move || {
while !done.load(Ordering::SeqCst) {
{
let mut server = server.lock().expect("RUDP server mutex poisoned");
let _ = server.receive_once()?;
server.poll_resends()?;
if server.connected() {
return Ok(());
}
}
thread::sleep(StdDuration::from_millis(5));
}
Ok(())
})
}
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
#[cultcache(
type = "ghostlight.agent-state",
@ -1258,6 +1281,100 @@ fn cultmesh_facade_creates_rudp_client_from_peer_endpoint() -> Result<()> {
Ok(())
}
#[test]
fn cultmesh_facade_connects_authorized_rudp_client_for_schema_messages() -> Result<()> {
let connection_id = 0x2030_4051;
let options = CultMeshRudpSocketOptions {
resend_delay_ms: 25,
max_fragment_bytes: Some(1024),
max_pending_reliable_packets: Some(16),
..CultMeshRudpSocketOptions::default()
};
let server = Arc::new(Mutex::new(CultMesh::create_rudp_server(
"rust-cultmesh-connected-server",
connection_id,
options.clone(),
)?));
let server_port = server
.lock()
.expect("RUDP server mutex poisoned")
.profile
.transports[0]
.port
.expect("RUDP server profile advertises its local port");
let endpoint = CultMesh::parse_rudp_endpoint(&format!("rudp://127.0.0.1:{server_port}"))?;
let peer = CultMeshPeerCard::new("rust-cultmesh-connected-server", "local", [endpoint.uri()])
.with_roles(["schema"])
.with_authority_lease_id("lease:rust-cultmesh-connected-server");
let mut peers = CultMesh::create_peer_catalog();
peers.upsert(peer)?;
let now = Utc::now();
let mut leases = CultMesh::create_authority_lease_catalog();
leases.upsert(CultMeshAuthorityLease {
lease_id: "lease:rust-cultmesh-connected-server".to_string(),
verse_id: "local".to_string(),
peer_id: "rust-cultmesh-connected-server".to_string(),
roles: vec!["schema".to_string()],
shard_ids: Vec::new(),
issuer_runtime_id: Some("odin".to_string()),
valid_from: now - Duration::minutes(1),
expires_at: now + Duration::minutes(1),
})?;
let done = Arc::new(AtomicBool::new(false));
let pump = pump_rudp_server_until_connected(server.clone(), done.clone());
let mut client = CultMesh::connect_rudp_client_for_authorized_peer(
"rust-cultmesh-connected-client",
connection_id,
&peers,
&leases,
"local",
"schema",
None,
now,
CultMeshRudpClientOptions {
socket_options: options,
connect_payload: b"join".to_vec(),
connect_timeout: StdDuration::from_secs(1),
poll_interval: StdDuration::from_millis(5),
},
)?;
done.store(true, Ordering::SeqCst);
pump.join()
.map_err(|_| anyhow::anyhow!("RUDP server pump panicked"))??;
assert!(client.connected());
assert!(
server
.lock()
.expect("RUDP server mutex poisoned")
.connected()
);
client.send_schema_message(&CultNetMessage::SchemaCatalogRequest {
message_id: "rust-cultmesh-rudp-schema-catalog".to_string(),
include_schema_json: Some(true),
schema_ids: None,
kinds: Some(vec![CultNetSchemaKind::DocumentPayload]),
})?;
let request = {
let mut server = server.lock().expect("RUDP server mutex poisoned");
receive_rudp_schema_message(&mut server)?
};
let CultNetMessage::SchemaCatalogRequest {
message_id, kinds, ..
} = request
else {
anyhow::bail!("RUDP schema message did not decode as schema catalog request");
};
assert_eq!(message_id, "rust-cultmesh-rudp-schema-catalog");
assert_eq!(kinds, Some(vec![CultNetSchemaKind::DocumentPayload]));
assert_eq!(
client.profile.transports[0].protocol,
CultNetTransportProtocol::Rudp
);
Ok(())
}
#[test]
fn cultmesh_facade_exposes_schema_registry_and_shard_catalog_owners() -> Result<()> {
let mut schemas = CultMesh::create_schema_registry();