cultmesh-rs: a non-blocking RUDP subscription client over the cultnet-rs assembler; an error answering a subscribe faults it (rs-subscribe-rudp)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
31e8dbdd50
commit
bc861a45af
5 changed files with 974 additions and 5 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;
|
||||
|
||||
|
|
|
|||
399
packages/cultmesh-rs/src/rudp_subscription.rs
Normal file
399
packages/cultmesh-rs/src/rudp_subscription.rs
Normal file
|
|
@ -0,0 +1,399 @@
|
|||
//! 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;
|
||||
|
||||
/// 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 most documents and changes that may sit undrained before the subscription faults.
|
||||
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),
|
||||
resend_delay_ms: 50,
|
||||
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(),
|
||||
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",
|
||||
)
|
||||
}
|
||||
|
||||
/// 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,
|
||||
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) {
|
||||
if self.session.is_none() {
|
||||
match open(&self.options) {
|
||||
Ok(session) => self.session = Some(session),
|
||||
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);
|
||||
}
|
||||
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 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}")
|
||||
}
|
||||
509
packages/cultmesh-rs/tests/rudp_subscription.rs
Normal file
509
packages/cultmesh-rs/tests/rudp_subscription.rs
Normal file
|
|
@ -0,0 +1,509 @@
|
|||
//! 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,
|
||||
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 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;
|
||||
}
|
||||
};
|
||||
let Ok(packet) = decode_rudp_packet(&wire[..length]) else {
|
||||
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_reliable("schema", payload).unwrap();
|
||||
}
|
||||
PeerCommand::Disconnect => {
|
||||
session.disconnect(b"scripted-goodbye".to_vec()).unwrap();
|
||||
continue 'sessions;
|
||||
}
|
||||
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(message_id: &str) -> CultNetMessage {
|
||||
match decode(&session()[1]) {
|
||||
CultNetMessage::SnapshotResponseRawV1 { matched, as_of, next, headers, documents, .. } => {
|
||||
CultNetMessage::SnapshotResponseRawV1 { message_id: message_id.into(), matched, as_of, next, headers, documents }
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
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_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"));
|
||||
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"));
|
||||
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 { .. })));
|
||||
}
|
||||
|
||||
/// Needs `dotnet` and a built CultLib: `CULTLIB_CS_SUBSCRIPTION_PEER=1`. The C# `rudp-subscription-serve` mode of the
|
||||
/// interop peer serves a `CultNetDatabase` over RUDP and, once the first subscribe is answered, commits a record
|
||||
/// and then two records in one commit.
|
||||
#[test]
|
||||
fn live_csharp_subscription() {
|
||||
if std::env::var_os("CULTLIB_CS_SUBSCRIPTION_PEER").is_none() {
|
||||
return;
|
||||
}
|
||||
use std::io::{BufRead, BufReader};
|
||||
use std::process::{Command, Stdio};
|
||||
let project = concat!(env!("CARGO_MANIFEST_DIR"), "/../../tests/GameCult.Networking.InteropPeer");
|
||||
let mut peer = Command::new("dotnet")
|
||||
.args(["run", "--project", project, "-c", "Release", "--", "rudp-subscription-serve"])
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.spawn()
|
||||
.expect("dotnet runs the interop peer");
|
||||
struct Kill(std::process::Child);
|
||||
impl Drop for Kill {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.0.kill();
|
||||
let _ = self.0.wait();
|
||||
}
|
||||
}
|
||||
let stdout = peer.stdout.take().unwrap();
|
||||
let peer = Kill(peer);
|
||||
let mut lines = BufReader::new(stdout).lines();
|
||||
let port = loop {
|
||||
let line = lines.next().expect("the peer announces its port").unwrap();
|
||||
if let Some(rest) = line.strip_prefix("listening ") {
|
||||
break rest.trim().parse::<u16>().unwrap();
|
||||
}
|
||||
};
|
||||
let mut options = CultMeshRudpSubscriptionOptions::new(SocketAddr::from(([127, 0, 0, 1], port)), "rust-subscriber");
|
||||
options.connect_timeout = Duration::from_secs(10);
|
||||
let client = CultMeshRudpSubscriptionClient::connect(options).unwrap();
|
||||
client.subscribe("live", Selection::default()).unwrap();
|
||||
// snapshot (empty), then the peer's scripted commits: one record, then two records in one commit.
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
let mut events = Vec::new();
|
||||
while Instant::now() < deadline && !events.iter().any(|e| matches!(e, CultMeshSubscriptionEvent::Subscription(SubscriptionEvent::Commit { changes, .. }) if changes.len() == 2)) {
|
||||
events.extend(client.try_drain());
|
||||
thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
assert!(matches!(&events[0], CultMeshSubscriptionEvent::Subscription(SubscriptionEvent::Snapshot { subscription_id, .. }) if subscription_id == "live"), "{events:?}");
|
||||
let commits: Vec<_> = events
|
||||
.iter()
|
||||
.filter_map(|e| match e {
|
||||
CultMeshSubscriptionEvent::Subscription(SubscriptionEvent::Commit { changes, .. }) => Some(changes.len()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(commits, [1, 2], "{events:?}");
|
||||
drop(client);
|
||||
drop(peer);
|
||||
}
|
||||
|
|
@ -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());
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue