cultmesh-rs: a non-blocking subscription client with dead-peer detection (#194)
This commit is contained in:
parent
31e8dbdd50
commit
437f5e7b76
7 changed files with 1224 additions and 8 deletions
|
|
@ -25,9 +25,11 @@ use std::time::Duration;
|
|||
use std::time::Instant;
|
||||
|
||||
mod rudp_document_server;
|
||||
mod rudp_subscription;
|
||||
pub mod authority;
|
||||
|
||||
pub use rudp_document_server::*;
|
||||
pub use rudp_subscription::*;
|
||||
|
||||
pub const CULTMESH_RUDP_DOCUMENT_CATALOG_CONNECTION_ID: u32 = 0x0d1d_0002;
|
||||
|
||||
|
|
@ -816,6 +818,7 @@ pub fn request_raw_snapshot_from_rudp_catalog(
|
|||
options.poll_interval,
|
||||
options.resend_delay_ms,
|
||||
"cultmesh-rudp-snapshot-client",
|
||||
None,
|
||||
)?;
|
||||
|
||||
let request = cultnet_rs::CultNetMessage::SnapshotRequest {
|
||||
|
|
@ -940,6 +943,7 @@ pub fn publish_cultnet_messages_to_rudp_catalog(
|
|||
options.poll_interval,
|
||||
options.resend_delay_ms,
|
||||
"cultmesh-rudp-document-publisher",
|
||||
None,
|
||||
)?;
|
||||
|
||||
let mut receipts = Vec::with_capacity(messages.len());
|
||||
|
|
@ -1007,6 +1011,7 @@ fn connect_rudp_client(
|
|||
poll_interval: Duration,
|
||||
resend_delay_ms: u64,
|
||||
transport_id: &str,
|
||||
connection_id: Option<u32>,
|
||||
) -> Result<CultNetRudpSocketTransportConnection> {
|
||||
let bind_addr = if target.is_ipv4() {
|
||||
SocketAddr::from(([0, 0, 0, 0], 0))
|
||||
|
|
@ -1022,7 +1027,7 @@ fn connect_rudp_client(
|
|||
socket,
|
||||
mode: cultnet_rs::CultNetRudpSocketMode::Client,
|
||||
remote_addr: Some(target),
|
||||
connection_id: fresh_rudp_connection_epoch(),
|
||||
connection_id: connection_id.unwrap_or_else(fresh_rudp_connection_epoch),
|
||||
initial_sequence: None,
|
||||
resend_delay_ms,
|
||||
transport_id: Some(transport_id.to_string()),
|
||||
|
|
@ -1040,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)
|
||||
}
|
||||
|
|
|
|||
438
packages/cultmesh-rs/src/rudp_subscription.rs
Normal file
438
packages/cultmesh-rs/src/rudp_subscription.rs
Normal file
|
|
@ -0,0 +1,438 @@
|
|||
//! A live `cultnet.database_subscribe.v1` subscription over RUDP, for a caller that cannot block on the network.
|
||||
//!
|
||||
//! One background thread owns the RUDP session and the cultnet-rs [`SubscriptionAssembler`]; the caller's handle
|
||||
//! only queues commands and drains events. RUDP acknowledgements and resends keep their cadence while the caller is
|
||||
//! idle, which is why this is a thread and not a method the caller must tick.
|
||||
//!
|
||||
//! Lifetime: dropping the client unsubscribes each live id, disconnects and joins the thread, so no thread outlives
|
||||
//! its handle. A closed or failed session is an event ([`CultMeshSubscriptionEvent::Disconnected`]), never a hang;
|
||||
//! after it the thread reads nothing and waits for `resubscribe_all` or the drop.
|
||||
//!
|
||||
//! Bounds: the assembler bounds what it holds of incomplete commits and faults the connection past that. What the
|
||||
//! caller has not drained is bounded too, by [`CultMeshRudpSubscriptionOptions::max_undrained`], counted in
|
||||
//! documents and changes: a caller that stops draining past it gets a [`SubscriptionEvent::Faulted`], delivery
|
||||
//! stops, and [`resubscribe_all`](CultMeshRudpSubscriptionClient::resubscribe_all) starts over from fresh
|
||||
//! snapshots. Memory never grows without bound.
|
||||
|
||||
use super::{connect_rudp_client, recognised_refusal};
|
||||
use anyhow::{Result, anyhow};
|
||||
use cultnet_rs::{
|
||||
CultNetMessage, CultNetRudpReliableSendReceipt, CultNetRudpReliableSendStatus, CultNetRudpSocketTransportConnection,
|
||||
CultNetWireContract, Selection, SubscriptionAssembler, SubscriptionEvent, decode_cultnet_message_from_slice,
|
||||
encode_cultnet_message_to_vec,
|
||||
};
|
||||
use std::collections::BTreeMap;
|
||||
use std::net::SocketAddr;
|
||||
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, Instant};
|
||||
|
||||
/// How a subscription client reaches its peer.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct CultMeshRudpSubscriptionOptions {
|
||||
pub target: SocketAddr,
|
||||
pub runtime_id: String,
|
||||
/// How long `connect` (and a reconnecting `resubscribe_all`) waits for the peer to accept.
|
||||
pub connect_timeout: Duration,
|
||||
/// The pump's cadence: how long it waits on the socket, and so how soon it sees a command.
|
||||
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 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>,
|
||||
/// 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.
|
||||
pub max_undrained: usize,
|
||||
}
|
||||
|
||||
impl CultMeshRudpSubscriptionOptions {
|
||||
pub fn new(target: SocketAddr, runtime_id: impl Into<String>) -> Self {
|
||||
Self {
|
||||
target,
|
||||
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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a subscription client delivers: the assembler's events, and the end of the session.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum CultMeshSubscriptionEvent {
|
||||
Subscription(SubscriptionEvent),
|
||||
/// The session ended or failed. Delivered once; nothing follows until `resubscribe_all` reconnects.
|
||||
Disconnected { reason: String },
|
||||
}
|
||||
|
||||
impl CultMeshSubscriptionEvent {
|
||||
fn weight(&self) -> usize {
|
||||
match self {
|
||||
Self::Subscription(SubscriptionEvent::Snapshot { documents, .. }) => documents.len().max(1),
|
||||
Self::Subscription(SubscriptionEvent::Commit { changes, .. }) => changes.len().max(1),
|
||||
_ => 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum Command {
|
||||
Subscribe(String, Selection),
|
||||
Unsubscribe(String),
|
||||
Resubscribe,
|
||||
Close,
|
||||
}
|
||||
|
||||
/// A live subscription connection. Methods never block on the network.
|
||||
pub struct CultMeshRudpSubscriptionClient {
|
||||
commands: Sender<Command>,
|
||||
events: Mutex<Receiver<CultMeshSubscriptionEvent>>,
|
||||
undrained: Arc<AtomicUsize>,
|
||||
pump: Option<JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl CultMeshRudpSubscriptionClient {
|
||||
/// Connects (blocking up to `connect_timeout`) and starts the pump thread.
|
||||
pub fn connect(options: CultMeshRudpSubscriptionOptions) -> Result<Self> {
|
||||
if options.runtime_id.trim().is_empty() {
|
||||
return Err(anyhow!("runtime_id must be non-empty"));
|
||||
}
|
||||
let session = open(&options)?;
|
||||
let (commands, command_rx) = mpsc::channel();
|
||||
let (event_tx, events) = mpsc::channel();
|
||||
let undrained = Arc::new(AtomicUsize::new(0));
|
||||
let pump = Pump {
|
||||
options,
|
||||
session: Some(session),
|
||||
assembler: SubscriptionAssembler::new(),
|
||||
subscriptions: BTreeMap::new(),
|
||||
receipts: Vec::new(),
|
||||
epoch: super::fresh_rudp_connection_epoch(),
|
||||
last_ping: Instant::now(),
|
||||
sent: 0,
|
||||
commands: command_rx,
|
||||
events: event_tx,
|
||||
undrained: undrained.clone(),
|
||||
};
|
||||
let pump = thread::Builder::new()
|
||||
.name("cultmesh-rudp-subscription".into())
|
||||
.spawn(move || pump.run())?;
|
||||
Ok(Self { commands, events: Mutex::new(events), undrained, pump: Some(pump) })
|
||||
}
|
||||
|
||||
/// Queues a subscribe with a snapshot and returns; the snapshot arrives as an event. Subscribing an id that is
|
||||
/// live replaces it. While the session is disconnected or faulted the subscription is kept and sent by
|
||||
/// `resubscribe_all`.
|
||||
pub fn subscribe(&self, subscription_id: impl Into<String>, selection: Selection) -> Result<()> {
|
||||
self.send(Command::Subscribe(subscription_id.into(), selection))
|
||||
}
|
||||
|
||||
/// Queues an unsubscribe and forgets the subscription, so `resubscribe_all` no longer resends it.
|
||||
pub fn unsubscribe(&self, subscription_id: impl Into<String>) -> Result<()> {
|
||||
self.send(Command::Unsubscribe(subscription_id.into()))
|
||||
}
|
||||
|
||||
/// After a `Faulted` or `Disconnected` event: reconnects if the session ended, starts the assembler over, and
|
||||
/// resends every subscription with a fresh message id. Each is answered by a new snapshot, which replaces what
|
||||
/// the consumer held for that id.
|
||||
pub fn resubscribe_all(&self) -> Result<()> {
|
||||
self.send(Command::Resubscribe)
|
||||
}
|
||||
|
||||
/// Everything delivered since the last call, in order. Never blocks.
|
||||
pub fn try_drain(&self) -> Vec<CultMeshSubscriptionEvent> {
|
||||
let events = self.events.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
let drained: Vec<_> = events.try_iter().collect();
|
||||
self.undrained.fetch_sub(drained.iter().map(CultMeshSubscriptionEvent::weight).sum(), Ordering::SeqCst);
|
||||
drained
|
||||
}
|
||||
|
||||
fn send(&self, command: Command) -> Result<()> {
|
||||
self.commands.send(command).map_err(|_| anyhow!("the subscription pump has stopped"))
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for CultMeshRudpSubscriptionClient {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.commands.send(Command::Close);
|
||||
if let Some(pump) = self.pump.take() {
|
||||
let _ = pump.join();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn open(options: &CultMeshRudpSubscriptionOptions) -> Result<CultNetRudpSocketTransportConnection> {
|
||||
connect_rudp_client(
|
||||
options.target,
|
||||
&options.runtime_id,
|
||||
options.connect_timeout,
|
||||
options.poll_interval,
|
||||
options.resend_delay_ms,
|
||||
"cultmesh-rudp-subscription-client",
|
||||
options.connection_id,
|
||||
)
|
||||
}
|
||||
|
||||
/// The most frames one pump pass reads before it looks at commands again.
|
||||
const FRAMES_PER_PASS: usize = 64;
|
||||
/// The longest peer-supplied goodbye text an event carries.
|
||||
const REASON_CHARS: usize = 200;
|
||||
|
||||
struct Pump {
|
||||
options: CultMeshRudpSubscriptionOptions,
|
||||
/// `None` after the session ended: the pump reads nothing and waits for a command.
|
||||
session: Option<CultNetRudpSocketTransportConnection>,
|
||||
assembler: SubscriptionAssembler,
|
||||
/// What `resubscribe_all` resends. The assembler owns what is live; it holds no selections.
|
||||
subscriptions: BTreeMap<String, Selection>,
|
||||
receipts: Vec<CultNetRudpReliableSendReceipt>,
|
||||
epoch: u32,
|
||||
last_ping: Instant,
|
||||
sent: u64,
|
||||
commands: Receiver<Command>,
|
||||
events: Sender<CultMeshSubscriptionEvent>,
|
||||
undrained: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
impl Pump {
|
||||
fn run(mut self) {
|
||||
loop {
|
||||
let command = if self.session.is_some() {
|
||||
match self.commands.try_recv() {
|
||||
Ok(command) => Some(command),
|
||||
Err(TryRecvError::Empty) => None,
|
||||
Err(TryRecvError::Disconnected) => Some(Command::Close),
|
||||
}
|
||||
} else {
|
||||
match self.commands.recv_timeout(Duration::from_secs(3600)) {
|
||||
Ok(command) => Some(command),
|
||||
Err(RecvTimeoutError::Timeout) => None,
|
||||
Err(RecvTimeoutError::Disconnected) => Some(Command::Close),
|
||||
}
|
||||
};
|
||||
match command {
|
||||
Some(Command::Close) => return self.close(),
|
||||
Some(command) => self.apply(command),
|
||||
None => self.service(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn apply(&mut self, command: Command) {
|
||||
match command {
|
||||
Command::Subscribe(id, selection) => {
|
||||
if self.subscriptions.insert(id.clone(), selection).is_some() {
|
||||
self.assembler.end(&id);
|
||||
}
|
||||
self.begin(&id);
|
||||
}
|
||||
Command::Unsubscribe(id) => {
|
||||
self.subscriptions.remove(&id);
|
||||
self.assembler.end(&id);
|
||||
let message = CultNetMessage::DatabaseUnsubscribe { message_id: self.next_message_id(), subscription_id: id };
|
||||
self.transmit(&message);
|
||||
}
|
||||
Command::Resubscribe => self.resubscribe(),
|
||||
Command::Close => unreachable!("handled by the loop"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The one subscribe path: the first subscribe and every resubscribe send through here, each with a fresh
|
||||
/// message id. A faulted assembler refuses, and the subscription waits for `resubscribe_all`.
|
||||
fn begin(&mut self, id: &str) {
|
||||
let Some(selection) = self.subscriptions.get(id).cloned() else { return };
|
||||
if self.session.is_none() {
|
||||
return;
|
||||
}
|
||||
let message_id = self.next_message_id();
|
||||
if self.assembler.begin(id, &message_id).is_err() {
|
||||
return;
|
||||
}
|
||||
let message = CultNetMessage::DatabaseSubscribeV1 {
|
||||
message_id,
|
||||
subscription_id: id.to_owned(),
|
||||
selection,
|
||||
include_snapshot: true,
|
||||
consumer_runtime_id: Some(self.options.runtime_id.clone()),
|
||||
body_ids: None,
|
||||
supported_body_transports: None,
|
||||
};
|
||||
self.transmit(&message);
|
||||
}
|
||||
|
||||
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);
|
||||
self.last_ping = Instant::now();
|
||||
}
|
||||
Err(error) => {
|
||||
let reason = format!("reconnect failed: {error}");
|
||||
return self.push(CultMeshSubscriptionEvent::Disconnected { reason });
|
||||
}
|
||||
}
|
||||
}
|
||||
self.assembler.reset();
|
||||
self.receipts.clear();
|
||||
let ids: Vec<_> = self.subscriptions.keys().cloned().collect();
|
||||
for id in ids {
|
||||
self.begin(&id);
|
||||
}
|
||||
}
|
||||
|
||||
/// One pass over the session: resends, frames, receipts, goodbye.
|
||||
fn service(&mut self) {
|
||||
let Some(session) = self.session.as_mut() else { return };
|
||||
let mut frames = Vec::new();
|
||||
let mut failure = None;
|
||||
if let Err(error) = session.poll_resends() {
|
||||
failure = Some(error.to_string());
|
||||
}
|
||||
while failure.is_none() && frames.len() < FRAMES_PER_PASS {
|
||||
match session.receive_once() {
|
||||
Ok(Some(frame)) => frames.push(frame),
|
||||
Ok(None) => break,
|
||||
Err(error) => failure = Some(error.to_string()),
|
||||
}
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
if failure.is_none() {
|
||||
failure = self.invalidated();
|
||||
}
|
||||
if let Some(reason) = failure {
|
||||
self.disconnected(reason);
|
||||
}
|
||||
}
|
||||
|
||||
/// A frame that does not decode is the sender's business: dropped, as the transport drops a malformed datagram.
|
||||
fn receive(&mut self, payload: &[u8]) {
|
||||
let Ok(message) = decode_cultnet_message_from_slice(payload, CultNetWireContract::CultNetSchemaV0) else { return };
|
||||
let events = match message {
|
||||
CultNetMessage::Error { error, .. } => self.assembler.refused(None, &recognised_refusal(&error)),
|
||||
CultNetMessage::ErrorV1 { error, message_id, .. } => {
|
||||
self.assembler.refused(message_id.as_deref(), &recognised_refusal(&error))
|
||||
}
|
||||
other => self.assembler.accept(other),
|
||||
};
|
||||
for event in events {
|
||||
self.deliver(event);
|
||||
}
|
||||
}
|
||||
|
||||
/// Past `max_undrained` the event is not queued: the connection faults instead, once, and the consumer
|
||||
/// resubscribes for a snapshot.
|
||||
fn deliver(&mut self, event: SubscriptionEvent) {
|
||||
let event = CultMeshSubscriptionEvent::Subscription(event);
|
||||
let queued = self.undrained.load(Ordering::SeqCst);
|
||||
let fault = matches!(event, CultMeshSubscriptionEvent::Subscription(SubscriptionEvent::Faulted { .. }));
|
||||
if !fault && queued.saturating_add(event.weight()) > self.options.max_undrained {
|
||||
let reason = format!(
|
||||
"the consumer left more than {} documents and changes undrained; drain, then resubscribe",
|
||||
self.options.max_undrained
|
||||
);
|
||||
for fault in self.assembler.latch_fault(reason) {
|
||||
self.push(CultMeshSubscriptionEvent::Subscription(fault));
|
||||
}
|
||||
return;
|
||||
}
|
||||
self.push(event);
|
||||
}
|
||||
|
||||
fn push(&self, event: CultMeshSubscriptionEvent) {
|
||||
self.undrained.fetch_add(event.weight(), Ordering::SeqCst);
|
||||
let _ = self.events.send(event);
|
||||
}
|
||||
|
||||
fn next_message_id(&mut self) -> String {
|
||||
self.sent += 1;
|
||||
format!("{}-{:08x}-{}", self.options.runtime_id, self.epoch, self.sent)
|
||||
}
|
||||
|
||||
/// Sends one reliable frame; a failed send ends the session.
|
||||
fn transmit(&mut self, message: &CultNetMessage) {
|
||||
let Some(session) = self.session.as_mut() else { return };
|
||||
let result = encode_cultnet_message_to_vec(message, CultNetWireContract::CultNetSchemaV0)
|
||||
.and_then(|payload| session.send_reliable("schema", payload));
|
||||
match result {
|
||||
Ok(receipt) => self.receipts.push(receipt),
|
||||
Err(error) => self.disconnected(format!("send failed: {error}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Forgets acknowledged sends; a send the session gave up on is a lost session.
|
||||
fn invalidated(&mut self) -> Option<String> {
|
||||
let session = self.session.as_ref()?;
|
||||
let mut lost = false;
|
||||
self.receipts.retain(|receipt| match session.reliable_send_status(receipt) {
|
||||
CultNetRudpReliableSendStatus::Acknowledged => false,
|
||||
CultNetRudpReliableSendStatus::Invalidated => {
|
||||
lost = true;
|
||||
false
|
||||
}
|
||||
CultNetRudpReliableSendStatus::Pending => true,
|
||||
});
|
||||
lost.then(|| "a reliable send was invalidated".to_owned())
|
||||
}
|
||||
|
||||
fn disconnected(&mut self, reason: String) {
|
||||
if self.session.take().is_some() {
|
||||
self.receipts.clear();
|
||||
self.push(CultMeshSubscriptionEvent::Disconnected { reason });
|
||||
}
|
||||
}
|
||||
|
||||
fn close(&mut self) {
|
||||
let ids: Vec<_> = self.subscriptions.keys().cloned().collect();
|
||||
for id in ids {
|
||||
let message = CultNetMessage::DatabaseUnsubscribe { message_id: self.next_message_id(), subscription_id: id };
|
||||
self.transmit(&message);
|
||||
}
|
||||
if let Some(session) = self.session.as_mut() {
|
||||
let _ = session.disconnect(b"subscription-closed".to_vec());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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}")
|
||||
}
|
||||
633
packages/cultmesh-rs/tests/rudp_subscription.rs
Normal file
633
packages/cultmesh-rs/tests/rudp_subscription.rs
Normal file
|
|
@ -0,0 +1,633 @@
|
|||
//! The RUDP subscription client against a scripted peer (a real RUDP session on a loopback socket that replays the
|
||||
//! C#-written `database-subscription` vector), and against a live C# subscription server when asked to.
|
||||
|
||||
use cultmesh_rs::{CultMeshRudpSubscriptionClient, CultMeshRudpSubscriptionOptions, CultMeshSubscriptionEvent};
|
||||
use cultnet_rs::{
|
||||
Change, CultNetErrorCode, CultNetMessage, CultNetRudpSocketMode, CultNetRudpSocketTransportConnection,
|
||||
CultNetRudpSocketTransportOptions, CultNetWireContract, DatabaseChangeKind, Selection, SubscriptionEvent,
|
||||
decode_cultnet_message_from_slice, decode_rudp_packet, encode_cultnet_message_to_vec,
|
||||
};
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::net::{SocketAddr, UdpSocket};
|
||||
use std::sync::mpsc::{self, Receiver, Sender};
|
||||
use std::thread::{self, JoinHandle};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
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,
|
||||
}
|
||||
|
||||
/// A peer that accepts RUDP connects on a loopback socket and reports every schema message it receives.
|
||||
struct Peer {
|
||||
addr: SocketAddr,
|
||||
commands: Sender<PeerCommand>,
|
||||
received: Receiver<CultNetMessage>,
|
||||
thread: Option<JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl Peer {
|
||||
fn start() -> Self {
|
||||
let socket = UdpSocket::bind("127.0.0.1:0").unwrap();
|
||||
let addr = socket.local_addr().unwrap();
|
||||
let (commands, command_rx) = mpsc::channel();
|
||||
let (received_tx, received) = mpsc::channel();
|
||||
let thread = thread::spawn(move || serve(socket, command_rx, received_tx));
|
||||
Self { addr, commands, received, thread: Some(thread) }
|
||||
}
|
||||
|
||||
fn send(&self, message: &CultNetMessage) {
|
||||
let payload = encode_cultnet_message_to_vec(message, CultNetWireContract::CultNetSchemaV0).unwrap();
|
||||
self.commands.send(PeerCommand::Send(payload)).unwrap();
|
||||
}
|
||||
|
||||
fn send_raw(&self, payload: Vec<u8>) {
|
||||
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();
|
||||
}
|
||||
|
||||
fn next(&self) -> CultNetMessage {
|
||||
self.received.recv_timeout(Duration::from_secs(5)).expect("the peer received a message")
|
||||
}
|
||||
|
||||
fn subscribe_id(&self) -> (String, String) {
|
||||
match self.next() {
|
||||
CultNetMessage::DatabaseSubscribeV1 { message_id, subscription_id, include_snapshot, .. } => {
|
||||
assert!(include_snapshot);
|
||||
(message_id, subscription_id)
|
||||
}
|
||||
other => panic!("expected a subscribe, got {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Peer {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.commands.send(PeerCommand::Stop);
|
||||
if let Some(thread) = self.thread.take() {
|
||||
let _ = thread.join();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn serve(socket: UdpSocket, commands: Receiver<PeerCommand>, received: Sender<CultNetMessage>) {
|
||||
socket.set_read_timeout(Some(Duration::from_millis(2))).unwrap();
|
||||
'sessions: loop {
|
||||
// The client's connection id is its own epoch: read it from the Connect before the session exists.
|
||||
let mut wire = vec![0_u8; 65_535];
|
||||
let (length, _) = loop {
|
||||
match commands.try_recv() {
|
||||
Ok(PeerCommand::Stop) | Err(mpsc::TryRecvError::Disconnected) => return,
|
||||
_ => {}
|
||||
}
|
||||
if let Ok(found) = socket.peek_from(&mut wire) {
|
||||
break found;
|
||||
}
|
||||
};
|
||||
// Only a Connect starts a session; whatever else is waiting (a dead session's pings and resends) is dropped.
|
||||
let packet = match decode_rudp_packet(&wire[..length]) {
|
||||
Ok(packet) if packet.packet_type == cultnet_rs::CultNetRudpPacketType::Connect => packet,
|
||||
_ => {
|
||||
let _ = socket.recv_from(&mut wire);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let mut session = CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions {
|
||||
media_delivery: None,
|
||||
runtime_id: "scripted-peer".into(),
|
||||
socket: socket.try_clone().unwrap(),
|
||||
mode: CultNetRudpSocketMode::Server,
|
||||
remote_addr: None,
|
||||
connection_id: packet.connection_id,
|
||||
initial_sequence: Some(1),
|
||||
resend_delay_ms: 10,
|
||||
transport_id: None,
|
||||
max_payload_bytes: None,
|
||||
max_fragment_bytes: Some(1200),
|
||||
max_pending_reliable_packets: Some(1024),
|
||||
media_reliable_expire_after_ms: None,
|
||||
reconnect_policy: None,
|
||||
})
|
||||
.unwrap();
|
||||
loop {
|
||||
while let Ok(command) = commands.try_recv() {
|
||||
match command {
|
||||
PeerCommand::Send(payload) => {
|
||||
session.send("schema", payload).unwrap();
|
||||
}
|
||||
PeerCommand::Disconnect => {
|
||||
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,
|
||||
}
|
||||
}
|
||||
while let Ok(Some(frame)) = session.receive_once() {
|
||||
if frame.channel_id == "schema" {
|
||||
if let Ok(message) = decode_cultnet_message_from_slice(&frame.payload, CultNetWireContract::CultNetSchemaV0) {
|
||||
let _ = received.send(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
session.poll_resends().unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn options(peer: &Peer) -> CultMeshRudpSubscriptionOptions {
|
||||
let mut options = CultMeshRudpSubscriptionOptions::new(peer.addr, "subscription-test");
|
||||
options.poll_interval = Duration::from_millis(2);
|
||||
options.resend_delay_ms = 10;
|
||||
options
|
||||
}
|
||||
|
||||
/// The C#-written session, one message per entry: subscribe, snapshot, a single change, a two-change commit (two
|
||||
/// messages), a removal.
|
||||
fn session() -> Vec<Vec<u8>> {
|
||||
use serde::Deserialize;
|
||||
let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../tests/vectors/database-subscription/session.msgpack");
|
||||
let bytes = std::fs::read(path).expect("the vector is committed");
|
||||
let mut cursor = std::io::Cursor::new(bytes.as_slice());
|
||||
let mut out = Vec::new();
|
||||
while (cursor.position() as usize) < bytes.len() {
|
||||
let start = cursor.position() as usize;
|
||||
let mut de = rmp_serde::Deserializer::new(&mut cursor);
|
||||
serde::de::IgnoredAny::deserialize(&mut de).expect("a msgpack value");
|
||||
out.push(bytes[start..cursor.position() as usize].to_vec());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn decode(bytes: &[u8]) -> CultNetMessage {
|
||||
decode_cultnet_message_from_slice(bytes, CultNetWireContract::CultNetSchemaV0).unwrap()
|
||||
}
|
||||
|
||||
fn vector_selection() -> Selection {
|
||||
match decode(&session()[0]) {
|
||||
CultNetMessage::DatabaseSubscribeV1 { selection, .. } => selection,
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The vector's snapshot, answering `message_id`.
|
||||
fn snapshot_answering(answered: &str) -> CultNetMessage {
|
||||
let mut message = decode(&session()[1]);
|
||||
let CultNetMessage::SnapshotResponseRawV1 { message_id, .. } = &mut message else { panic!("{message:?}") };
|
||||
*message_id = answered.into();
|
||||
message
|
||||
}
|
||||
|
||||
fn change_part(message_id: &str, subscription: &str, commit: &str) -> CultNetMessage {
|
||||
CultNetMessage::DatabaseChangeRaw {
|
||||
message_id: message_id.into(),
|
||||
subscription_id: subscription.into(),
|
||||
change_kind: DatabaseChangeKind::Removed,
|
||||
document: None,
|
||||
record_key: Some("k".into()),
|
||||
schema_id: Some("note".into()),
|
||||
commit_id: Some(commit.into()),
|
||||
commit_count: Some(2),
|
||||
}
|
||||
}
|
||||
|
||||
fn single_change(message_id: &str, subscription: &str) -> CultNetMessage {
|
||||
CultNetMessage::DatabaseChangeRaw {
|
||||
message_id: message_id.into(),
|
||||
subscription_id: subscription.into(),
|
||||
change_kind: DatabaseChangeKind::Removed,
|
||||
document: None,
|
||||
record_key: Some("k".into()),
|
||||
schema_id: Some("note".into()),
|
||||
commit_id: None,
|
||||
commit_count: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Drains until `count` events have arrived, or fails after five seconds.
|
||||
fn drain_events(client: &CultMeshRudpSubscriptionClient, count: usize) -> Vec<CultMeshSubscriptionEvent> {
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
let mut events = Vec::new();
|
||||
while events.len() < count && Instant::now() < deadline {
|
||||
events.extend(client.try_drain());
|
||||
thread::sleep(Duration::from_millis(2));
|
||||
}
|
||||
assert_eq!(events.len(), count, "{events:?}");
|
||||
events
|
||||
}
|
||||
|
||||
fn quiet(client: &CultMeshRudpSubscriptionClient) {
|
||||
thread::sleep(Duration::from_millis(150));
|
||||
assert_eq!(client.try_drain(), vec![]);
|
||||
}
|
||||
|
||||
fn keys(event: &CultMeshSubscriptionEvent) -> Vec<&str> {
|
||||
match event {
|
||||
CultMeshSubscriptionEvent::Subscription(SubscriptionEvent::Commit { changes, .. }) => {
|
||||
changes.iter().map(|Change { record_key, .. }| record_key.as_str()).collect()
|
||||
}
|
||||
other => panic!("expected a commit, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn faulted(event: &CultMeshSubscriptionEvent) -> &str {
|
||||
match event {
|
||||
CultMeshSubscriptionEvent::Subscription(SubscriptionEvent::Faulted { reason }) => reason,
|
||||
other => panic!("expected a fault, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subscribe_and_try_drain_return_at_once_against_a_peer_that_never_answers() {
|
||||
let peer = Peer::start();
|
||||
let client = CultMeshRudpSubscriptionClient::connect(options(&peer)).unwrap();
|
||||
assert_eq!(client.try_drain(), vec![]);
|
||||
let started = Instant::now();
|
||||
client.subscribe("sub-1", vector_selection()).unwrap();
|
||||
assert_eq!(client.try_drain(), vec![]);
|
||||
client.unsubscribe("never-made").unwrap();
|
||||
client.resubscribe_all().unwrap();
|
||||
assert!(started.elapsed() < Duration::from_millis(100), "{:?}", started.elapsed());
|
||||
let (_, subscription_id) = peer.subscribe_id();
|
||||
assert_eq!(subscription_id, "sub-1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_vector_session_yields_a_snapshot_two_commits_and_a_removal_in_order() {
|
||||
let peer = Peer::start();
|
||||
let client = CultMeshRudpSubscriptionClient::connect(options(&peer)).unwrap();
|
||||
client.subscribe("sub-1", vector_selection()).unwrap();
|
||||
let (message_id, _) = peer.subscribe_id();
|
||||
peer.send(&snapshot_answering(&message_id));
|
||||
for bytes in session().into_iter().skip(2) {
|
||||
peer.send_raw(bytes);
|
||||
}
|
||||
let events = drain_events(&client, 4);
|
||||
let CultMeshSubscriptionEvent::Subscription(SubscriptionEvent::Snapshot { subscription_id, documents }) = &events[0]
|
||||
else {
|
||||
panic!("{events:?}")
|
||||
};
|
||||
assert_eq!(subscription_id, "sub-1");
|
||||
assert_eq!(documents.iter().map(|d| d.record_key.as_str()).collect::<Vec<_>>(), ["a", "b"]);
|
||||
assert_eq!(keys(&events[1]), ["c"]);
|
||||
assert_eq!(keys(&events[2]), ["a", "b"]);
|
||||
assert_eq!(keys(&events[3]), ["c"]);
|
||||
quiet(&client);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sixty_fifth_incomplete_commit_faults_then_nothing_and_resubscribe_all_snapshots_every_live_id() {
|
||||
let peer = Peer::start();
|
||||
let client = CultMeshRudpSubscriptionClient::connect(options(&peer)).unwrap();
|
||||
client.subscribe("one", vector_selection()).unwrap();
|
||||
client.subscribe("two", vector_selection()).unwrap();
|
||||
let mut first = [peer.subscribe_id(), peer.subscribe_id()];
|
||||
first.sort_by(|a, b| a.1.cmp(&b.1));
|
||||
for (message_id, _) in &first {
|
||||
peer.send(&snapshot_answering(message_id));
|
||||
}
|
||||
assert_eq!(drain_events(&client, 2).len(), 2);
|
||||
for index in 0..65 {
|
||||
peer.send(&change_part(&format!("m{index}"), "one", &format!("c{index}")));
|
||||
}
|
||||
let events = drain_events(&client, 1);
|
||||
assert_eq!(faulted(&events[0]), "CultNet subscription 'one': more than 64 commits are incomplete at once.");
|
||||
peer.send(&single_change("after", "one"));
|
||||
quiet(&client);
|
||||
|
||||
client.resubscribe_all().unwrap();
|
||||
let mut again = [peer.subscribe_id(), peer.subscribe_id()];
|
||||
again.sort_by(|a, b| a.1.cmp(&b.1));
|
||||
assert_eq!(again.iter().map(|(_, id)| id.as_str()).collect::<Vec<_>>(), ["one", "two"]);
|
||||
assert!(again.iter().all(|(id, _)| first.iter().all(|(old, _)| old != id)), "fresh message ids");
|
||||
for (message_id, _) in &again {
|
||||
peer.send(&snapshot_answering(message_id));
|
||||
}
|
||||
let events = drain_events(&client, 2);
|
||||
assert!(events.iter().all(|e| matches!(e, CultMeshSubscriptionEvent::Subscription(SubscriptionEvent::Snapshot { .. }))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_error_answering_a_subscribe_is_a_fault_and_only_a_recognised_text_is_quoted() {
|
||||
let peer = Peer::start();
|
||||
let client = CultMeshRudpSubscriptionClient::connect(options(&peer)).unwrap();
|
||||
client.subscribe("sub-1", vector_selection()).unwrap();
|
||||
let (message_id, _) = peer.subscribe_id();
|
||||
peer.send(&CultNetMessage::ErrorV1 {
|
||||
error: "the catalog refused the document".into(),
|
||||
code: Some(CultNetErrorCode::LimitReached),
|
||||
details: None,
|
||||
message_id: Some(message_id.clone()),
|
||||
});
|
||||
let events = drain_events(&client, 1);
|
||||
assert_eq!(faulted(&events[0]), "CultNet subscription 'sub-1' was refused by the peer: the catalog refused the document.");
|
||||
// Answered, so a snapshot for the refused subscribe is nobody's.
|
||||
peer.send(&snapshot_answering(&message_id));
|
||||
quiet(&client);
|
||||
|
||||
client.resubscribe_all().unwrap();
|
||||
let (message_id, _) = peer.subscribe_id();
|
||||
peer.send(&CultNetMessage::ErrorV1 {
|
||||
error: "CANARY-secret".into(),
|
||||
code: None,
|
||||
details: None,
|
||||
message_id: Some(message_id),
|
||||
});
|
||||
let events = drain_events(&client, 1);
|
||||
assert_eq!(faulted(&events[0]), "CultNet subscription 'sub-1' was refused by the peer.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_error_without_a_request_id_faults_the_outstanding_subscribe() {
|
||||
let peer = Peer::start();
|
||||
let client = CultMeshRudpSubscriptionClient::connect(options(&peer)).unwrap();
|
||||
client.subscribe("sub-1", vector_selection()).unwrap();
|
||||
peer.subscribe_id();
|
||||
peer.send(&CultNetMessage::Error { error: "the snapshot source failed".into(), code: None, details: None });
|
||||
let events = drain_events(&client, 1);
|
||||
assert_eq!(faulted(&events[0]), "CultNet subscription was refused by the peer: the snapshot source failed.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_error_for_something_else_leaves_the_subscription_alone() {
|
||||
let peer = Peer::start();
|
||||
let client = CultMeshRudpSubscriptionClient::connect(options(&peer)).unwrap();
|
||||
client.subscribe("sub-1", vector_selection()).unwrap();
|
||||
let (message_id, _) = peer.subscribe_id();
|
||||
peer.send(&CultNetMessage::ErrorV1 { error: "x".into(), code: None, details: None, message_id: Some("other".into()) });
|
||||
peer.send(&snapshot_answering(&message_id));
|
||||
let events = drain_events(&client, 1);
|
||||
assert!(matches!(&events[0], CultMeshSubscriptionEvent::Subscription(SubscriptionEvent::Snapshot { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_peer_going_away_is_one_disconnected_and_resubscribe_all_reconnects() {
|
||||
let peer = Peer::start();
|
||||
let client = CultMeshRudpSubscriptionClient::connect(options(&peer)).unwrap();
|
||||
client.subscribe("sub-1", vector_selection()).unwrap();
|
||||
let (message_id, _) = peer.subscribe_id();
|
||||
peer.send(&snapshot_answering(&message_id));
|
||||
assert_eq!(drain_events(&client, 1).len(), 1);
|
||||
|
||||
peer.disconnect();
|
||||
let events = drain_events(&client, 1);
|
||||
assert!(
|
||||
matches!(&events[0], CultMeshSubscriptionEvent::Disconnected { reason } if reason.contains("scripted-goodbye")),
|
||||
"{events:?}"
|
||||
);
|
||||
quiet(&client);
|
||||
// A subscribe while disconnected is kept, not lost and not a hang.
|
||||
client.subscribe("late", vector_selection()).unwrap();
|
||||
quiet(&client);
|
||||
|
||||
client.resubscribe_all().unwrap();
|
||||
let mut again = [peer.subscribe_id(), peer.subscribe_id()];
|
||||
again.sort_by(|a, b| a.1.cmp(&b.1));
|
||||
assert_eq!(again.iter().map(|(_, id)| id.as_str()).collect::<Vec<_>>(), ["late", "sub-1"]);
|
||||
for (message_id, _) in &again {
|
||||
peer.send(&snapshot_answering(message_id));
|
||||
}
|
||||
assert_eq!(drain_events(&client, 2).len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reconnect_to_a_peer_that_is_gone_is_a_disconnected_not_a_hang() {
|
||||
let peer = Peer::start();
|
||||
let mut options = options(&peer);
|
||||
options.connect_timeout = Duration::from_millis(200);
|
||||
let client = CultMeshRudpSubscriptionClient::connect(options).unwrap();
|
||||
client.subscribe("sub-1", vector_selection()).unwrap();
|
||||
peer.subscribe_id();
|
||||
peer.disconnect();
|
||||
drain_events(&client, 1);
|
||||
drop(peer);
|
||||
client.resubscribe_all().unwrap();
|
||||
let events = drain_events(&client, 1);
|
||||
assert!(matches!(&events[0], CultMeshSubscriptionEvent::Disconnected { reason } if reason.starts_with("reconnect failed")), "{events:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dropping_the_client_unsubscribes_each_live_id_and_stops_its_thread() {
|
||||
let peer = Peer::start();
|
||||
let client = CultMeshRudpSubscriptionClient::connect(options(&peer)).unwrap();
|
||||
client.subscribe("one", vector_selection()).unwrap();
|
||||
client.subscribe("two", vector_selection()).unwrap();
|
||||
client.unsubscribe("two").unwrap();
|
||||
peer.subscribe_id();
|
||||
peer.subscribe_id();
|
||||
assert!(matches!(peer.next(), CultNetMessage::DatabaseUnsubscribe { subscription_id, .. } if subscription_id == "two"));
|
||||
// An unsubscribed id is forgotten: not resent, not unsubscribed again.
|
||||
client.resubscribe_all().unwrap();
|
||||
assert_eq!(peer.subscribe_id().1, "one");
|
||||
let before = thread_count();
|
||||
let started = Instant::now();
|
||||
drop(client);
|
||||
assert!(started.elapsed() < Duration::from_secs(2), "drop joins promptly");
|
||||
assert!(matches!(peer.next(), CultNetMessage::DatabaseUnsubscribe { subscription_id, .. } if subscription_id == "one"));
|
||||
assert!(peer.received.recv_timeout(Duration::from_millis(300)).is_err(), "nothing else is sent");
|
||||
if cfg!(target_os = "linux") {
|
||||
assert!(thread_count() < before, "the pump thread is gone with its handle");
|
||||
}
|
||||
}
|
||||
|
||||
fn thread_count() -> usize {
|
||||
std::fs::read_dir("/proc/self/task").map(|tasks| tasks.count()).unwrap_or(usize::MAX)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_the_caller_leaves_undrained_is_bounded_and_past_it_the_subscription_faults() {
|
||||
let peer = Peer::start();
|
||||
let mut options = options(&peer);
|
||||
options.max_undrained = 3;
|
||||
let client = CultMeshRudpSubscriptionClient::connect(options).unwrap();
|
||||
client.subscribe("sub-1", vector_selection()).unwrap();
|
||||
let (message_id, _) = peer.subscribe_id();
|
||||
peer.send(&snapshot_answering(&message_id)); // two documents
|
||||
peer.send(&single_change("c1", "sub-1")); // three: at the bound
|
||||
peer.send(&single_change("c2", "sub-1")); // four: past it
|
||||
peer.send(&single_change("c3", "sub-1"));
|
||||
thread::sleep(Duration::from_millis(400)); // the caller is not draining
|
||||
let events = client.try_drain();
|
||||
assert_eq!(events.len(), 3, "{events:?}");
|
||||
assert!(matches!(&events[0], CultMeshSubscriptionEvent::Subscription(SubscriptionEvent::Snapshot { .. })));
|
||||
assert_eq!(keys(&events[1]), ["k"]);
|
||||
assert_eq!(
|
||||
faulted(&events[2]),
|
||||
"the consumer left more than 3 documents and changes undrained; drain, then resubscribe"
|
||||
);
|
||||
peer.send(&single_change("c4", "sub-1"));
|
||||
quiet(&client);
|
||||
|
||||
client.resubscribe_all().unwrap();
|
||||
let (message_id, _) = peer.subscribe_id();
|
||||
peer.send(&snapshot_answering(&message_id));
|
||||
assert!(matches!(&drain_events(&client, 1)[0], CultMeshSubscriptionEvent::Subscription(SubscriptionEvent::Snapshot { .. })));
|
||||
}
|
||||
|
||||
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 out = concat!(env!("CARGO_MANIFEST_DIR"), "/target/interop-peer");
|
||||
let build = Command::new("dotnet")
|
||||
.args(["build", project, "-c", "Release", "-v", "q", "--nologo", "-o", out])
|
||||
.status()
|
||||
.expect("dotnet builds the interop peer");
|
||||
assert!(build.success());
|
||||
let dll = format!("{out}/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 mut said = Vec::new();
|
||||
let port = loop {
|
||||
let line = lines.next().unwrap_or_else(|| panic!("the peer ended without announcing its port; it said {said:?}")).unwrap();
|
||||
if let Some(rest) = line.strip_prefix("listening ") {
|
||||
break rest.trim().parse::<u16>().unwrap();
|
||||
}
|
||||
said.push(line);
|
||||
};
|
||||
Self { child, port }
|
||||
}
|
||||
|
||||
/// Ends the process with no goodbye on the wire.
|
||||
fn kill(&mut self) {
|
||||
let _ = self.child.kill();
|
||||
let _ = self.child.wait();
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
|
||||
/// 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![]);
|
||||
}
|
||||
|
|
@ -89,8 +89,9 @@ impl SubscriptionAssembler {
|
|||
self.fault.as_deref()
|
||||
}
|
||||
|
||||
/// Feeds one decoded message. Messages that are not a snapshot response or a change (an error, a hello) are
|
||||
/// not this assembler's and return nothing.
|
||||
/// Feeds one decoded message. Messages that are not a snapshot response or a change (a hello; an error, which
|
||||
/// the driver reports through [`refused`](Self::refused), because only the driver may quote its text) are not
|
||||
/// this assembler's and return nothing.
|
||||
pub fn accept(&mut self, message: CultNetMessage) -> Vec<SubscriptionEvent> {
|
||||
if self.fault.is_some() {
|
||||
return Vec::new();
|
||||
|
|
@ -129,6 +130,27 @@ impl SubscriptionAssembler {
|
|||
}
|
||||
}
|
||||
|
||||
/// The peer answered a subscribe with an error. `answering` is the error's request id when it carries one
|
||||
/// (`cultnet.error.v1`): an id that is not an outstanding subscribe is not this assembler's and returns nothing,
|
||||
/// and an outstanding one stops being outstanding. An error with no request id (`cultnet.error.v0`) faults only
|
||||
/// while some subscribe is outstanding, since a subscribe is the only request a subscription connection makes.
|
||||
/// The fault is the connection's, like every other: the consumer resubscribes, or ends the subscription and
|
||||
/// gives up. `detail` is the driver's quotable text for the refusal (empty, or `": text"`).
|
||||
pub fn refused(&mut self, answering: Option<&str>, detail: &str) -> Vec<SubscriptionEvent> {
|
||||
if self.fault.is_some() {
|
||||
return Vec::new();
|
||||
}
|
||||
let named = match answering {
|
||||
Some(message_id) => match self.outstanding.remove(message_id) {
|
||||
Some(subscription_id) => format!(" '{subscription_id}'"),
|
||||
None => return Vec::new(),
|
||||
},
|
||||
None if self.outstanding.is_empty() => return Vec::new(),
|
||||
None => String::new(),
|
||||
};
|
||||
self.latch_fault(format!("CultNet subscription{named} was refused by the peer{detail}."))
|
||||
}
|
||||
|
||||
fn snapshot(&mut self, message_id: &str, documents: Vec<SelectionDocumentRecord>) -> Vec<SubscriptionEvent> {
|
||||
let Some(subscription_id) = self.outstanding.remove(message_id) else {
|
||||
return Vec::new();
|
||||
|
|
@ -163,7 +185,7 @@ impl SubscriptionAssembler {
|
|||
Ok(Some(complete)) => complete,
|
||||
Ok(None) => return Vec::new(),
|
||||
Err(refusal) => {
|
||||
return self.fault_with(format!("CultNet subscription '{subscription_id}': {refusal}."));
|
||||
return self.latch_fault(format!("CultNet subscription '{subscription_id}': {refusal}."));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -227,8 +249,12 @@ impl SubscriptionAssembler {
|
|||
Ok(self.commits.remove(&held).map(|commit| commit.changes))
|
||||
}
|
||||
|
||||
/// The one fault path: drop what was waiting, latch, say so once.
|
||||
fn fault_with(&mut self, reason: String) -> Vec<SubscriptionEvent> {
|
||||
/// The one fault path: drop what was waiting, latch, say so once. A driver whose own bound is exceeded uses it
|
||||
/// too, so that the replica a consumer holds and its source never silently differ.
|
||||
pub fn latch_fault(&mut self, reason: String) -> Vec<SubscriptionEvent> {
|
||||
if self.fault.is_some() {
|
||||
return Vec::new();
|
||||
}
|
||||
self.commits.clear();
|
||||
for subscription in self.subscriptions.values_mut() {
|
||||
subscription.waiting.clear();
|
||||
|
|
|
|||
|
|
@ -410,3 +410,36 @@ fn a_one_change_announcement_never_counts_against_a_full_buffer() {
|
|||
assert_eq!(keys(&events[0]), ["k1"], "a single change is not a buffered commit, so the full cap does not refuse it");
|
||||
assert!(assembler.fault().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_error_answering_a_subscribe_faults_it_and_the_subscribe_is_no_longer_outstanding() {
|
||||
let mut assembler = SubscriptionAssembler::new();
|
||||
assembler.begin("sub", "m1").unwrap();
|
||||
assembler.begin("other", "m2").unwrap();
|
||||
assert!(assembler.refused(Some("unrelated"), ": nope").is_empty(), "an id that is no subscribe's is not ours");
|
||||
assert!(assembler.fault().is_none());
|
||||
let events = assembler.refused(Some("m1"), ": denied");
|
||||
assert_eq!(faulted(&events), "CultNet subscription 'sub' was refused by the peer: denied.");
|
||||
assert!(assembler.refused(Some("m2"), "").is_empty(), "one fault, said once");
|
||||
assembler.reset();
|
||||
assembler.begin("sub", "m1").unwrap();
|
||||
assert!(
|
||||
assembler.accept(snapshot("m1", &["r"])).iter().any(|e| matches!(e, SubscriptionEvent::Snapshot { .. })),
|
||||
"a reset starts clean, so the refused id can be asked again"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_error_without_a_request_id_faults_only_while_a_subscribe_is_outstanding() {
|
||||
let mut assembler = SubscriptionAssembler::new();
|
||||
assert!(assembler.refused(None, "").is_empty());
|
||||
assembler.begin("sub", "m").unwrap();
|
||||
assert_eq!(faulted(&assembler.refused(None, "")), "CultNet subscription was refused by the peer.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_answered_subscribe_is_not_refused_afterwards() {
|
||||
let mut assembler = live("sub");
|
||||
assert!(assembler.refused(Some("begin-sub"), "").is_empty(), "the snapshot already answered it");
|
||||
assert!(assembler.fault().is_none());
|
||||
}
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ static async Task<int> ProgramMainAsync(string[] args)
|
|||
{
|
||||
if (args.Length == 0)
|
||||
{
|
||||
throw new InvalidOperationException("Expected mode: serve | probe | dial | rudp-serve-once | rudp-dial-once | rudp-serve-message-once | rudp-dial-message-once | quic-realtime-serve | receipt-serve | receipt-relay");
|
||||
throw new InvalidOperationException("Expected mode: serve | probe | dial | rudp-serve-once | rudp-dial-once | rudp-serve-message-once | rudp-dial-message-once | quic-realtime-serve | receipt-serve | receipt-relay | rudp-subscription-serve");
|
||||
}
|
||||
|
||||
var mode = args[0];
|
||||
|
|
@ -56,6 +56,11 @@ static async Task<int> ProgramMainAsync(string[] args)
|
|||
case "receipt-serve":
|
||||
await GameCult.Networking.InteropPeer.ReceiptHarness.ServeAsync();
|
||||
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("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));
|
||||
return 0;
|
||||
|
|
|
|||
71
tests/GameCult.Networking.InteropPeer/SubscriptionHarness.cs
Normal file
71
tests/GameCult.Networking.InteropPeer/SubscriptionHarness.cs
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GameCult.Caching;
|
||||
using GameCult.Networking;
|
||||
|
||||
// A real C# subscription server on RUDP for the Rust subscription client (packages/cultmesh-rs/tests/rudp_subscription.rs,
|
||||
// live_csharp_subscription). It serves a CultNetDatabase with one document type; once the first subscribe is active it
|
||||
// commits one record, then two records in one commit, so the client sees a snapshot, a single change and a two-change commit.
|
||||
namespace GameCult.Networking.InteropPeer
|
||||
{
|
||||
[CultDocument("subscription.interop_note", SubscriptionHarness.SchemaId)]
|
||||
[MessagePack.MessagePackObject]
|
||||
public sealed class SubscriptionInteropNote
|
||||
{
|
||||
[MessagePack.Key(0)]
|
||||
public string Text { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
internal static class SubscriptionHarness
|
||||
{
|
||||
public const string SchemaId = "subscription.interop_note.v1";
|
||||
|
||||
// `--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
|
||||
});
|
||||
using var subscriptions = new CultNetDatabaseSubscriptionServer(server, database);
|
||||
var committed = 0;
|
||||
subscriptions.DemandChanged += demand =>
|
||||
{
|
||||
if (!demand.Active || Interlocked.Exchange(ref committed, 1) == 1) return;
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
await Task.Delay(300).ConfigureAwait(false);
|
||||
cache.Commit(batch => batch.Upsert(typeof(SubscriptionInteropNote), new SubscriptionInteropNote { Text = "one" }, new CultRecordKey("one")));
|
||||
await Task.Delay(100).ConfigureAwait(false);
|
||||
cache.Commit(batch =>
|
||||
{
|
||||
batch.Upsert(typeof(SubscriptionInteropNote), new SubscriptionInteropNote { Text = "two" }, new CultRecordKey("two"));
|
||||
batch.Upsert(typeof(SubscriptionInteropNote), new SubscriptionInteropNote { Text = "three" }, new CultRecordKey("three"));
|
||||
});
|
||||
});
|
||||
};
|
||||
using var stop = new CancellationTokenSource();
|
||||
var pump = Task.Run(async () =>
|
||||
{
|
||||
while (!stop.IsCancellationRequested)
|
||||
{
|
||||
var worked = (await server.PollAvailableAsync(64).ConfigureAwait(false)).TransportItemsConsumed > 0;
|
||||
server.PollResends();
|
||||
if (!worked) await Task.Delay(1).ConfigureAwait(false);
|
||||
}
|
||||
});
|
||||
lock (Console.Out) Console.Out.WriteLine($"listening {server.LocalEndPoint.Port}");
|
||||
await Task.Run(() => Console.In.ReadToEnd());
|
||||
stop.Cancel();
|
||||
await pump.ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue