Cut idunn-daemon and the vendored cultmesh fork out of Odin
Idunn now lives at https://github.com/GameCult/Idunn with its full 136-commit history. Odin no longer contains the deployment authority that manages it. Also removes vendor/cultmesh-rs, the private fork that had diverged from CultLib in both directions. Its unique capability -- the RUDP document server and the message_id correlation rework -- was reconciled into CultLib first, so this deletes a duplicate rather than a capability. The four crates that consumed it by path (muninn-daemon, odin-core, odin-daemon, sleipnir-daemon) now consume CultLib at c13b6ba like everything else. What deliberately stays in Odin: crates/odin-core/src/idunn.rs, which is Odin's own projection of Idunn state for aggregation and is Odin's to own; src/odin/idunn-rudp.cjs, its client for talking to Idunn; and deployment/idunn/recipe.toml, which despite the path is Odin's own deployment recipe expressed in Idunn's format -- it builds odin-daemon. odin-core: 22 passed, 0 failed, unchanged across the cut. odin-daemon still fails to compile on Windows for the pre-existing Unix-only std::os::fd reason. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
parent
0995222c17
commit
7ea146dd36
21 changed files with 4 additions and 23592 deletions
|
|
@ -1,7 +1,6 @@
|
|||
[workspace]
|
||||
members = [
|
||||
"crates/sleipnir-daemon",
|
||||
"crates/idunn-daemon",
|
||||
"crates/muninn-daemon",
|
||||
"crates/muninn-move-tracker",
|
||||
"crates/muninn-psmoveapi-tracker",
|
||||
|
|
@ -11,7 +10,6 @@ members = [
|
|||
resolver = "3"
|
||||
exclude = [
|
||||
"vendor/cultcache-rs",
|
||||
"vendor/cultmesh-rs",
|
||||
"vendor/cultnet-rs",
|
||||
]
|
||||
|
||||
|
|
|
|||
|
|
@ -1,37 +0,0 @@
|
|||
[package]
|
||||
name = "idunn-daemon"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "idunn"
|
||||
path = "src/main.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "idunn-provision"
|
||||
path = "src/bin/idunn-provision.rs"
|
||||
|
||||
[lib]
|
||||
name = "idunn_daemon"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1"
|
||||
cultmesh-rs = { path = "../../vendor/cultmesh-rs" }
|
||||
cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c13b6ba07e99f2535b455da74d07d88c308731f5", package = "cultcache-rs" }
|
||||
cultnet-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c13b6ba07e99f2535b455da74d07d88c308731f5", package = "cultnet-rs" }
|
||||
rmp-serde = "1.3"
|
||||
sha2 = "0.10"
|
||||
chrono = "0.4"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
ed25519-dalek = "2.2"
|
||||
toml = "0.8"
|
||||
uuid = { version = "1", features = ["v4"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
|
@ -1,6 +0,0 @@
|
|||
fn main() {
|
||||
if let Err(error) = idunn_daemon::provisioning::run(std::env::args().skip(1)) {
|
||||
eprintln!("idunn-provision: {error:#}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
|
|
@ -1,5 +0,0 @@
|
|||
pub mod control_plane;
|
||||
pub mod deployment;
|
||||
pub mod deployment_plan;
|
||||
pub mod drivers;
|
||||
pub mod provisioning;
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
fn main() -> anyhow::Result<()> {
|
||||
idunn_daemon::control_plane::run(std::env::args().skip(1))
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
12
crates/idunn-daemon/tests/fixtures/README.md
vendored
12
crates/idunn-daemon/tests/fixtures/README.md
vendored
|
|
@ -1,12 +0,0 @@
|
|||
# Bifrost release-authority wire fixture
|
||||
|
||||
`bifrost-release-authority-v1.payload.hex` is the exact MessagePack payload
|
||||
emitted on 2026-07-16 by Bifrost's TypeScript CultCache writer
|
||||
`tools/bifrost-repository-release-authority.mjs` for `GameCult/Epiphany`,
|
||||
`refs/heads/main`, commit
|
||||
`0123456789abcdef0123456789abcdef01234567`.
|
||||
|
||||
It is checked in because the TypeScript runtime emits a camelCase MessagePack
|
||||
map while Rust `DatabaseEntry` derives tuple payloads. Idunn must prove it can
|
||||
decode the producer's real wire shape rather than round-tripping a fixture it
|
||||
serialized itself.
|
||||
|
|
@ -1 +0,0 @@
|
|||
de0018aa736368656d614e616d65d924626966726f73742e7265706f7369746f72795f72656c656173655f617574686f72697479ad736368656d6156657273696f6ed927626966726f73742e7265706f7369746f72795f72656c656173655f617574686f726974792e7631ab617574686f726974794964d95272656c656173653a47616d6543756c742f4570697068616e793a726566732f68656164732f6d61696e3a30313233343536373839616263646566303132333435363738396162636465663031323334353637a9636f6d6d616e644964d92163756c746d6573682d636f6d6d616e642d6570697068616e792d72656c65617365b163726f7373696e67526563656970744964b963726f7373696e675f6570697068616e795f72656c65617365b27265706f7369746f727946756c6c4e616d65b147616d6543756c742f4570697068616e79ab757073747265616d526566af726566732f68656164732f6d61696ea9636f6d6d6974536861d92830313233343536373839616263646566303132333435363738396162636465663031323334353637a86465636973696f6ea9617574686f72697a65a6737461747573aa617574686f72697a6564b0706f6c6963794465636973696f6e4964b7706f6c6963792d6570697068616e792d72656c65617365b2617574686f726974795265666572656e6365b8626966726f73743a72656c656173653a6570697068616e79ad6163746f724964656e74697479a86d65746163726174aa736f757263654b696e64b8626966726f73742e676f7665726e616e63652e746f706963a8736f757263654964b6746f7069632d6570697068616e792d72656c65617365ad6570697068616e7952756e4964b472756e2d6570697068616e792d72656c65617365ae6570697068616e794c616e654964b168616e64732d7075626c69636174696f6eb56570697068616e794167656e744964656e74697479a86570697068616e79b265787465726e616c5265636569707455726cd95468747470733a2f2f6769746875622e636f6d2f47616d6543756c742f4570697068616e792f636f6d6d69742f30313233343536373839616263646566303132333435363738396162636465663031323334353637b165787465726e616c526563656970744964d92830313233343536373839616263646566303132333435363738396162636465663031323334353637ac617574686f72697a65644174b4323032362d30372d31365430303a30303a30305aa9657870697265734174a0a97265766f6b65644174a0b07265766f636174696f6e526561736f6ea0
|
||||
|
|
@ -15,7 +15,7 @@ path = "src/main.rs"
|
|||
|
||||
[dependencies]
|
||||
anyhow = "1"
|
||||
cultmesh-rs = { path = "../../vendor/cultmesh-rs" }
|
||||
cultmesh-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c13b6ba07e99f2535b455da74d07d88c308731f5", package = "cultmesh-rs" }
|
||||
cultnet-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c13b6ba07e99f2535b455da74d07d88c308731f5", package = "cultnet-rs" }
|
||||
libc = "0.2"
|
||||
muninn-move-tracker = { path = "../muninn-move-tracker" }
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ path = "src/lib.rs"
|
|||
[dependencies]
|
||||
anyhow = "1"
|
||||
cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c13b6ba07e99f2535b455da74d07d88c308731f5", package = "cultcache-rs" }
|
||||
cultmesh-rs = { path = "../../vendor/cultmesh-rs" }
|
||||
cultmesh-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c13b6ba07e99f2535b455da74d07d88c308731f5", package = "cultmesh-rs" }
|
||||
serde_json = "1"
|
||||
cultnet-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c13b6ba07e99f2535b455da74d07d88c308731f5", package = "cultnet-rs" }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ path = "src/lib.rs"
|
|||
anyhow = "1"
|
||||
chrono = "0.4"
|
||||
cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c13b6ba07e99f2535b455da74d07d88c308731f5", package = "cultcache-rs" }
|
||||
cultmesh-rs = { path = "../../vendor/cultmesh-rs" }
|
||||
cultmesh-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c13b6ba07e99f2535b455da74d07d88c308731f5", package = "cultmesh-rs" }
|
||||
cultnet-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c13b6ba07e99f2535b455da74d07d88c308731f5", package = "cultnet-rs" }
|
||||
fs2 = "0.4"
|
||||
rmp-serde = "1.3"
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ path = "src/main.rs"
|
|||
|
||||
[dependencies]
|
||||
anyhow = "1"
|
||||
cultmesh-rs = { path = "../../vendor/cultmesh-rs" }
|
||||
cultmesh-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c13b6ba07e99f2535b455da74d07d88c308731f5", package = "cultmesh-rs" }
|
||||
cultnet-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c13b6ba07e99f2535b455da74d07d88c308731f5", package = "cultnet-rs" }
|
||||
cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c13b6ba07e99f2535b455da74d07d88c308731f5", package = "cultcache-rs" }
|
||||
odin-core = { path = "../odin-core" }
|
||||
|
|
|
|||
1360
vendor/cultmesh-rs/Cargo.lock
generated
vendored
1360
vendor/cultmesh-rs/Cargo.lock
generated
vendored
File diff suppressed because it is too large
Load diff
20
vendor/cultmesh-rs/Cargo.toml
vendored
20
vendor/cultmesh-rs/Cargo.toml
vendored
|
|
@ -1,20 +0,0 @@
|
|||
[package]
|
||||
name = "cultmesh-rs"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
publish = false
|
||||
|
||||
[lib]
|
||||
name = "cultmesh_rs"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1"
|
||||
cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c13b6ba07e99f2535b455da74d07d88c308731f5", package = "cultcache-rs" }
|
||||
cultnet-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c13b6ba07e99f2535b455da74d07d88c308731f5", package = "cultnet-rs" }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
|
||||
[dev-dependencies]
|
||||
pretty_assertions = "1.4.1"
|
||||
rmp-serde = "1"
|
||||
tempfile = "3"
|
||||
1557
vendor/cultmesh-rs/src/lib.rs
vendored
1557
vendor/cultmesh-rs/src/lib.rs
vendored
File diff suppressed because it is too large
Load diff
647
vendor/cultmesh-rs/src/rudp_document_server.rs
vendored
647
vendor/cultmesh-rs/src/rudp_document_server.rs
vendored
|
|
@ -1,647 +0,0 @@
|
|||
use anyhow::{Result, anyhow};
|
||||
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,
|
||||
};
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::ErrorKind;
|
||||
use std::net::{SocketAddr, UdpSocket};
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
const MAX_UDP_DATAGRAM_BYTES: usize = 65_535;
|
||||
|
||||
/// The transport identity of one remote CultNet RUDP session.
|
||||
///
|
||||
/// Connection identifiers are scoped to a remote socket address. Two clients
|
||||
/// may therefore use the same connection identifier without sharing ordering,
|
||||
/// acknowledgement, resend, or fragment state.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub struct CultMeshRudpSessionKey {
|
||||
pub remote_addr: SocketAddr,
|
||||
pub connection_id: u32,
|
||||
}
|
||||
|
||||
/// A raw document plus the receipt fact owned by the receiving process.
|
||||
///
|
||||
/// `document.payload` is the exact byte vector decoded from the CultNet raw
|
||||
/// record. The trusted receipt time lives beside the sender-owned record so the
|
||||
/// transport never rewrites its metadata or payload.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct CultMeshRudpRawDocumentReceipt {
|
||||
pub session: CultMeshRudpSessionKey,
|
||||
pub message_id: String,
|
||||
pub transport_sequence: u32,
|
||||
pub received_at_unix_millis: u64,
|
||||
pub document: CultNetRawDocumentRecord,
|
||||
}
|
||||
|
||||
/// The caller-visible query for a read-only raw snapshot.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct CultMeshRudpSnapshotQuery {
|
||||
pub session: CultMeshRudpSessionKey,
|
||||
pub message_id: String,
|
||||
pub requested_at_unix_millis: u64,
|
||||
pub schema_ids: Option<Vec<String>>,
|
||||
pub record_keys: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
/// Caller-owned admission/persistence port for received raw documents.
|
||||
pub trait CultMeshRudpRawDocumentSink {
|
||||
fn accept_raw_document(&mut self, receipt: CultMeshRudpRawDocumentReceipt) -> Result<()>;
|
||||
}
|
||||
|
||||
impl<F> CultMeshRudpRawDocumentSink for F
|
||||
where
|
||||
F: FnMut(CultMeshRudpRawDocumentReceipt) -> Result<()>,
|
||||
{
|
||||
fn accept_raw_document(&mut self, receipt: CultMeshRudpRawDocumentReceipt) -> Result<()> {
|
||||
self(receipt)
|
||||
}
|
||||
}
|
||||
|
||||
/// Caller-owned catalog port for serving raw snapshot requests.
|
||||
///
|
||||
/// The caller decides which records the requester may see. CultMesh preserves
|
||||
/// those records as raw CultNet documents and does not interpret their schemas.
|
||||
pub trait CultMeshRudpSnapshotSource {
|
||||
fn raw_snapshot(
|
||||
&mut self,
|
||||
query: &CultMeshRudpSnapshotQuery,
|
||||
) -> Result<Vec<CultNetRawDocumentRecord>>;
|
||||
}
|
||||
|
||||
impl<F> CultMeshRudpSnapshotSource for F
|
||||
where
|
||||
F: FnMut(&CultMeshRudpSnapshotQuery) -> Result<Vec<CultNetRawDocumentRecord>>,
|
||||
{
|
||||
fn raw_snapshot(
|
||||
&mut self,
|
||||
query: &CultMeshRudpSnapshotQuery,
|
||||
) -> Result<Vec<CultNetRawDocumentRecord>> {
|
||||
self(query)
|
||||
}
|
||||
}
|
||||
|
||||
/// Trusted local clocks for receipt facts and transport maintenance.
|
||||
///
|
||||
/// Receipt time is wall time. Expiry and resend decisions use the monotonic
|
||||
/// value, so a wall-clock correction cannot resurrect or pin a session.
|
||||
pub trait CultMeshRudpServerClock {
|
||||
fn now_unix_millis(&self) -> u64;
|
||||
fn now_monotonic_millis(&self) -> u64;
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct CultMeshSystemClock {
|
||||
monotonic_origin: Instant,
|
||||
}
|
||||
|
||||
impl Default for CultMeshSystemClock {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
monotonic_origin: Instant::now(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CultMeshRudpServerClock for CultMeshSystemClock {
|
||||
fn now_unix_millis(&self) -> u64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_millis()
|
||||
.try_into()
|
||||
.unwrap_or(u64::MAX)
|
||||
}
|
||||
|
||||
fn now_monotonic_millis(&self) -> u64 {
|
||||
self.monotonic_origin
|
||||
.elapsed()
|
||||
.as_millis()
|
||||
.try_into()
|
||||
.unwrap_or(u64::MAX)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct CultMeshRudpDocumentServerOptions {
|
||||
pub max_sessions: usize,
|
||||
pub session_idle_timeout: Duration,
|
||||
pub session_max_lifetime: Duration,
|
||||
/// Conservative payload admission budget across all live sessions.
|
||||
///
|
||||
/// Admitted ingress and queued snapshot-response bytes are charged until
|
||||
/// the session ends even when CultNet releases them sooner. Together with
|
||||
/// CultNet's per-session receive caps, this makes retained payload memory
|
||||
/// finite without duplicating its fragment/ordering machinery here.
|
||||
pub max_admitted_payload_bytes: usize,
|
||||
pub max_admitted_payload_bytes_per_session: usize,
|
||||
pub max_snapshot_response_bytes: usize,
|
||||
pub max_snapshot_documents: usize,
|
||||
pub resend_delay: Duration,
|
||||
pub max_pending_reliable_packets_per_session: usize,
|
||||
pub max_fragment_bytes: usize,
|
||||
}
|
||||
|
||||
impl Default for CultMeshRudpDocumentServerOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
max_sessions: 64,
|
||||
session_idle_timeout: Duration::from_secs(30),
|
||||
session_max_lifetime: Duration::from_secs(15 * 60),
|
||||
max_admitted_payload_bytes: 32 * 1024 * 1024,
|
||||
max_admitted_payload_bytes_per_session: 4 * 1024 * 1024,
|
||||
max_snapshot_response_bytes: 1024 * 1024,
|
||||
max_snapshot_documents: 4096,
|
||||
resend_delay: Duration::from_millis(50),
|
||||
max_pending_reliable_packets_per_session: 1024,
|
||||
max_fragment_bytes: 1200,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct CultMeshRudpMaintenance {
|
||||
pub sessions_expired: usize,
|
||||
pub packets_resent: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum CultMeshRudpApplicationOperation {
|
||||
DocumentPutRaw,
|
||||
SnapshotRequest,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct CultMeshRudpApplicationRejection {
|
||||
pub session: CultMeshRudpSessionKey,
|
||||
pub operation: CultMeshRudpApplicationOperation,
|
||||
pub message_id: String,
|
||||
pub reason: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum CultMeshRudpPollOutcome {
|
||||
Idle,
|
||||
Handled,
|
||||
ApplicationRejected(CultMeshRudpApplicationRejection),
|
||||
}
|
||||
|
||||
struct SessionEntry {
|
||||
session: CultNetRudpSession,
|
||||
created_at_monotonic_millis: u64,
|
||||
last_activity_monotonic_millis: u64,
|
||||
admitted_payload_bytes: usize,
|
||||
}
|
||||
|
||||
/// A synchronous, multi-session CultNet RUDP raw-document server.
|
||||
///
|
||||
/// The server owns exactly one UDP socket. Call `poll_once` from an existing
|
||||
/// daemon loop; no executor or background thread is created here.
|
||||
pub struct CultMeshRudpDocumentServer<S, Q, C> {
|
||||
socket: UdpSocket,
|
||||
sessions: BTreeMap<CultMeshRudpSessionKey, SessionEntry>,
|
||||
sink: S,
|
||||
snapshot_source: Q,
|
||||
clock: C,
|
||||
options: CultMeshRudpDocumentServerOptions,
|
||||
}
|
||||
|
||||
impl<S, Q, C> CultMeshRudpDocumentServer<S, Q, C>
|
||||
where
|
||||
S: CultMeshRudpRawDocumentSink,
|
||||
Q: CultMeshRudpSnapshotSource,
|
||||
C: CultMeshRudpServerClock,
|
||||
{
|
||||
pub fn new(
|
||||
socket: UdpSocket,
|
||||
sink: S,
|
||||
snapshot_source: Q,
|
||||
clock: C,
|
||||
options: CultMeshRudpDocumentServerOptions,
|
||||
) -> Result<Self> {
|
||||
validate_options(&options)?;
|
||||
socket.local_addr().map_err(|error| {
|
||||
anyhow!("CultMesh RUDP server requires a bound UDP socket: {error}")
|
||||
})?;
|
||||
socket.set_nonblocking(true)?;
|
||||
Ok(Self {
|
||||
socket,
|
||||
sessions: BTreeMap::new(),
|
||||
sink,
|
||||
snapshot_source,
|
||||
clock,
|
||||
options,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn local_addr(&self) -> Result<SocketAddr> {
|
||||
Ok(self.socket.local_addr()?)
|
||||
}
|
||||
|
||||
pub fn session_count(&self) -> usize {
|
||||
self.sessions.len()
|
||||
}
|
||||
|
||||
/// 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.
|
||||
pub fn poll_once(&mut self) -> Result<CultMeshRudpPollOutcome> {
|
||||
self.maintain()?;
|
||||
let mut wire = vec![0_u8; MAX_UDP_DATAGRAM_BYTES];
|
||||
let (received, remote_addr) = match self.socket.recv_from(&mut wire) {
|
||||
Ok(value) => value,
|
||||
Err(error) if error.kind() == ErrorKind::WouldBlock => {
|
||||
return Ok(CultMeshRudpPollOutcome::Idle);
|
||||
}
|
||||
Err(error) => return Err(error.into()),
|
||||
};
|
||||
wire.truncate(received);
|
||||
|
||||
let packet = match decode_rudp_packet(&wire) {
|
||||
Ok(packet) => packet,
|
||||
Err(_) => return Ok(CultMeshRudpPollOutcome::Handled),
|
||||
};
|
||||
let now_unix = self.clock.now_unix_millis();
|
||||
let now_monotonic = self.clock.now_monotonic_millis();
|
||||
let key = CultMeshRudpSessionKey {
|
||||
remote_addr,
|
||||
connection_id: packet.connection_id,
|
||||
};
|
||||
|
||||
if packet.packet_type == CultNetRudpPacketType::Connect {
|
||||
self.accept_connection(key, &packet, now_monotonic)?;
|
||||
return Ok(CultMeshRudpPollOutcome::Handled);
|
||||
}
|
||||
|
||||
if !self.sessions.contains_key(&key) {
|
||||
return Ok(CultMeshRudpPollOutcome::Handled);
|
||||
}
|
||||
if packet.packet_type == CultNetRudpPacketType::Data
|
||||
&& packet.channel_id == "schema"
|
||||
&& !packet.reliable
|
||||
{
|
||||
return Ok(CultMeshRudpPollOutcome::Handled);
|
||||
}
|
||||
let payload_charge = if packet.packet_type == CultNetRudpPacketType::Data {
|
||||
packet.payload.len()
|
||||
} else {
|
||||
0
|
||||
};
|
||||
if !self.payload_budget_allows(key, payload_charge) {
|
||||
return Ok(CultMeshRudpPollOutcome::Handled);
|
||||
}
|
||||
|
||||
let result = {
|
||||
let entry = self
|
||||
.sessions
|
||||
.get_mut(&key)
|
||||
.expect("checked session must remain present");
|
||||
entry.last_activity_monotonic_millis = now_monotonic;
|
||||
entry.admitted_payload_bytes =
|
||||
entry.admitted_payload_bytes.saturating_add(payload_charge);
|
||||
entry.session.receive(&packet, now_monotonic)
|
||||
};
|
||||
let result = match result {
|
||||
Ok(result) => result,
|
||||
Err(_) => {
|
||||
self.sessions.remove(&key);
|
||||
return Ok(CultMeshRudpPollOutcome::Handled);
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(reply) = result.reply {
|
||||
self.send_packet(key.remote_addr, &reply)?;
|
||||
}
|
||||
|
||||
if result.disconnected {
|
||||
self.sessions.remove(&key);
|
||||
return Ok(CultMeshRudpPollOutcome::Handled);
|
||||
}
|
||||
|
||||
for frame in result.delivered {
|
||||
if frame.channel_id != "schema" {
|
||||
continue;
|
||||
}
|
||||
let message = match decode_cultnet_message_from_slice(
|
||||
&frame.payload,
|
||||
CultNetWireContract::CultNetSchemaV0,
|
||||
) {
|
||||
Ok(message) => message,
|
||||
Err(_) => continue,
|
||||
};
|
||||
if let Some(rejection) = self.deliver_application_message(
|
||||
key,
|
||||
frame.sequence,
|
||||
message,
|
||||
now_unix,
|
||||
now_monotonic,
|
||||
)? {
|
||||
self.sessions.remove(&key);
|
||||
return Ok(CultMeshRudpPollOutcome::ApplicationRejected(rejection));
|
||||
}
|
||||
}
|
||||
|
||||
if packet.reliable {
|
||||
let ack = self
|
||||
.sessions
|
||||
.get_mut(&key)
|
||||
.ok_or_else(|| anyhow!("CultMesh RUDP session disappeared before ACK"))?
|
||||
.session
|
||||
.create_ack();
|
||||
self.send_packet(key.remote_addr, &ack)?;
|
||||
}
|
||||
Ok(CultMeshRudpPollOutcome::Handled)
|
||||
}
|
||||
|
||||
/// Expire idle sessions and resend reliable packets whose deadline passed.
|
||||
pub fn maintain(&mut self) -> Result<CultMeshRudpMaintenance> {
|
||||
let now = self.clock.now_monotonic_millis();
|
||||
let idle_timeout_ms = duration_millis(self.options.session_idle_timeout);
|
||||
let lifetime_ms = duration_millis(self.options.session_max_lifetime);
|
||||
let before = self.sessions.len();
|
||||
self.sessions.retain(|_, entry| {
|
||||
now.saturating_sub(entry.last_activity_monotonic_millis) <= idle_timeout_ms
|
||||
&& now.saturating_sub(entry.created_at_monotonic_millis) <= lifetime_ms
|
||||
});
|
||||
let expired = before - self.sessions.len();
|
||||
|
||||
let mut resends = Vec::new();
|
||||
for (key, entry) in &mut self.sessions {
|
||||
for packet in entry.session.due_resends(now) {
|
||||
resends.push((key.remote_addr, packet));
|
||||
}
|
||||
}
|
||||
for (remote_addr, packet) in &resends {
|
||||
self.send_packet(*remote_addr, packet)?;
|
||||
}
|
||||
Ok(CultMeshRudpMaintenance {
|
||||
sessions_expired: expired,
|
||||
packets_resent: resends.len(),
|
||||
})
|
||||
}
|
||||
|
||||
fn accept_connection(
|
||||
&mut self,
|
||||
key: CultMeshRudpSessionKey,
|
||||
packet: &CultNetRudpPacket,
|
||||
now: u64,
|
||||
) -> Result<()> {
|
||||
if !self.sessions.contains_key(&key) {
|
||||
if self.sessions.len() >= self.options.max_sessions {
|
||||
return Ok(());
|
||||
}
|
||||
self.sessions.insert(
|
||||
key,
|
||||
SessionEntry {
|
||||
session: CultNetRudpSession::new(CultNetRudpSessionOptions {
|
||||
connection_id: key.connection_id,
|
||||
initial_sequence: 1,
|
||||
resend_delay_ms: duration_millis(self.options.resend_delay),
|
||||
max_pending_reliable_packets: Some(
|
||||
self.options.max_pending_reliable_packets_per_session,
|
||||
),
|
||||
}),
|
||||
created_at_monotonic_millis: now,
|
||||
last_activity_monotonic_millis: now,
|
||||
admitted_payload_bytes: 0,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
let accept = {
|
||||
let entry = self
|
||||
.sessions
|
||||
.get_mut(&key)
|
||||
.expect("accepted session must be present");
|
||||
// The same key is a retransmitted Connect for the existing epoch.
|
||||
// A genuinely fresh client incarnation must choose a fresh id.
|
||||
entry.last_activity_monotonic_millis = now;
|
||||
entry.session.accept_connect(packet, now, Vec::new())?
|
||||
};
|
||||
self.send_packet(key.remote_addr, &accept)
|
||||
}
|
||||
|
||||
fn deliver_application_message(
|
||||
&mut self,
|
||||
key: CultMeshRudpSessionKey,
|
||||
transport_sequence: u32,
|
||||
message: CultNetMessage,
|
||||
now_unix: u64,
|
||||
now: u64,
|
||||
) -> Result<Option<CultMeshRudpApplicationRejection>> {
|
||||
match message {
|
||||
CultNetMessage::DocumentPutRaw {
|
||||
message_id,
|
||||
document,
|
||||
} => {
|
||||
let receipt = CultMeshRudpRawDocumentReceipt {
|
||||
session: key,
|
||||
message_id: message_id.clone(),
|
||||
transport_sequence,
|
||||
received_at_unix_millis: now_unix,
|
||||
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:#}"),
|
||||
}));
|
||||
}
|
||||
}
|
||||
CultNetMessage::SnapshotRequest {
|
||||
message_id,
|
||||
schema_ids,
|
||||
record_keys,
|
||||
} => {
|
||||
let query = CultMeshRudpSnapshotQuery {
|
||||
session: key,
|
||||
message_id: message_id.clone(),
|
||||
requested_at_unix_millis: now_unix,
|
||||
schema_ids,
|
||||
record_keys,
|
||||
};
|
||||
let documents = match self.snapshot_source.raw_snapshot(&query) {
|
||||
Ok(documents) => documents,
|
||||
Err(error) => {
|
||||
return Ok(Some(CultMeshRudpApplicationRejection {
|
||||
session: key,
|
||||
operation: CultMeshRudpApplicationOperation::SnapshotRequest,
|
||||
message_id,
|
||||
reason: format!("{error:#}"),
|
||||
}));
|
||||
}
|
||||
};
|
||||
if documents.len() > self.options.max_snapshot_documents {
|
||||
return Ok(Some(CultMeshRudpApplicationRejection {
|
||||
session: key,
|
||||
operation: CultMeshRudpApplicationOperation::SnapshotRequest,
|
||||
message_id,
|
||||
reason: format!(
|
||||
"snapshot returned {} documents; limit is {}",
|
||||
documents.len(),
|
||||
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,
|
||||
) {
|
||||
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:#}"),
|
||||
}));
|
||||
}
|
||||
};
|
||||
if payload.len() > self.options.max_snapshot_response_bytes {
|
||||
return Ok(Some(CultMeshRudpApplicationRejection {
|
||||
session: key,
|
||||
operation: CultMeshRudpApplicationOperation::SnapshotRequest,
|
||||
message_id,
|
||||
reason: format!(
|
||||
"snapshot response is {} bytes; limit is {}",
|
||||
payload.len(),
|
||||
self.options.max_snapshot_response_bytes
|
||||
),
|
||||
}));
|
||||
}
|
||||
if !self.payload_budget_allows(key, payload.len()) {
|
||||
return Ok(Some(CultMeshRudpApplicationRejection {
|
||||
session: key,
|
||||
operation: CultMeshRudpApplicationOperation::SnapshotRequest,
|
||||
message_id,
|
||||
reason: "retained payload budget is full".into(),
|
||||
}));
|
||||
}
|
||||
let payload_bytes = payload.len();
|
||||
let entry = self
|
||||
.sessions
|
||||
.get_mut(&key)
|
||||
.ok_or_else(|| anyhow!("CultMesh RUDP session disappeared before response"))?;
|
||||
let packets = match entry.session.send_many(
|
||||
"schema",
|
||||
payload,
|
||||
CultNetRudpSendOptions {
|
||||
reliable: true,
|
||||
ordered: true,
|
||||
sequenced: false,
|
||||
now_ms: now,
|
||||
reliable_expire_after_ms: None,
|
||||
},
|
||||
Some(self.options.max_fragment_bytes),
|
||||
) {
|
||||
Ok(packets) => packets,
|
||||
Err(error) => {
|
||||
return Ok(Some(CultMeshRudpApplicationRejection {
|
||||
session: key,
|
||||
operation: CultMeshRudpApplicationOperation::SnapshotRequest,
|
||||
message_id,
|
||||
reason: format!("snapshot response could not be queued: {error:#}"),
|
||||
}));
|
||||
}
|
||||
};
|
||||
entry.admitted_payload_bytes =
|
||||
entry.admitted_payload_bytes.saturating_add(payload_bytes);
|
||||
for packet in &packets {
|
||||
self.send_packet(key.remote_addr, packet)?;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn payload_budget_allows(&self, key: CultMeshRudpSessionKey, bytes: usize) -> bool {
|
||||
let Some(session_bytes) = self
|
||||
.sessions
|
||||
.get(&key)
|
||||
.map(|entry| entry.admitted_payload_bytes)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
if session_bytes
|
||||
.checked_add(bytes)
|
||||
.is_none_or(|total| total > self.options.max_admitted_payload_bytes_per_session)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
self.sessions
|
||||
.values()
|
||||
.try_fold(0_usize, |total, entry| {
|
||||
total.checked_add(entry.admitted_payload_bytes)
|
||||
})
|
||||
.and_then(|total| total.checked_add(bytes))
|
||||
.is_some_and(|total| total <= self.options.max_admitted_payload_bytes)
|
||||
}
|
||||
|
||||
fn send_packet(&mut self, remote_addr: SocketAddr, packet: &CultNetRudpPacket) -> Result<()> {
|
||||
let wire = encode_rudp_packet(packet)?;
|
||||
self.socket.send_to(&wire, remote_addr)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_options(options: &CultMeshRudpDocumentServerOptions) -> Result<()> {
|
||||
if options.max_sessions == 0 {
|
||||
return Err(anyhow!("max_sessions must be greater than zero"));
|
||||
}
|
||||
if options.session_idle_timeout.is_zero() {
|
||||
return Err(anyhow!("session_idle_timeout must be greater than zero"));
|
||||
}
|
||||
if options.session_max_lifetime.is_zero() {
|
||||
return Err(anyhow!("session_max_lifetime must be greater than zero"));
|
||||
}
|
||||
if options.max_admitted_payload_bytes == 0 {
|
||||
return Err(anyhow!(
|
||||
"max_admitted_payload_bytes must be greater than zero"
|
||||
));
|
||||
}
|
||||
if options.max_admitted_payload_bytes_per_session == 0
|
||||
|| options.max_admitted_payload_bytes_per_session > options.max_admitted_payload_bytes
|
||||
{
|
||||
return Err(anyhow!(
|
||||
"per-session admitted payload limit must be non-zero and no larger than the server limit"
|
||||
));
|
||||
}
|
||||
if options.max_snapshot_response_bytes == 0
|
||||
|| options.max_snapshot_response_bytes > options.max_admitted_payload_bytes_per_session
|
||||
{
|
||||
return Err(anyhow!(
|
||||
"snapshot response limit must be non-zero and fit in one session's payload budget"
|
||||
));
|
||||
}
|
||||
if options.max_snapshot_documents == 0 {
|
||||
return Err(anyhow!("max_snapshot_documents must be greater than zero"));
|
||||
}
|
||||
if options.resend_delay.is_zero() {
|
||||
return Err(anyhow!("resend_delay must be greater than zero"));
|
||||
}
|
||||
if options.max_pending_reliable_packets_per_session == 0 {
|
||||
return Err(anyhow!(
|
||||
"max_pending_reliable_packets_per_session must be greater than zero"
|
||||
));
|
||||
}
|
||||
if options.max_fragment_bytes == 0 {
|
||||
return Err(anyhow!("max_fragment_bytes must be greater than zero"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn duration_millis(duration: Duration) -> u64 {
|
||||
duration.as_millis().try_into().unwrap_or(u64::MAX)
|
||||
}
|
||||
553
vendor/cultmesh-rs/tests/rudp_document_server.rs
vendored
553
vendor/cultmesh-rs/tests/rudp_document_server.rs
vendored
|
|
@ -1,553 +0,0 @@
|
|||
use anyhow::Result;
|
||||
use cultmesh_rs::{
|
||||
CultMeshRudpApplicationOperation, CultMeshRudpDocumentServer,
|
||||
CultMeshRudpDocumentServerOptions, CultMeshRudpPollOutcome, CultMeshRudpRawDocumentReceipt,
|
||||
CultMeshRudpRawDocumentSink, CultMeshRudpServerClock, CultMeshRudpSnapshotQuery,
|
||||
CultMeshRudpSnapshotSource,
|
||||
};
|
||||
use cultnet_rs::{
|
||||
CultNetMessage, CultNetRawDocumentRecord, CultNetRawPayloadEncoding,
|
||||
CultNetRudpReliableSendReceipt, CultNetRudpReliableSendStatus, CultNetRudpSocketMode,
|
||||
CultNetRudpSocketTransportConnection, CultNetRudpSocketTransportOptions, CultNetWireContract,
|
||||
decode_cultnet_message_from_slice, encode_cultnet_message_to_vec,
|
||||
};
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::net::{SocketAddr, UdpSocket};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
#[derive(Default)]
|
||||
struct SinkState {
|
||||
receipts: Vec<CultMeshRudpRawDocumentReceipt>,
|
||||
failures_remaining: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct Sink(Arc<Mutex<SinkState>>);
|
||||
|
||||
impl Sink {
|
||||
fn fail_once() -> Self {
|
||||
Self(Arc::new(Mutex::new(SinkState {
|
||||
failures_remaining: 1,
|
||||
..Default::default()
|
||||
})))
|
||||
}
|
||||
}
|
||||
|
||||
impl CultMeshRudpRawDocumentSink for Sink {
|
||||
fn accept_raw_document(&mut self, receipt: CultMeshRudpRawDocumentReceipt) -> Result<()> {
|
||||
let mut state = self.0.lock().unwrap();
|
||||
if state.failures_remaining > 0 {
|
||||
state.failures_remaining -= 1;
|
||||
anyhow::bail!("injected sink failure");
|
||||
}
|
||||
state.receipts.push(receipt);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct SourceState {
|
||||
documents: Vec<CultNetRawDocumentRecord>,
|
||||
failures_remaining: usize,
|
||||
calls: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct Source(Arc<Mutex<SourceState>>);
|
||||
|
||||
impl Source {
|
||||
fn documents(documents: Vec<CultNetRawDocumentRecord>) -> Self {
|
||||
Self(Arc::new(Mutex::new(SourceState {
|
||||
documents,
|
||||
..Default::default()
|
||||
})))
|
||||
}
|
||||
|
||||
fn fail_once(documents: Vec<CultNetRawDocumentRecord>) -> Self {
|
||||
Self(Arc::new(Mutex::new(SourceState {
|
||||
documents,
|
||||
failures_remaining: 1,
|
||||
calls: 0,
|
||||
})))
|
||||
}
|
||||
}
|
||||
|
||||
impl CultMeshRudpSnapshotSource for Source {
|
||||
fn raw_snapshot(
|
||||
&mut self,
|
||||
_: &CultMeshRudpSnapshotQuery,
|
||||
) -> Result<Vec<CultNetRawDocumentRecord>> {
|
||||
let mut state = self.0.lock().unwrap();
|
||||
state.calls += 1;
|
||||
if state.failures_remaining > 0 {
|
||||
state.failures_remaining -= 1;
|
||||
anyhow::bail!("injected source failure");
|
||||
}
|
||||
Ok(state.documents.clone())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Clock {
|
||||
unix: Arc<AtomicU64>,
|
||||
monotonic: Arc<AtomicU64>,
|
||||
}
|
||||
|
||||
impl Clock {
|
||||
fn new(now: u64) -> Self {
|
||||
Self {
|
||||
unix: Arc::new(AtomicU64::new(now)),
|
||||
monotonic: Arc::new(AtomicU64::new(now)),
|
||||
}
|
||||
}
|
||||
|
||||
fn set(&self, now: u64) {
|
||||
self.unix.store(now, Ordering::SeqCst);
|
||||
self.monotonic.store(now, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
fn set_unix(&self, now: u64) {
|
||||
self.unix.store(now, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
fn set_monotonic(&self, now: u64) {
|
||||
self.monotonic.store(now, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
impl CultMeshRudpServerClock for Clock {
|
||||
fn now_unix_millis(&self) -> u64 {
|
||||
self.unix.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
fn now_monotonic_millis(&self) -> u64 {
|
||||
self.monotonic.load(Ordering::SeqCst)
|
||||
}
|
||||
}
|
||||
|
||||
type Server = CultMeshRudpDocumentServer<Sink, Source, Clock>;
|
||||
|
||||
fn document(key: &str, payload: Vec<u8>) -> CultNetRawDocumentRecord {
|
||||
CultNetRawDocumentRecord {
|
||||
schema_id: "test.raw.v1".into(),
|
||||
record_key: key.into(),
|
||||
stored_at: "2026-09-03T00:00:00Z".into(),
|
||||
payload_encoding: CultNetRawPayloadEncoding::Messagepack,
|
||||
payload,
|
||||
source_runtime_id: Some(format!("runtime-{key}")),
|
||||
source_agent_id: None,
|
||||
source_role: None,
|
||||
tags: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn server(
|
||||
options: CultMeshRudpDocumentServerOptions,
|
||||
clock: Clock,
|
||||
sink: Sink,
|
||||
source: Source,
|
||||
) -> Result<Server> {
|
||||
CultMeshRudpDocumentServer::new(
|
||||
UdpSocket::bind("127.0.0.1:0")?,
|
||||
sink,
|
||||
source,
|
||||
clock,
|
||||
options,
|
||||
)
|
||||
}
|
||||
|
||||
fn client(target: SocketAddr, id: u32) -> Result<CultNetRudpSocketTransportConnection> {
|
||||
let socket = UdpSocket::bind("127.0.0.1:0")?;
|
||||
socket.set_nonblocking(true)?;
|
||||
CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions {
|
||||
runtime_id: "test-client".into(),
|
||||
socket,
|
||||
mode: CultNetRudpSocketMode::Client,
|
||||
remote_addr: Some(target),
|
||||
connection_id: id,
|
||||
initial_sequence: 1,
|
||||
resend_delay_ms: 10,
|
||||
transport_id: None,
|
||||
max_payload_bytes: None,
|
||||
max_fragment_bytes: Some(1200),
|
||||
max_pending_reliable_packets: Some(64),
|
||||
media_reliable_expire_after_ms: None,
|
||||
})
|
||||
}
|
||||
|
||||
fn connect(
|
||||
server: &mut Server,
|
||||
clients: &mut [&mut CultNetRudpSocketTransportConnection],
|
||||
) -> Result<()> {
|
||||
for client in &mut *clients {
|
||||
client.connect(Vec::new())?;
|
||||
}
|
||||
for _ in 0..500 {
|
||||
server.poll_once()?;
|
||||
for client in &mut *clients {
|
||||
client.receive_once()?;
|
||||
}
|
||||
if clients.iter().all(|client| client.connected()) {
|
||||
for _ in 0..clients.len() {
|
||||
server.poll_once()?;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
anyhow::bail!("client connection timed out")
|
||||
}
|
||||
|
||||
fn send(client: &mut CultNetRudpSocketTransportConnection, message: &CultNetMessage) -> Result<()> {
|
||||
client.send(
|
||||
"schema",
|
||||
encode_cultnet_message_to_vec(message, CultNetWireContract::CultNetSchemaV0)?,
|
||||
)
|
||||
}
|
||||
|
||||
fn send_reliable(
|
||||
client: &mut CultNetRudpSocketTransportConnection,
|
||||
message: &CultNetMessage,
|
||||
) -> Result<CultNetRudpReliableSendReceipt> {
|
||||
client.send_reliable(
|
||||
"schema",
|
||||
encode_cultnet_message_to_vec(message, CultNetWireContract::CultNetSchemaV0)?,
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_connection_id_is_peer_scoped_and_raw_bytes_are_untouched() -> Result<()> {
|
||||
let clock = Clock::new(42_000);
|
||||
let sink = Sink::default();
|
||||
let mut server = server(Default::default(), clock, sink.clone(), Source::default())?;
|
||||
let mut a = client(server.local_addr()?, 77)?;
|
||||
let mut b = client(server.local_addr()?, 77)?;
|
||||
connect(&mut server, &mut [&mut a, &mut b])?;
|
||||
|
||||
let a_bytes = vec![0xc4, 0x04, 0x00, 0xff, 0x80, 0x01];
|
||||
let b_bytes = vec![0x92, 0x01, 0xc4, 0x02, 0x00, 0xff];
|
||||
send(
|
||||
&mut a,
|
||||
&CultNetMessage::DocumentPutRaw {
|
||||
message_id: "a".into(),
|
||||
document: document("a", a_bytes.clone()),
|
||||
},
|
||||
)?;
|
||||
send(
|
||||
&mut b,
|
||||
&CultNetMessage::DocumentPutRaw {
|
||||
message_id: "b".into(),
|
||||
document: document("b", b_bytes.clone()),
|
||||
},
|
||||
)?;
|
||||
for _ in 0..500 {
|
||||
server.poll_once()?;
|
||||
a.receive_once()?;
|
||||
b.receive_once()?;
|
||||
if sink.0.lock().unwrap().receipts.len() == 2 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let receipts = sink.0.lock().unwrap();
|
||||
assert_eq!(server.session_count(), 2);
|
||||
assert_eq!(receipts.receipts.len(), 2);
|
||||
assert_ne!(
|
||||
receipts.receipts[0].session.remote_addr,
|
||||
receipts.receipts[1].session.remote_addr
|
||||
);
|
||||
assert_eq!(
|
||||
receipts
|
||||
.receipts
|
||||
.iter()
|
||||
.find(|r| r.message_id == "a")
|
||||
.unwrap()
|
||||
.document
|
||||
.payload,
|
||||
a_bytes
|
||||
);
|
||||
assert_eq!(
|
||||
receipts
|
||||
.receipts
|
||||
.iter()
|
||||
.find(|r| r.message_id == "b")
|
||||
.unwrap()
|
||||
.document
|
||||
.payload,
|
||||
b_bytes
|
||||
);
|
||||
assert!(
|
||||
receipts
|
||||
.receipts
|
||||
.iter()
|
||||
.all(|r| r.received_at_unix_millis == 42_000)
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_connect_preserves_epoch_and_fresh_epoch_is_separate() -> Result<()> {
|
||||
let clock = Clock::new(45_000);
|
||||
let sink = Sink::default();
|
||||
let mut server = server(Default::default(), clock, sink.clone(), Source::default())?;
|
||||
let target = server.local_addr()?;
|
||||
let mut incumbent = client(target, 91)?;
|
||||
connect(&mut server, &mut [&mut incumbent])?;
|
||||
|
||||
incumbent.connect(Vec::new())?;
|
||||
server.poll_once()?;
|
||||
incumbent.receive_once()?;
|
||||
assert_eq!(server.session_count(), 1);
|
||||
|
||||
send(
|
||||
&mut incumbent,
|
||||
&CultNetMessage::DocumentPutRaw {
|
||||
message_id: "after-duplicate".into(),
|
||||
document: document("incumbent", vec![1, 2, 3]),
|
||||
},
|
||||
)?;
|
||||
for _ in 0..20 {
|
||||
server.poll_once()?;
|
||||
if sink.0.lock().unwrap().receipts.len() == 1 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert_eq!(sink.0.lock().unwrap().receipts.len(), 1);
|
||||
|
||||
let mut fresh_epoch = client(target, 92)?;
|
||||
connect(&mut server, &mut [&mut fresh_epoch])?;
|
||||
assert_eq!(server.session_count(), 2);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn application_rejection_is_nonfatal_peer_scoped_and_unacknowledged() -> Result<()> {
|
||||
let clock = Clock::new(48_000);
|
||||
let sink = Sink::fail_once();
|
||||
let source = Source::fail_once(vec![document("snapshot", vec![4, 5, 6])]);
|
||||
let mut server = server(
|
||||
Default::default(),
|
||||
clock.clone(),
|
||||
sink.clone(),
|
||||
source.clone(),
|
||||
)?;
|
||||
let target = server.local_addr()?;
|
||||
|
||||
let mut publisher = client(target, 101)?;
|
||||
let mut snapshot_client = client(target, 102)?;
|
||||
let mut survivor = client(target, 103)?;
|
||||
connect(
|
||||
&mut server,
|
||||
&mut [&mut publisher, &mut snapshot_client, &mut survivor],
|
||||
)?;
|
||||
let publish_receipt = send_reliable(
|
||||
&mut publisher,
|
||||
&CultNetMessage::DocumentPutRaw {
|
||||
message_id: "rejected-put".into(),
|
||||
document: document("rejected", vec![0, 255, 1]),
|
||||
},
|
||||
)?;
|
||||
let CultMeshRudpPollOutcome::ApplicationRejected(rejection) = server.poll_once()? else {
|
||||
panic!("sink rejection must be returned as a nonfatal poll outcome");
|
||||
};
|
||||
assert_eq!(rejection.session.connection_id, 101);
|
||||
assert_eq!(
|
||||
rejection.operation,
|
||||
CultMeshRudpApplicationOperation::DocumentPutRaw
|
||||
);
|
||||
assert_eq!(rejection.message_id, "rejected-put");
|
||||
assert!(rejection.reason.contains("injected sink failure"));
|
||||
assert_eq!(server.session_count(), 2);
|
||||
publisher.receive_once()?;
|
||||
assert_eq!(
|
||||
publisher.reliable_send_status(&publish_receipt),
|
||||
CultNetRudpReliableSendStatus::Pending
|
||||
);
|
||||
|
||||
let snapshot_receipt = send_reliable(
|
||||
&mut snapshot_client,
|
||||
&CultNetMessage::SnapshotRequest {
|
||||
message_id: "rejected-snapshot".into(),
|
||||
schema_ids: None,
|
||||
record_keys: None,
|
||||
},
|
||||
)?;
|
||||
let CultMeshRudpPollOutcome::ApplicationRejected(rejection) = server.poll_once()? else {
|
||||
panic!("source rejection must be returned as a nonfatal poll outcome");
|
||||
};
|
||||
assert_eq!(rejection.session.connection_id, 102);
|
||||
assert_eq!(
|
||||
rejection.operation,
|
||||
CultMeshRudpApplicationOperation::SnapshotRequest
|
||||
);
|
||||
assert_eq!(rejection.message_id, "rejected-snapshot");
|
||||
assert!(rejection.reason.contains("injected source failure"));
|
||||
assert_eq!(server.session_count(), 1);
|
||||
snapshot_client.receive_once()?;
|
||||
assert_eq!(
|
||||
snapshot_client.reliable_send_status(&snapshot_receipt),
|
||||
CultNetRudpReliableSendStatus::Pending
|
||||
);
|
||||
|
||||
let survivor_receipt = send_reliable(
|
||||
&mut survivor,
|
||||
&CultNetMessage::DocumentPutRaw {
|
||||
message_id: "accepted-after-rejections".into(),
|
||||
document: document("survivor", vec![9, 8, 7]),
|
||||
},
|
||||
)?;
|
||||
assert_eq!(server.poll_once()?, CultMeshRudpPollOutcome::Handled);
|
||||
for _ in 0..20 {
|
||||
survivor.receive_once()?;
|
||||
if survivor.reliable_send_status(&survivor_receipt)
|
||||
== CultNetRudpReliableSendStatus::Acknowledged
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
survivor.reliable_send_status(&survivor_receipt),
|
||||
CultNetRudpReliableSendStatus::Acknowledged
|
||||
);
|
||||
assert_eq!(sink.0.lock().unwrap().receipts.len(), 1);
|
||||
assert_eq!(source.0.lock().unwrap().calls, 1);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_response_resends_until_acknowledged() -> Result<()> {
|
||||
let clock = Clock::new(51_000);
|
||||
let expected = document("catalog", vec![0x81, 0xa1, 0x78, 0x2a]);
|
||||
let source = Source::documents(vec![expected.clone()]);
|
||||
let options = CultMeshRudpDocumentServerOptions {
|
||||
resend_delay: Duration::from_millis(10),
|
||||
..Default::default()
|
||||
};
|
||||
let mut server = server(options, clock.clone(), Sink::default(), source)?;
|
||||
let mut client = client(server.local_addr()?, 88)?;
|
||||
connect(&mut server, &mut [&mut client])?;
|
||||
send(
|
||||
&mut client,
|
||||
&CultNetMessage::SnapshotRequest {
|
||||
message_id: "snapshot".into(),
|
||||
schema_ids: Some(vec!["test.raw.v1".into()]),
|
||||
record_keys: Some(vec!["catalog".into()]),
|
||||
},
|
||||
)?;
|
||||
server.poll_once()?;
|
||||
|
||||
clock.set(51_011);
|
||||
assert_eq!(server.maintain()?.packets_resent, 1);
|
||||
let response = loop {
|
||||
if let Some(frame) = client.receive_once()? {
|
||||
break decode_cultnet_message_from_slice(
|
||||
&frame.payload,
|
||||
CultNetWireContract::CultNetSchemaV0,
|
||||
)?;
|
||||
}
|
||||
};
|
||||
assert_eq!(
|
||||
response,
|
||||
CultNetMessage::SnapshotResponseRaw {
|
||||
message_id: "snapshot".into(),
|
||||
documents: vec![expected],
|
||||
}
|
||||
);
|
||||
|
||||
for _ in 0..20 {
|
||||
server.poll_once()?;
|
||||
}
|
||||
clock.set(51_022);
|
||||
assert_eq!(server.maintain()?.packets_resent, 0);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn payload_and_snapshot_output_budgets_fail_closed() -> Result<()> {
|
||||
let clock = Clock::new(55_000);
|
||||
let sink = Sink::default();
|
||||
let message = CultNetMessage::DocumentPutRaw {
|
||||
message_id: "budget".into(),
|
||||
document: document("budget", vec![7; 64]),
|
||||
};
|
||||
let encoded = encode_cultnet_message_to_vec(&message, CultNetWireContract::CultNetSchemaV0)?;
|
||||
let options = CultMeshRudpDocumentServerOptions {
|
||||
max_admitted_payload_bytes: encoded.len(),
|
||||
max_admitted_payload_bytes_per_session: encoded.len(),
|
||||
max_snapshot_response_bytes: encoded.len(),
|
||||
..Default::default()
|
||||
};
|
||||
let mut budget_server = server(options, clock, sink.clone(), Source::default())?;
|
||||
let target = budget_server.local_addr()?;
|
||||
let mut first = client(target, 111)?;
|
||||
let mut second = client(target, 112)?;
|
||||
connect(&mut budget_server, &mut [&mut first, &mut second])?;
|
||||
send(&mut first, &message)?;
|
||||
budget_server.poll_once()?;
|
||||
send(&mut second, &message)?;
|
||||
budget_server.poll_once()?;
|
||||
assert_eq!(sink.0.lock().unwrap().receipts.len(), 1);
|
||||
|
||||
let oversized = Source::documents(vec![document("oversized", vec![8; 512])]);
|
||||
let options = CultMeshRudpDocumentServerOptions {
|
||||
max_snapshot_response_bytes: 128,
|
||||
..Default::default()
|
||||
};
|
||||
let mut snapshot_server = server(options, Clock::new(56_000), Sink::default(), oversized)?;
|
||||
let mut snapshot_client = client(snapshot_server.local_addr()?, 113)?;
|
||||
connect(&mut snapshot_server, &mut [&mut snapshot_client])?;
|
||||
let receipt = send_reliable(
|
||||
&mut snapshot_client,
|
||||
&CultNetMessage::SnapshotRequest {
|
||||
message_id: "too-large".into(),
|
||||
schema_ids: None,
|
||||
record_keys: None,
|
||||
},
|
||||
)?;
|
||||
let CultMeshRudpPollOutcome::ApplicationRejected(rejection) = snapshot_server.poll_once()?
|
||||
else {
|
||||
panic!("oversized snapshot must reject only its session");
|
||||
};
|
||||
assert_eq!(
|
||||
rejection.operation,
|
||||
CultMeshRudpApplicationOperation::SnapshotRequest
|
||||
);
|
||||
assert_eq!(rejection.message_id, "too-large");
|
||||
assert!(rejection.reason.contains("snapshot response is"));
|
||||
assert_eq!(snapshot_server.session_count(), 0);
|
||||
snapshot_client.receive_once()?;
|
||||
assert_eq!(
|
||||
snapshot_client.reliable_send_status(&receipt),
|
||||
CultNetRudpReliableSendStatus::Pending
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_cap_and_expiry_use_monotonic_time() -> Result<()> {
|
||||
let clock = Clock::new(60_000);
|
||||
let options = CultMeshRudpDocumentServerOptions {
|
||||
max_sessions: 1,
|
||||
session_idle_timeout: Duration::from_secs(1),
|
||||
session_max_lifetime: Duration::from_millis(100),
|
||||
..Default::default()
|
||||
};
|
||||
let mut server = server(options, clock.clone(), Sink::default(), Source::default())?;
|
||||
let target = server.local_addr()?;
|
||||
let mut admitted = client(target, 1)?;
|
||||
connect(&mut server, &mut [&mut admitted])?;
|
||||
let mut rejected = client(target, 1)?;
|
||||
rejected.connect(Vec::new())?;
|
||||
server.poll_once()?;
|
||||
assert_eq!(server.session_count(), 1);
|
||||
assert!(!rejected.connected());
|
||||
|
||||
clock.set_unix(1);
|
||||
clock.set_monotonic(60_101);
|
||||
assert_eq!(server.maintain()?.sessions_expired, 1);
|
||||
assert_eq!(server.session_count(), 0);
|
||||
Ok(())
|
||||
}
|
||||
Loading…
Reference in a new issue