1use std::sync::Arc;
43use std::time::Duration;
44
45use futures::{SinkExt, StreamExt};
46use tokio::sync::mpsc::{self, error::TrySendError};
47use tokio::time::{sleep, timeout};
48use tokio_tungstenite::{connect_async, tungstenite::Message};
49use tracing::{error, info, warn};
50
51use crate::wallet::HypercallWallet;
52
53pub(crate) const INBOUND_CHANNEL_CLOSED: &str = "Inbound channel closed";
54pub(crate) const WS_WRITE_TIMEOUT: Duration = Duration::from_secs(5);
55
56pub(crate) type WsSink = futures::stream::SplitSink<
58 tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>,
59 Message,
60>;
61pub(crate) type WsStream = futures::stream::SplitStream<
63 tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>,
64>;
65
66pub use hypercall_ws_protocol::{
67 IndicativeQuote, QpClientMessage as ClientOutbound, QpResponseLeg as ResponseLeg,
68 QpRfqLeg as RfqLeg, QpServerMessage as ServerInbound,
69};
70
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub enum QpDisconnectReason {
74 Closed,
75 Error,
76 InboundChannelClosed,
77}
78
79impl QpDisconnectReason {
80 pub const fn as_str(self) -> &'static str {
81 match self {
82 Self::Closed => "closed",
83 Self::Error => "error",
84 Self::InboundChannelClosed => "inbound_closed",
85 }
86 }
87}
88
89impl std::fmt::Display for QpDisconnectReason {
90 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
91 f.write_str(self.as_str())
92 }
93}
94
95#[derive(Debug, Clone, Copy, PartialEq, Eq)]
97pub enum QpWriteOperation {
98 Auth,
99 Heartbeat,
100 Outbound,
101 Pong,
102}
103
104impl QpWriteOperation {
105 pub const fn as_str(self) -> &'static str {
106 match self {
107 Self::Auth => "auth",
108 Self::Heartbeat => "heartbeat",
109 Self::Outbound => "outbound",
110 Self::Pong => "pong",
111 }
112 }
113}
114
115impl std::fmt::Display for QpWriteOperation {
116 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
117 f.write_str(self.as_str())
118 }
119}
120
121#[derive(Debug, Clone, Copy, PartialEq, Eq)]
123pub enum QpWriteFailure {
124 Timeout,
125 SendError,
126}
127
128impl QpWriteFailure {
129 pub const fn as_str(self) -> &'static str {
130 match self {
131 Self::Timeout => "timeout",
132 Self::SendError => "send_error",
133 }
134 }
135}
136
137impl std::fmt::Display for QpWriteFailure {
138 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
139 f.write_str(self.as_str())
140 }
141}
142
143#[derive(Debug, Clone, Copy, PartialEq, Eq)]
148pub enum RfqDropReason {
149 Expired,
151 WriteFailed,
153 WriteTimeout,
155}
156
157impl RfqDropReason {
158 pub const fn as_str(self) -> &'static str {
159 match self {
160 Self::Expired => "expired",
161 Self::WriteFailed => "write_failed",
162 Self::WriteTimeout => "write_timeout",
163 }
164 }
165}
166
167impl std::fmt::Display for RfqDropReason {
168 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
169 f.write_str(self.as_str())
170 }
171}
172
173pub trait QpClientCallbacks: Send + Sync + 'static {
177 fn on_connected(&self) {}
178 fn on_disconnected(&self, _reason: QpDisconnectReason) {}
179 fn on_stale_messages_drained(&self, _count: u64) {}
188 fn on_rfq_response_dropped(&self, _message: &ClientOutbound, _reason: RfqDropReason) {}
195 fn on_inbound_message_dropped(&self) {}
196 fn on_transport_activity(&self) {}
197 fn on_write_failed(&self, _operation: QpWriteOperation, _failure: QpWriteFailure) {}
198}
199
200pub struct NoopCallbacks;
201impl QpClientCallbacks for NoopCallbacks {}
202
203pub struct QpClientConfig {
205 pub api_url: String,
206 pub reconnect_delay: Duration,
207 pub indicative_republish_interval: Duration,
215}
216
217impl QpClientConfig {
218 pub fn new(api_url: String) -> Self {
219 Self {
220 api_url,
221 reconnect_delay: Duration::from_secs(5),
222 indicative_republish_interval: Duration::from_secs(15),
223 }
224 }
225}
226
227pub async fn run_qp_client(
233 config: QpClientConfig,
234 wallet: Arc<HypercallWallet>,
235 mut outbound_rx: mpsc::Receiver<ClientOutbound>,
236 inbound_tx: mpsc::Sender<ServerInbound>,
237 callbacks: Arc<dyn QpClientCallbacks>,
238) {
239 loop {
240 match connect_and_run(
241 &config.api_url,
242 &wallet,
243 &mut outbound_rx,
244 &inbound_tx,
245 callbacks.as_ref(),
246 )
247 .await
248 {
249 Ok(_) => {
250 warn!(
251 "QP WebSocket closed, reconnecting in {:?}",
252 config.reconnect_delay
253 );
254 callbacks.on_disconnected(QpDisconnectReason::Closed);
255 }
256 Err(e) => {
257 if e == INBOUND_CHANNEL_CLOSED {
258 error!("QP inbound channel closed; stopping client task");
259 callbacks.on_disconnected(QpDisconnectReason::InboundChannelClosed);
260 break;
261 }
262 error!(
263 "QP WebSocket error: {}, reconnecting in {:?}",
264 e, config.reconnect_delay
265 );
266 callbacks.on_disconnected(QpDisconnectReason::Error);
267 }
268 }
269 let mut drained = 0u64;
270 while outbound_rx.try_recv().is_ok() {
271 drained += 1;
272 }
273 if drained > 0 {
274 info!(
275 "Drained {} stale outbound messages before reconnect",
276 drained
277 );
278 callbacks.on_stale_messages_drained(drained);
279 }
280 sleep(config.reconnect_delay).await;
281 }
282}
283
284pub(crate) fn forward_inbound_or_close(
285 inbound_tx: &mpsc::Sender<ServerInbound>,
286 msg: ServerInbound,
287 callbacks: &dyn QpClientCallbacks,
288) -> Result<(), String> {
289 match inbound_tx.try_send(msg) {
290 Ok(()) => Ok(()),
291 Err(TrySendError::Closed(_)) => Err(INBOUND_CHANNEL_CLOSED.to_string()),
292 Err(TrySendError::Full(msg)) => {
293 warn!(
294 message = ?msg,
295 "Inbound RFQ channel full, dropping server message to keep WebSocket writer responsive"
296 );
297 callbacks.on_inbound_message_dropped();
298 Ok(())
299 }
300 }
301}
302
303pub(crate) async fn connect_and_auth(
307 api_url: &str,
308 wallet: &HypercallWallet,
309 callbacks: &dyn QpClientCallbacks,
310) -> Result<(WsSink, WsStream, Vec<String>), String> {
311 let ws_url = if api_url.starts_with("https") {
312 format!("{}/ws/quotes", api_url.replacen("https", "wss", 1))
313 } else {
314 format!("{}/ws/quotes", api_url.replacen("http", "ws", 1))
315 };
316
317 info!("Connecting to {}", ws_url);
318 let (ws_stream, _) = connect_async(&ws_url)
319 .await
320 .map_err(|e| format!("WebSocket connect failed: {e}"))?;
321 info!("WebSocket connected");
322 callbacks.on_connected();
323 callbacks.on_transport_activity();
324
325 let (mut ws_sender, mut ws_receiver) = ws_stream.split();
326
327 let now_ms = std::time::SystemTime::now()
329 .duration_since(std::time::UNIX_EPOCH)
330 .unwrap()
331 .as_millis() as u64;
332 let nonce = wallet.next_nonce();
333 let signature = wallet
334 .sign_connect_quote_provider(alloy::primitives::U256::from(now_ms), nonce)
335 .await
336 .map_err(|e| format!("Failed to sign auth: {e}"))?;
337
338 let auth_msg = ClientOutbound::ConnectQuoteProvider {
339 wallet: wallet.address.as_hex(),
340 timestamp: now_ms.to_string(),
341 nonce,
342 signature,
343 };
344 let json = serde_json::to_string(&auth_msg).map_err(|e| format!("JSON encode: {e}"))?;
345 match timeout(WS_WRITE_TIMEOUT, ws_sender.send(Message::Text(json))).await {
346 Ok(Ok(())) => {}
347 Ok(Err(e)) => {
348 callbacks.on_write_failed(QpWriteOperation::Auth, QpWriteFailure::SendError);
349 return Err(format!("Send auth failed: {e}"));
350 }
351 Err(_) => {
352 callbacks.on_write_failed(QpWriteOperation::Auth, QpWriteFailure::Timeout);
353 return Err("Send auth timed out".to_string());
354 }
355 }
356
357 let auth_response = tokio::time::timeout(Duration::from_secs(10), ws_receiver.next())
359 .await
360 .map_err(|_| "Auth response timeout".to_string())?
361 .ok_or_else(|| "Connection closed before auth".to_string())?
362 .map_err(|e| format!("Auth frame error: {e}"))?;
363 callbacks.on_transport_activity();
364
365 let auth_text = match auth_response {
366 Message::Text(t) => t,
367 Message::Binary(b) => {
368 String::from_utf8(b.to_vec()).map_err(|_| "Invalid binary frame".to_string())?
369 }
370 Message::Ping(data) => {
371 match timeout(WS_WRITE_TIMEOUT, ws_sender.send(Message::Pong(data))).await {
372 Ok(Ok(())) => {}
373 Ok(Err(_)) => {
374 callbacks.on_write_failed(QpWriteOperation::Pong, QpWriteFailure::SendError);
375 }
376 Err(_) => {
377 callbacks.on_write_failed(QpWriteOperation::Pong, QpWriteFailure::Timeout);
378 }
379 }
380 callbacks.on_transport_activity();
381 return Err("Unexpected ping during auth".into());
382 }
383 Message::Pong(_) => return Err("Unexpected pong during auth".into()),
384 _ => return Err("Unexpected frame type during auth".into()),
385 };
386
387 let server_msg: ServerInbound =
388 serde_json::from_str(&auth_text).map_err(|e| format!("Auth parse: {e}"))?;
389 let capabilities = match server_msg {
390 ServerInbound::Authenticated {
391 wallet: w,
392 capabilities,
393 } => {
394 info!("Authenticated as QP: {}", w);
395 capabilities
396 }
397 ServerInbound::AuthFailed { reason } => {
398 return Err(format!("Authentication failed: {}", reason));
399 }
400 other => return Err(format!("Unexpected message during auth: {:?}", other)),
401 };
402
403 Ok((ws_sender, ws_receiver, capabilities))
404}
405
406async fn connect_and_run(
407 api_url: &str,
408 wallet: &HypercallWallet,
409 outbound_rx: &mut mpsc::Receiver<ClientOutbound>,
410 inbound_tx: &mpsc::Sender<ServerInbound>,
411 callbacks: &dyn QpClientCallbacks,
412) -> Result<(), String> {
413 let (mut ws_sender, mut ws_receiver, _capabilities) =
414 connect_and_auth(api_url, wallet, callbacks).await?;
415
416 let mut heartbeat = tokio::time::interval(Duration::from_secs(30));
418 let mut last_activity = tokio::time::Instant::now();
419 let heartbeat_timeout = Duration::from_secs(90);
420
421 loop {
422 tokio::select! {
423 _ = heartbeat.tick() => {
424 if last_activity.elapsed() > heartbeat_timeout {
425 warn!("QP WebSocket heartbeat timeout ({}s with no activity), reconnecting",
426 last_activity.elapsed().as_secs());
427 break;
428 }
429 match timeout(WS_WRITE_TIMEOUT, ws_sender.send(Message::Ping(vec![]))).await {
430 Ok(Ok(())) => {}
431 Ok(Err(e)) => {
432 callbacks.on_write_failed(QpWriteOperation::Heartbeat, QpWriteFailure::SendError);
433 return Err(format!("Send heartbeat failed: {e}"));
434 }
435 Err(_) => {
436 callbacks.on_write_failed(QpWriteOperation::Heartbeat, QpWriteFailure::Timeout);
437 return Err("Send heartbeat timed out".to_string());
438 }
439 }
440 callbacks.on_transport_activity();
441 }
442 Some(msg) = outbound_rx.recv() => {
443 let json = serde_json::to_string(&msg).map_err(|e| format!("JSON encode: {e}"))?;
444 match timeout(WS_WRITE_TIMEOUT, ws_sender.send(Message::Text(json))).await {
445 Ok(Ok(())) => {}
446 Ok(Err(e)) => {
447 callbacks.on_write_failed(QpWriteOperation::Outbound, QpWriteFailure::SendError);
448 return Err(format!("Send outbound failed: {e}"));
449 }
450 Err(_) => {
451 callbacks.on_write_failed(QpWriteOperation::Outbound, QpWriteFailure::Timeout);
452 return Err("Send outbound timed out".to_string());
453 }
454 }
455 callbacks.on_transport_activity();
456 }
457 Some(Ok(frame)) = ws_receiver.next() => {
458 last_activity = tokio::time::Instant::now();
459 callbacks.on_transport_activity();
460 match frame {
461 Message::Text(text) => {
462 match serde_json::from_str::<ServerInbound>(&text) {
463 Ok(msg) => {
464 forward_inbound_or_close(inbound_tx, msg, callbacks)?;
465 }
466 Err(e) => {
467 warn!("Failed to parse server message: {}", e);
468 }
469 }
470 }
471 Message::Binary(bytes) => {
472 if let Ok(text) = String::from_utf8(bytes.to_vec()) {
473 if let Ok(msg) = serde_json::from_str::<ServerInbound>(&text) {
474 forward_inbound_or_close(inbound_tx, msg, callbacks)?;
475 }
476 }
477 }
478 Message::Ping(data) => {
479 match timeout(WS_WRITE_TIMEOUT, ws_sender.send(Message::Pong(data))).await {
480 Ok(Ok(())) => {}
481 Ok(Err(_)) => {
482 callbacks.on_write_failed(QpWriteOperation::Pong, QpWriteFailure::SendError);
483 }
484 Err(_) => {
485 callbacks.on_write_failed(QpWriteOperation::Pong, QpWriteFailure::Timeout);
486 }
487 }
488 callbacks.on_transport_activity();
489 }
490 Message::Pong(_) => {}
491 Message::Close(_) => break,
492 _ => {}
493 }
494 }
495 else => break,
496 }
497 }
498
499 Ok(())
500}
501
502#[cfg(test)]
503mod tests {
504 use super::*;
505 use std::sync::atomic::{AtomicUsize, Ordering};
506
507 use tokio::net::TcpListener;
508 use tokio_tungstenite::accept_async;
509
510 const TEST_PRIVATE_KEY: &str =
511 "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80";
512
513 #[derive(Default)]
514 struct RecordingCallbacks {
515 connected: AtomicUsize,
516 transport_activity: AtomicUsize,
517 }
518
519 impl QpClientCallbacks for RecordingCallbacks {
520 fn on_connected(&self) {
521 self.connected.fetch_add(1, Ordering::Relaxed);
522 }
523
524 fn on_transport_activity(&self) {
525 self.transport_activity.fetch_add(1, Ordering::Relaxed);
526 }
527 }
528
529 #[tokio::test]
530 async fn connect_and_run_reports_transport_activity_for_ping_pong() {
531 let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
532 let addr = listener.local_addr().unwrap();
533
534 let server = tokio::spawn(async move {
535 let (stream, _) = listener.accept().await.unwrap();
536 let mut ws = accept_async(stream).await.unwrap();
537
538 let auth = ws.next().await.unwrap().unwrap();
539 assert!(matches!(auth, Message::Text(_)));
540
541 let authenticated = ServerInbound::Authenticated {
542 wallet: "0x0000000000000000000000000000000000000000".to_string(),
543 capabilities: Vec::new(),
544 };
545 ws.send(Message::Text(
546 serde_json::to_string(&authenticated).unwrap(),
547 ))
548 .await
549 .unwrap();
550
551 ws.send(Message::Ping(vec![1, 2, 3])).await.unwrap();
552
553 while let Some(frame) = ws.next().await {
554 match frame.unwrap() {
555 Message::Ping(data) => {
556 ws.send(Message::Pong(data)).await.unwrap();
557 }
558 Message::Pong(data) if data == vec![1, 2, 3] => {
559 ws.close(None).await.unwrap();
560 break;
561 }
562 Message::Close(_) => break,
563 _ => {}
564 }
565 }
566 });
567
568 let wallet = HypercallWallet::from_private_key(TEST_PRIVATE_KEY, 998).unwrap();
569 let (_outbound_tx, mut outbound_rx) = mpsc::channel(8);
570 let (inbound_tx, _inbound_rx) = mpsc::channel(8);
571 let callbacks = RecordingCallbacks::default();
572
573 let result = tokio::time::timeout(
574 Duration::from_secs(5),
575 connect_and_run(
576 &format!("http://{}", addr),
577 &wallet,
578 &mut outbound_rx,
579 &inbound_tx,
580 &callbacks,
581 ),
582 )
583 .await
584 .expect("QP client test timed out");
585
586 result.unwrap();
587 server.await.unwrap();
588
589 assert_eq!(callbacks.connected.load(Ordering::Relaxed), 1);
590 assert!(
591 callbacks.transport_activity.load(Ordering::Relaxed) >= 3,
592 "expected connect, auth, and ping/pong activity callbacks"
593 );
594 }
595}