use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use futures::{SinkExt, StreamExt};
use serde::Serialize;
use tokio::sync::{mpsc, watch, Notify};
use tokio::time::{sleep, timeout, Instant};
use tokio_tungstenite::tungstenite::Message;
use tracing::{info, warn};
use crate::qp_client::{
connect_and_auth, forward_inbound_or_close, ClientOutbound, IndicativeQuote, QpClientCallbacks,
QpClientConfig, QpDisconnectReason, QpWriteFailure, QpWriteOperation, RfqDropReason,
ServerInbound, WS_WRITE_TIMEOUT,
};
use hypercall_ws_protocol::{ScopeId, CAP_SCOPED_INDICATIVE};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConnectionState {
Disconnected,
Connected { capabilities: Vec<String> },
}
impl ConnectionState {
pub fn scoped_indicative(&self) -> bool {
match self {
Self::Connected { capabilities } => {
capabilities.iter().any(|c| c == CAP_SCOPED_INDICATIVE)
}
Self::Disconnected => false,
}
}
}
struct TimedRfqResponse {
message: ClientOutbound,
deadline: Instant,
}
#[derive(Debug)]
enum OutboundFrame {
Scoped {
scope: ScopeId,
quotes: Arc<Vec<IndicativeQuote>>,
},
Union(Vec<IndicativeQuote>),
}
#[derive(Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
enum OutboundFrameWire<'a> {
ScopedIndicativeQuoteUpdate {
scope: ScopeId,
quotes: &'a [IndicativeQuote],
},
IndicativeQuoteUpdate {
quotes: &'a [IndicativeQuote],
},
}
impl OutboundFrame {
fn to_json(&self) -> Result<String, serde_json::Error> {
let wire = match self {
Self::Scoped { scope, quotes } => OutboundFrameWire::ScopedIndicativeQuoteUpdate {
scope: *scope,
quotes,
},
Self::Union(quotes) => OutboundFrameWire::IndicativeQuoteUpdate { quotes },
};
serde_json::to_string(&wire)
}
}
enum OutboundItem {
Rfq(ClientOutbound),
Frame(OutboundFrame),
}
#[derive(Default)]
struct ScopedOutboundState {
slots: HashMap<ScopeId, Arc<Vec<IndicativeQuote>>>,
dirty: VecDeque<ScopeId>,
dirty_set: HashSet<ScopeId>,
superseded: u64,
}
impl ScopedOutboundState {
fn set(&mut self, scope: ScopeId, quotes: Vec<IndicativeQuote>) {
if self.slots.insert(scope, Arc::new(quotes)).is_some() && self.dirty_set.contains(&scope) {
self.superseded += 1;
}
if self.dirty_set.insert(scope) {
self.dirty.push_back(scope);
}
}
fn mark_all_dirty(&mut self) {
for scope in self.slots.keys() {
if self.dirty_set.insert(*scope) {
self.dirty.push_back(*scope);
}
}
}
fn next_frame(&mut self, scoped_supported: bool) -> Option<OutboundFrame> {
if scoped_supported {
let scope = loop {
let scope = self.dirty.pop_front()?;
if self.dirty_set.remove(&scope) {
break scope;
}
};
let quotes = self
.slots
.get(&scope)
.expect("dirty scope must have a slot")
.clone();
return Some(OutboundFrame::Scoped { scope, quotes });
}
if self.dirty.is_empty() {
return None;
}
self.dirty.clear();
self.dirty_set.clear();
let mut quotes = Vec::new();
for slot in self.slots.values() {
quotes.extend(slot.iter().cloned());
}
Some(OutboundFrame::Union(quotes))
}
fn finish_scoped_clear(&mut self, scope: ScopeId) {
if !self.dirty_set.contains(&scope)
&& self.slots.get(&scope).is_some_and(|slot| slot.is_empty())
{
self.slots.remove(&scope);
}
}
fn finish_union_flush(&mut self) {
let Self {
slots, dirty_set, ..
} = self;
slots.retain(|scope, slot| !slot.is_empty() || dirty_set.contains(scope));
}
fn take_superseded(&mut self) -> u64 {
std::mem::take(&mut self.superseded)
}
}
struct SharedScopedState {
outbound: Mutex<ScopedOutboundState>,
outbound_notify: Notify,
connection: watch::Sender<ConnectionState>,
}
#[derive(Clone)]
pub struct QpScopedHandle {
shared: Arc<SharedScopedState>,
rfq_tx: mpsc::Sender<TimedRfqResponse>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[displaystr::display]
pub enum RfqSendError {
LaneFull = "RFQ priority lane full",
RuntimeClosed = "scoped QP runtime closed",
}
impl QpScopedHandle {
pub fn set_indicative_quotes(&self, scope: ScopeId, quotes: Vec<IndicativeQuote>) {
self.shared
.outbound
.lock()
.expect("scoped outbound lock poisoned")
.set(scope, quotes);
self.shared.outbound_notify.notify_one();
}
pub fn send_rfq_response(
&self,
message: ClientOutbound,
deadline: Instant,
) -> Result<(), RfqSendError> {
match self.rfq_tx.try_send(TimedRfqResponse { message, deadline }) {
Ok(()) => Ok(()),
Err(mpsc::error::TrySendError::Full(_)) => Err(RfqSendError::LaneFull),
Err(mpsc::error::TrySendError::Closed(_)) => Err(RfqSendError::RuntimeClosed),
}
}
pub fn connection_state(&self) -> watch::Receiver<ConnectionState> {
self.shared.connection.subscribe()
}
}
const RFQ_LANE_CAPACITY: usize = 64;
pub fn qp_scoped_channel() -> (QpScopedHandle, QpScopedRuntime) {
let shared = Arc::new(SharedScopedState {
outbound: Mutex::new(ScopedOutboundState::default()),
outbound_notify: Notify::new(),
connection: watch::channel(ConnectionState::Disconnected).0,
});
let (rfq_tx, rfq_rx) = mpsc::channel(RFQ_LANE_CAPACITY);
(
QpScopedHandle {
shared: shared.clone(),
rfq_tx,
},
QpScopedRuntime { shared, rfq_rx },
)
}
pub struct QpScopedRuntime {
shared: Arc<SharedScopedState>,
rfq_rx: mpsc::Receiver<TimedRfqResponse>,
}
async fn next_outbound(
rfq_rx: &mut mpsc::Receiver<TimedRfqResponse>,
shared: &SharedScopedState,
scoped_supported: bool,
callbacks: &dyn QpClientCallbacks,
) -> OutboundItem {
let mut rfq_open = true;
loop {
if rfq_open {
loop {
match rfq_rx.try_recv() {
Ok(timed) if Instant::now() <= timed.deadline => {
return OutboundItem::Rfq(timed.message);
}
Ok(expired) => {
callbacks.on_rfq_response_dropped(&expired.message, RfqDropReason::Expired);
callbacks.on_stale_messages_drained(1);
}
Err(mpsc::error::TryRecvError::Empty) => break,
Err(mpsc::error::TryRecvError::Disconnected) => {
rfq_open = false;
break;
}
}
}
}
let (superseded, frame) = {
let mut outbound = shared
.outbound
.lock()
.expect("scoped outbound lock poisoned");
(
outbound.take_superseded(),
outbound.next_frame(scoped_supported),
)
};
if superseded > 0 {
callbacks.on_stale_messages_drained(superseded);
}
if let Some(frame) = frame {
return OutboundItem::Frame(frame);
}
if rfq_open {
tokio::select! {
_ = shared.outbound_notify.notified() => {}
maybe = rfq_rx.recv() => match maybe {
Some(timed) if Instant::now() <= timed.deadline => {
return OutboundItem::Rfq(timed.message);
}
Some(expired) => {
callbacks.on_rfq_response_dropped(&expired.message, RfqDropReason::Expired);
callbacks.on_stale_messages_drained(1);
}
None => rfq_open = false,
},
}
} else {
shared.outbound_notify.notified().await;
}
}
}
pub async fn run_qp_scoped_client(
config: QpClientConfig,
wallet: Arc<crate::wallet::HypercallWallet>,
mut runtime: QpScopedRuntime,
inbound_tx: mpsc::Sender<ServerInbound>,
callbacks: Arc<dyn QpClientCallbacks>,
) {
loop {
let result = connect_and_run_scoped(
&config,
&wallet,
&mut runtime,
&inbound_tx,
callbacks.as_ref(),
)
.await;
runtime
.shared
.connection
.send_replace(ConnectionState::Disconnected);
match result {
Ok(()) => {
warn!(
"Scoped QP WebSocket closed, reconnecting in {:?}",
config.reconnect_delay
);
callbacks.on_disconnected(QpDisconnectReason::Closed);
}
Err(e) if e == crate::qp_client::INBOUND_CHANNEL_CLOSED => {
callbacks.on_disconnected(QpDisconnectReason::InboundChannelClosed);
break;
}
Err(e) => {
warn!(
"Scoped QP WebSocket error: {e}, reconnecting in {:?}",
config.reconnect_delay
);
callbacks.on_disconnected(QpDisconnectReason::Error);
}
}
sleep(config.reconnect_delay).await;
}
}
async fn connect_and_run_scoped(
config: &QpClientConfig,
wallet: &crate::wallet::HypercallWallet,
runtime: &mut QpScopedRuntime,
inbound_tx: &mpsc::Sender<ServerInbound>,
callbacks: &dyn QpClientCallbacks,
) -> Result<(), String> {
let (mut ws_sender, mut ws_receiver, capabilities) =
connect_and_auth(&config.api_url, wallet, callbacks).await?;
let scoped_supported = capabilities.iter().any(|c| c == CAP_SCOPED_INDICATIVE);
if !scoped_supported {
info!("Server did not advertise {CAP_SCOPED_INDICATIVE}; using full-snapshot fallback");
}
runtime
.shared
.connection
.send_replace(ConnectionState::Connected { capabilities });
runtime
.shared
.outbound
.lock()
.expect("scoped outbound lock poisoned")
.mark_all_dirty();
runtime.shared.outbound_notify.notify_one();
let mut heartbeat = tokio::time::interval(Duration::from_secs(30));
let keepalive_period = if config.indicative_republish_interval.is_zero() {
Duration::from_secs(24 * 60 * 60)
} else {
config.indicative_republish_interval
};
let mut keepalive =
tokio::time::interval_at(Instant::now() + keepalive_period, keepalive_period);
let mut last_activity = Instant::now();
let heartbeat_timeout = Duration::from_secs(90);
let QpScopedRuntime { shared, rfq_rx } = runtime;
loop {
tokio::select! {
biased;
polled = ws_receiver.next() => {
let frame = match polled {
Some(Ok(frame)) => frame,
Some(Err(e)) => return Err(format!("WebSocket read failed: {e}")),
None => return Ok(()),
};
last_activity = Instant::now();
callbacks.on_transport_activity();
match frame {
Message::Text(text) => match serde_json::from_str::<ServerInbound>(&text) {
Ok(msg) => forward_inbound_or_close(inbound_tx, msg, callbacks)?,
Err(e) => warn!("Failed to parse server message: {e}"),
},
Message::Binary(bytes) => {
if let Ok(text) = String::from_utf8(bytes.to_vec()) {
if let Ok(msg) = serde_json::from_str::<ServerInbound>(&text) {
forward_inbound_or_close(inbound_tx, msg, callbacks)?;
}
}
}
Message::Ping(data) => {
match timeout(WS_WRITE_TIMEOUT, ws_sender.send(Message::Pong(data))).await {
Ok(Ok(())) => {}
Ok(Err(_)) => callbacks
.on_write_failed(QpWriteOperation::Pong, QpWriteFailure::SendError),
Err(_) => callbacks
.on_write_failed(QpWriteOperation::Pong, QpWriteFailure::Timeout),
}
callbacks.on_transport_activity();
}
Message::Pong(_) => {}
Message::Close(_) => return Ok(()),
_ => {}
}
}
_ = heartbeat.tick() => {
if last_activity.elapsed() > heartbeat_timeout {
warn!(
"Scoped QP WebSocket heartbeat timeout ({}s with no activity), reconnecting",
last_activity.elapsed().as_secs()
);
return Ok(());
}
match timeout(WS_WRITE_TIMEOUT, ws_sender.send(Message::Ping(vec![]))).await {
Ok(Ok(())) => {}
Ok(Err(e)) => {
callbacks.on_write_failed(QpWriteOperation::Heartbeat, QpWriteFailure::SendError);
return Err(format!("Send heartbeat failed: {e}"));
}
Err(_) => {
callbacks.on_write_failed(QpWriteOperation::Heartbeat, QpWriteFailure::Timeout);
return Err("Send heartbeat timed out".to_string());
}
}
callbacks.on_transport_activity();
}
_ = keepalive.tick() => {
let mut outbound = shared
.outbound
.lock()
.expect("scoped outbound lock poisoned");
outbound.mark_all_dirty();
drop(outbound);
shared.outbound_notify.notify_one();
}
item = next_outbound(rfq_rx, shared, scoped_supported, callbacks) => {
let json = match &item {
OutboundItem::Rfq(msg) => {
serde_json::to_string(msg).map_err(|e| format!("JSON encode: {e}"))?
}
OutboundItem::Frame(frame) => {
frame.to_json().map_err(|e| format!("JSON encode: {e}"))?
}
};
match timeout(WS_WRITE_TIMEOUT, ws_sender.send(Message::Text(json))).await {
Ok(Ok(())) => {}
Ok(Err(e)) => {
callbacks.on_write_failed(QpWriteOperation::Outbound, QpWriteFailure::SendError);
if let OutboundItem::Rfq(msg) = &item {
callbacks.on_rfq_response_dropped(msg, RfqDropReason::WriteFailed);
callbacks.on_stale_messages_drained(1);
}
return Err(format!("Send outbound failed: {e}"));
}
Err(_) => {
callbacks.on_write_failed(QpWriteOperation::Outbound, QpWriteFailure::Timeout);
if let OutboundItem::Rfq(msg) = &item {
callbacks.on_rfq_response_dropped(msg, RfqDropReason::WriteTimeout);
callbacks.on_stale_messages_drained(1);
}
return Err("Send outbound timed out".to_string());
}
}
match &item {
OutboundItem::Frame(OutboundFrame::Scoped { scope, quotes })
if quotes.is_empty() =>
{
shared
.outbound
.lock()
.expect("scoped outbound lock poisoned")
.finish_scoped_clear(*scope);
}
OutboundItem::Frame(OutboundFrame::Union(_)) => {
shared
.outbound
.lock()
.expect("scoped outbound lock poisoned")
.finish_union_flush();
}
_ => {}
}
callbacks.on_transport_activity();
}
}
}
}
#[cfg(test)]
#[path = "qp_scoped_test.rs"]
mod tests;