cultmesh-rs: close and Drop stay in bounds during a reconnect; close/Drop tests proven, not slept (h4) (#198)
This commit is contained in:
parent
0c890c79cc
commit
453b360f61
5 changed files with 271 additions and 54 deletions
1
packages/cultmesh-rs/Cargo.lock
generated
1
packages/cultmesh-rs/Cargo.lock
generated
|
|
@ -235,6 +235,7 @@ dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"base64",
|
"base64",
|
||||||
"cultcache-rs",
|
"cultcache-rs",
|
||||||
|
"cultmesh-rs",
|
||||||
"cultnet-rs",
|
"cultnet-rs",
|
||||||
"p256",
|
"p256",
|
||||||
"pretty_assertions",
|
"pretty_assertions",
|
||||||
|
|
|
||||||
|
|
@ -9,6 +9,10 @@ publish = false
|
||||||
name = "cultmesh_rs"
|
name = "cultmesh_rs"
|
||||||
path = "src/lib.rs"
|
path = "src/lib.rs"
|
||||||
|
|
||||||
|
[features]
|
||||||
|
# Seams only this crate's own tests use; not part of the API a consumer builds against.
|
||||||
|
test-hooks = []
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
anyhow = "1"
|
anyhow = "1"
|
||||||
cultcache-rs = { path = "../cultcache-rs" }
|
cultcache-rs = { path = "../cultcache-rs" }
|
||||||
|
|
@ -18,6 +22,8 @@ p256 = { version = "0.13", default-features = false, features = ["ecdsa", "std"]
|
||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
|
# The tests enable the crate's own `test-hooks` feature.
|
||||||
|
cultmesh-rs = { path = ".", features = ["test-hooks"] }
|
||||||
pretty_assertions = "1.4.1"
|
pretty_assertions = "1.4.1"
|
||||||
rmp-serde = "1"
|
rmp-serde = "1"
|
||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
|
|
|
||||||
|
|
@ -819,6 +819,7 @@ pub fn request_raw_snapshot_from_rudp_catalog(
|
||||||
options.resend_delay_ms,
|
options.resend_delay_ms,
|
||||||
"cultmesh-rudp-snapshot-client",
|
"cultmesh-rudp-snapshot-client",
|
||||||
None,
|
None,
|
||||||
|
&|| false,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
let request = cultnet_rs::CultNetMessage::SnapshotRequest {
|
let request = cultnet_rs::CultNetMessage::SnapshotRequest {
|
||||||
|
|
@ -944,6 +945,7 @@ pub fn publish_cultnet_messages_to_rudp_catalog(
|
||||||
options.resend_delay_ms,
|
options.resend_delay_ms,
|
||||||
"cultmesh-rudp-document-publisher",
|
"cultmesh-rudp-document-publisher",
|
||||||
None,
|
None,
|
||||||
|
&|| false,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
let mut receipts = Vec::with_capacity(messages.len());
|
let mut receipts = Vec::with_capacity(messages.len());
|
||||||
|
|
@ -1012,6 +1014,7 @@ fn connect_rudp_client(
|
||||||
resend_delay_ms: u64,
|
resend_delay_ms: u64,
|
||||||
transport_id: &str,
|
transport_id: &str,
|
||||||
connection_id: Option<u32>,
|
connection_id: Option<u32>,
|
||||||
|
cancelled: &dyn Fn() -> bool,
|
||||||
) -> Result<CultNetRudpSocketTransportConnection> {
|
) -> Result<CultNetRudpSocketTransportConnection> {
|
||||||
let bind_addr = if target.is_ipv4() {
|
let bind_addr = if target.is_ipv4() {
|
||||||
SocketAddr::from(([0, 0, 0, 0], 0))
|
SocketAddr::from(([0, 0, 0, 0], 0))
|
||||||
|
|
@ -1040,6 +1043,9 @@ fn connect_rudp_client(
|
||||||
client.connect(Vec::new())?;
|
client.connect(Vec::new())?;
|
||||||
let connect_deadline = Instant::now() + connect_timeout;
|
let connect_deadline = Instant::now() + connect_timeout;
|
||||||
while !client.connected() && Instant::now() < connect_deadline {
|
while !client.connected() && Instant::now() < connect_deadline {
|
||||||
|
if cancelled() {
|
||||||
|
anyhow::bail!("connecting CultMesh RUDP client {runtime_id} to {target} was cancelled");
|
||||||
|
}
|
||||||
let _ = client.receive_once()?;
|
let _ = client.receive_once()?;
|
||||||
client.poll_resends()?;
|
client.poll_resends()?;
|
||||||
thread::sleep(poll_interval);
|
thread::sleep(poll_interval);
|
||||||
|
|
|
||||||
|
|
@ -4,8 +4,11 @@
|
||||||
//! only queues commands and drains events. RUDP acknowledgements and resends keep their cadence while the caller is
|
//! 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.
|
//! 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
|
//! Lifetime: [`close`](CultMeshRudpSubscriptionClient::close) unsubscribes each live id, waits up to 500 ms for the
|
||||||
//! its handle. A closed or failed session is an event ([`CultMeshSubscriptionEvent::Disconnected`]), never a hang;
|
//! peer to acknowledge, disconnects, joins the thread and returns whether the acknowledgement arrived. Dropping the
|
||||||
|
//! client does the same without the wait: best effort, the unsubscribes are sent and the peer's answer is not
|
||||||
|
//! awaited. Either way no thread outlives its handle, and a reconnect in progress is abandoned at its next poll
|
||||||
|
//! instead of waiting out `connect_timeout`. 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.
|
//! 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
|
//! Bounds: the assembler bounds what it holds of incomplete commits and faults the connection past that. What the
|
||||||
|
|
@ -36,9 +39,9 @@ use cultnet_rs::{
|
||||||
use std::collections::{BTreeMap, BTreeSet, VecDeque};
|
use std::collections::{BTreeMap, BTreeSet, VecDeque};
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
use std::net::SocketAddr;
|
use std::net::SocketAddr;
|
||||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||||
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender, TryRecvError};
|
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender, TryRecvError};
|
||||||
use std::sync::{Arc, Mutex, Weak};
|
use std::sync::{Arc, Mutex};
|
||||||
use std::thread::{self, JoinHandle};
|
use std::thread::{self, JoinHandle};
|
||||||
use std::time::{Duration, Instant};
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
|
@ -211,18 +214,21 @@ enum Command {
|
||||||
Subscribe(String, Selection),
|
Subscribe(String, Selection),
|
||||||
Unsubscribe(String),
|
Unsubscribe(String),
|
||||||
Resubscribe,
|
Resubscribe,
|
||||||
/// Ends the session. With a `reply`, waits (bounded) for the unsubscribes to be acknowledged and says whether
|
/// Ends the session. With `wait`, first waits (bounded) for the unsubscribes to be acknowledged; without it,
|
||||||
/// they were; without one, sends them and goes.
|
/// sends them and goes. The pump thread's result says whether they were acknowledged.
|
||||||
Close { reply: Option<Sender<bool>> },
|
Close { wait: bool },
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A live subscription connection. Methods never block on the network.
|
/// A live subscription connection. Methods return without waiting on the peer, except `connect`, which waits up to
|
||||||
|
/// `connect_timeout`, and `close`, which waits up to 500 ms for the unsubscribes to be acknowledged.
|
||||||
pub struct CultMeshRudpSubscriptionClient {
|
pub struct CultMeshRudpSubscriptionClient {
|
||||||
commands: Sender<Command>,
|
commands: Sender<Command>,
|
||||||
events: Mutex<Receiver<(CultMeshSubscriptionEvent, usize)>>,
|
events: Mutex<Receiver<(CultMeshSubscriptionEvent, usize)>>,
|
||||||
undrained: Arc<AtomicUsize>,
|
undrained: Arc<AtomicUsize>,
|
||||||
pump_alive: Weak<()>,
|
#[cfg(feature = "test-hooks")]
|
||||||
pump: Option<JoinHandle<()>>,
|
pump_alive: std::sync::Weak<()>,
|
||||||
|
closing: Arc<AtomicBool>,
|
||||||
|
pump: Option<JoinHandle<bool>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CultMeshRudpSubscriptionClient {
|
impl CultMeshRudpSubscriptionClient {
|
||||||
|
|
@ -231,13 +237,17 @@ impl CultMeshRudpSubscriptionClient {
|
||||||
if options.runtime_id.trim().is_empty() {
|
if options.runtime_id.trim().is_empty() {
|
||||||
return Err(anyhow!("runtime_id must be non-empty"));
|
return Err(anyhow!("runtime_id must be non-empty"));
|
||||||
}
|
}
|
||||||
let session = open(&options)?;
|
let session = open(&options, &|| false)?;
|
||||||
|
let closing = Arc::new(AtomicBool::new(false));
|
||||||
let (commands, command_rx) = mpsc::channel();
|
let (commands, command_rx) = mpsc::channel();
|
||||||
let (event_tx, events) = mpsc::channel();
|
let (event_tx, events) = mpsc::channel();
|
||||||
let undrained = Arc::new(AtomicUsize::new(0));
|
let undrained = Arc::new(AtomicUsize::new(0));
|
||||||
|
#[cfg(feature = "test-hooks")]
|
||||||
let alive = Arc::new(());
|
let alive = Arc::new(());
|
||||||
|
#[cfg(feature = "test-hooks")]
|
||||||
let pump_alive = Arc::downgrade(&alive);
|
let pump_alive = Arc::downgrade(&alive);
|
||||||
let pump = Pump {
|
let pump = Pump {
|
||||||
|
closing: closing.clone(),
|
||||||
options,
|
options,
|
||||||
session: Some(session),
|
session: Some(session),
|
||||||
assembler: SubscriptionAssembler::new(),
|
assembler: SubscriptionAssembler::new(),
|
||||||
|
|
@ -246,7 +256,8 @@ impl CultMeshRudpSubscriptionClient {
|
||||||
pending_weight: 0,
|
pending_weight: 0,
|
||||||
awaiting: Vec::new(),
|
awaiting: Vec::new(),
|
||||||
backoff: BTreeMap::new(),
|
backoff: BTreeMap::new(),
|
||||||
alive,
|
#[cfg(feature = "test-hooks")]
|
||||||
|
_alive: alive,
|
||||||
subscriptions: BTreeMap::new(),
|
subscriptions: BTreeMap::new(),
|
||||||
receipts: Vec::new(),
|
receipts: Vec::new(),
|
||||||
epoch: super::fresh_rudp_connection_epoch(),
|
epoch: super::fresh_rudp_connection_epoch(),
|
||||||
|
|
@ -259,12 +270,22 @@ impl CultMeshRudpSubscriptionClient {
|
||||||
let pump = thread::Builder::new()
|
let pump = thread::Builder::new()
|
||||||
.name("cultmesh-rudp-subscription".into())
|
.name("cultmesh-rudp-subscription".into())
|
||||||
.spawn(move || pump.run())?;
|
.spawn(move || pump.run())?;
|
||||||
Ok(Self { commands, events: Mutex::new(events), undrained, pump_alive, pump: Some(pump) })
|
Ok(Self {
|
||||||
|
commands,
|
||||||
|
events: Mutex::new(events),
|
||||||
|
undrained,
|
||||||
|
#[cfg(feature = "test-hooks")]
|
||||||
|
pump_alive,
|
||||||
|
closing,
|
||||||
|
pump: Some(pump),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A weak handle that upgrades while this client's own pump thread exists, and never after it has been joined.
|
/// A weak handle that upgrades while this client's own pump thread exists, and never after it has been joined.
|
||||||
/// Tests use it to prove that dropping the client ends its thread.
|
/// Only under the `test-hooks` feature, which this crate's own tests enable: not part of the API a consumer
|
||||||
pub fn pump_liveness(&self) -> Weak<()> {
|
/// builds against.
|
||||||
|
#[cfg(feature = "test-hooks")]
|
||||||
|
pub fn pump_liveness(&self) -> std::sync::Weak<()> {
|
||||||
self.pump_alive.clone()
|
self.pump_alive.clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -303,15 +324,12 @@ impl CultMeshRudpSubscriptionClient {
|
||||||
impl CultMeshRudpSubscriptionClient {
|
impl CultMeshRudpSubscriptionClient {
|
||||||
/// The explicit shutdown: unsubscribes each live id, waits up to 500 ms for the peer to acknowledge, ends the
|
/// The explicit shutdown: unsubscribes each live id, waits up to 500 ms for the peer to acknowledge, ends the
|
||||||
/// session and joins the pump thread. Returns whether the acknowledgement arrived; `false` says the peer may
|
/// session and joins the pump thread. Returns whether the acknowledgement arrived; `false` says the peer may
|
||||||
/// still hold the subscriptions until its own idle timeout.
|
/// still hold the subscriptions until its own idle timeout. A reconnect in progress is abandoned at once, and
|
||||||
|
/// then there is nothing to acknowledge.
|
||||||
pub fn close(mut self) -> bool {
|
pub fn close(mut self) -> bool {
|
||||||
let (reply, answer) = mpsc::channel();
|
self.closing.store(true, Ordering::SeqCst);
|
||||||
let sent = self.commands.send(Command::Close { reply: Some(reply) }).is_ok();
|
let _ = self.commands.send(Command::Close { wait: true });
|
||||||
let acknowledged = sent && answer.recv_timeout(CLOSE_ACK_WAIT * 2).unwrap_or(false);
|
self.pump.take().is_some_and(|pump| pump.join().unwrap_or(false))
|
||||||
if let Some(pump) = self.pump.take() {
|
|
||||||
let _ = pump.join();
|
|
||||||
}
|
|
||||||
acknowledged
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -319,14 +337,15 @@ impl CultMeshRudpSubscriptionClient {
|
||||||
/// [`close`](CultMeshRudpSubscriptionClient::close) to learn whether the peer acknowledged.
|
/// [`close`](CultMeshRudpSubscriptionClient::close) to learn whether the peer acknowledged.
|
||||||
impl Drop for CultMeshRudpSubscriptionClient {
|
impl Drop for CultMeshRudpSubscriptionClient {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
let _ = self.commands.send(Command::Close { reply: None });
|
self.closing.store(true, Ordering::SeqCst);
|
||||||
|
let _ = self.commands.send(Command::Close { wait: false });
|
||||||
if let Some(pump) = self.pump.take() {
|
if let Some(pump) = self.pump.take() {
|
||||||
let _ = pump.join();
|
let _ = pump.join();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn open(options: &CultMeshRudpSubscriptionOptions) -> Result<CultNetRudpSocketTransportConnection> {
|
fn open(options: &CultMeshRudpSubscriptionOptions, cancelled: &dyn Fn() -> bool) -> Result<CultNetRudpSocketTransportConnection> {
|
||||||
connect_rudp_client(
|
connect_rudp_client(
|
||||||
options.target,
|
options.target,
|
||||||
&options.runtime_id,
|
&options.runtime_id,
|
||||||
|
|
@ -335,6 +354,7 @@ fn open(options: &CultMeshRudpSubscriptionOptions) -> Result<CultNetRudpSocketTr
|
||||||
options.resend_delay_ms,
|
options.resend_delay_ms,
|
||||||
"cultmesh-rudp-subscription-client",
|
"cultmesh-rudp-subscription-client",
|
||||||
options.connection_id,
|
options.connection_id,
|
||||||
|
cancelled,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -346,6 +366,9 @@ const REASON_CHARS: usize = 200;
|
||||||
const CLOSE_ACK_WAIT: Duration = Duration::from_millis(500);
|
const CLOSE_ACK_WAIT: Duration = Duration::from_millis(500);
|
||||||
|
|
||||||
struct Pump {
|
struct Pump {
|
||||||
|
/// Set by `close` and `Drop` before they send `Close`: a reconnect in progress gives up at its next poll
|
||||||
|
/// instead of waiting out `connect_timeout`.
|
||||||
|
closing: Arc<AtomicBool>,
|
||||||
options: CultMeshRudpSubscriptionOptions,
|
options: CultMeshRudpSubscriptionOptions,
|
||||||
/// `None` after the session ended: the pump reads nothing and waits for a command.
|
/// `None` after the session ended: the pump reads nothing and waits for a command.
|
||||||
session: Option<CultNetRudpSocketTransportConnection>,
|
session: Option<CultNetRudpSocketTransportConnection>,
|
||||||
|
|
@ -362,8 +385,8 @@ struct Pump {
|
||||||
/// this passes asks afresh.
|
/// this passes asks afresh.
|
||||||
backoff: BTreeMap<SchemaKey, Instant>,
|
backoff: BTreeMap<SchemaKey, Instant>,
|
||||||
/// Held for as long as the pump thread runs; see `pump_liveness`.
|
/// Held for as long as the pump thread runs; see `pump_liveness`.
|
||||||
#[allow(dead_code)]
|
#[cfg(feature = "test-hooks")]
|
||||||
alive: Arc<()>,
|
_alive: Arc<()>,
|
||||||
/// What `resubscribe_all` resends. The assembler owns what is live; it holds no selections.
|
/// What `resubscribe_all` resends. The assembler owns what is live; it holds no selections.
|
||||||
subscriptions: BTreeMap<String, Selection>,
|
subscriptions: BTreeMap<String, Selection>,
|
||||||
receipts: Vec<CultNetRudpReliableSendReceipt>,
|
receipts: Vec<CultNetRudpReliableSendReceipt>,
|
||||||
|
|
@ -376,23 +399,24 @@ struct Pump {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Pump {
|
impl Pump {
|
||||||
fn run(mut self) {
|
/// Returns whether `close` found every unsubscribe acknowledged; `false` when it was not asked to wait.
|
||||||
|
fn run(mut self) -> bool {
|
||||||
loop {
|
loop {
|
||||||
let command = if self.session.is_some() {
|
let command = if self.session.is_some() {
|
||||||
match self.commands.try_recv() {
|
match self.commands.try_recv() {
|
||||||
Ok(command) => Some(command),
|
Ok(command) => Some(command),
|
||||||
Err(TryRecvError::Empty) => None,
|
Err(TryRecvError::Empty) => None,
|
||||||
Err(TryRecvError::Disconnected) => Some(Command::Close { reply: None }),
|
Err(TryRecvError::Disconnected) => Some(Command::Close { wait: false }),
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
match self.commands.recv_timeout(Duration::from_secs(3600)) {
|
match self.commands.recv_timeout(Duration::from_secs(3600)) {
|
||||||
Ok(command) => Some(command),
|
Ok(command) => Some(command),
|
||||||
Err(RecvTimeoutError::Timeout) => None,
|
Err(RecvTimeoutError::Timeout) => None,
|
||||||
Err(RecvTimeoutError::Disconnected) => Some(Command::Close { reply: None }),
|
Err(RecvTimeoutError::Disconnected) => Some(Command::Close { wait: false }),
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
match command {
|
match command {
|
||||||
Some(Command::Close { reply }) => return self.close(reply),
|
Some(Command::Close { wait }) => return self.close(wait),
|
||||||
Some(command) => self.apply(command),
|
Some(command) => self.apply(command),
|
||||||
None => self.service(),
|
None => self.service(),
|
||||||
}
|
}
|
||||||
|
|
@ -450,7 +474,7 @@ impl Pump {
|
||||||
self.session = None;
|
self.session = None;
|
||||||
}
|
}
|
||||||
if self.session.is_none() {
|
if self.session.is_none() {
|
||||||
match open(&self.options) {
|
match open(&self.options, &|| self.closing.load(Ordering::SeqCst)) {
|
||||||
Ok(session) => {
|
Ok(session) => {
|
||||||
self.session = Some(session);
|
self.session = Some(session);
|
||||||
self.last_ping = Instant::now();
|
self.last_ping = Instant::now();
|
||||||
|
|
@ -754,29 +778,27 @@ impl Pump {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Unsubscribes every live id and ends the session. With `reply`, first waits up to `CLOSE_ACK_WAIT` for every
|
/// Unsubscribes every live id and ends the session. With `wait`, first waits up to `CLOSE_ACK_WAIT` for every
|
||||||
/// outstanding reliable send to be acknowledged (resending a lost one), since nothing resends after the goodbye,
|
/// outstanding reliable send to be acknowledged (resending a lost one), since nothing resends after the goodbye.
|
||||||
/// and tells whether they all were.
|
/// Says whether they all were; with no wait, `false`.
|
||||||
fn close(&mut self, reply: Option<Sender<bool>>) {
|
fn close(&mut self, wait: bool) -> bool {
|
||||||
let ids: Vec<_> = self.subscriptions.keys().cloned().collect();
|
let ids: Vec<_> = self.subscriptions.keys().cloned().collect();
|
||||||
for id in ids {
|
for id in ids {
|
||||||
let message = CultNetMessage::DatabaseUnsubscribe { message_id: self.next_message_id(), subscription_id: id };
|
let message = CultNetMessage::DatabaseUnsubscribe { message_id: self.next_message_id(), subscription_id: id };
|
||||||
self.transmit(&message);
|
self.transmit(&message);
|
||||||
}
|
}
|
||||||
if reply.is_some() {
|
if wait {
|
||||||
let deadline = Instant::now() + CLOSE_ACK_WAIT;
|
let deadline = Instant::now() + CLOSE_ACK_WAIT;
|
||||||
while self.session.is_some() && !self.receipts.is_empty() && Instant::now() < deadline {
|
while self.session.is_some() && !self.receipts.is_empty() && Instant::now() < deadline {
|
||||||
self.service();
|
self.service();
|
||||||
thread::sleep(self.options.poll_interval);
|
thread::sleep(self.options.poll_interval);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let acknowledged = self.session.is_some() && self.receipts.is_empty();
|
let acknowledged = wait && self.session.is_some() && self.receipts.is_empty();
|
||||||
if let Some(session) = self.session.as_mut() {
|
if let Some(session) = self.session.as_mut() {
|
||||||
let _ = session.disconnect(b"subscription-closed".to_vec());
|
let _ = session.disconnect(b"subscription-closed".to_vec());
|
||||||
}
|
}
|
||||||
if let Some(reply) = reply {
|
acknowledged
|
||||||
let _ = reply.send(acknowledged);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -22,14 +22,31 @@ enum PeerCommand {
|
||||||
Disconnect,
|
Disconnect,
|
||||||
/// Reads nothing and answers nothing (no pong, no ack) until `Disconnect`: a peer that died without a goodbye.
|
/// Reads nothing and answers nothing (no pong, no ack) until `Disconnect`: a peer that died without a goodbye.
|
||||||
Stall,
|
Stall,
|
||||||
|
/// Between sessions, reads and answers no Connect, but reports each one it sees, until `Disconnect`: a peer that
|
||||||
|
/// is unreachable while a client tries to reconnect.
|
||||||
|
Refuse,
|
||||||
Stop,
|
Stop,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// What the peer's thread says about itself, so a test waits for a fact and not for a sleep.
|
||||||
|
#[derive(Debug, PartialEq, Eq)]
|
||||||
|
enum PeerEvent {
|
||||||
|
/// `Stall` has taken effect: the peer reads nothing from now on.
|
||||||
|
Stalled,
|
||||||
|
/// `Refuse` has taken effect: no Connect sent from now on is answered.
|
||||||
|
Refusing,
|
||||||
|
/// A Connect arrived while refusing.
|
||||||
|
ConnectSeen,
|
||||||
|
/// The client ended the session and said why.
|
||||||
|
Goodbye(Vec<u8>),
|
||||||
|
}
|
||||||
|
|
||||||
/// A peer that accepts RUDP connects on a loopback socket and reports every schema message it receives.
|
/// A peer that accepts RUDP connects on a loopback socket and reports every schema message it receives.
|
||||||
struct Peer {
|
struct Peer {
|
||||||
addr: SocketAddr,
|
addr: SocketAddr,
|
||||||
commands: Sender<PeerCommand>,
|
commands: Sender<PeerCommand>,
|
||||||
received: Receiver<CultNetMessage>,
|
received: Receiver<CultNetMessage>,
|
||||||
|
events: Receiver<PeerEvent>,
|
||||||
thread: Option<JoinHandle<()>>,
|
thread: Option<JoinHandle<()>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -39,8 +56,9 @@ impl Peer {
|
||||||
let addr = socket.local_addr().unwrap();
|
let addr = socket.local_addr().unwrap();
|
||||||
let (commands, command_rx) = mpsc::channel();
|
let (commands, command_rx) = mpsc::channel();
|
||||||
let (received_tx, received) = mpsc::channel();
|
let (received_tx, received) = mpsc::channel();
|
||||||
let thread = thread::spawn(move || serve(socket, command_rx, received_tx));
|
let (event_tx, events) = mpsc::channel();
|
||||||
Self { addr, commands, received, thread: Some(thread) }
|
let thread = thread::spawn(move || serve(socket, command_rx, received_tx, event_tx));
|
||||||
|
Self { addr, commands, received, events, thread: Some(thread) }
|
||||||
}
|
}
|
||||||
|
|
||||||
fn send(&self, message: &CultNetMessage) {
|
fn send(&self, message: &CultNetMessage) {
|
||||||
|
|
@ -52,8 +70,22 @@ impl Peer {
|
||||||
self.commands.send(PeerCommand::Send(payload)).unwrap();
|
self.commands.send(PeerCommand::Send(payload)).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Returns once the peer's thread has entered the stall, so what the test does next meets a peer that is
|
||||||
|
/// silent, not one that has not yet read the command.
|
||||||
fn stall(&self) {
|
fn stall(&self) {
|
||||||
self.commands.send(PeerCommand::Stall).unwrap();
|
self.commands.send(PeerCommand::Stall).unwrap();
|
||||||
|
self.expect(PeerEvent::Stalled);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn expect(&self, expected: PeerEvent) {
|
||||||
|
let event = self.events.recv_timeout(Duration::from_secs(5)).expect("the peer reported an event");
|
||||||
|
assert_eq!(event, expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns once the peer is refusing Connects, so none sent after it returns is answered.
|
||||||
|
fn refuse_connects(&self) {
|
||||||
|
self.commands.send(PeerCommand::Refuse).unwrap();
|
||||||
|
self.expect(PeerEvent::Refusing);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn disconnect(&self) {
|
fn disconnect(&self) {
|
||||||
|
|
@ -84,7 +116,12 @@ impl Drop for Peer {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn serve(socket: UdpSocket, commands: Receiver<PeerCommand>, received: Sender<CultNetMessage>) {
|
fn serve(
|
||||||
|
socket: UdpSocket,
|
||||||
|
commands: Receiver<PeerCommand>,
|
||||||
|
received: Sender<CultNetMessage>,
|
||||||
|
events: Sender<PeerEvent>,
|
||||||
|
) {
|
||||||
socket.set_read_timeout(Some(Duration::from_millis(2))).unwrap();
|
socket.set_read_timeout(Some(Duration::from_millis(2))).unwrap();
|
||||||
'sessions: loop {
|
'sessions: loop {
|
||||||
// The client's connection id is its own epoch: read it from the Connect before the session exists.
|
// The client's connection id is its own epoch: read it from the Connect before the session exists.
|
||||||
|
|
@ -92,6 +129,23 @@ fn serve(socket: UdpSocket, commands: Receiver<PeerCommand>, received: Sender<Cu
|
||||||
let (length, _) = loop {
|
let (length, _) = loop {
|
||||||
match commands.try_recv() {
|
match commands.try_recv() {
|
||||||
Ok(PeerCommand::Stop) | Err(mpsc::TryRecvError::Disconnected) => return,
|
Ok(PeerCommand::Stop) | Err(mpsc::TryRecvError::Disconnected) => return,
|
||||||
|
Ok(PeerCommand::Refuse) => {
|
||||||
|
let _ = events.send(PeerEvent::Refusing);
|
||||||
|
loop {
|
||||||
|
match commands.try_recv() {
|
||||||
|
Ok(PeerCommand::Stop) | Err(mpsc::TryRecvError::Disconnected) => return,
|
||||||
|
Ok(PeerCommand::Disconnect) => continue 'sessions,
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
if let Ok((length, _)) = socket.recv_from(&mut wire) {
|
||||||
|
if decode_rudp_packet(&wire[..length])
|
||||||
|
.is_ok_and(|packet| packet.packet_type == cultnet_rs::CultNetRudpPacketType::Connect)
|
||||||
|
{
|
||||||
|
let _ = events.send(PeerEvent::ConnectSeen);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
if let Ok(found) = socket.peek_from(&mut wire) {
|
if let Ok(found) = socket.peek_from(&mut wire) {
|
||||||
|
|
@ -123,6 +177,7 @@ fn serve(socket: UdpSocket, commands: Receiver<PeerCommand>, received: Sender<Cu
|
||||||
reconnect_policy: None,
|
reconnect_policy: None,
|
||||||
})
|
})
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
let mut said_goodbye = false;
|
||||||
loop {
|
loop {
|
||||||
while let Ok(command) = commands.try_recv() {
|
while let Ok(command) = commands.try_recv() {
|
||||||
match command {
|
match command {
|
||||||
|
|
@ -133,13 +188,17 @@ fn serve(socket: UdpSocket, commands: Receiver<PeerCommand>, received: Sender<Cu
|
||||||
session.disconnect(b"scripted-goodbye".to_vec()).unwrap();
|
session.disconnect(b"scripted-goodbye".to_vec()).unwrap();
|
||||||
continue 'sessions;
|
continue 'sessions;
|
||||||
}
|
}
|
||||||
PeerCommand::Stall => loop {
|
PeerCommand::Stall => {
|
||||||
match commands.recv() {
|
let _ = events.send(PeerEvent::Stalled);
|
||||||
Ok(PeerCommand::Disconnect) => continue 'sessions,
|
loop {
|
||||||
Ok(PeerCommand::Stop) | Err(_) => return,
|
match commands.recv() {
|
||||||
Ok(_) => {}
|
Ok(PeerCommand::Disconnect) => continue 'sessions,
|
||||||
|
Ok(PeerCommand::Stop) | Err(_) => return,
|
||||||
|
Ok(_) => {}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
|
PeerCommand::Refuse => {}
|
||||||
PeerCommand::Stop => return,
|
PeerCommand::Stop => return,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -150,6 +209,10 @@ fn serve(socket: UdpSocket, commands: Receiver<PeerCommand>, received: Sender<Cu
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if let Some(reason) = session.disconnect_reason().filter(|_| !said_goodbye) {
|
||||||
|
said_goodbye = true;
|
||||||
|
let _ = events.send(PeerEvent::Goodbye(reason.to_vec()));
|
||||||
|
}
|
||||||
session.poll_resends().unwrap();
|
session.poll_resends().unwrap();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -575,9 +638,9 @@ fn dropping_the_client_unsubscribes_each_live_id_and_stops_its_thread() {
|
||||||
let started = Instant::now();
|
let started = Instant::now();
|
||||||
assert!(client.close(), "a live peer acknowledges the unsubscribe");
|
assert!(client.close(), "a live peer acknowledges the unsubscribe");
|
||||||
assert!(started.elapsed() < Duration::from_secs(2), "close returns promptly");
|
assert!(started.elapsed() < Duration::from_secs(2), "close returns promptly");
|
||||||
|
assert!(pump.upgrade().is_none(), "close has joined the pump thread when it returns");
|
||||||
assert!(matches!(peer.next(), CultNetMessage::DatabaseUnsubscribe { subscription_id, .. } if subscription_id == "one"));
|
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");
|
assert!(peer.received.recv_timeout(Duration::from_millis(300)).is_err(), "nothing else is sent");
|
||||||
assert!(pump.upgrade().is_none(), "the pump thread is gone with its handle");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|
@ -1120,8 +1183,7 @@ fn close_waits_for_the_acknowledgement_and_says_when_it_does_not_come() {
|
||||||
let client = CultMeshRudpSubscriptionClient::connect(options(&peer)).unwrap();
|
let client = CultMeshRudpSubscriptionClient::connect(options(&peer)).unwrap();
|
||||||
client.subscribe("sub-1", vector_selection()).unwrap();
|
client.subscribe("sub-1", vector_selection()).unwrap();
|
||||||
peer.subscribe_id();
|
peer.subscribe_id();
|
||||||
peer.stall(); // reads nothing, acknowledges nothing
|
peer.stall(); // returns once the peer reads nothing and acknowledges nothing
|
||||||
thread::sleep(Duration::from_millis(100)); // the peer thread has taken the stall before the client closes
|
|
||||||
let started = Instant::now();
|
let started = Instant::now();
|
||||||
assert!(!client.close(), "no acknowledgement came");
|
assert!(!client.close(), "no acknowledgement came");
|
||||||
let waited = started.elapsed();
|
let waited = started.elapsed();
|
||||||
|
|
@ -1136,10 +1198,130 @@ fn drop_does_not_wait_for_a_peer_that_acknowledges_nothing() {
|
||||||
client.subscribe("sub-1", vector_selection()).unwrap();
|
client.subscribe("sub-1", vector_selection()).unwrap();
|
||||||
peer.subscribe_id();
|
peer.subscribe_id();
|
||||||
peer.stall();
|
peer.stall();
|
||||||
thread::sleep(Duration::from_millis(100));
|
|
||||||
let pump = client.pump_liveness();
|
let pump = client.pump_liveness();
|
||||||
let started = Instant::now();
|
let started = Instant::now();
|
||||||
drop(client);
|
drop(client);
|
||||||
assert!(started.elapsed() < Duration::from_millis(300), "{:?}", started.elapsed());
|
assert!(started.elapsed() < Duration::from_millis(300), "{:?}", started.elapsed());
|
||||||
assert!(pump.upgrade().is_none(), "the thread still stops");
|
assert!(pump.upgrade().is_none(), "the thread still stops");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A client whose session ended and whose `resubscribe_all` is inside its reconnect to a peer that answers nothing,
|
||||||
|
/// proven so: the peer has seen the client's Connect, and the client would wait out `connect_timeout` (3 s) for an
|
||||||
|
/// answer that never comes.
|
||||||
|
fn reconnecting_to_a_silent_peer() -> (Peer, CultMeshRudpSubscriptionClient) {
|
||||||
|
let peer = Peer::start();
|
||||||
|
let mut options = options_ending_sessions(&peer);
|
||||||
|
options.connect_timeout = Duration::from_secs(3);
|
||||||
|
let client = CultMeshRudpSubscriptionClient::connect(options).unwrap();
|
||||||
|
subscribed(&peer, &client);
|
||||||
|
peer.disconnect();
|
||||||
|
drain_events(&client, 1);
|
||||||
|
peer.refuse_connects();
|
||||||
|
client.resubscribe_all().unwrap();
|
||||||
|
peer.expect(PeerEvent::ConnectSeen);
|
||||||
|
(peer, client)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn close_stays_within_its_bound_while_the_pump_reconnects_to_a_silent_peer() {
|
||||||
|
let (_peer, client) = reconnecting_to_a_silent_peer();
|
||||||
|
let started = Instant::now();
|
||||||
|
assert!(!client.close(), "there is no session whose unsubscribes could have been acknowledged");
|
||||||
|
assert!(started.elapsed() < Duration::from_millis(300), "{:?}", started.elapsed());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn drop_does_not_wait_for_a_reconnect_to_a_silent_peer() {
|
||||||
|
let (_peer, client) = reconnecting_to_a_silent_peer();
|
||||||
|
let pump = client.pump_liveness();
|
||||||
|
let started = Instant::now();
|
||||||
|
drop(client);
|
||||||
|
assert!(started.elapsed() < Duration::from_millis(300), "{:?}", started.elapsed());
|
||||||
|
assert!(pump.upgrade().is_none(), "the thread still stops");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn drop_sends_an_unsubscribe_for_each_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();
|
||||||
|
client.subscribe("gone", vector_selection()).unwrap();
|
||||||
|
client.unsubscribe("gone").unwrap();
|
||||||
|
for _ in 0..3 {
|
||||||
|
peer.subscribe_id();
|
||||||
|
}
|
||||||
|
assert!(matches!(peer.next(), CultNetMessage::DatabaseUnsubscribe { subscription_id, .. } if subscription_id == "gone"));
|
||||||
|
drop(client);
|
||||||
|
let mut unsubscribed: Vec<String> = (0..2)
|
||||||
|
.map(|_| match peer.next() {
|
||||||
|
CultNetMessage::DatabaseUnsubscribe { subscription_id, .. } => subscription_id,
|
||||||
|
other => panic!("expected an unsubscribe, got {other:?}"),
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
unsubscribed.sort();
|
||||||
|
assert_eq!(unsubscribed, ["one", "two"]);
|
||||||
|
peer.expect(PeerEvent::Goodbye(b"subscription-closed".to_vec()));
|
||||||
|
assert!(peer.received.recv_timeout(Duration::from_millis(300)).is_err(), "nothing else is sent");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn close_returns_when_the_acknowledgement_arrives_and_says_goodbye() {
|
||||||
|
let peer = Peer::start();
|
||||||
|
let client = CultMeshRudpSubscriptionClient::connect(options(&peer)).unwrap();
|
||||||
|
client.subscribe("sub-1", vector_selection()).unwrap();
|
||||||
|
peer.subscribe_id();
|
||||||
|
let started = Instant::now();
|
||||||
|
assert!(client.close());
|
||||||
|
assert!(started.elapsed() < Duration::from_millis(450), "it does not wait out its 500 ms: {:?}", started.elapsed());
|
||||||
|
assert!(matches!(peer.next(), CultNetMessage::DatabaseUnsubscribe { subscription_id, .. } if subscription_id == "sub-1"));
|
||||||
|
peer.expect(PeerEvent::Goodbye(b"subscription-closed".to_vec()));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn close_reports_false_once_the_session_has_ended() {
|
||||||
|
let peer = Peer::start();
|
||||||
|
let client = CultMeshRudpSubscriptionClient::connect(options_ending_sessions(&peer)).unwrap();
|
||||||
|
subscribed(&peer, &client);
|
||||||
|
peer.disconnect();
|
||||||
|
drain_events(&client, 1);
|
||||||
|
let started = Instant::now();
|
||||||
|
assert!(!client.close(), "no peer holds a session whose unsubscribes could be acknowledged");
|
||||||
|
assert!(started.elapsed() < Duration::from_millis(300), "{:?}", started.elapsed());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn draining_releases_the_weight_of_every_document_in_an_event() {
|
||||||
|
let peer = Peer::start();
|
||||||
|
let mut options = options(&peer);
|
||||||
|
options.max_undrained = 3;
|
||||||
|
let client = CultMeshRudpSubscriptionClient::connect(options).unwrap();
|
||||||
|
subscribed(&peer, &client);
|
||||||
|
// A two-change commit weighs two. If draining released one per event, each round would leave one more
|
||||||
|
// counted and the third would pass the bound of three.
|
||||||
|
for round in 0..4 {
|
||||||
|
peer.send(&change_part(&format!("a{round}"), "sub-1", &format!("c{round}")));
|
||||||
|
peer.send(&change_part(&format!("b{round}"), "sub-1", &format!("c{round}")));
|
||||||
|
assert_eq!(keys(&drain_events(&client, 1)[0]), ["k", "k"], "round {round}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_refused_subscribe_is_a_fault_while_a_catalog_request_is_in_flight() {
|
||||||
|
let peer = Peer::start();
|
||||||
|
let client = CultMeshRudpSubscriptionClient::connect(options(&peer)).unwrap();
|
||||||
|
client.subscribe("sub-1", vector_selection()).unwrap();
|
||||||
|
client.subscribe("sub-2", vector_selection()).unwrap();
|
||||||
|
let mut ids = [peer.subscribe_id(), peer.subscribe_id()];
|
||||||
|
ids.sort_by(|a, b| a.1.cmp(&b.1));
|
||||||
|
peer.send(&snapshot_answering(&ids[0].0));
|
||||||
|
let (request_id, _) = catalog_request(&peer); // in flight, not yet answered
|
||||||
|
peer.send(&CultNetMessage::ErrorV1 { error: "x".into(), code: None, details: None, message_id: Some(ids[1].0.clone()) });
|
||||||
|
// The fault queues behind the snapshot that waits for its rows.
|
||||||
|
quiet(&client);
|
||||||
|
let (schema_id, hash) = vector_schema();
|
||||||
|
answer_catalog(&peer, &request_id, vec![descriptor(&schema_id, &hash, Some(vector_members()))]);
|
||||||
|
let events = drain_events(&client, 2);
|
||||||
|
assert!(matches!(&events[0], CultMeshSubscriptionEvent::Snapshot { subscription_id, .. } if subscription_id == "sub-1"), "{events:?}");
|
||||||
|
assert_eq!(faulted(&events[1]), "CultNet subscription 'sub-2' was refused by the peer.");
|
||||||
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue