Skip to main content

aimdb_core/session/
client.rs

1//! The proactive **client** engine of the session substrate — the dual of the
2//! [`server`](super::server): it *dials* a [`Connection`] via a [`Dialer`],
3//! *sends* [`Inbound`] / *receives* [`Outbound`], and demultiplexes replies by `id`.
4//!
5//! [`run_client`] owns the demux core and returns a [`ClientHandle`] for
6//! caller-initiated RPC (`call`/`subscribe`/`write`) plus the engine future for
7//! the runner to drive (spawn-free). [`pump_client`] is a thin wrapper that
8//! mirrors records over the same engine.
9//!
10//! Runtime-neutral: the only runtime-specific primitive is *time* (reconnect
11//! backoff + keepalive), via a [`RuntimeContext`](crate::RuntimeContext); everything else is
12//! `futures` channels. The demux loop uses the same **extract-then-act** shape as
13//! the server (compute a [`ClientStep`], then act once the arm borrows release).
14
15use crate::session::events::{report, SessionEvent};
16
17use alloc::boxed::Box;
18use alloc::string::{String, ToString};
19use alloc::sync::Arc;
20use alloc::vec::Vec;
21use core::sync::atomic::{AtomicUsize, Ordering};
22
23use async_channel::{Receiver, Sender};
24use futures_channel::oneshot;
25use futures_util::{select_biased, FutureExt, StreamExt};
26use hashbrown::HashMap;
27
28use super::{
29    BoxFut, BoxStream, CodecError, Connection, Dialer, EnvelopeCodec, Inbound, Outbound, Payload,
30    RpcError, SubUpdate, TransportError,
31};
32use crate::AimDb;
33
34/// Capacity of a subscription's client-side event sink. Bounded (was
35/// `unbounded`) so a slow consumer can't grow memory without limit under a fast
36/// wildcard set; matches the server's per-connection `EVENT_BUFFER`. On overflow
37/// the run loop drops the update and lets the loss surface as a `seq` gap
38/// (`SubUpdate::skipped`) on the next delivered update — for late-join snapshots
39/// too, which a wildcard subscription can burst well past this cap.
40const SUBSCRIBE_CHANNEL_CAP: usize = 256;
41
42/// Ceiling on [`ClientConfig::max_offline_queue`]: the channel preallocates its
43/// ring, so `usize::MAX` would abort in the allocator rather than reach it.
44const MAX_COMMAND_QUEUE_CAP: usize = 8192;
45
46/// Client engine knobs. Durations are in **milliseconds** so the engine stays
47/// `no_std`-clean; plain milliseconds turned into `core::time::Duration` for the clock.
48#[derive(Debug, Clone)]
49pub struct ClientConfig {
50    /// Redial after a dropped/failed connection instead of ending the engine.
51    /// Replays outbound traffic only: pending calls fail and open subscriptions
52    /// are not re-issued (so `pump_client` inbound mirroring stops after the first
53    /// disconnect; outbound survives).
54    pub reconnect: bool,
55    /// Base delay (ms) before the first redial; subsequent redials grow
56    /// exponentially, capped at [`max_reconnect_delay`](Self::max_reconnect_delay).
57    pub reconnect_delay: u64,
58    /// Upper bound (ms) for the reconnect backoff. Defaults to
59    /// [`reconnect_delay`](Self::reconnect_delay) (a fixed delay).
60    pub max_reconnect_delay: u64,
61    /// Maximum redial attempts before giving up. `0` = unlimited (default).
62    pub max_reconnect_attempts: usize,
63    /// Send a keepalive `Ping` after this many ms of an idle connection; any
64    /// traffic resets the idle window. `None` (default) disables it.
65    pub keepalive_interval: Option<u64>,
66    /// Capacity of the command channel, which buffers callers while the engine
67    /// isn't draining it (a pending dial, the backoff between redials). A full
68    /// channel evicts its oldest, visibly: a dropped `call` resolves
69    /// [`RpcError::Internal`], a dropped `subscribe` ends its stream. Defaults to
70    /// 256; clamped to `1..=MAX_COMMAND_QUEUE_CAP`.
71    pub max_offline_queue: usize,
72    /// Send a Ping handshake on connect and await the Pong before serving caller
73    /// commands. A real protocol swaps Ping/Pong for its Hello.
74    pub sends_hello: bool,
75}
76
77impl Default for ClientConfig {
78    fn default() -> Self {
79        Self {
80            reconnect: true,
81            reconnect_delay: 200,
82            max_reconnect_delay: 200,
83            max_reconnect_attempts: 0,
84            keepalive_interval: None,
85            max_offline_queue: 256,
86            sends_hello: false,
87        }
88    }
89}
90
91/// Exponential backoff (ms) for the `attempt`-th redial (1-based), capped at
92/// [`ClientConfig::max_reconnect_delay`].
93fn backoff_delay(config: &ClientConfig, attempt: usize) -> u64 {
94    let base = config.reconnect_delay;
95    let cap = config.max_reconnect_delay.max(base);
96    let shift = attempt.saturating_sub(1).min(16) as u32;
97    base.saturating_mul(1u64 << shift).min(cap)
98}
99
100/// A cheap-clone handle to a running [`run_client`] engine — the caller-facing
101/// RPC surface. Every method funnels a command to the engine, which owns the
102/// pending-call map and the wire.
103#[derive(Clone)]
104pub struct ClientHandle {
105    cmd_tx: Sender<ClientCmd>,
106    /// Wakes the engine to reclaim abandoned calls by inspection, when the exact
107    /// [`ClientCmd::CancelCall`] never reaches it (see [`Self::enqueue`]).
108    ///
109    /// A channel, not a flag: the caller learns of an eviction only from
110    /// `force_send`'s return value, by which point the engine may already have
111    /// looked, and a flag set then sits unread beside a parked engine. Capacity
112    /// one suffices — the sweep is idempotent, so one queued signal covers any
113    /// number of lost cancellations.
114    prune_tx: Sender<()>,
115    /// Correlation ids, allocated caller-side and shared by every clone.
116    ///
117    /// The *caller* numbers its requests so that abandoning one is race-free:
118    /// the id is known before the command is queued, so the cancellation that
119    /// follows on the same FIFO channel always names an entry the engine has
120    /// already created (see [`CancelOnDrop`]). With engine-assigned ids there is
121    /// an unavoidable window in which the caller gives up before learning the id
122    /// and has nothing to cancel. Calls and subscriptions draw from this one
123    /// counter because they share an id space on the wire.
124    ///
125    /// `usize` rather than `u64`: 64-bit atomics are not native on every
126    /// supported MCU (thumbv7em), and `portable_atomic::AtomicU64` covers that
127    /// only via its `critical-section` fallback — a dependency the engine will
128    /// not impose on every no_std consumer for a counter. The width bounds the
129    /// ids one process can issue — 2^32 on a 32-bit target, all of them
130    /// JSON-safe — and [`ClientHandle::next_id`] refuses rather than wraps at
131    /// the ceiling.
132    next_id: Arc<AtomicUsize>,
133}
134
135/// Commands the [`ClientHandle`] funnels to the engine. The caller allocates the
136/// correlation `id`; the engine owns the demux maps keyed by it.
137enum ClientCmd {
138    Call {
139        id: u64,
140        method: String,
141        params: Payload,
142        reply: oneshot::Sender<CallReply>,
143    },
144    /// The caller abandoned call `id` (its future was dropped). Frees the
145    /// pending-call entry immediately, without waiting for a reply that may
146    /// never come.
147    CancelCall {
148        id: u64,
149    },
150    Subscribe {
151        id: u64,
152        topic: String,
153        events: Sender<Result<SubUpdate, RpcError>>,
154    },
155    Write {
156        topic: String,
157        payload: Payload,
158    },
159}
160
161/// Frees a call's engine-side state if the caller stops awaiting it.
162///
163/// A dropped [`ClientHandle::call`] future takes the reply channel's receiver
164/// with it, which the engine cannot observe: a peer that holds the connection
165/// open but never answers produces neither a `Reply` nor a disconnect. The guard
166/// turns that silent drop into a [`ClientCmd::CancelCall`], so reclamation is
167/// exact and immediate — it needs no later call, no keepalive tick, and no scan
168/// of the pending table.
169///
170/// Alone among the commands it does not evict to make room — that would trade a
171/// caller's queued `Write` for bookkeeping. A full queue falls back to
172/// [`ClientHandle::prune_tx`], which frees the same entry without naming it.
173struct CancelOnDrop<'a> {
174    handle: &'a ClientHandle,
175    id: u64,
176    /// Cleared once the call resolves — a completed call has already left the
177    /// table, so cancelling it would only add channel traffic.
178    armed: bool,
179}
180
181impl Drop for CancelOnDrop<'_> {
182    fn drop(&mut self) {
183        if self.armed {
184            // Closed: the engine is gone with its table. Full: the sweep stands
185            // in for the exact id.
186            if self
187                .handle
188                .cmd_tx
189                .try_send(ClientCmd::CancelCall { id: self.id })
190                .is_err()
191            {
192                self.handle.request_prune();
193            }
194        }
195    }
196}
197
198impl ClientHandle {
199    /// Funnel a command to the engine, never blocking: a full channel evicts its
200    /// oldest, so the bound is the channel's own and holds across cloned handles
201    /// without an admission lock. Dropping the evictee drops its reply sender,
202    /// which is how the displaced caller learns. Fails once the engine has stopped.
203    ///
204    /// A [`ClientCmd::CancelCall`] is the one command that must not be evicted
205    /// *silently*: its entry is already in the engine's table, and nothing else
206    /// frees it before the connection ends. Eviction is FIFO-oldest and a
207    /// cancellation is always younger than its own request, so an evicted one
208    /// names an entry the engine already holds or never created — never one
209    /// still in flight. It degrades to a [`Self::request_prune`] signal, which
210    /// carries no id and so cannot itself be evicted.
211    fn enqueue(&self, cmd: ClientCmd) -> Result<(), RpcError> {
212        match self.cmd_tx.force_send(cmd) {
213            Ok(Some(ClientCmd::CancelCall { .. })) => {
214                self.request_prune();
215                Ok(())
216            }
217            Ok(_) => Ok(()),
218            Err(_) => Err(RpcError::Internal),
219        }
220    }
221
222    /// Ask the engine to reclaim every abandoned pending call. The sweep is
223    /// idempotent, so a full channel already carries the request.
224    fn request_prune(&self) {
225        let _ = self.prune_tx.try_send(());
226    }
227
228    /// Allocate the next correlation id. Monotonic across reconnects, so an id
229    /// is never reused by a later connection.
230    ///
231    /// Exhaustion is *refused*, not wrapped: `fetch_add` at the ceiling would
232    /// restart at `0` and re-issue ids still held by live subscriptions, whose
233    /// updates would then be demuxed into the wrong sink. Refusing turns that
234    /// silent mis-route into a failed `call`/`subscribe`. The ceiling is
235    /// `usize::MAX` — 2^32−1 on a 32-bit target, i.e. unreachable in practice
236    /// (4 billion allocations on one connection lineage).
237    ///
238    /// [`RpcError::Internal`] doubles as "engine stopped" (see [`Self::enqueue`]);
239    /// a dedicated variant would add wire surface (`session::aimx`'s codec maps
240    /// every variant to a protocol string) for a case that cannot be recovered
241    /// from anyway.
242    fn next_id(&self) -> Result<u64, RpcError> {
243        self.next_id
244            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1))
245            .map(|id| id as u64)
246            .map_err(|_| RpcError::Internal)
247    }
248
249    /// One-shot RPC: send a request and await its single reply. Returns
250    /// [`RpcError::Internal`] if the engine has stopped or the connection drops
251    /// before the reply arrives.
252    ///
253    /// Cancel-safe: dropping this future (a timeout losing the race, an aborted
254    /// task) releases the engine's pending-call entry rather than leaving it
255    /// until the connection ends.
256    pub async fn call(
257        &self,
258        method: impl Into<String>,
259        params: Payload,
260    ) -> Result<Payload, RpcError> {
261        let id = self.next_id()?;
262        let (reply, rx) = oneshot::channel();
263        self.enqueue(ClientCmd::Call {
264            id,
265            method: method.into(),
266            params,
267            reply,
268        })?;
269        // Armed across the await only: from here, any exit path that isn't the
270        // reply itself tells the engine to drop the entry.
271        let mut cancel = CancelOnDrop {
272            handle: self,
273            id,
274            armed: true,
275        };
276        let reply = rx.await;
277        cancel.armed = false;
278        reply.map_err(|_| RpcError::Internal)?
279    }
280
281    /// Open a subscription; returns the stream of updates immediately (the engine
282    /// sends the `Subscribe` request asynchronously). Dropping the stream stops
283    /// local delivery. The stream is not re-subscribed on reconnect (see
284    /// [`ClientConfig::reconnect`]) — re-call to resume.
285    ///
286    /// Each item is `Ok(`[`SubUpdate`]`)` for a delivered update, carrying the
287    /// concrete record topic when the server tags it (wildcard subscriptions fan
288    /// in many records under this one stream). A server rejection surfaces as a
289    /// terminal `Err(`[`RpcError`]`)` item, letting the caller distinguish a
290    /// denied subscription (do not retry) from a disconnect-shaped stream end
291    /// (retry to resume).
292    ///
293    /// Late-join snapshots arrive first, the last of them flagged
294    /// [`SubUpdate::snapshot_end`] with the burst's total loss in `skipped` (see
295    /// [`Session::snapshots`](super::Session::snapshots)). Read that flag to
296    /// close out the initial state, but drive the stream normally rather than
297    /// looping *until* it: a subscription matching no records never emits one,
298    /// and neither does one whose final snapshot frame was lost — the stream
299    /// stays open and simply proceeds to live events.
300    pub fn subscribe(
301        &self,
302        topic: impl Into<String>,
303    ) -> Result<BoxStream<'static, Result<SubUpdate, RpcError>>, RpcError> {
304        let (events, rx) =
305            async_channel::bounded::<Result<SubUpdate, RpcError>>(SUBSCRIBE_CHANNEL_CAP);
306        self.enqueue(ClientCmd::Subscribe {
307            id: self.next_id()?,
308            topic: topic.into(),
309            events,
310        })?;
311        // The receiver is itself a `Stream<Item = SubUpdate>`.
312        Ok(Box::pin(rx))
313    }
314
315    /// Fire-and-forget write to a remote topic (no reply).
316    pub fn write(&self, topic: impl Into<String>, payload: Payload) -> Result<(), RpcError> {
317        self.enqueue(ClientCmd::Write {
318            topic: topic.into(),
319            payload,
320        })
321    }
322}
323
324/// Build the client engine: returns a [`ClientHandle`] for issuing RPC and the
325/// engine future to drive on the runner (spawn-free). The future runs until all
326/// `ClientHandle` clones are dropped (graceful stop) — or, with
327/// [`ClientConfig::reconnect`] off, until the first disconnect.
328///
329/// `ctx` is a [`RuntimeContext`](crate::RuntimeContext) (`db.runtime_ctx()`
330/// inside an instance, `RuntimeContext::new(adapter)` outside one); the engine
331/// uses its clock and sleep for the reconnect backoff and keepalive — the
332/// *only* runtime dependency, so the rest of the engine is runtime-neutral.
333pub fn run_client<D, C>(
334    dialer: D,
335    codec: C,
336    config: ClientConfig,
337    ctx: crate::RuntimeContext,
338) -> (ClientHandle, BoxFut<'static, ()>)
339where
340    D: Dialer + 'static,
341    C: EnvelopeCodec + 'static,
342{
343    let (cmd_tx, cmd_rx) =
344        async_channel::bounded(config.max_offline_queue.clamp(1, MAX_COMMAND_QUEUE_CAP));
345    // Capacity one: the signal is a request to sweep, not a queue of them.
346    let (prune_tx, prune_rx) = async_channel::bounded(1);
347    let handle = ClientHandle {
348        cmd_tx,
349        prune_tx,
350        // Ids start at 1: `0` stays free as a "no correlation" sentinel for
351        // protocols that want one.
352        next_id: Arc::new(AtomicUsize::new(1)),
353    };
354    let fut = Box::pin(client_loop(dialer, codec, config, cmd_rx, prune_rx, ctx));
355    (handle, fut)
356}
357
358/// Why one connection's session ended — decides reconnect vs stop.
359enum Ended {
360    /// The connection dropped/errored; redial if configured.
361    Disconnected,
362    /// Every [`ClientHandle`] was dropped — stop the engine.
363    HandlesDropped,
364}
365
366/// On engine exit, close and drain the command channel so buffered/in-flight
367/// commands are dropped — each `ClientCmd::Call` drops its `reply` sender, so a
368/// waiting [`ClientHandle::call`] resolves with [`RpcError::Internal`] instead of
369/// hanging.
370///
371/// Needed because `async-channel` keeps buffered items alive while any `Sender`
372/// exists, and dropping the `Receiver` only closes the queue without draining it.
373struct DrainOnExit<'a>(&'a Receiver<ClientCmd>);
374
375impl Drop for DrainOnExit<'_> {
376    fn drop(&mut self) {
377        self.0.close();
378        while self.0.try_recv().is_ok() {}
379    }
380}
381
382/// How an inbound update competes for room in its subscription's sink.
383///
384/// Every update stops one slot short of a full sink: that last slot belongs to
385/// the terminal error [`end_sub`] may still have to deliver, so a slow
386/// subscriber sees *why* its stream ended rather than a disconnect-shaped EOF.
387#[derive(Clone, Copy, PartialEq, Eq)]
388enum Delivery {
389    /// A live event: dropped when the sink is full.
390    Event,
391    /// A snapshot with more of its burst to come: dropped when the sink is
392    /// full, and additionally stops one more slot short so
393    /// [`Delivery::BurstEnd`] always fits.
394    BurstBody,
395    /// The burst's final snapshot: carries the burst's whole loss count and
396    /// [`SubUpdate::snapshot_end`], delivered into the slot
397    /// [`Delivery::BurstBody`] stopped short of.
398    ///
399    /// Only a `BurstBody` reserves that slot, so a single-snapshot burst rests
400    /// on ordering instead: the sink predates the subscribe reply, and the
401    /// server sends every snapshot before registering the event pump. A burst
402    /// with no snapshots sends no `BurstEnd` at all.
403    BurstEnd,
404}
405
406/// Route one subscription update (snapshot or event) to its sink, folding any
407/// loss since the last delivery into its [`SubUpdate::skipped`].
408///
409/// Server `seq` counts true production across the *whole* subscription — the
410/// late-join snapshot burst (`1..=N`) and then its events (`N + 1`…), with
411/// server-side buffer lag folded in via `+= skipped + 1` and funnel drops
412/// bumping the counter before dropping. So one delta against the last delivered
413/// seq captures every loss point, plus any prior local full-channel drop that
414/// left `last_seq` behind.
415///
416/// A gap only *reaches* the subscriber on an update that is actually delivered,
417/// which is why the burst reserves a slot for its final snapshot: a burst
418/// truncated at the tail would otherwise stay silent until some later event
419/// closed the sequence, and a static subscription may never produce one.
420///
421/// `seq` is peer-supplied and unvalidated, so neither its monotonicity nor its
422/// range can be assumed: the arithmetic saturates, and the cursor only ever
423/// advances. A repeated or reordered frame is still delivered — dropping it
424/// would discard data over a number — but it cannot rewind the cursor into
425/// reporting a gap that never happened.
426///
427/// `update` carries the frame's topic, value and stamp; `deliver` fills in the
428/// loss accounting (`skipped`, `snapshot_end`).
429fn deliver(
430    subs: &mut HashMap<String, Sender<Result<SubUpdate, RpcError>>>,
431    last_seq: &mut HashMap<String, u64>,
432    sub: &str,
433    seq: u64,
434    mut update: SubUpdate,
435    mode: Delivery,
436) {
437    let prev = last_seq.get(sub).copied().unwrap_or(0);
438    let skipped = seq.saturating_sub(prev.saturating_add(1));
439    // `None` here is a late update for a dropped sub — ignore.
440    if let Some(tx) = subs.get(sub) {
441        // Hold the last slot back for a terminal error, and a burst body one
442        // more for the burst's final snapshot. Only this loop ever sends, so
443        // `len()` can only *fall* before the `try_send` below — a slot seen
444        // free here stays free, making those deliveries infallible rather than
445        // merely likely.
446        let reserved = if mode == Delivery::BurstBody { 2 } else { 1 };
447        if tx.capacity().is_some_and(|cap| tx.len() + reserved >= cap) {
448            // Slow consumer: drop this update but leave `last_seq` so the
449            // shortfall folds into the next delivered update's `skipped`.
450            return;
451        }
452        update.skipped = skipped;
453        update.snapshot_end = mode == Delivery::BurstEnd;
454        match tx.try_send(Ok(update)) {
455            // Delivered — advance the per-sub cursor, never rewind it.
456            Ok(()) => {
457                last_seq.insert(sub.to_string(), seq.max(prev));
458            }
459            // Full despite the check above: only a channel without a capacity
460            // gets here. Same as a slow consumer.
461            Err(e) if e.is_full() => {}
462            // Receiver gone — the sub was dropped; prune it.
463            Err(_) => {
464                subs.remove(sub);
465                last_seq.remove(sub);
466            }
467        }
468    }
469}
470
471/// End a subscription with a terminal `err` and drop its sink.
472///
473/// The error lands in the slot [`deliver`] never fills, so it reaches the
474/// subscriber even behind a full queue of buffered updates.
475fn end_sub(
476    subs: &mut HashMap<String, Sender<Result<SubUpdate, RpcError>>>,
477    last_seq: &mut HashMap<String, u64>,
478    sub: &str,
479    err: RpcError,
480) {
481    if let Some(tx) = subs.remove(sub) {
482        let _ = tx.try_send(Err(err));
483        last_seq.remove(sub);
484    }
485}
486
487/// What [`drive_connection`]'s `select_biased!` decided this iteration — extracted
488/// so the work runs after the arm futures' borrow of `conn` releases.
489enum ClientStep {
490    /// A frame (or close/error) arrived from the server.
491    Inbound(super::TransportResult<Option<Vec<u8>>>),
492    /// The keepalive timer fired — send a `Ping`.
493    Keepalive,
494    /// A cancellation was lost on the way here — reclaim abandoned calls by
495    /// inspecting the pending table instead of by id.
496    Prune,
497    /// A caller command (or `None` = all handles dropped).
498    Cmd(Option<ClientCmd>),
499}
500
501async fn client_loop<D, C>(
502    dialer: D,
503    codec: C,
504    config: ClientConfig,
505    cmd_rx: Receiver<ClientCmd>,
506    prune_rx: Receiver<()>,
507    ctx: crate::RuntimeContext,
508) where
509    D: Dialer,
510    C: EnvelopeCodec,
511{
512    // Whenever the engine returns, fail any buffered/in-flight calls (see guard).
513    let _drain = DrainOnExit(&cmd_rx);
514    // Consecutive failed attempts; drives backoff and the attempt cap.
515    let mut attempt: usize = 0;
516    loop {
517        let conn = match dialer.connect().await {
518            Ok(conn) => {
519                attempt = 0;
520                conn
521            }
522            Err(e) => {
523                report(SessionEvent::DialFailed { error: &e });
524                // `Closed` is terminal — the dialer signals it will never succeed
525                // again (e.g. the caller stopped the bridge), so retrying would
526                // spin a permanently-failing redial forever. Only transient
527                // failures (`Io`, `Busy`) earn a backoff+retry. Other transports' dialers
528                // map connect failures to `Io`, never `Closed`, so this is safe.
529                if e == TransportError::Closed {
530                    return;
531                }
532                match reconnect_after(&mut attempt, &config, &ctx).await {
533                    true => continue,
534                    false => return,
535                }
536            }
537        };
538
539        match drive_connection(conn, &codec, &cmd_rx, &prune_rx, &config, &ctx).await {
540            Ended::HandlesDropped => return,
541            Ended::Disconnected => match reconnect_after(&mut attempt, &config, &ctx).await {
542                true => continue,
543                false => return,
544            },
545        }
546    }
547}
548
549/// Decide whether to redial: honor `reconnect`, the attempt cap, and the
550/// exponential backoff sleep (via the runtime clock). Returns `true` to retry,
551/// `false` to stop the engine.
552async fn reconnect_after(
553    attempt: &mut usize,
554    config: &ClientConfig,
555    ctx: &crate::RuntimeContext,
556) -> bool {
557    if !config.reconnect {
558        return false;
559    }
560    *attempt += 1;
561    if config.max_reconnect_attempts != 0 && *attempt >= config.max_reconnect_attempts {
562        report(SessionEvent::ReconnectExhausted {
563            attempts: config.max_reconnect_attempts,
564        });
565        return false;
566    }
567    ctx.time()
568        .sleep(core::time::Duration::from_millis(backoff_delay(
569            config, *attempt,
570        )))
571        .await;
572    true
573}
574
575/// What a caller awaiting [`ClientHandle::call`] eventually receives.
576type CallReply = Result<Payload, RpcError>;
577
578/// The engine's in-flight call table: correlation `id` → the caller's reply
579/// channel.
580type PendingCalls = HashMap<u64, oneshot::Sender<CallReply>>;
581
582/// Reclaim every entry whose caller stopped waiting — the fallback for a
583/// [`ClientCmd::CancelCall`] the bounded command queue dropped.
584///
585/// A dropped receiver is exactly what an abandoned [`ClientHandle::call`] leaves
586/// behind, so this needs no id and cannot miss an earlier loss. `O(N)`, but
587/// reached only from the eviction path; a surviving cancellation stays `O(1)`.
588fn sweep_abandoned(pending: &mut PendingCalls) {
589    pending.retain(|_, reply| !reply.is_canceled());
590}
591
592/// Drive one dialed [`Connection`]: optional handshake, then `biased` demux of
593/// server frames (resolve `Reply` by `id`, route `Event`/`Snapshot` to their
594/// subscription channels) interleaved with caller commands. Pending state is
595/// per-connection: a disconnect fails outstanding calls (their `oneshot`
596/// senders drop → callers see [`RpcError::Internal`]). Calls the *caller*
597/// abandoned arrive as [`ClientCmd::CancelCall`] and are removed by id in O(1),
598/// so an unanswering peer that keeps the link open can't grow the table — with
599/// no dependence on later traffic or on the keepalive being enabled. One the
600/// command queue dropped instead arrives on `prune_rx` as a request to sweep.
601/// `pending` is per-connection, so a signal raised while dialing lands on a
602/// fresh table — a no-op, since the disconnect already dropped every entry.
603async fn drive_connection<C>(
604    mut conn: Box<dyn Connection>,
605    codec: &C,
606    cmd_rx: &Receiver<ClientCmd>,
607    prune_rx: &Receiver<()>,
608    config: &ClientConfig,
609    ctx: &crate::RuntimeContext,
610) -> Ended
611where
612    C: EnvelopeCodec + ?Sized,
613{
614    let mut pending: PendingCalls = HashMap::new();
615    // sub-id → event sink. The sub-id is `id.to_string()` of the opening
616    // request, matching the server's derivation so `Event.sub` routes back.
617    let mut subs: HashMap<String, Sender<Result<SubUpdate, RpcError>>> = HashMap::new();
618    // sub-id → last *delivered* wire `seq`. Baseline is 0, so the server's first
619    // seq (`1`) is the expected first delivery; any shortfall is loss. Not
620    // advanced on a locally-dropped event, so a full-channel drop also surfaces
621    // as a gap on the next delivery.
622    let mut last_seq: HashMap<String, u64> = HashMap::new();
623    let mut out = Vec::new();
624    let keepalive_ms = config.keepalive_interval;
625    // Keepalive is deadline-based: activity only records a timestamp (one dyn
626    // clock read, no allocation) and the boxed `ctx.time().sleep` stays armed for a
627    // full idle window — re-created roughly once per interval, not on every
628    // processed frame (`dyn RuntimeOps::sleep` heap-allocates its future).
629    let mut last_activity = ctx.time().now().as_nanos();
630    let mut keepalive_timer = keepalive_ms.map(|ms| {
631        ctx.time()
632            .sleep(core::time::Duration::from_millis(ms))
633            .fuse()
634    });
635
636    // Handshake-as-caller: prove the link with Ping/Pong before serving commands.
637    if config.sends_hello {
638        out.clear();
639        if codec.encode_inbound(Inbound::Ping, &mut out).is_err() || conn.send(&out).await.is_err()
640        {
641            return Ended::Disconnected;
642        }
643        match conn.recv().await {
644            Ok(Some(frame)) => match codec.decode_outbound(&frame) {
645                Ok(Outbound::Pong) => {}
646                _ => return Ended::Disconnected,
647            },
648            _ => return Ended::Disconnected,
649        }
650    }
651
652    loop {
653        // Biased toward the server read. The select only decides the next step.
654        let step = {
655            let mut recv = conn.recv().fuse();
656            // The armed idle timer (see above); with no interval it parks on
657            // `pending()` forever. `Either` re-borrows the persistent timer,
658            // so this is allocation-free per iteration.
659            let mut keepalive = match keepalive_timer.as_mut() {
660                Some(timer) => futures_util::future::Either::Left(timer),
661                None => futures_util::future::Either::Right(futures_util::future::pending::<()>()),
662            };
663            // `recv()` is `!Unpin`, so pin it for the arm.
664            let mut cmd = core::pin::pin!(cmd_rx.recv().fuse());
665            let mut prune = core::pin::pin!(async {
666                if prune_rx.recv().await.is_err() {
667                    // Handles all dropped — the `cmd` arm reports that. A closed
668                    // channel resolves immediately and this arm outranks `cmd`,
669                    // so park rather than spin ahead of the shutdown.
670                    futures_util::future::pending::<()>().await;
671                }
672            }
673            .fuse());
674            select_biased! {
675                // ---- inbound from server: Reply / Event / Snapshot / Pong --
676                r = recv => ClientStep::Inbound(r),
677                // ---- keepalive: the idle timer fired ------------------------
678                _ = keepalive => ClientStep::Keepalive,
679                // ---- a lost cancellation asked for a sweep ------------------
680                // Above `cmd`: a full command queue is what raises the signal,
681                // so a lower arm would be starved by its own trigger.
682                _ = prune => ClientStep::Prune,
683                // ---- caller commands from ClientHandle ---------------------
684                // `recv()` errors only when every `ClientHandle` is dropped → `None`.
685                c = cmd => ClientStep::Cmd(c.ok()),
686            }
687        };
688
689        // Frames and commands are link activity; only a genuinely idle link
690        // needs a Ping. A sweep is local bookkeeping with no wire traffic, so a
691        // busy-cancelling caller must not suppress the keepalive with it.
692        if !matches!(step, ClientStep::Keepalive | ClientStep::Prune) {
693            last_activity = ctx.time().now().as_nanos();
694        }
695
696        match step {
697            ClientStep::Inbound(recv) => {
698                let frame = match recv {
699                    Ok(Some(frame)) => frame,
700                    Ok(None) | Err(_) => return Ended::Disconnected,
701                };
702                match codec.decode_outbound(&frame) {
703                    Ok(Outbound::Reply { id, result }) => {
704                        if let Some(tx) = pending.remove(&id) {
705                            let _ = tx.send(result);
706                        } else if let Err(err) = result {
707                            // A subscribe is acked implicitly by its events; the
708                            // server replies only on failure, carrying the subscribe
709                            // `id` (never a pending call). Surface the rejection as a
710                            // terminal error item before dropping the sink, so the
711                            // subscriber can tell "denied" from a disconnect-shaped
712                            // stream end instead of re-subscribing forever.
713                            end_sub(&mut subs, &mut last_seq, &id.to_string(), err);
714                        }
715                    }
716                    Ok(Outbound::Event {
717                        sub,
718                        seq,
719                        topic,
720                        ts,
721                        data,
722                    }) => deliver(
723                        &mut subs,
724                        &mut last_seq,
725                        sub,
726                        seq,
727                        match topic {
728                            Some(topic) => SubUpdate::tagged(Arc::from(topic), data, ts),
729                            None => SubUpdate::new(data, ts),
730                        },
731                        Delivery::Event,
732                    ),
733                    // Snapshots ride the same accounting as events (they share
734                    // the subscription's `seq` space), so a late-join burst that
735                    // overruns a slow consumer's sink is reported as `skipped`
736                    // instead of vanishing. The burst's final snapshot is
737                    // delivered unconditionally, so "one snapshot per matched
738                    // record" is checkable the moment the burst ends — no live
739                    // event required.
740                    Ok(Outbound::Snapshot {
741                        sub,
742                        seq,
743                        last,
744                        topic,
745                        ts,
746                        data,
747                    }) => deliver(
748                        &mut subs,
749                        &mut last_seq,
750                        sub,
751                        seq,
752                        SubUpdate::tagged(Arc::from(topic), data, ts),
753                        if last {
754                            Delivery::BurstEnd
755                        } else {
756                            Delivery::BurstBody
757                        },
758                    ),
759                    Ok(Outbound::Pong) => {}
760                    // Explicit subscribe ack — informational; the sink already exists.
761                    Ok(Outbound::Subscribed { .. }) => {}
762                    // A value without its stamp breaks the protocol for that
763                    // subscription: end it with an error the subscriber sees,
764                    // as a refusal does, instead of dropping the frame unseen.
765                    Err(CodecError::MissingStamp { sub }) => {
766                        end_sub(&mut subs, &mut last_seq, &sub, RpcError::Protocol)
767                    }
768                    Err(_e) => continue, // skip a malformed frame, keep the connection
769                }
770            }
771
772            // A cancellation was dropped by the bounded command queue, so the
773            // engine can't be told *which* entry died — but it can see it.
774            ClientStep::Prune => sweep_abandoned(&mut pending),
775
776            ClientStep::Keepalive => {
777                // `keepalive_timer` is `Some` whenever this step fires.
778                let interval_ms = keepalive_ms.unwrap_or(0);
779                let idle_ms = ctx.time().now().as_nanos().saturating_sub(last_activity) / 1_000_000;
780                if idle_ms >= interval_ms {
781                    // Genuinely idle for a full window: ping and re-arm.
782                    out.clear();
783                    if codec.encode_inbound(Inbound::Ping, &mut out).is_ok()
784                        && conn.send(&out).await.is_err()
785                    {
786                        return Ended::Disconnected;
787                    }
788                    last_activity = ctx.time().now().as_nanos();
789                    keepalive_timer = Some(
790                        ctx.time()
791                            .sleep(core::time::Duration::from_millis(interval_ms))
792                            .fuse(),
793                    );
794                } else {
795                    // Activity happened while the timer was armed: no ping,
796                    // re-arm for the remainder of the idle window.
797                    keepalive_timer = Some(
798                        ctx.time()
799                            .sleep(core::time::Duration::from_millis(interval_ms - idle_ms))
800                            .fuse(),
801                    );
802                }
803            }
804
805            ClientStep::Cmd(cmd) => {
806                let cmd = match cmd {
807                    Some(cmd) => cmd,
808                    None => return Ended::HandlesDropped, // all handles dropped
809                };
810                match cmd {
811                    ClientCmd::Call {
812                        id,
813                        method,
814                        params,
815                        reply,
816                    } => {
817                        // The caller may have given up while the command sat in
818                        // the queue — don't spend a wire request on a reply
819                        // nobody is waiting for. Its `CancelCall` is already
820                        // queued behind this one and will find nothing to free.
821                        if reply.is_canceled() {
822                            continue;
823                        }
824                        pending.insert(id, reply);
825                        out.clear();
826                        let sent = codec
827                            .encode_inbound(Inbound::Request { id, method, params }, &mut out)
828                            .is_ok()
829                            && conn.send(&out).await.is_ok();
830                        if !sent {
831                            if let Some(tx) = pending.remove(&id) {
832                                let _ = tx.send(Err(RpcError::Internal));
833                            }
834                            return Ended::Disconnected;
835                        }
836                    }
837                    // The caller abandoned this call: drop its reply channel now
838                    // rather than holding it until a reply that may never arrive
839                    // (or the disconnect). A resolved or never-dispatched call
840                    // is simply absent — removing it is a no-op.
841                    ClientCmd::CancelCall { id } => {
842                        pending.remove(&id);
843                    }
844                    ClientCmd::Subscribe { id, topic, events } => {
845                        subs.insert(id.to_string(), events);
846                        out.clear();
847                        let sent = codec
848                            .encode_inbound(Inbound::Subscribe { id, topic }, &mut out)
849                            .is_ok()
850                            && conn.send(&out).await.is_ok();
851                        if !sent {
852                            return Ended::Disconnected;
853                        }
854                    }
855                    ClientCmd::Write { topic, payload } => {
856                        out.clear();
857                        let sent = codec
858                            .encode_inbound(Inbound::Write { topic, payload }, &mut out)
859                            .is_ok()
860                            && conn.send(&out).await.is_ok();
861                        if !sent {
862                            return Ended::Disconnected;
863                        }
864                    }
865                }
866            }
867        }
868    }
869}
870
871/// Mirror records between a local [`AimDb`] and a remote peer over a running
872/// [`run_client`] engine — the connector-link half of the client capability.
873///
874/// For the given connector `scheme` (e.g. `"aimx"`):
875/// - **outbound** routes ([`OutboundRoutes`](crate::OutboundRoutes)) stream
876///   local record updates to the remote via [`ClientHandle::write`], all from
877///   one task;
878/// - **inbound** routes (`inbound`, an [`InboundDispatch`](crate::InboundDispatch)) subscribe to the remote and
879///   produce each update into the local record through the producer/arbiter path
880///   — single-writer-per-key stays intact (a mirrored-in record is produced
881///   through its inbound producer, never a direct co-writer). Mirroring is
882///   latest-state and best-effort — a gap the server reports
883///   ([`SubUpdate::skipped`]) is logged and stepped over, never backfilled.
884///
885/// Returns spawn-free futures for the runner to drive (mirroring the
886/// `ConnectorBuilder::build -> Vec<BoxFuture>` spine): one for every outbound
887/// route together, when there are any, and one per inbound subscription. They
888/// drive the **same** engine as [`run_client`], never a second one. Fails when
889/// an outbound link cannot be served (see
890/// [`OutboundRoutes::new`](crate::OutboundRoutes::new)).
891///
892/// [`ClientHandle::write`] enqueues onto the engine's bounded command queue
893/// and displaces the oldest command when it is full, so during an outage that
894/// queue, not the record buffer, decides what survives.
895///
896/// Reconnect caveat: inbound pumps subscribe once and are not replayed across a
897/// reconnect (see [`ClientConfig::reconnect`]); outbound mirroring is unaffected.
898pub fn pump_client(
899    db: &AimDb,
900    scheme: &str,
901    inbound: crate::InboundDispatch,
902    handle: &ClientHandle,
903) -> crate::DbResult<Vec<BoxFut<'static, ()>>> {
904    let mut pumps: Vec<BoxFut<'static, ()>> = Vec::new();
905
906    // --- outbound: local record updates -> remote `write`, one task --------
907    // Skips, lag and closed routes are handled and counted inside
908    // `OutboundRoutes`; `next` ends once every route has closed.
909    let mut outbound = crate::OutboundRoutes::new(db, scheme)?;
910    if !outbound.routes().is_empty() {
911        let handle = handle.clone();
912        pumps.push(Box::pin(async move {
913            while let Some(msg) = outbound.next().await {
914                let payload = match msg.payload {
915                    crate::OutboundPayload::Borrowed(bytes) => Payload::from(bytes),
916                    crate::OutboundPayload::Owned(bytes) => Payload::from(bytes),
917                };
918                if handle.write(msg.topic, payload).is_err() {
919                    break; // engine stopped — all handles dropped
920                }
921            }
922        }));
923    }
924
925    // --- inbound: remote events -> local producer --------------------------
926    // The dispatcher applies each route's deserializer and produces the
927    // value; one subscription per unique remote topic feeds it.
928    for id in inbound.subscriptions() {
929        pumps.push(Box::pin(inbound_pump(handle.clone(), inbound.clone(), id)));
930    }
931
932    Ok(pumps)
933}
934
935/// Drive one inbound mirror: subscribe to remote topic `id` and produce every
936/// update into the local record through the [`InboundDispatch`](crate::InboundDispatch).
937///
938/// **Loss contract: a mirror is latest-state, best-effort.** A mirrored record
939/// answers "what is the current value", not "what was every value" — so a gap
940/// reported by the server ([`SubUpdate::skipped`], raised when a subscription's
941/// sink overran) is *logged and stepped over*, never backfilled. The mirror does
942/// not resync, and a consumer must not read a mirrored record as a complete
943/// history. Callers that need gap-aware delivery subscribe through
944/// `AimxConnection` (`aimdb-client`), which surfaces `skipped` per update;
945/// [`ClientHandle::subscribe`] carries the same metadata for anyone riding the
946/// handle directly.
947async fn inbound_pump(handle: ClientHandle, inbound: crate::InboundDispatch, id: Arc<str>) {
948    let mut stream = match handle.subscribe(id.as_ref()) {
949        Ok(s) => s,
950        Err(_e) => return,
951    };
952    while let Some(update) = stream.next().await {
953        match update {
954            Ok(update) => {
955                // Per the loss contract above: surface the hole, keep mirroring.
956                if update.skipped > 0 {
957                    report(SessionEvent::MirrorGap {
958                        topic: id.as_ref(),
959                        skipped: update.skipped,
960                    });
961                }
962                inbound.dispatch(id.as_ref(), &update.data);
963            }
964            // Server rejected the subscription — terminal, not replayed.
965            Err(_e) => break,
966        }
967    }
968}
969
970#[cfg(test)]
971mod tests {
972    use super::*;
973    use crate::session::{CodecError, PeerInfo, TransportResult};
974    use core::future::pending;
975
976    /// Sink connection: swallows every frame and never yields one, i.e. a peer
977    /// that keeps the link open and answers nothing.
978    #[derive(Default)]
979    struct SilentPeer {
980        peer: PeerInfo,
981    }
982
983    impl Connection for SilentPeer {
984        fn recv(&mut self) -> BoxFut<'_, TransportResult<Option<Vec<u8>>>> {
985            Box::pin(pending())
986        }
987        fn send<'a>(&'a mut self, _frame: &'a [u8]) -> BoxFut<'a, TransportResult<()>> {
988            Box::pin(async { Ok(()) })
989        }
990        fn peer(&self) -> &PeerInfo {
991            &self.peer
992        }
993    }
994
995    /// Frames are never inspected in these tests — only the pending-call
996    /// bookkeeping is.
997    struct NullCodec;
998
999    impl EnvelopeCodec for NullCodec {
1000        fn decode(&self, _frame: &[u8]) -> Result<Inbound, CodecError> {
1001            Err(CodecError::Malformed)
1002        }
1003        fn encode(&self, _msg: Outbound<'_>, _out: &mut Vec<u8>) -> Result<(), CodecError> {
1004            Ok(())
1005        }
1006        fn encode_inbound(&self, _msg: Inbound, _out: &mut Vec<u8>) -> Result<(), CodecError> {
1007            Ok(())
1008        }
1009        fn decode_outbound<'a>(&self, _frame: &'a [u8]) -> Result<Outbound<'a>, CodecError> {
1010            Err(CodecError::Malformed)
1011        }
1012    }
1013
1014    /// A handle whose channel nobody drains — an engine still dialing, or
1015    /// sleeping between redials. `cap` is [`ClientConfig::max_offline_queue`].
1016    /// The prune receiver comes back too: dropping it would close the signal
1017    /// channel and silently no-op every [`ClientHandle::request_prune`].
1018    fn test_handle_capped(cap: usize) -> (ClientHandle, Receiver<ClientCmd>, Receiver<()>) {
1019        let (cmd_tx, cmd_rx) = async_channel::bounded(cap.max(1));
1020        let (prune_tx, prune_rx) = async_channel::bounded(1);
1021        (
1022            ClientHandle {
1023                cmd_tx,
1024                prune_tx,
1025                next_id: Arc::new(AtomicUsize::new(1)),
1026            },
1027            cmd_rx,
1028            prune_rx,
1029        )
1030    }
1031
1032    fn test_handle() -> (ClientHandle, Receiver<ClientCmd>, Receiver<()>) {
1033        test_handle_capped(256)
1034    }
1035
1036    /// Poll a call once — enough to queue its command — then abandon it, which
1037    /// is what a lost timeout race does to the future.
1038    async fn abandon_call(handle: &ClientHandle, method: &'static str) {
1039        let call = handle.call(method, Payload::from(&b"x"[..]));
1040        assert!(
1041            tokio::time::timeout(core::time::Duration::ZERO, call)
1042                .await
1043                .is_err(),
1044            "the call must not resolve"
1045        );
1046    }
1047
1048    /// The caller half of the reclaim path: abandoning a call queues a
1049    /// `CancelCall` naming exactly that call, so the engine never has to guess
1050    /// which entry died.
1051    #[tokio::test]
1052    async fn abandoning_a_call_queues_its_cancellation() {
1053        let (handle, cmd_rx, _prune_rx) = test_handle();
1054        abandon_call(&handle, "one").await;
1055
1056        match cmd_rx.try_recv() {
1057            Ok(ClientCmd::Call { id: 1, .. }) => {}
1058            _ => panic!("the call must be queued first"),
1059        }
1060        match cmd_rx.try_recv() {
1061            Ok(ClientCmd::CancelCall { id: 1 }) => {}
1062            _ => panic!("abandoning the call must queue its cancellation"),
1063        }
1064        assert!(cmd_rx.is_empty(), "no other command is emitted");
1065    }
1066
1067    /// A call that resolves normally must not also queue a cancellation — the
1068    /// engine already dropped its entry when it routed the reply.
1069    #[tokio::test]
1070    async fn a_resolved_call_queues_no_cancellation() {
1071        let (handle, cmd_rx, _prune_rx) = test_handle();
1072        let call = handle.call("one", Payload::from(&b"x"[..]));
1073        let answer = async {
1074            // Take the reply channel out of the queued command and answer it.
1075            match cmd_rx.recv().await {
1076                Ok(ClientCmd::Call { reply, .. }) => {
1077                    let _ = reply.send(Ok(Payload::from(&b"ok"[..])));
1078                }
1079                _ => panic!("the call must be queued"),
1080            }
1081        };
1082        let (reply, ()) = futures_util::future::join(call, answer).await;
1083        assert_eq!(&*reply.expect("the call resolves"), b"ok");
1084        assert!(
1085            cmd_rx.is_empty(),
1086            "a resolved call must not queue a cancellation"
1087        );
1088    }
1089
1090    /// Regression for the *concurrent* timeout batch: every call is issued and
1091    /// tracked while its receiver is live, then all of them are abandoned at
1092    /// once, with keepalive disabled and no later call to trigger a sweep.
1093    ///
1094    /// Each entry the engine frees drops its reply sender, which the (retained)
1095    /// receiver observes as `Canceled` — so this asserts the table actually
1096    /// empties rather than that some reclaim path merely ran. Pre-fix all 1000
1097    /// entries stayed until the connection ended.
1098    #[tokio::test]
1099    async fn a_concurrent_batch_of_cancellations_frees_every_entry() {
1100        const BATCH: u64 = 1_000;
1101        let (cmd_tx, cmd_rx) = async_channel::unbounded::<ClientCmd>();
1102        let config = ClientConfig {
1103            reconnect: false,
1104            // The point of the test: nothing but the cancellations can reclaim.
1105            keepalive_interval: None,
1106            ..Default::default()
1107        };
1108        let ctx =
1109            crate::RuntimeContext::new(Arc::new(crate::executor::test_support::NoopRuntimeOps));
1110        // Never signalled: this asserts the by-id path reclaims on its own.
1111        let (_prune_tx, prune_rx) = async_channel::bounded::<()>(1);
1112        let engine = drive_connection(
1113            Box::new(SilentPeer::default()),
1114            &NullCodec,
1115            &cmd_rx,
1116            &prune_rx,
1117            &config,
1118            &ctx,
1119        );
1120
1121        let exercise = async {
1122            // All in flight at once: every receiver is alive as its call is
1123            // tracked, so nothing is reclaimable until the batch is abandoned.
1124            let mut replies = Vec::new();
1125            for id in 1..=BATCH {
1126                let (reply, rx) = oneshot::channel();
1127                cmd_tx
1128                    .try_send(ClientCmd::Call {
1129                        id,
1130                        method: String::from("hang"),
1131                        params: Payload::from(&b"x"[..]),
1132                        reply,
1133                    })
1134                    .expect("the channel is unbounded");
1135                replies.push(rx);
1136            }
1137            // Then the whole batch times out.
1138            for id in 1..=BATCH {
1139                cmd_tx
1140                    .try_send(ClientCmd::CancelCall { id })
1141                    .expect("the channel is unbounded");
1142            }
1143            for (i, rx) in replies.into_iter().enumerate() {
1144                assert!(
1145                    rx.await.is_err(),
1146                    "call {} was still held by the engine",
1147                    i + 1
1148                );
1149            }
1150        };
1151
1152        futures_util::pin_mut!(engine);
1153        futures_util::pin_mut!(exercise);
1154        match futures_util::future::select(engine, exercise).await {
1155            futures_util::future::Either::Left(_) => panic!("the engine ended early"),
1156            futures_util::future::Either::Right(((), _)) => {}
1157        }
1158    }
1159
1160    /// The id counter refuses rather than wraps at its ceiling: a wrapped id
1161    /// would re-issue one a live subscription still holds, and the engine would
1162    /// demux that subscription's updates into the wrong sink. Both allocating
1163    /// call sites fail, and neither reaches the engine — so no pending entry is
1164    /// ever created under an id that would be mis-routed.
1165    #[tokio::test]
1166    async fn exhausted_ids_are_refused_not_wrapped() {
1167        let (cmd_tx, cmd_rx) = async_channel::bounded(256);
1168        let (prune_tx, _prune_rx) = async_channel::bounded(1);
1169        let handle = ClientHandle {
1170            cmd_tx,
1171            prune_tx,
1172            next_id: Arc::new(AtomicUsize::new(usize::MAX)),
1173        };
1174
1175        // Bounded at zero: the refusal happens before the id is queued, so it
1176        // resolves on the first poll. A wrapping counter would instead queue the
1177        // call and await a reply forever — the timeout turns that regression
1178        // into a failure rather than a hang.
1179        let refused = tokio::time::timeout(
1180            core::time::Duration::ZERO,
1181            handle.call("one", Payload::from(&b"x"[..])),
1182        )
1183        .await
1184        .expect("a refused call must not reach the engine and await a reply");
1185        assert!(
1186            matches!(refused, Err(RpcError::Internal)),
1187            "a call at the id ceiling must be refused"
1188        );
1189        assert!(
1190            handle.subscribe("tele").is_err(),
1191            "a subscription at the id ceiling must be refused"
1192        );
1193        assert!(
1194            cmd_rx.is_empty(),
1195            "a refused allocation must not reach the engine"
1196        );
1197    }
1198
1199    /// Evict-oldest puts a cancellation on the same lossy footing as a write,
1200    /// but dropping one silently strands its pending entry until the connection
1201    /// ends — so the eviction has to be noticed. Nothing drains the queue here:
1202    /// the saturated state a pending dial or a backoff sleep produces.
1203    #[tokio::test]
1204    async fn an_evicted_cancellation_raises_the_prune_signal() {
1205        let (handle, cmd_rx, prune_rx) = test_handle_capped(1);
1206
1207        handle
1208            .enqueue(ClientCmd::CancelCall { id: 1 })
1209            .expect("the engine is still running");
1210        assert!(prune_rx.is_empty(), "nothing has been evicted yet");
1211
1212        // Fills the single slot, displacing the cancellation.
1213        handle
1214            .write("tele", Payload::from(&b"x"[..]))
1215            .expect("the engine is still running");
1216
1217        assert_eq!(cmd_rx.len(), 1, "the cap still holds");
1218        assert_eq!(
1219            prune_rx.len(),
1220            1,
1221            "an evicted cancellation must fall back to a sweep"
1222        );
1223    }
1224
1225    /// The negative control: eviction is the documented, caller-visible cost of
1226    /// the bound for ordinary commands. Signalling on every one would drag an
1227    /// `O(N)` sweep into steady-state backpressure.
1228    #[tokio::test]
1229    async fn an_evicted_write_raises_no_prune_signal() {
1230        let (handle, _cmd_rx, prune_rx) = test_handle_capped(1);
1231
1232        for topic in ["one", "two"] {
1233            handle
1234                .write(topic, Payload::from(&b"x"[..]))
1235                .expect("the engine is still running");
1236        }
1237
1238        assert!(
1239            prune_rx.is_empty(),
1240            "an evicted write is expected loss, not a leak"
1241        );
1242    }
1243
1244    /// A cancellation is bookkeeping; a queued `Write` is work the caller asked
1245    /// for. Cap 2, so the write and the call itself both fit and the
1246    /// cancellation is the only command that finds the queue full.
1247    #[tokio::test]
1248    async fn a_cancellation_never_evicts_a_queued_write() {
1249        let (handle, cmd_rx, prune_rx) = test_handle_capped(2);
1250
1251        handle
1252            .write("tele", Payload::from(&b"x"[..]))
1253            .expect("the engine is still running");
1254        abandon_call(&handle, "hang").await;
1255
1256        assert_eq!(cmd_rx.len(), 2, "the cap still holds");
1257        match cmd_rx.try_recv() {
1258            Ok(ClientCmd::Write { topic, .. }) => assert_eq!(topic, "tele"),
1259            _ => panic!("the caller's write must survive the cancellation"),
1260        }
1261        match cmd_rx.try_recv() {
1262            Ok(ClientCmd::Call { id: 1, .. }) => {}
1263            _ => panic!("the call itself must still be queued"),
1264        }
1265        assert_eq!(
1266            prune_rx.len(),
1267            1,
1268            "the cancellation it could not queue must fall back to a sweep"
1269        );
1270    }
1271
1272    /// The reclaim itself: an abandoned entry goes, a live one stays. Identity
1273    /// is the dropped receiver, which is why the sweep can stand in for a
1274    /// cancellation that never arrived.
1275    #[test]
1276    fn the_sweep_frees_abandoned_entries_and_keeps_live_ones() {
1277        let mut pending: PendingCalls = HashMap::new();
1278        let (abandoned, rx) = oneshot::channel();
1279        let (live, _live_rx) = oneshot::channel();
1280        pending.insert(1, abandoned);
1281        pending.insert(2, live);
1282        drop(rx); // the caller's future went away
1283
1284        sweep_abandoned(&mut pending);
1285
1286        assert!(
1287            !pending.contains_key(&1),
1288            "the abandoned call must be freed"
1289        );
1290        assert!(
1291            pending.contains_key(&2),
1292            "a caller still awaiting its reply must not be dropped"
1293        );
1294    }
1295
1296    /// End to end at capacity 1 against a peer that answers nothing: the exact
1297    /// loss the bound can inflict. The engine files a call while its caller
1298    /// still waits, the caller then abandons it — the cancellation lands in the
1299    /// drained queue — and a write evicts that cancellation. The engine still
1300    /// reclaims: keepalive off and no later command, so the signal is the only
1301    /// thing that can wake the sweep.
1302    ///
1303    /// Consuming the signal *is* the sweep running (one match arm), and
1304    /// [`the_sweep_frees_abandoned_entries_and_keeps_live_ones`] pins what it
1305    /// then does. The table is engine-local, and it cannot be watched from a
1306    /// retained receiver either: an entry whose receiver is retained is exactly
1307    /// the entry the sweep must keep. The timeout turns "never woke" into a
1308    /// failure rather than a hang.
1309    #[tokio::test]
1310    async fn an_evicted_cancellation_is_still_reclaimed() {
1311        use core::future::Future;
1312
1313        let (handle, cmd_rx, prune_rx) = test_handle_capped(1);
1314        let config = ClientConfig {
1315            reconnect: false,
1316            // Nothing but the signal may reclaim.
1317            keepalive_interval: None,
1318            ..Default::default()
1319        };
1320        let ctx =
1321            crate::RuntimeContext::new(Arc::new(crate::executor::test_support::NoopRuntimeOps));
1322        let engine = drive_connection(
1323            Box::new(SilentPeer::default()),
1324            &NullCodec,
1325            &cmd_rx,
1326            &prune_rx,
1327            &config,
1328            &ctx,
1329        );
1330
1331        let exercise = async {
1332            // Queue the call, then let the engine file it *while the caller
1333            // still waits* — a receiver already dropped when the command is
1334            // read is discarded on arrival and never reaches the table.
1335            let mut call = Box::pin(handle.call("hang", Payload::from(&b"x"[..])));
1336            core::future::poll_fn(|cx| {
1337                assert!(
1338                    call.as_mut().poll(cx).is_pending(),
1339                    "the call must not resolve"
1340                );
1341                core::task::Poll::Ready(())
1342            })
1343            .await;
1344            tokio::task::yield_now().await;
1345            assert!(cmd_rx.is_empty(), "the engine must have filed the call");
1346
1347            // Abandon it: the queue is drained, so the cancellation lands. No
1348            // yield before the write — the engine must not get the chance to
1349            // remove the entry by id.
1350            drop(call);
1351            assert_eq!(cmd_rx.len(), 1, "the cancellation must be queued");
1352            assert!(prune_rx.is_empty(), "nothing has fallen back to a sweep");
1353            handle
1354                .write("tele", Payload::from(&b"x"[..]))
1355                .expect("the engine is still running");
1356            assert_eq!(prune_rx.len(), 1, "the eviction must have been noticed");
1357
1358            // The wake-up is the point: the engine is parked on a silent peer
1359            // with keepalive off, so only the signal itself can reach it.
1360            tokio::time::timeout(core::time::Duration::from_secs(5), async {
1361                while !prune_rx.is_empty() {
1362                    tokio::task::yield_now().await;
1363                }
1364            })
1365            .await
1366            .expect("the signal must wake the engine and be consumed");
1367        };
1368
1369        futures_util::pin_mut!(engine);
1370        futures_util::pin_mut!(exercise);
1371        match futures_util::future::select(engine, exercise).await {
1372            futures_util::future::Either::Left(_) => panic!("the engine ended early"),
1373            futures_util::future::Either::Right(((), _)) => {}
1374        }
1375    }
1376
1377    /// The cap is a hard bound: nothing drains this channel, as during a pending
1378    /// dial or a backoff sleep.
1379    #[tokio::test]
1380    async fn the_command_queue_is_bounded() {
1381        let (handle, cmd_rx, _prune_rx) = test_handle_capped(2);
1382
1383        for topic in ["one", "two", "three", "four"] {
1384            handle
1385                .write(topic, Payload::from(&b"x"[..]))
1386                .expect("the engine is still running");
1387        }
1388
1389        assert_eq!(cmd_rx.len(), 2, "the backlog must not exceed the cap");
1390        // Oldest-first: the two most recent writes are the ones kept.
1391        for expected in ["three", "four"] {
1392            match cmd_rx.try_recv() {
1393                Ok(ClientCmd::Write { topic, .. }) => assert_eq!(topic, expected),
1394                _ => panic!("the newest writes must survive eviction"),
1395            }
1396        }
1397    }
1398
1399    /// `usize::MAX` was the old "unbounded" sentinel; preallocated, it would abort
1400    /// in the allocator, so it has to degrade to the ceiling instead.
1401    #[tokio::test]
1402    async fn an_unbounded_cap_degrades_to_the_ceiling() {
1403        struct UndialableRemote;
1404        impl Dialer for UndialableRemote {
1405            fn connect(&self) -> BoxFut<'_, TransportResult<Box<dyn Connection>>> {
1406                Box::pin(async { Err(TransportError::Closed) })
1407            }
1408        }
1409
1410        let config = ClientConfig {
1411            max_offline_queue: usize::MAX,
1412            ..Default::default()
1413        };
1414        let ctx =
1415            crate::RuntimeContext::new(Arc::new(crate::executor::test_support::NoopRuntimeOps));
1416        let (handle, _engine) = run_client(UndialableRemote, NullCodec, config, ctx);
1417
1418        handle
1419            .write("t", Payload::from(&b"x"[..]))
1420            .expect("the engine is still running");
1421    }
1422
1423    /// A zero cap is clamped, not honored: every command reaches the engine
1424    /// through this channel, so a zero-capacity one could never deliver.
1425    #[tokio::test]
1426    async fn a_zero_cap_is_clamped_to_one() {
1427        let (handle, cmd_rx, _prune_rx) = test_handle_capped(0);
1428        let (reply, rx) = oneshot::channel();
1429
1430        handle
1431            .enqueue(ClientCmd::Call {
1432                id: 1,
1433                method: String::from("one"),
1434                params: Payload::from(&b"x"[..]),
1435                reply,
1436            })
1437            .expect("the engine is still running");
1438        handle
1439            .write("later", Payload::from(&b"x"[..]))
1440            .expect("the engine is still running");
1441
1442        assert_eq!(cmd_rx.len(), 1, "a clamped cap still holds exactly one");
1443        assert!(rx.await.is_err(), "and the evicted caller learns it");
1444    }
1445
1446    /// The cap is the channel's own, so it holds across cloned handles without an
1447    /// admission lock: a full channel evicts rather than admitting a second sender.
1448    #[tokio::test]
1449    async fn cloned_handles_cannot_exceed_the_cap() {
1450        let (handle, cmd_rx, _prune_rx) = test_handle_capped(1);
1451        let other = handle.clone();
1452
1453        handle
1454            .write("first", Payload::from(&b"x"[..]))
1455            .expect("the engine is still running");
1456        other
1457            .write("second", Payload::from(&b"x"[..]))
1458            .expect("the engine is still running");
1459
1460        assert_eq!(cmd_rx.len(), 1, "clones share one bounded channel");
1461        match cmd_rx.try_recv() {
1462            Ok(ClientCmd::Write { topic, .. }) => assert_eq!(topic, "second"),
1463            _ => panic!("oldest-first eviction must hold across clones"),
1464        }
1465    }
1466
1467    /// A trimmed command is not silently lost: it carried the only sender of its
1468    /// reply channel, so the caller resolves rather than awaiting a reply the
1469    /// engine will never send.
1470    #[tokio::test]
1471    async fn a_trimmed_call_fails_its_caller() {
1472        let (handle, _cmd_rx, _prune_rx) = test_handle_capped(1);
1473        let (reply, rx) = oneshot::channel();
1474        handle
1475            .enqueue(ClientCmd::Call {
1476                id: 1,
1477                method: String::from("one"),
1478                params: Payload::from(&b"x"[..]),
1479                reply,
1480            })
1481            .expect("the engine is still running");
1482
1483        // At cap 1 the next command displaces it.
1484        handle
1485            .write("later", Payload::from(&b"x"[..]))
1486            .expect("the engine is still running");
1487
1488        assert!(
1489            rx.await.is_err(),
1490            "a trimmed call must not leave its caller waiting"
1491        );
1492    }
1493
1494    type SubSinks = HashMap<String, Sender<Result<SubUpdate, RpcError>>>;
1495    type SubCursors = HashMap<String, u64>;
1496
1497    /// One sink and its cursor, for driving [`deliver`] directly.
1498    fn test_sink() -> (SubSinks, SubCursors, Receiver<Result<SubUpdate, RpcError>>) {
1499        let (tx, rx) = async_channel::bounded(SUBSCRIBE_CHANNEL_CAP);
1500        let mut subs = HashMap::new();
1501        subs.insert(String::from("1"), tx);
1502        (subs, HashMap::new(), rx)
1503    }
1504
1505    fn deliver_event(subs: &mut SubSinks, last_seq: &mut SubCursors, seq: u64) {
1506        deliver(
1507            subs,
1508            last_seq,
1509            "1",
1510            seq,
1511            SubUpdate::new(Payload::from(&b"x"[..]), crate::Stamp::from_nanos(0)),
1512            Delivery::Event,
1513        );
1514    }
1515
1516    /// `seq` arrives off the wire unvalidated, so the ceiling is reachable by a
1517    /// peer. Computing the gap as `prev + 1` panicked in debug on the *next*
1518    /// frame, and wrapped to a nonsense gap in release.
1519    #[tokio::test]
1520    async fn a_saturated_sequence_does_not_overflow() {
1521        let (mut subs, mut last_seq, rx) = test_sink();
1522
1523        deliver_event(&mut subs, &mut last_seq, u64::MAX);
1524        deliver_event(&mut subs, &mut last_seq, 5);
1525
1526        let skips: Vec<u64> = core::iter::from_fn(|| rx.try_recv().ok())
1527            .map(|u| u.unwrap().skipped)
1528            .collect();
1529        assert_eq!(skips.len(), 2, "both frames must be delivered");
1530        assert_eq!(skips[1], 0, "a saturated cursor cannot manufacture a gap");
1531    }
1532
1533    /// A repeated or reordered `seq` is delivered but must not rewind the cursor:
1534    /// a lower cursor makes the *next* valid frame look like a jump, reporting a
1535    /// loss that never happened.
1536    #[tokio::test]
1537    async fn a_rewound_sequence_does_not_invent_a_gap() {
1538        let (mut subs, mut last_seq, rx) = test_sink();
1539
1540        for seq in [1, 3, 2, 4] {
1541            deliver_event(&mut subs, &mut last_seq, seq);
1542        }
1543
1544        let skips: Vec<u64> = core::iter::from_fn(|| rx.try_recv().ok())
1545            .map(|u| u.unwrap().skipped)
1546            .collect();
1547        assert_eq!(
1548            skips,
1549            alloc::vec![0, 1, 0, 0],
1550            "only the real gap (2 missing between 1 and 3) may be reported"
1551        );
1552        assert_eq!(last_seq.get("1"), Some(&4));
1553    }
1554
1555    /// A slow subscriber whose sink is already full of updates must still see
1556    /// the terminal error, not buffered values followed by a bare EOF.
1557    #[tokio::test]
1558    async fn a_terminal_error_survives_a_full_sink() {
1559        let (mut subs, mut last_seq, rx) = test_sink();
1560
1561        for seq in 1..=(SUBSCRIBE_CHANNEL_CAP as u64 + 10) {
1562            deliver_event(&mut subs, &mut last_seq, seq);
1563        }
1564        end_sub(&mut subs, &mut last_seq, "1", RpcError::Protocol);
1565
1566        let items: Vec<_> = core::iter::from_fn(|| rx.try_recv().ok()).collect();
1567        assert_eq!(items.len(), SUBSCRIBE_CHANNEL_CAP);
1568        assert!(items[..items.len() - 1].iter().all(Result::is_ok));
1569        assert!(matches!(items.last(), Some(Err(RpcError::Protocol))));
1570        assert!(rx.is_closed(), "the sink is dropped after the error");
1571    }
1572
1573    /// The mirror's loss contract (see [`inbound_pump`]): a server-reported gap
1574    /// is stepped over, not treated as a fault. The update *carrying* `skipped`
1575    /// is itself produced into the local record — it is current state, which is
1576    /// all a mirror promises — and delivery continues past it.
1577    #[tokio::test]
1578    async fn a_mirror_gap_still_routes_and_keeps_mirroring() {
1579        let seen: Arc<spin::Mutex<Vec<Vec<u8>>>> = Arc::new(spin::Mutex::new(Vec::new()));
1580        let recorder = seen.clone();
1581        let ingest: crate::connector::IngestFn = Arc::new(move |_ctx, _m, bytes: &[u8]| {
1582            recorder.lock().push(bytes.to_vec());
1583            Ok(())
1584        });
1585        let route = crate::router::CompiledRoute::exact("tele", ingest);
1586        let router = crate::router::Router::new(&crate::ExactGrammar, alloc::vec![route]);
1587        let ctx =
1588            crate::RuntimeContext::new(Arc::new(crate::executor::test_support::NoopRuntimeOps));
1589        let inbound = crate::InboundDispatch::from_parts(router, ctx);
1590        let (handle, cmd_rx, _prune_rx) = test_handle();
1591
1592        let pump = inbound_pump(handle, inbound, Arc::from("tele"));
1593        let remote = async {
1594            // The pump subscribes on its first poll; take its sink and play a
1595            // gapped update followed by a clean one.
1596            let events = match cmd_rx.recv().await {
1597                Ok(ClientCmd::Subscribe { events, .. }) => events,
1598                _ => panic!("the pump must subscribe"),
1599            };
1600            for (data, skipped) in [(&b"gapped"[..], 7u64), (&b"after"[..], 0)] {
1601                events
1602                    .send(Ok(SubUpdate::new(
1603                        Payload::from(data),
1604                        crate::Stamp::from_nanos(0),
1605                    )
1606                    .with_skipped(skipped)))
1607                    .await
1608                    .expect("the pump holds the receiver");
1609            }
1610            // Dropping the sink ends the stream, so the pump returns.
1611            drop(events);
1612        };
1613        #[cfg(feature = "std")]
1614        let gap_seen = Arc::new(core::sync::atomic::AtomicUsize::new(0));
1615        #[cfg(feature = "std")]
1616        let pump = crate::session::events::capture::future(
1617            {
1618                let seen = gap_seen.clone();
1619                Arc::new(move |event| match event {
1620                    SessionEvent::MirrorGap { topic, skipped } => {
1621                        assert_eq!((*topic, *skipped), ("tele", 7));
1622                        seen.fetch_add(1, Ordering::Relaxed);
1623                    }
1624                    other => panic!("unexpected event: {other:?}"),
1625                })
1626            },
1627            pump,
1628        );
1629        futures_util::future::join(pump, remote).await;
1630        #[cfg(feature = "std")]
1631        assert_eq!(gap_seen.load(Ordering::Relaxed), 1);
1632
1633        let seen = seen.lock();
1634        assert_eq!(seen.len(), 2, "the gap must not drop or end the mirror");
1635        assert_eq!(
1636            seen[0].as_slice(),
1637            b"gapped",
1638            "the update reporting the gap must still be produced"
1639        );
1640        assert_eq!(seen[1].as_slice(), b"after", "mirroring must continue");
1641    }
1642}