cultmesh-rs: an idle timeout and keepalive end a dead session; resubscribe_all handshakes afresh; the live test is ignored until asked for
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
c7aedf5494
commit
20004e91e2
5 changed files with 202 additions and 58 deletions
|
|
@ -1045,7 +1045,12 @@ fn connect_rudp_client(
|
|||
thread::sleep(poll_interval);
|
||||
}
|
||||
if !client.connected() {
|
||||
anyhow::bail!("timed out connecting CultMesh RUDP client {runtime_id} to {target}");
|
||||
let hint = if connection_id.is_none() {
|
||||
"; a peer that serves one fixed RUDP connection id (the default C# RudpCultNetSchemaServer serves 0x43554c54) is reached by naming it in connection_id"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
anyhow::bail!("timed out connecting CultMesh RUDP client {runtime_id} to {target}{hint}");
|
||||
}
|
||||
Ok(client)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,7 +27,7 @@ use std::sync::atomic::{AtomicUsize, Ordering};
|
|||
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender, TryRecvError};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::thread::{self, JoinHandle};
|
||||
use std::time::Duration;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// How a subscription client reaches its peer.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
|
|
@ -40,11 +40,18 @@ pub struct CultMeshRudpSubscriptionOptions {
|
|||
pub poll_interval: Duration,
|
||||
pub resend_delay_ms: u64,
|
||||
/// The RUDP connection id every packet carries. `None` picks a fresh one per connection, which a CultMesh
|
||||
/// catalog adopts; a peer that serves one fixed id (the C# `RudpCultNetSchemaServer` serves `0x43554c54` unless
|
||||
/// configured) is reached by naming it.
|
||||
/// catalog adopts; a peer that serves one fixed id is reached only by naming it. The default C#
|
||||
/// `RudpCultNetSchemaServer` serves `0x43554c54`, so against it `None` times out connecting (the error says so).
|
||||
pub connection_id: Option<u32>,
|
||||
/// The most documents and changes that may sit undrained before the subscription faults.
|
||||
pub max_undrained: usize,
|
||||
/// A ping goes to the peer this often while the session is quiet, so a live peer's pong keeps the idle clock
|
||||
/// reset. The C# transport offers `Ping` but never sends one itself; this client does.
|
||||
pub keepalive_interval: Duration,
|
||||
/// A session in which no packet arrives for this long ends as `Disconnected`, and `resubscribe_all` opens a
|
||||
/// fresh one. The C# transport's `CheckTimeout(timeoutMs)` is the same rule, but its caller must drive it and
|
||||
/// no default exists there; this one is stated here.
|
||||
pub idle_timeout: Duration,
|
||||
/// The most documents and changes that may sit undrained before the subscription faults. A single snapshot
|
||||
/// larger than this always faults, however promptly it is drained.
|
||||
}
|
||||
|
||||
impl CultMeshRudpSubscriptionOptions {
|
||||
|
|
@ -54,6 +61,8 @@ impl CultMeshRudpSubscriptionOptions {
|
|||
runtime_id: runtime_id.into(),
|
||||
connect_timeout: Duration::from_secs(5),
|
||||
poll_interval: Duration::from_millis(5),
|
||||
keepalive_interval: Duration::from_secs(2),
|
||||
idle_timeout: Duration::from_secs(10),
|
||||
resend_delay_ms: 50,
|
||||
connection_id: None,
|
||||
max_undrained: 1_000_000,
|
||||
|
|
@ -111,6 +120,7 @@ impl CultMeshRudpSubscriptionClient {
|
|||
subscriptions: BTreeMap::new(),
|
||||
receipts: Vec::new(),
|
||||
epoch: super::fresh_rudp_connection_epoch(),
|
||||
last_ping: Instant::now(),
|
||||
sent: 0,
|
||||
commands: command_rx,
|
||||
events: event_tx,
|
||||
|
|
@ -189,6 +199,7 @@ struct Pump {
|
|||
subscriptions: BTreeMap<String, Selection>,
|
||||
receipts: Vec<CultNetRudpReliableSendReceipt>,
|
||||
epoch: u32,
|
||||
last_ping: Instant,
|
||||
sent: u64,
|
||||
commands: Receiver<Command>,
|
||||
events: Sender<CultMeshSubscriptionEvent>,
|
||||
|
|
@ -262,9 +273,17 @@ impl Pump {
|
|||
}
|
||||
|
||||
fn resubscribe(&mut self) {
|
||||
// A session that has been silent past the idle timeout is dead, though no goodbye said so: it is not
|
||||
// reused for the resend.
|
||||
if self.session.as_mut().is_some_and(|session| session.check_timeout(idle_ms(&self.options))) {
|
||||
self.session = None;
|
||||
}
|
||||
if self.session.is_none() {
|
||||
match open(&self.options) {
|
||||
Ok(session) => self.session = Some(session),
|
||||
Ok(session) => {
|
||||
self.session = Some(session);
|
||||
self.last_ping = Instant::now();
|
||||
}
|
||||
Err(error) => {
|
||||
let reason = format!("reconnect failed: {error}");
|
||||
return self.push(CultMeshSubscriptionEvent::Disconnected { reason });
|
||||
|
|
@ -297,6 +316,15 @@ impl Pump {
|
|||
if failure.is_none() {
|
||||
failure = session.disconnect_reason().map(goodbye_text);
|
||||
}
|
||||
if failure.is_none() && self.last_ping.elapsed() >= self.options.keepalive_interval {
|
||||
self.last_ping = Instant::now();
|
||||
if let Err(error) = session.ping(Vec::new()) {
|
||||
failure = Some(error.to_string());
|
||||
}
|
||||
}
|
||||
if failure.is_none() && session.check_timeout(idle_ms(&self.options)) {
|
||||
failure = Some(format!("no packet from the peer for {:?}", self.options.idle_timeout));
|
||||
}
|
||||
for frame in frames {
|
||||
if frame.channel_id == "schema" {
|
||||
self.receive(&frame.payload);
|
||||
|
|
@ -399,6 +427,10 @@ impl Pump {
|
|||
}
|
||||
}
|
||||
|
||||
fn idle_ms(options: &CultMeshRudpSubscriptionOptions) -> u64 {
|
||||
options.idle_timeout.as_millis() as u64
|
||||
}
|
||||
|
||||
fn goodbye_text(reason: &[u8]) -> String {
|
||||
let text: String = String::from_utf8_lossy(reason).chars().take(REASON_CHARS).collect();
|
||||
format!("the peer ended the session: {text}")
|
||||
|
|
|
|||
|
|
@ -17,6 +17,8 @@ enum PeerCommand {
|
|||
Send(Vec<u8>),
|
||||
/// Ends the session and waits for a new Connect.
|
||||
Disconnect,
|
||||
/// Reads nothing and answers nothing (no pong, no ack) until `Disconnect`: a peer that died without a goodbye.
|
||||
Stall,
|
||||
Stop,
|
||||
}
|
||||
|
||||
|
|
@ -47,6 +49,10 @@ impl Peer {
|
|||
self.commands.send(PeerCommand::Send(payload)).unwrap();
|
||||
}
|
||||
|
||||
fn stall(&self) {
|
||||
self.commands.send(PeerCommand::Stall).unwrap();
|
||||
}
|
||||
|
||||
fn disconnect(&self) {
|
||||
self.commands.send(PeerCommand::Disconnect).unwrap();
|
||||
}
|
||||
|
|
@ -120,6 +126,13 @@ fn serve(socket: UdpSocket, commands: Receiver<PeerCommand>, received: Sender<Cu
|
|||
session.disconnect(b"scripted-goodbye".to_vec()).unwrap();
|
||||
continue 'sessions;
|
||||
}
|
||||
PeerCommand::Stall => loop {
|
||||
match commands.recv() {
|
||||
Ok(PeerCommand::Disconnect) => continue 'sessions,
|
||||
Ok(PeerCommand::Stop) | Err(_) => return,
|
||||
Ok(_) => {}
|
||||
}
|
||||
},
|
||||
PeerCommand::Stop => return,
|
||||
}
|
||||
}
|
||||
|
|
@ -464,60 +477,150 @@ fn what_the_caller_leaves_undrained_is_bounded_and_past_it_the_subscription_faul
|
|||
assert!(matches!(&drain_events(&client, 1)[0], CultMeshSubscriptionEvent::Subscription(SubscriptionEvent::Snapshot { .. })));
|
||||
}
|
||||
|
||||
/// Needs `dotnet` and a built CultLib: `CULTLIB_CS_SUBSCRIPTION_PEER=1`. The C# `rudp-subscription-serve` mode of the
|
||||
/// interop peer serves a `CultNetDatabase` over RUDP and, once the first subscribe is answered, commits a record
|
||||
/// and then two records in one commit.
|
||||
#[test]
|
||||
fn live_csharp_subscription() {
|
||||
if std::env::var_os("CULTLIB_CS_SUBSCRIPTION_PEER").is_none() {
|
||||
return;
|
||||
}
|
||||
use std::io::{BufRead, BufReader};
|
||||
use std::process::{Command, Stdio};
|
||||
let project = concat!(env!("CARGO_MANIFEST_DIR"), "/../../tests/GameCult.Networking.InteropPeer");
|
||||
let mut peer = Command::new("dotnet")
|
||||
.args(["run", "--project", project, "-c", "Release", "--", "rudp-subscription-serve"])
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.spawn()
|
||||
.expect("dotnet runs the interop peer");
|
||||
struct Kill(std::process::Child);
|
||||
impl Drop for Kill {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.0.kill();
|
||||
let _ = self.0.wait();
|
||||
struct Csharp {
|
||||
child: std::process::Child,
|
||||
port: u16,
|
||||
}
|
||||
|
||||
impl Csharp {
|
||||
/// The interop peer, built once and run directly (not through `dotnet run`, whose host would outlive a kill of
|
||||
/// it), in its `rudp-subscription-serve` mode. `port` None binds any port.
|
||||
fn start(port: Option<u16>) -> Self {
|
||||
use std::io::{BufRead, BufReader};
|
||||
use std::process::{Command, Stdio};
|
||||
let project = concat!(env!("CARGO_MANIFEST_DIR"), "/../../tests/GameCult.Networking.InteropPeer");
|
||||
let build = Command::new("dotnet")
|
||||
.args(["build", project, "-c", "Release", "-v", "q", "--nologo"])
|
||||
.status()
|
||||
.expect("dotnet builds the interop peer");
|
||||
assert!(build.success());
|
||||
let dll = format!("{project}/bin/Release/net10.0/GameCult.Networking.InteropPeer.dll");
|
||||
let mut command = Command::new("dotnet");
|
||||
command.args([dll.as_str(), "rudp-subscription-serve"]);
|
||||
if let Some(port) = port {
|
||||
command.args(["--port", &port.to_string()]);
|
||||
}
|
||||
let mut child = command.stdin(Stdio::piped()).stdout(Stdio::piped()).spawn().expect("dotnet runs the interop peer");
|
||||
let mut lines = BufReader::new(child.stdout.take().unwrap()).lines();
|
||||
let port = loop {
|
||||
let line = lines.next().expect("the peer announces its port").unwrap();
|
||||
if let Some(rest) = line.strip_prefix("listening ") {
|
||||
break rest.trim().parse::<u16>().unwrap();
|
||||
}
|
||||
};
|
||||
Self { child, port }
|
||||
}
|
||||
let stdout = peer.stdout.take().unwrap();
|
||||
let peer = Kill(peer);
|
||||
let mut lines = BufReader::new(stdout).lines();
|
||||
let port = loop {
|
||||
let line = lines.next().expect("the peer announces its port").unwrap();
|
||||
if let Some(rest) = line.strip_prefix("listening ") {
|
||||
break rest.trim().parse::<u16>().unwrap();
|
||||
}
|
||||
};
|
||||
let mut options = CultMeshRudpSubscriptionOptions::new(SocketAddr::from(([127, 0, 0, 1], port)), "rust-subscriber");
|
||||
options.connect_timeout = Duration::from_secs(10);
|
||||
options.connection_id = Some(0x4355_4c54);
|
||||
let client = CultMeshRudpSubscriptionClient::connect(options).unwrap();
|
||||
client.subscribe("live", Selection::default()).unwrap();
|
||||
// snapshot (empty), then the peer's scripted commits: one record, then two records in one commit.
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
let mut events = Vec::new();
|
||||
while Instant::now() < deadline && !events.iter().any(|e| matches!(e, CultMeshSubscriptionEvent::Subscription(SubscriptionEvent::Commit { changes, .. }) if changes.len() == 2)) {
|
||||
events.extend(client.try_drain());
|
||||
thread::sleep(Duration::from_millis(10));
|
||||
|
||||
/// Ends the process with no goodbye on the wire.
|
||||
fn kill(&mut self) {
|
||||
let _ = self.child.kill();
|
||||
let _ = self.child.wait();
|
||||
}
|
||||
assert!(matches!(&events[0], CultMeshSubscriptionEvent::Subscription(SubscriptionEvent::Snapshot { subscription_id, .. }) if subscription_id == "live"), "{events:?}");
|
||||
let commits: Vec<_> = events
|
||||
}
|
||||
|
||||
impl Drop for Csharp {
|
||||
fn drop(&mut self) {
|
||||
self.kill();
|
||||
}
|
||||
}
|
||||
|
||||
fn is_snapshot(event: &CultMeshSubscriptionEvent) -> bool {
|
||||
matches!(event, CultMeshSubscriptionEvent::Subscription(SubscriptionEvent::Snapshot { subscription_id, .. }) if subscription_id == "live")
|
||||
}
|
||||
|
||||
fn commit_sizes(events: &[CultMeshSubscriptionEvent]) -> Vec<usize> {
|
||||
events
|
||||
.iter()
|
||||
.filter_map(|e| match e {
|
||||
CultMeshSubscriptionEvent::Subscription(SubscriptionEvent::Commit { changes, .. }) => Some(changes.len()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(commits, [1, 2], "{events:?}");
|
||||
drop(client);
|
||||
drop(peer);
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Drains until `done` holds for what has arrived, or fails after `seconds`.
|
||||
fn drain_until(
|
||||
client: &CultMeshRudpSubscriptionClient,
|
||||
seconds: u64,
|
||||
done: impl Fn(&[CultMeshSubscriptionEvent]) -> bool,
|
||||
) -> Vec<CultMeshSubscriptionEvent> {
|
||||
let deadline = Instant::now() + Duration::from_secs(seconds);
|
||||
let mut events = Vec::new();
|
||||
while Instant::now() < deadline && !done(&events) {
|
||||
events.extend(client.try_drain());
|
||||
thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
assert!(done(&events), "{events:?}");
|
||||
events
|
||||
}
|
||||
|
||||
/// A real C# subscription server over RUDP: the snapshot and a two-change commit arrive; the server then dies with no
|
||||
/// goodbye, the client says `Disconnected` within its idle timeout, and once a server is back on the same port
|
||||
/// `resubscribe_all` handshakes afresh and the snapshot arrives again.
|
||||
#[test]
|
||||
#[ignore = "needs dotnet and the C# interop peer; run with `cargo test --test rudp_subscription -- --ignored`"]
|
||||
fn live_csharp_subscription() {
|
||||
let mut csharp = Csharp::start(None);
|
||||
let port = csharp.port;
|
||||
let mut options = CultMeshRudpSubscriptionOptions::new(SocketAddr::from(([127, 0, 0, 1], port)), "rust-subscriber");
|
||||
options.connect_timeout = Duration::from_secs(10);
|
||||
options.connection_id = Some(0x4355_4c54);
|
||||
options.keepalive_interval = Duration::from_millis(200);
|
||||
options.idle_timeout = Duration::from_secs(1);
|
||||
let client = CultMeshRudpSubscriptionClient::connect(options).unwrap();
|
||||
client.subscribe("live", Selection::default()).unwrap();
|
||||
let events = drain_until(&client, 30, |events| commit_sizes(events).contains(&2));
|
||||
assert!(is_snapshot(&events[0]), "{events:?}");
|
||||
assert_eq!(commit_sizes(&events), [1, 2], "{events:?}");
|
||||
|
||||
csharp.kill();
|
||||
let started = Instant::now();
|
||||
let events = drain_until(&client, 10, |events| !events.is_empty());
|
||||
assert!(matches!(&events[0], CultMeshSubscriptionEvent::Disconnected { reason } if reason.contains("no packet")), "{events:?}");
|
||||
assert!(started.elapsed() < Duration::from_secs(5), "{:?}", started.elapsed());
|
||||
quiet(&client);
|
||||
|
||||
let _restarted = Csharp::start(Some(port));
|
||||
client.resubscribe_all().unwrap();
|
||||
let events = drain_until(&client, 30, |events| commit_sizes(events).contains(&2));
|
||||
assert!(is_snapshot(&events[0]), "{events:?}");
|
||||
}
|
||||
|
||||
/// A peer that goes silent without a goodbye is a `Disconnected` after the idle timeout, and `resubscribe_all` then
|
||||
/// handshakes afresh.
|
||||
#[test]
|
||||
fn a_silent_peer_is_disconnected_after_the_idle_timeout_and_resubscribe_all_handshakes_afresh() {
|
||||
let peer = Peer::start();
|
||||
let mut options = options(&peer);
|
||||
options.keepalive_interval = Duration::from_millis(50);
|
||||
options.idle_timeout = Duration::from_millis(400);
|
||||
let client = CultMeshRudpSubscriptionClient::connect(options).unwrap();
|
||||
client.subscribe("sub-1", vector_selection()).unwrap();
|
||||
peer.subscribe_id();
|
||||
peer.stall();
|
||||
let started = Instant::now();
|
||||
let events = drain_events(&client, 1);
|
||||
assert!(matches!(&events[0], CultMeshSubscriptionEvent::Disconnected { reason } if reason.contains("no packet")), "{events:?}");
|
||||
assert!(started.elapsed() >= Duration::from_millis(300), "not before the idle timeout: {:?}", started.elapsed());
|
||||
quiet(&client);
|
||||
peer.disconnect();
|
||||
client.resubscribe_all().unwrap();
|
||||
let (message_id, subscription_id) = peer.subscribe_id();
|
||||
assert_eq!(subscription_id, "sub-1");
|
||||
peer.send(&snapshot_answering(&message_id));
|
||||
assert!(matches!(&drain_events(&client, 1)[0], CultMeshSubscriptionEvent::Subscription(SubscriptionEvent::Snapshot { .. })));
|
||||
}
|
||||
|
||||
/// A live peer's pongs keep a quiet session open past the idle timeout.
|
||||
#[test]
|
||||
fn a_quiet_but_live_peer_is_not_disconnected() {
|
||||
let peer = Peer::start();
|
||||
let mut options = options(&peer);
|
||||
options.keepalive_interval = Duration::from_millis(50);
|
||||
options.idle_timeout = Duration::from_millis(400);
|
||||
let client = CultMeshRudpSubscriptionClient::connect(options).unwrap();
|
||||
client.subscribe("sub-1", vector_selection()).unwrap();
|
||||
peer.subscribe_id();
|
||||
thread::sleep(Duration::from_millis(1200));
|
||||
assert_eq!(client.try_drain(), vec![]);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -58,7 +58,8 @@ static async Task<int> ProgramMainAsync(string[] args)
|
|||
return 0;
|
||||
case "rudp-subscription-serve":
|
||||
await GameCult.Networking.InteropPeer.SubscriptionHarness.ServeAsync(
|
||||
options.TryGetValue("connection-id", out var connectionId) ? uint.Parse(connectionId, CultureInfo.InvariantCulture) : 0x43554c54);
|
||||
options.TryGetValue("connection-id", out var connectionId) ? uint.Parse(connectionId, CultureInfo.InvariantCulture) : 0x43554c54,
|
||||
options.TryGetValue("port", out var port) ? int.Parse(port, CultureInfo.InvariantCulture) : 0);
|
||||
return 0;
|
||||
case "receipt-relay":
|
||||
await GameCult.Networking.InteropPeer.ReceiptHarness.RelayAsync(int.Parse(options["port"], CultureInfo.InvariantCulture));
|
||||
|
|
|
|||
|
|
@ -21,14 +21,17 @@ namespace GameCult.Networking.InteropPeer
|
|||
{
|
||||
public const string SchemaId = "subscription.interop_note.v1";
|
||||
|
||||
// stdout: `listening <port>`; runs until stdin closes.
|
||||
public static async Task ServeAsync(uint connectionId)
|
||||
// `--port N` binds that port (0 or absent: any). stdout: `listening <port>`; runs until stdin closes.
|
||||
public static async Task ServeAsync(uint connectionId, int port)
|
||||
{
|
||||
var cache = new CultCache();
|
||||
cache.Registry.GetRequired<SubscriptionInteropNote>();
|
||||
using var database = new CultNetDatabase(cache);
|
||||
var socket = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
|
||||
socket.Bind(new System.Net.IPEndPoint(System.Net.IPAddress.Loopback, port));
|
||||
using var server = new RudpCultNetSchemaServer(new RudpCultNetSchemaServerOptions
|
||||
{
|
||||
Socket = socket,
|
||||
RuntimeId = "csharp-subscription-peer",
|
||||
ConnectionId = connectionId
|
||||
});
|
||||
|
|
|
|||
Loading…
Reference in a new issue