Skip to main content

hypercall_client/
qp_scoped.rs

1//! Scoped Quote Provider client runtime.
2//!
3//! A typed outbound layer over the `/ws/quotes` protocol that replaces the
4//! raw `mpsc::Receiver<ClientOutbound>` pipe of [`crate::qp_client`] for
5//! indicative publishing:
6//!
7//! - **Per-scope conflating slots**: [`QpScopedHandle::set_indicative_quotes`]
8//!   stores the latest snapshot per [`ScopeId`]; a fast-repricing scope
9//!   supersedes only itself and can never starve or discard another scope's
10//!   pending update.
11//! - **Reconnect replay**: the server evicts a wallet's quotes when its last
12//!   session disconnects, so on every (re)connect the runtime marks all
13//!   slots dirty and republishes them. A quiet scope therefore reappears
14//!   without waiting for its next natural update.
15//! - **Capability fallback**: scoped frames are sent only when the server
16//!   advertised [`CAP_SCOPED_INDICATIVE`] during auth. Against an older
17//!   server, dirty slots are flushed as one legacy full-wallet
18//!   `IndicativeQuoteUpdate` carrying the union of every slot.
19//! - **TTL keepalive**: every live slot is republished on
20//!   [`QpClientConfig::indicative_republish_interval`] even without
21//!   changes, so the server's TTL sweep never evicts a quiet-but-live
22//!   scope.
23//! - **RFQ priority lane**: [`QpScopedHandle::send_rfq_response`] carries a
24//!   deadline; responses are written before any pending indicative flush
25//!   and are dropped once expired rather than sent stale. Every drop is
26//!   reported with the message itself via
27//!   [`QpClientCallbacks::on_rfq_response_dropped`] so the caller can
28//!   attribute it to an `rfq_id`, and also counted through the bulk
29//!   [`QpClientCallbacks::on_stale_messages_drained`] for compatibility.
30//! - **Connection state**: [`QpScopedHandle::connection_state`] exposes a
31//!   `watch` channel with the negotiated capabilities, so callers can gate
32//!   RFQ handling on connectivity instead of inferring it from callbacks.
33
34use std::collections::{HashMap, HashSet, VecDeque};
35use std::sync::{Arc, Mutex};
36use std::time::Duration;
37
38use futures::{SinkExt, StreamExt};
39use serde::Serialize;
40use tokio::sync::{mpsc, watch, Notify};
41use tokio::time::{sleep, timeout, Instant};
42use tokio_tungstenite::tungstenite::Message;
43use tracing::{info, warn};
44
45use crate::qp_client::{
46    connect_and_auth, forward_inbound_or_close, ClientOutbound, IndicativeQuote, QpClientCallbacks,
47    QpClientConfig, QpDisconnectReason, QpWriteFailure, QpWriteOperation, RfqDropReason,
48    ServerInbound, WS_WRITE_TIMEOUT,
49};
50use hypercall_ws_protocol::{ScopeId, CAP_SCOPED_INDICATIVE};
51
52/// Connection state surfaced through [`QpScopedHandle::connection_state`].
53#[derive(Debug, Clone, PartialEq, Eq)]
54pub enum ConnectionState {
55    /// Not connected; the runtime is between attempts.
56    Disconnected,
57    /// Authenticated. `capabilities` is the server's advertised list;
58    /// [`ConnectionState::scoped_indicative`] reports the one this runtime
59    /// acts on.
60    Connected { capabilities: Vec<String> },
61}
62
63impl ConnectionState {
64    pub fn scoped_indicative(&self) -> bool {
65        match self {
66            Self::Connected { capabilities } => {
67                capabilities.iter().any(|c| c == CAP_SCOPED_INDICATIVE)
68            }
69            Self::Disconnected => false,
70        }
71    }
72}
73
74/// An RFQ response with the latest instant at which sending it is useful.
75struct TimedRfqResponse {
76    message: ClientOutbound,
77    deadline: Instant,
78}
79
80/// An indicative frame selected for writing. Scoped frames share the slot
81/// through the `Arc` so serialization never deep-clones the batch (5 heap
82/// `String`s per leg at quote rate); the union fallback owns its one-off
83/// merged batch by construction.
84#[derive(Debug)]
85enum OutboundFrame {
86    Scoped {
87        scope: ScopeId,
88        quotes: Arc<Vec<IndicativeQuote>>,
89    },
90    Union(Vec<IndicativeQuote>),
91}
92
93/// Borrow-serializing shadow of the two indicative [`ClientOutbound`]
94/// variants. MUST stay wire-identical to the owned enum's serde shape
95/// (same tag field, same snake_case names); the
96/// `outbound_frame_wire_shape_matches_client_outbound` test pins this.
97#[derive(Serialize)]
98#[serde(tag = "type", rename_all = "snake_case")]
99enum OutboundFrameWire<'a> {
100    ScopedIndicativeQuoteUpdate {
101        scope: ScopeId,
102        quotes: &'a [IndicativeQuote],
103    },
104    IndicativeQuoteUpdate {
105        quotes: &'a [IndicativeQuote],
106    },
107}
108
109impl OutboundFrame {
110    fn to_json(&self) -> Result<String, serde_json::Error> {
111        let wire = match self {
112            Self::Scoped { scope, quotes } => OutboundFrameWire::ScopedIndicativeQuoteUpdate {
113                scope: *scope,
114                quotes,
115            },
116            Self::Union(quotes) => OutboundFrameWire::IndicativeQuoteUpdate { quotes },
117        };
118        serde_json::to_string(&wire)
119    }
120}
121
122/// One item selected for the socket writer: RFQ responses always outrank
123/// indicative frames.
124enum OutboundItem {
125    Rfq(ClientOutbound),
126    Frame(OutboundFrame),
127}
128
129/// Latest-per-scope outbound snapshots plus dirty tracking. Pure state so
130/// the conflation/fallback/replay rules are unit-testable without a socket.
131#[derive(Default)]
132struct ScopedOutboundState {
133    slots: HashMap<ScopeId, Arc<Vec<IndicativeQuote>>>,
134    dirty: VecDeque<ScopeId>,
135    dirty_set: HashSet<ScopeId>,
136    superseded: u64,
137}
138
139impl ScopedOutboundState {
140    /// Store the latest snapshot for `scope` and mark it dirty. An empty
141    /// snapshot is meaningful ("clear this scope" on the wire) but removes
142    /// the slot afterwards so dead scopes are not replayed forever.
143    fn set(&mut self, scope: ScopeId, quotes: Vec<IndicativeQuote>) {
144        if self.slots.insert(scope, Arc::new(quotes)).is_some() && self.dirty_set.contains(&scope) {
145            self.superseded += 1;
146        }
147        if self.dirty_set.insert(scope) {
148            self.dirty.push_back(scope);
149        }
150    }
151
152    /// Mark every slot dirty: the (re)connected server has none of our
153    /// state (disconnect evicts the wallet), so everything must republish.
154    fn mark_all_dirty(&mut self) {
155        for scope in self.slots.keys() {
156            if self.dirty_set.insert(*scope) {
157                self.dirty.push_back(*scope);
158            }
159        }
160    }
161
162    /// Next frame to write, honoring the server's capability. Returns
163    /// `None` when nothing is dirty. An empty ("clear this scope") slot is
164    /// KEPT until [`Self::finish_scoped_clear`] confirms its write: if the
165    /// write fails, reconnect replay re-marks the surviving slot and the
166    /// clear is re-sent instead of silently lost.
167    fn next_frame(&mut self, scoped_supported: bool) -> Option<OutboundFrame> {
168        if scoped_supported {
169            let scope = loop {
170                let scope = self.dirty.pop_front()?;
171                if self.dirty_set.remove(&scope) {
172                    break scope;
173                }
174            };
175            // Every dirty marker is paired with a slot insertion; a miss
176            // here is a state-machine bug, and per repo policy broken
177            // invariants crash loud rather than silently dropping frames.
178            let quotes = self
179                .slots
180                .get(&scope)
181                .expect("dirty scope must have a slot")
182                .clone();
183            return Some(OutboundFrame::Scoped { scope, quotes });
184        }
185        // Legacy fallback: one full-wallet snapshot carrying the union of
186        // every slot. All dirtiness is discharged by a single frame.
187        // Empty slots are KEPT until [`Self::finish_union_flush`] confirms
188        // the write: if the cleared scope was the wallet's only slot and
189        // the write failed, nothing else would ever go dirty again and
190        // the clear would be silently lost.
191        if self.dirty.is_empty() {
192            return None;
193        }
194        self.dirty.clear();
195        self.dirty_set.clear();
196        let mut quotes = Vec::new();
197        for slot in self.slots.values() {
198            quotes.extend(slot.iter().cloned());
199        }
200        Some(OutboundFrame::Union(quotes))
201    }
202
203    /// Confirm a written "clear this scope" frame: drop the empty slot so
204    /// the cleared scope stops replaying. A no-op if the caller re-set the
205    /// scope (dirty again, or the slot is no longer empty) between the
206    /// frame's selection and the write completing. "Confirmed" means the
207    /// transport accepted the write; a frame lost after buffering is
208    /// repaired by server-side eviction (full disconnect) or its TTL.
209    fn finish_scoped_clear(&mut self, scope: ScopeId) {
210        if !self.dirty_set.contains(&scope)
211            && self.slots.get(&scope).is_some_and(|slot| slot.is_empty())
212        {
213            self.slots.remove(&scope);
214        }
215    }
216
217    /// Confirm a written union frame: drop slots that are still empty and
218    /// not re-dirtied, so cleared scopes stop replaying once their
219    /// omission reached the wire.
220    fn finish_union_flush(&mut self) {
221        let Self {
222            slots, dirty_set, ..
223        } = self;
224        slots.retain(|scope, slot| !slot.is_empty() || dirty_set.contains(scope));
225    }
226
227    fn take_superseded(&mut self) -> u64 {
228        std::mem::take(&mut self.superseded)
229    }
230}
231
232/// Shared state between the handle and the runtime task.
233struct SharedScopedState {
234    outbound: Mutex<ScopedOutboundState>,
235    outbound_notify: Notify,
236    connection: watch::Sender<ConnectionState>,
237}
238
239/// Caller-facing handle for the scoped QP runtime.
240#[derive(Clone)]
241pub struct QpScopedHandle {
242    shared: Arc<SharedScopedState>,
243    rfq_tx: mpsc::Sender<TimedRfqResponse>,
244}
245
246/// Error returned when an RFQ response cannot be queued.
247#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
248#[displaystr::display]
249pub enum RfqSendError {
250    /// The bounded priority lane is full; the response was NOT queued.
251    LaneFull = "RFQ priority lane full",
252    /// The runtime task has exited.
253    RuntimeClosed = "scoped QP runtime closed",
254}
255
256impl QpScopedHandle {
257    /// Publish the latest indicative snapshot for one scope. Never blocks;
258    /// an unsent previous snapshot for the same scope is superseded.
259    pub fn set_indicative_quotes(&self, scope: ScopeId, quotes: Vec<IndicativeQuote>) {
260        self.shared
261            .outbound
262            .lock()
263            .expect("scoped outbound lock poisoned")
264            .set(scope, quotes);
265        self.shared.outbound_notify.notify_one();
266    }
267
268    /// Queue a firm RFQ response with a delivery deadline. Responses are
269    /// written ahead of any pending indicative flush; once `deadline`
270    /// passes an unsent response is dropped and reported via
271    /// [`QpClientCallbacks::on_stale_messages_drained`] rather than sent
272    /// stale to the venue.
273    pub fn send_rfq_response(
274        &self,
275        message: ClientOutbound,
276        deadline: Instant,
277    ) -> Result<(), RfqSendError> {
278        match self.rfq_tx.try_send(TimedRfqResponse { message, deadline }) {
279            Ok(()) => Ok(()),
280            Err(mpsc::error::TrySendError::Full(_)) => Err(RfqSendError::LaneFull),
281            Err(mpsc::error::TrySendError::Closed(_)) => Err(RfqSendError::RuntimeClosed),
282        }
283    }
284
285    /// Watch the connection state (including negotiated capabilities).
286    pub fn connection_state(&self) -> watch::Receiver<ConnectionState> {
287        self.shared.connection.subscribe()
288    }
289}
290
291/// Capacity of the RFQ priority lane. RFQ rate is venue-throttled; the
292/// bound exists so a dead connection cannot buffer unbounded signed quotes.
293const RFQ_LANE_CAPACITY: usize = 64;
294
295/// Build the handle/runtime pair. Spawn [`run_qp_scoped_client`] with the
296/// returned runtime half; keep the handle for publishing.
297pub fn qp_scoped_channel() -> (QpScopedHandle, QpScopedRuntime) {
298    let shared = Arc::new(SharedScopedState {
299        outbound: Mutex::new(ScopedOutboundState::default()),
300        outbound_notify: Notify::new(),
301        connection: watch::channel(ConnectionState::Disconnected).0,
302    });
303    let (rfq_tx, rfq_rx) = mpsc::channel(RFQ_LANE_CAPACITY);
304    (
305        QpScopedHandle {
306            shared: shared.clone(),
307            rfq_tx,
308        },
309        QpScopedRuntime { shared, rfq_rx },
310    )
311}
312
313/// Runtime half of [`qp_scoped_channel`], consumed by
314/// [`run_qp_scoped_client`].
315pub struct QpScopedRuntime {
316    shared: Arc<SharedScopedState>,
317    rfq_rx: mpsc::Receiver<TimedRfqResponse>,
318}
319
320/// Resolve the next outbound item: any live (unexpired) RFQ response
321/// outranks any indicative frame; expired responses are dropped and
322/// reported. Pends until something is writable.
323///
324/// Cancellation-safe as a `select!` arm: a message is only consumed at
325/// points from which this function returns synchronously (no `.await`
326/// between consumption and return), so dropping the future mid-pend never
327/// loses a live RFQ response. State is also re-examined from scratch on
328/// every call, so a lost notify permit can only delay via the next wakeup,
329/// never skip work.
330async fn next_outbound(
331    rfq_rx: &mut mpsc::Receiver<TimedRfqResponse>,
332    shared: &SharedScopedState,
333    scoped_supported: bool,
334    callbacks: &dyn QpClientCallbacks,
335) -> OutboundItem {
336    let mut rfq_open = true;
337    loop {
338        if rfq_open {
339            loop {
340                match rfq_rx.try_recv() {
341                    Ok(timed) if Instant::now() <= timed.deadline => {
342                        return OutboundItem::Rfq(timed.message);
343                    }
344                    Ok(expired) => {
345                        callbacks.on_rfq_response_dropped(&expired.message, RfqDropReason::Expired);
346                        callbacks.on_stale_messages_drained(1);
347                    }
348                    Err(mpsc::error::TryRecvError::Empty) => break,
349                    Err(mpsc::error::TryRecvError::Disconnected) => {
350                        rfq_open = false;
351                        break;
352                    }
353                }
354            }
355        }
356        // The user-implemented callback runs OUTSIDE the outbound lock: a
357        // callback that touches the handle (same mutex) must not deadlock,
358        // and a slow one must not block publishers.
359        let (superseded, frame) = {
360            let mut outbound = shared
361                .outbound
362                .lock()
363                .expect("scoped outbound lock poisoned");
364            (
365                outbound.take_superseded(),
366                outbound.next_frame(scoped_supported),
367            )
368        };
369        if superseded > 0 {
370            callbacks.on_stale_messages_drained(superseded);
371        }
372        if let Some(frame) = frame {
373            return OutboundItem::Frame(frame);
374        }
375        if rfq_open {
376            tokio::select! {
377                _ = shared.outbound_notify.notified() => {}
378                maybe = rfq_rx.recv() => match maybe {
379                    Some(timed) if Instant::now() <= timed.deadline => {
380                        return OutboundItem::Rfq(timed.message);
381                    }
382                    Some(expired) => {
383                        callbacks.on_rfq_response_dropped(&expired.message, RfqDropReason::Expired);
384                        callbacks.on_stale_messages_drained(1);
385                    }
386                    None => rfq_open = false,
387                },
388            }
389        } else {
390            shared.outbound_notify.notified().await;
391        }
392    }
393}
394
395/// Run the scoped QP client with auto-reconnect. Mirrors
396/// [`crate::qp_client::run_qp_client`] but drives outbound from the scoped
397/// handle instead of a raw message channel.
398pub async fn run_qp_scoped_client(
399    config: QpClientConfig,
400    wallet: Arc<crate::wallet::HypercallWallet>,
401    mut runtime: QpScopedRuntime,
402    inbound_tx: mpsc::Sender<ServerInbound>,
403    callbacks: Arc<dyn QpClientCallbacks>,
404) {
405    loop {
406        let result = connect_and_run_scoped(
407            &config,
408            &wallet,
409            &mut runtime,
410            &inbound_tx,
411            callbacks.as_ref(),
412        )
413        .await;
414        // Publish Disconnected BEFORE the disconnect callbacks so a
415        // callback consulting connection_state() never observes a
416        // contradictory Connected. `send_replace`, never `send`:
417        // `watch::Sender::send` refuses to STORE the value when no
418        // receiver currently exists, so a caller subscribing later would
419        // read a stale state forever.
420        runtime
421            .shared
422            .connection
423            .send_replace(ConnectionState::Disconnected);
424        match result {
425            Ok(()) => {
426                warn!(
427                    "Scoped QP WebSocket closed, reconnecting in {:?}",
428                    config.reconnect_delay
429                );
430                callbacks.on_disconnected(QpDisconnectReason::Closed);
431            }
432            Err(e) if e == crate::qp_client::INBOUND_CHANNEL_CLOSED => {
433                callbacks.on_disconnected(QpDisconnectReason::InboundChannelClosed);
434                break;
435            }
436            Err(e) => {
437                warn!(
438                    "Scoped QP WebSocket error: {e}, reconnecting in {:?}",
439                    config.reconnect_delay
440                );
441                callbacks.on_disconnected(QpDisconnectReason::Error);
442            }
443        }
444        // Deliberately NOT draining the scoped slots: they are the replay
445        // source for the next connection. Only expired RFQ responses are
446        // dropped, in the outbound selection itself.
447        sleep(config.reconnect_delay).await;
448    }
449}
450
451async fn connect_and_run_scoped(
452    config: &QpClientConfig,
453    wallet: &crate::wallet::HypercallWallet,
454    runtime: &mut QpScopedRuntime,
455    inbound_tx: &mpsc::Sender<ServerInbound>,
456    callbacks: &dyn QpClientCallbacks,
457) -> Result<(), String> {
458    let (mut ws_sender, mut ws_receiver, capabilities) =
459        connect_and_auth(&config.api_url, wallet, callbacks).await?;
460    let scoped_supported = capabilities.iter().any(|c| c == CAP_SCOPED_INDICATIVE);
461    if !scoped_supported {
462        info!("Server did not advertise {CAP_SCOPED_INDICATIVE}; using full-snapshot fallback");
463    }
464    // `send_replace` stores the value even with zero receivers, so a
465    // caller that subscribes after connect still reads Connected.
466    runtime
467        .shared
468        .connection
469        .send_replace(ConnectionState::Connected { capabilities });
470
471    // Reconnect replay: the server holds nothing for this wallet after a
472    // full disconnect, so everything we know must be republished.
473    runtime
474        .shared
475        .outbound
476        .lock()
477        .expect("scoped outbound lock poisoned")
478        .mark_all_dirty();
479    runtime.shared.outbound_notify.notify_one();
480
481    let mut heartbeat = tokio::time::interval(Duration::from_secs(30));
482    // Keepalive republish: the server TTL-evicts rows whose snapshot has
483    // not been re-received within its TTL, and this runtime only writes
484    // when a slot is dirty, so a live scope whose prices simply stop
485    // changing would silently vanish server-side. Re-marking every slot
486    // dirty on an interval well inside the server TTL keeps quiet scopes
487    // alive; conflation makes the republish cost one frame per scope. The
488    // first tick is deferred a full period so it does not double-send the
489    // reconnect replay above. Duration::ZERO disables the keepalive (a
490    // zero interval period would panic); a daily tick stands in because
491    // select! needs a live arm.
492    let keepalive_period = if config.indicative_republish_interval.is_zero() {
493        Duration::from_secs(24 * 60 * 60)
494    } else {
495        config.indicative_republish_interval
496    };
497    let mut keepalive =
498        tokio::time::interval_at(Instant::now() + keepalive_period, keepalive_period);
499    let mut last_activity = Instant::now();
500    let heartbeat_timeout = Duration::from_secs(90);
501    let QpScopedRuntime { shared, rfq_rx } = runtime;
502
503    loop {
504        // `biased` with reads first: outbound selection can always be
505        // ready (a repricing flood keeps scopes dirty), and an
506        // outbound-first ordering would starve inbound RfqRequests for the
507        // duration of the flood -- worst at reconnect replay. Reads and
508        // pings therefore outrank writes; RFQ-before-indicative priority
509        // lives inside `next_outbound`.
510        tokio::select! {
511            biased;
512            polled = ws_receiver.next() => {
513                // Bind the raw poll result: a `Some(Ok(_))` pattern here
514                // would DISABLE this arm on stream end/error and leave the
515                // dead connection undetected until the heartbeat timeout.
516                let frame = match polled {
517                    Some(Ok(frame)) => frame,
518                    Some(Err(e)) => return Err(format!("WebSocket read failed: {e}")),
519                    None => return Ok(()),
520                };
521                last_activity = Instant::now();
522                callbacks.on_transport_activity();
523                match frame {
524                    Message::Text(text) => match serde_json::from_str::<ServerInbound>(&text) {
525                        Ok(msg) => forward_inbound_or_close(inbound_tx, msg, callbacks)?,
526                        Err(e) => warn!("Failed to parse server message: {e}"),
527                    },
528                    Message::Binary(bytes) => {
529                        if let Ok(text) = String::from_utf8(bytes.to_vec()) {
530                            if let Ok(msg) = serde_json::from_str::<ServerInbound>(&text) {
531                                forward_inbound_or_close(inbound_tx, msg, callbacks)?;
532                            }
533                        }
534                    }
535                    Message::Ping(data) => {
536                        match timeout(WS_WRITE_TIMEOUT, ws_sender.send(Message::Pong(data))).await {
537                            Ok(Ok(())) => {}
538                            Ok(Err(_)) => callbacks
539                                .on_write_failed(QpWriteOperation::Pong, QpWriteFailure::SendError),
540                            Err(_) => callbacks
541                                .on_write_failed(QpWriteOperation::Pong, QpWriteFailure::Timeout),
542                        }
543                        callbacks.on_transport_activity();
544                    }
545                    Message::Pong(_) => {}
546                    Message::Close(_) => return Ok(()),
547                    _ => {}
548                }
549            }
550            _ = heartbeat.tick() => {
551                if last_activity.elapsed() > heartbeat_timeout {
552                    warn!(
553                        "Scoped QP WebSocket heartbeat timeout ({}s with no activity), reconnecting",
554                        last_activity.elapsed().as_secs()
555                    );
556                    return Ok(());
557                }
558                match timeout(WS_WRITE_TIMEOUT, ws_sender.send(Message::Ping(vec![]))).await {
559                    Ok(Ok(())) => {}
560                    Ok(Err(e)) => {
561                        callbacks.on_write_failed(QpWriteOperation::Heartbeat, QpWriteFailure::SendError);
562                        return Err(format!("Send heartbeat failed: {e}"));
563                    }
564                    Err(_) => {
565                        callbacks.on_write_failed(QpWriteOperation::Heartbeat, QpWriteFailure::Timeout);
566                        return Err("Send heartbeat timed out".to_string());
567                    }
568                }
569                callbacks.on_transport_activity();
570            }
571            _ = keepalive.tick() => {
572                let mut outbound = shared
573                    .outbound
574                    .lock()
575                    .expect("scoped outbound lock poisoned");
576                outbound.mark_all_dirty();
577                drop(outbound);
578                shared.outbound_notify.notify_one();
579            }
580            item = next_outbound(rfq_rx, shared, scoped_supported, callbacks) => {
581                let json = match &item {
582                    OutboundItem::Rfq(msg) => {
583                        serde_json::to_string(msg).map_err(|e| format!("JSON encode: {e}"))?
584                    }
585                    OutboundItem::Frame(frame) => {
586                        frame.to_json().map_err(|e| format!("JSON encode: {e}"))?
587                    }
588                };
589                match timeout(WS_WRITE_TIMEOUT, ws_sender.send(Message::Text(json))).await {
590                    Ok(Ok(())) => {}
591                    Ok(Err(e)) => {
592                        callbacks.on_write_failed(QpWriteOperation::Outbound, QpWriteFailure::SendError);
593                        // A consumed RFQ response has no replay path
594                        // (unlike indicative slots): report the loss so
595                        // the caller can react before the taker's
596                        // deadline lapses.
597                        if let OutboundItem::Rfq(msg) = &item {
598                            callbacks.on_rfq_response_dropped(msg, RfqDropReason::WriteFailed);
599                            callbacks.on_stale_messages_drained(1);
600                        }
601                        return Err(format!("Send outbound failed: {e}"));
602                    }
603                    Err(_) => {
604                        callbacks.on_write_failed(QpWriteOperation::Outbound, QpWriteFailure::Timeout);
605                        if let OutboundItem::Rfq(msg) = &item {
606                            callbacks.on_rfq_response_dropped(msg, RfqDropReason::WriteTimeout);
607                            callbacks.on_stale_messages_drained(1);
608                        }
609                        return Err("Send outbound timed out".to_string());
610                    }
611                }
612                // The write is confirmed: cleared slots may now retire.
613                // Before this point they must survive so a failed write is
614                // replayed on reconnect.
615                match &item {
616                    OutboundItem::Frame(OutboundFrame::Scoped { scope, quotes })
617                        if quotes.is_empty() =>
618                    {
619                        shared
620                            .outbound
621                            .lock()
622                            .expect("scoped outbound lock poisoned")
623                            .finish_scoped_clear(*scope);
624                    }
625                    OutboundItem::Frame(OutboundFrame::Union(_)) => {
626                        shared
627                            .outbound
628                            .lock()
629                            .expect("scoped outbound lock poisoned")
630                            .finish_union_flush();
631                    }
632                    _ => {}
633                }
634                callbacks.on_transport_activity();
635            }
636        }
637    }
638}
639
640#[cfg(test)]
641#[path = "qp_scoped_test.rs"]
642mod tests;