1#![allow(dead_code)]
20
21use std::collections::{HashMap, HashSet, VecDeque};
22use std::sync::{Arc, Mutex};
23
24use futures::{SinkExt, StreamExt};
25use once_cell::sync::Lazy;
26use tokio::sync::{mpsc, Notify};
27use tokio_tungstenite::tungstenite::Message;
28
29use crate::Value;
30
31pub struct ClientState {
34 pub url: String,
35 outgoing: mpsc::UnboundedSender<Message>,
37 pending_rx: Mutex<Option<mpsc::UnboundedReceiver<Message>>>,
42 connect_gate: tokio::sync::Mutex<()>,
45 incoming: Mutex<VecDeque<Value>>,
47 notify: Notify,
49 resolved: Mutex<HashMap<String, Value>>,
51 rejections: Mutex<HashMap<String, Value>>,
53 subscriptions: Mutex<HashMap<String, Value>>,
56 futures: Mutex<HashSet<String>>,
59 flights: Mutex<HashMap<String, FlightSlot>>,
66 connected: Mutex<bool>,
67 closed: Mutex<bool>,
68 last_pong_ms: Mutex<i64>,
69 mock: Mutex<bool>,
74 mock_sent: Mutex<Vec<Value>>,
75 ws_test_completed: Mutex<bool>,
76}
77
78#[derive(Clone)]
84struct FlightSlot {
85 open: bool,
86 settled: Option<Result<Value, Value>>,
87}
88
89static REGISTRY: Lazy<Mutex<HashMap<String, Arc<ClientState>>>> =
90 Lazy::new(|| Mutex::new(HashMap::new()));
91
92fn now_ms() -> i64 {
94 std::time::SystemTime::now()
95 .duration_since(std::time::UNIX_EPOCH)
96 .map(|d| d.as_millis() as i64)
97 .unwrap_or(0)
98}
99
100fn parse_text(t: &str) -> Value {
103 match serde_json::from_str::<serde_json::Value>(t) {
104 Ok(j) => Value::from_json(&j),
105 Err(_) => Value::Str(t.to_string().into()),
106 }
107}
108
109fn parse_binary(b: &[u8]) -> Value {
112 use std::io::Read;
113 {
115 let mut d = flate2::read::GzDecoder::new(b);
116 let mut s = String::new();
117 if d.read_to_string(&mut s).is_ok() && !s.is_empty() {
118 return parse_text(&s);
119 }
120 }
121 {
123 let mut d = flate2::read::DeflateDecoder::new(b);
124 let mut s = String::new();
125 if d.read_to_string(&mut s).is_ok() && !s.is_empty() {
126 return parse_text(&s);
127 }
128 }
129 if let Ok(s) = std::str::from_utf8(b) {
132 return parse_text(s);
133 }
134 crate::exchange_stubs::bytes_to_value(b)
137}
138
139fn parse_raw_binary(b: &[u8]) -> Value {
144 match serde_json::from_slice::<serde_json::Value>(b) {
145 Ok(j) => Value::from_json(&j),
146 Err(_) => crate::exchange_stubs::bytes_to_value(b),
147 }
148}
149
150impl ClientState {
151 fn push_incoming(&self, v: Value) {
152 self.incoming.lock().unwrap().push_back(v);
153 self.notify.notify_waiters();
154 }
155
156 pub async fn next_message(&self) -> Option<Value> {
160 let mock = *self.mock.lock().unwrap();
161 loop {
162 let notified = self.notify.notified();
163 if let Some(v) = self.incoming.lock().unwrap().pop_front() {
164 return Some(v);
165 }
166 if *self.closed.lock().unwrap() {
167 return None;
168 }
169 if mock {
170 if tokio::time::timeout(std::time::Duration::from_millis(1500), notified).await.is_err() {
175 return None;
176 }
177 } else {
178 notified.await;
179 }
180 }
181 }
182
183 pub fn resolve(&self, hash: &str, value: Value) {
190 self.flight_settle(hash, Ok(value.clone()));
191 self.resolved.lock().unwrap().insert(hash.to_string(), value);
192 self.notify.notify_waiters();
193 }
194
195 pub fn reject(&self, hash: &str, err: Value) {
198 self.flight_settle(hash, Err(err.clone()));
199 self.rejections.lock().unwrap().insert(hash.to_string(), err);
200 self.notify.notify_waiters();
201 }
202
203 pub fn take_settled(&self, hashes: &[String]) -> Option<Result<Value, Value>> {
206 {
207 let mut rj = self.rejections.lock().unwrap();
208 for h in hashes {
209 if let Some(e) = rj.remove(h) {
210 return Some(Err(e));
211 }
212 }
213 }
214 let mut r = self.resolved.lock().unwrap();
215 for h in hashes {
216 if let Some(v) = r.remove(h) {
217 return Some(Ok(v));
218 }
219 }
220 None
221 }
222
223 pub fn note_futures(&self, hashes: &[String]) {
226 let mut f = self.futures.lock().unwrap();
227 for h in hashes {
228 f.insert(h.clone());
229 }
230 }
231
232 pub fn flight_begin(&self, hash: &str) -> bool {
241 let mut fl = self.flights.lock().unwrap();
242 match fl.get_mut(hash) {
243 Some(slot) if slot.open => false,
245 Some(slot) => {
248 slot.open = true;
249 self.futures.lock().unwrap().insert(hash.to_string());
250 true
251 }
252 None => {
253 fl.insert(hash.to_string(), FlightSlot { open: true, settled: None });
254 self.futures.lock().unwrap().insert(hash.to_string());
255 true
256 }
257 }
258 }
259
260 pub fn flight_peek(&self, hash: &str) -> Option<Result<Value, Value>> {
263 self.flights.lock().unwrap().get(hash).and_then(|s| s.settled.clone())
264 }
265
266 pub fn flight_is_open(&self, hash: &str) -> bool {
268 self.flights.lock().unwrap().get(hash).map(|s| s.open).unwrap_or(false)
269 }
270
271 pub fn flight_settle(&self, hash: &str, res: Result<Value, Value>) -> bool {
275 {
276 let mut fl = self.flights.lock().unwrap();
277 match fl.get_mut(hash) {
278 Some(slot) if slot.open => {
279 slot.open = false;
280 slot.settled = Some(res);
281 }
282 _ => return false,
283 }
284 }
285 self.futures.lock().unwrap().remove(hash);
288 self.notify.notify_waiters();
289 true
290 }
291
292 pub fn subscribe_once(&self, subscribe_hash: &str, subscription: Value) -> bool {
296 let mut subs = self.subscriptions.lock().unwrap();
297 if subs.contains_key(subscribe_hash) {
298 return false;
299 }
300 let stored = if matches!(subscription, Value::Null) {
301 Value::Bool(true)
302 } else {
303 subscription
304 };
305 subs.insert(subscribe_hash.to_string(), stored);
306 true
307 }
308
309 pub fn set_subscription(&self, subscribe_hash: &str, subscription: Value) {
312 self.subscriptions.lock().unwrap().insert(subscribe_hash.to_string(), subscription);
313 }
314
315 pub fn is_subscribed(&self, subscribe_hash: &str) -> bool {
316 self.subscriptions.lock().unwrap().contains_key(subscribe_hash)
317 }
318
319 pub fn send_text(&self, s: String) -> bool {
320 if std::env::var("CCXT_WS_DEBUG").is_ok() { eprintln!("[wssend] {}", s.chars().take(200).collect::<String>()); }
321 if *self.mock.lock().unwrap() {
324 self.mock_sent.lock().unwrap().push(parse_text(&s));
325 return true;
326 }
327 self.outgoing.send(Message::Text(s)).is_ok()
328 }
329
330 pub fn mock_enable(&self) {
333 *self.mock.lock().unwrap() = true;
334 *self.connected.lock().unwrap() = true;
335 }
336 pub fn mock_inject(&self, msg: Value) {
338 self.incoming.lock().unwrap().push_back(msg);
339 self.notify.notify_one();
340 }
341 pub fn is_mock(&self) -> bool { *self.mock.lock().unwrap() }
342 pub fn mock_sent_value(&self) -> Value {
344 Value::Array(self.mock_sent.lock().unwrap().clone())
345 }
346 pub fn has_pending_futures(&self) -> bool {
347 !self.futures.lock().unwrap().is_empty()
348 }
349 pub fn has_queued_messages(&self) -> bool {
351 !self.incoming.lock().unwrap().is_empty()
352 }
353 pub fn mark_ws_test_completed(&self) { *self.ws_test_completed.lock().unwrap() = true; }
354 pub fn is_ws_test_completed(&self) -> bool { *self.ws_test_completed.lock().unwrap() }
355 pub fn reject_pending_futures(&self, err: Value) {
358 let hashes: Vec<String> = self.futures.lock().unwrap().iter().cloned().collect();
359 for h in hashes { self.reject(&h, err.clone()); }
360 }
361
362 pub fn is_closed(&self) -> bool {
363 *self.closed.lock().unwrap()
364 }
365
366 pub fn on_pong(&self) {
367 *self.last_pong_ms.lock().unwrap() = now_ms();
368 }
369
370 pub fn reset(&self) {
375 self.resolved.lock().unwrap().clear();
376 self.rejections.lock().unwrap().clear();
377 self.subscriptions.lock().unwrap().clear();
378 self.futures.lock().unwrap().clear();
379 self.flights.lock().unwrap().clear();
380 }
381
382 pub fn reset_with_error(&self, error: Value) {
391 let hashes: Vec<String> = self.futures.lock().unwrap().iter().cloned().collect();
392 for h in &hashes {
393 if self.resolved.lock().unwrap().contains_key(h) {
394 continue;
395 }
396 self.reject(h, error.clone());
397 }
398 self.futures.lock().unwrap().clear();
399 }
400
401 pub fn subscriptions_value(&self) -> Value {
407 let subs = self.subscriptions.lock().unwrap();
408 let mut m = indexmap::IndexMap::new();
409 m.insert("__ws_subs_url".to_string(), Value::Str(self.url.clone().into()));
410 for (h, sub) in subs.iter() {
411 let tagged = match sub {
416 Value::Dict(d) => {
417 let mut inner = (**d).clone();
418 inner.insert("__ws_sub_ref".to_string(),
419 Value::Str(format!("{}\u{1}{}", self.url, h).into()));
420 Value::Dict(std::sync::Arc::new(inner))
421 }
422 other => other.clone(),
423 };
424 m.insert(h.clone(), tagged);
425 }
426 Value::Map(m)
427 }
428
429 pub fn set_subscription_field(&self, hash: &str, key: &str, val: Value) {
432 let mut subs = self.subscriptions.lock().unwrap();
433 match subs.get_mut(hash) {
434 Some(Value::Dict(d)) => { std::sync::Arc::make_mut(d).insert(key.to_string(), val); }
435 _ => {
436 let mut inner = indexmap::IndexMap::new();
437 inner.insert(key.to_string(), val);
438 subs.insert(hash.to_string(), Value::Dict(std::sync::Arc::new(inner)));
439 }
440 }
441 }
442
443 pub fn futures_value(&self) -> Value {
445 let f = self.futures.lock().unwrap();
446 let mut m = indexmap::IndexMap::new();
447 for h in f.iter() {
448 let mut fh = indexmap::IndexMap::new();
452 fh.insert("url".to_string(), Value::Str(self.url.clone().into()));
453 fh.insert("__ws_future_hash".to_string(), Value::Str(h.clone().into()));
454 m.insert(h.clone(), Value::Map(fh));
455 }
456 Value::Map(m)
457 }
458}
459
460pub fn get_client(url: &str) -> Option<Arc<ClientState>> {
462 let reg = REGISTRY.lock().unwrap();
463 reg.get(url).filter(|c| !c.is_closed()).cloned()
464}
465
466pub fn value_subs_insert(url: &str, key: &str, val: Value) {
469 if let Some(c) = get_client(url) { c.set_subscription(key, val); }
470}
471
472pub fn value_subs_remove(url: &str, key: &str) {
474 if let Some(c) = get_client(url) { c.subscriptions.lock().unwrap().remove(key); }
475}
476
477pub fn value_sub_field_write(subref: &str, key: &str, val: Value) {
480 if let Some((url, hash)) = subref.split_once('\u{1}') {
481 if let Some(c) = get_client(url) { c.set_subscription_field(hash, key, val); }
482 }
483}
484
485async fn connect_via_proxy(
491 url: &str,
492 proxy: &str,
493) -> Result<tokio_tungstenite::WebSocketStream<
494 tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>, String> {
495 use tokio::io::{AsyncReadExt, AsyncWriteExt};
496 let target = url::Url::parse(url).map_err(|e| format!("[NetworkError] ws url {url}: {e}"))?;
497 let host = target.host_str().ok_or_else(|| format!("[NetworkError] ws url {url} has no host"))?;
498 let port = target.port_or_known_default().unwrap_or(443);
499 let p = url::Url::parse(proxy).map_err(|e| format!("[NetworkError] ws proxy {proxy}: {e}"))?;
500 let p_host = p.host_str().ok_or_else(|| format!("[NetworkError] ws proxy {proxy} has no host"))?;
501 let p_port = p.port_or_known_default().unwrap_or(8080);
502 let mut stream = tokio::net::TcpStream::connect((p_host, p_port))
503 .await
504 .map_err(|e| format!("[NetworkError] ws proxy connect {proxy}: {e}"))?;
505 let connect = format!(
506 "CONNECT {host}:{port} HTTP/1.1\r\nHost: {host}:{port}\r\nProxy-Connection: Keep-Alive\r\n\r\n"
507 );
508 stream
509 .write_all(connect.as_bytes())
510 .await
511 .map_err(|e| format!("[NetworkError] ws proxy CONNECT {proxy}: {e}"))?;
512 let mut head = Vec::new();
513 let mut byte = [0u8; 1];
514 while !head.ends_with(b"\r\n\r\n") {
515 let n = stream
516 .read(&mut byte)
517 .await
518 .map_err(|e| format!("[NetworkError] ws proxy CONNECT {proxy}: {e}"))?;
519 if n == 0 {
520 return Err(format!("[NetworkError] ws proxy {proxy} closed during CONNECT"));
521 }
522 head.push(byte[0]);
523 if head.len() > 8192 {
524 return Err(format!("[NetworkError] ws proxy {proxy} sent an oversized CONNECT reply"));
525 }
526 }
527 let status = String::from_utf8_lossy(&head);
528 let first = status.lines().next().unwrap_or_default();
529 if !first.contains(" 200") {
530 return Err(format!("[NetworkError] ws proxy {proxy} refused CONNECT: {first}"));
531 }
532 let (ws, _resp) = tokio_tungstenite::client_async_tls(url, stream)
533 .await
534 .map_err(|e| format!("[NetworkError] ws connect {url} via {proxy}: {e}"))?;
535 Ok(ws)
536}
537
538pub async fn ensure_client(url: &str, proxy: Option<String>, decompress_binary: bool) -> Result<Arc<ClientState>, String> {
539 let state = ensure_slot(url);
540 if *state.connected.lock().unwrap() {
541 return Ok(state);
542 }
543 let gate_holder = state.clone();
546 let _gate = gate_holder.connect_gate.lock().await;
547 if *state.connected.lock().unwrap() {
548 return Ok(state);
549 }
550 let ws = match proxy.as_deref().filter(|p| !p.is_empty()) {
551 Some(p) => connect_via_proxy(url, p).await?,
552 None => {
553 let (ws, _resp) = tokio_tungstenite::connect_async(url)
554 .await
555 .map_err(|e| format!("[NetworkError] ws connect {url}: {e}"))?;
556 ws
557 }
558 };
559 let (mut write, mut read) = ws.split();
560 let mut rx = state.pending_rx.lock().unwrap().take()
561 .ok_or_else(|| format!("[NetworkError] ws {url} slot has no writer channel"))?;
562 *state.last_pong_ms.lock().unwrap() = now_ms();
563
564 tokio::spawn(async move {
566 while let Some(msg) = rx.recv().await {
567 if write.send(msg).await.is_err() {
568 break;
569 }
570 }
571 let _ = write.close().await;
572 });
573
574 let st = state.clone();
576 tokio::spawn(async move {
577 while let Some(frame) = read.next().await {
578 match frame {
579 Ok(Message::Text(t)) => st.push_incoming(parse_text(&t)),
580 Ok(Message::Binary(b)) => st.push_incoming(if decompress_binary { parse_binary(&b) } else { parse_raw_binary(&b) }),
581 Ok(Message::Pong(_)) => st.on_pong(),
582 Ok(Message::Ping(_)) => {}
584 Ok(Message::Close(_)) | Err(_) => break,
585 _ => {}
586 }
587 }
588 *st.connected.lock().unwrap() = false;
589 *st.closed.lock().unwrap() = true;
590 st.notify.notify_waiters();
591 });
592
593 let st2 = state.clone();
596 tokio::spawn(async move {
597 let mut iv = tokio::time::interval(std::time::Duration::from_secs(30));
598 iv.tick().await; loop {
600 iv.tick().await;
601 if st2.is_closed() {
602 break;
603 }
604 if st2.outgoing.send(Message::Ping(Vec::new())).is_err() {
605 break;
606 }
607 }
608 });
609
610 *state.connected.lock().unwrap() = true;
611 Ok(state)
612}
613
614pub fn client_field_live(url: &str, field: &str) -> Value {
618 match get_client(url) {
619 Some(c) if field == "futures" => c.futures_value(),
620 Some(c) => c.subscriptions_value(),
621 None => Value::Map(indexmap::IndexMap::new()),
622 }
623}
624
625fn ensure_slot(url: &str) -> Arc<ClientState> {
628 let mut reg = REGISTRY.lock().unwrap();
629 if let Some(c) = reg.get(url) {
630 if !c.is_closed() {
631 return c.clone();
632 }
633 }
634 let (tx, rx) = mpsc::unbounded_channel::<Message>();
635 let state = Arc::new(ClientState {
636 url: url.to_string(),
637 outgoing: tx,
638 pending_rx: Mutex::new(Some(rx)),
639 connect_gate: tokio::sync::Mutex::new(()),
640 incoming: Mutex::new(VecDeque::new()),
641 notify: Notify::new(),
642 resolved: Mutex::new(HashMap::new()),
643 rejections: Mutex::new(HashMap::new()),
644 subscriptions: Mutex::new(HashMap::new()),
645 futures: Mutex::new(HashSet::new()),
646 flights: Mutex::new(HashMap::new()),
647 connected: Mutex::new(false),
648 closed: Mutex::new(false),
649 last_pong_ms: Mutex::new(now_ms()),
650 mock: Mutex::new(false),
651 mock_sent: Mutex::new(Vec::new()),
652 ws_test_completed: Mutex::new(false),
653 });
654 reg.insert(url.to_string(), state.clone());
655 state
656}
657
658pub fn drop_client(url: &str) {
660 REGISTRY.lock().unwrap().remove(url);
661}
662
663pub fn mock_setup(url: &str) {
675 let c = ensure_slot(url);
676 c.reset();
677 c.mock_enable();
678 c.mock_sent.lock().unwrap().clear();
679 c.incoming.lock().unwrap().clear();
683 *c.ws_test_completed.lock().unwrap() = false;
684}
685pub fn mock_inject(url: &str, msg: Value) {
686 if let Some(c) = get_client(url) { c.mock_inject(msg); }
687}
688pub fn mock_sent_messages(url: &str) -> Value {
689 match get_client(url) { Some(c) => c.mock_sent_value(), None => Value::Array(vec![]) }
690}
691pub fn mock_has_pending_futures(url: &str) -> bool {
692 get_client(url).map(|c| c.has_pending_futures()).unwrap_or(false)
693}
694pub fn mock_has_queued_messages(url: &str) -> bool {
695 get_client(url).map(|c| c.has_queued_messages()).unwrap_or(false)
696}
697pub fn mock_mark_completed(url: &str) {
698 if let Some(c) = get_client(url) { c.mark_ws_test_completed(); }
699}
700pub fn mock_is_completed(url: &str) -> bool {
701 get_client(url).map(|c| c.is_ws_test_completed()).unwrap_or(true)
702}
703pub fn mock_reject_futures(url: &str) {
704 if let Some(c) = get_client(url) {
705 c.reject_pending_futures(Value::Str(
706 "[ExchangeError] static ws test: the injected messages did not resolve the watch future".to_string().into()));
707 }
708}
709
710pub fn client_value(url: &str) -> Value {
714 let c = ensure_slot(url);
717 let mut m = indexmap::IndexMap::new();
718 m.insert("url".to_string(), Value::Str(url.to_string().into()));
719 m.insert("subscriptions".to_string(), c.subscriptions_value());
720 m.insert("futures".to_string(), c.futures_value());
721 Value::Map(m)
722}
723
724pub fn begin_flight(url: &str, hash: &str) -> bool {
729 ensure_slot(url).flight_begin(hash)
730}
731
732
733pub fn flight_handle(url: &str, hash: &str, led: bool) -> Value {
738 let mut m = indexmap::IndexMap::new();
739 m.insert("url".to_string(), Value::Str(url.to_string().into()));
740 m.insert("__ws_flight_hash".to_string(), Value::Str(hash.to_string().into()));
741 m.insert("__ws_flight_led".to_string(), Value::Bool(led));
747 Value::Map(m)
748}
749
750fn flight_hash_of(handle: &Value) -> Option<String> {
753 for key in ["__ws_flight_hash", "__ws_future_hash"] {
754 if let Value::Str(h) = crate::get_value(handle, &Value::Str(key.to_string().into())) {
755 return Some(h.to_string());
756 }
757 }
758 None
759}
760
761pub async fn ws_await_flight(handle: &Value) -> Value {
768 let (url, hash) = match (url_of(handle), flight_hash_of(handle)) {
769 (Some(u), Some(h)) => (u, h),
770 _ => return Value::Null,
771 };
772 let client = match get_client(&url) {
773 Some(c) => c,
774 None => return Value::Null,
775 };
776 let settled = client.flight_peek(&hash);
777 let led = matches!(
782 crate::get_value(handle, &Value::Str("__ws_flight_led".into())),
783 Value::Bool(true)
784 );
785 if led || !client.flight_is_open(&hash) {
786 return match settled {
787 Some(Ok(v)) => v,
788 Some(Err(e)) => panic!(
789 "{}",
790 match &e {
791 Value::Str(s) => s.clone(),
792 v => crate::runtime::stringify_param(v).into(),
793 }
794 ),
795 None => Value::Null,
799 };
800 }
801 let budget = if client.is_mock() {
802 std::time::Duration::from_millis(1500)
803 } else {
804 std::time::Duration::from_secs(60)
805 };
806 let deadline = tokio::time::Instant::now() + budget;
807 loop {
808 let notified = client.notify.notified();
811 if let Some(res) = client.flight_peek(&hash) {
812 return match res {
813 Ok(v) => v,
814 Err(e) => panic!(
815 "{}",
816 match &e {
817 Value::Str(s) => s.clone(),
818 v => crate::runtime::stringify_param(v).into(),
819 }
820 ),
821 };
822 }
823 if !client.flight_is_open(&hash) {
824 return Value::Null;
826 }
827 if tokio::time::timeout_at(deadline, notified).await.is_err() {
828 panic!(
829 "[NetworkError] timed out waiting for the in-flight '{}' on {}",
830 hash, url
831 );
832 }
833 }
834}
835
836pub fn url_of(client: &Value) -> Option<String> {
838 match crate::get_value(client, &Value::Str("url".into())) {
839 Value::Str(s) => Some(s.to_string()),
840 _ => None,
841 }
842}
843
844fn hash_str(v: &Value) -> Option<String> {
845 match v {
846 Value::Str(s) => Some(s.to_string()),
847 _ => None,
848 }
849}
850
851pub fn value_resolve(client: &Value, args: &[Value]) -> Value {
853 let value = args.get(0).cloned().unwrap_or(Value::Null);
854 if let Some(hash) = future_hash_of(client) {
857 if let Some(url) = url_of(client) {
858 if let Some(c) = get_client(&url) { c.resolve(&hash, value.clone()); }
859 }
860 return value;
861 }
862 if let (Some(url), Some(hash)) = (url_of(client), args.get(1).and_then(hash_str)) {
863 if let Some(c) = get_client(&url) {
864 c.resolve(&hash, value.clone());
865 }
866 }
867 value
868}
869
870fn future_hash_of(client: &Value) -> Option<String> {
872 match crate::get_value(client, &Value::Str("__ws_future_hash".into())) {
873 Value::Str(s) => Some(s.to_string()),
874 _ => None,
875 }
876}
877
878pub fn value_reject(client: &Value, args: &[Value]) -> Value {
880 let err = args.get(0).cloned().unwrap_or(Value::Null);
881 if let Some(hash) = future_hash_of(client) {
883 if let Some(url) = url_of(client) {
884 if let Some(c) = get_client(&url) { c.reject(&hash, err.clone()); }
885 }
886 return err;
887 }
888 if let Some(url) = url_of(client) {
889 if let Some(c) = get_client(&url) {
890 match args.get(1).and_then(hash_str) {
891 Some(hash) => c.reject(&hash, err.clone()),
892 None => {
894 let hashes: Vec<String> = c.futures.lock().unwrap().iter().cloned().collect();
895 for h in hashes {
896 c.reject(&h, err.clone());
897 }
898 }
899 }
900 }
901 }
902 err
903}
904
905pub fn value_send(client: &Value, args: &[Value]) -> Value {
907 if let Some(url) = url_of(client) {
908 if let Some(c) = get_client(&url) {
909 let payload = match args.get(0) {
910 Some(Value::Str(s)) => s.to_string(),
911 Some(v) => v.to_json().to_string(),
912 None => String::new().into(),
913 };
914 c.send_text(payload);
915 }
916 }
917 Value::Null
918}
919
920pub fn value_reset(client: &Value, error: Value) -> Value {
924 if let Some(url) = url_of(client) {
925 if let Some(c) = get_client(&url) {
926 if matches!(error, Value::Null) {
927 c.reset();
928 } else {
929 c.reset_with_error(error);
930 }
931 }
932 }
933 Value::Null
934}
935
936pub fn value_on_pong(client: &Value) -> Value {
938 if let Some(url) = url_of(client) {
939 if let Some(c) = get_client(&url) {
940 c.on_pong();
941 }
942 }
943 Value::Null
944}
945
946#[cfg(test)]
947mod tests {
948 use super::*;
949 use tokio_tungstenite::tungstenite::Message as WsMessage;
950
951 async fn spawn_mock_server() -> String {
956 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
957 let addr = listener.local_addr().unwrap();
958 tokio::spawn(async move {
959 if let Ok((stream, _)) = listener.accept().await {
960 let mut ws = tokio_tungstenite::accept_async(stream).await.unwrap();
961 if let Some(Ok(WsMessage::Text(sub))) = ws.next().await {
963 assert!(sub.contains("subscribe"), "expected subscribe, got {sub}");
964 }
965 for px in ["100.5", "101.0", "101.5"] {
967 let msg = format!("{{\"channel\":\"ticker\",\"symbol\":\"BTC/USDT\",\"last\":\"{px}\"}}");
968 ws.send(WsMessage::Text(msg)).await.unwrap();
969 }
970 tokio::time::sleep(std::time::Duration::from_millis(50)).await;
972 let _ = ws.close(None).await;
973 }
974 });
975 format!("ws://{addr}")
976 }
977
978 #[test]
984 fn value_reset_rejects_pending_futures() {
985 let url = "ws://reset-with-error.test";
986 mock_setup(url);
987 let client = get_client(url).expect("mock client");
988 client.note_futures(&["pending".to_string(), "delivered".to_string()]);
989 client.resolve("delivered", Value::Str("payload".into()));
990
991 let handle = client_value(url);
992 let error = Value::Str("[InvalidNonce] gap detected".into());
993 value_reset(&handle, error.clone());
994
995 assert_eq!(
997 client.take_settled(&["pending".to_string()]),
998 Some(Err(error))
999 );
1000 assert_eq!(
1002 client.take_settled(&["delivered".to_string()]),
1003 Some(Ok(Value::Str("payload".into())))
1004 );
1005 assert!(!client.has_pending_futures());
1006
1007 client.note_futures(&["pending2".to_string()]);
1009 value_reset(&handle, Value::Null);
1010 assert_eq!(client.take_settled(&["pending2".to_string()]), None);
1011 assert!(!client.has_pending_futures());
1012
1013 drop_client(url);
1014 }
1015
1016 #[tokio::test]
1017 async fn transport_roundtrip() {
1018 let url = spawn_mock_server().await;
1019 let client = ensure_client(&url, None, true).await.expect("connect");
1020
1021 assert!(client.subscribe_once("ticker:BTC/USDT", Value::Null));
1023 assert!(!client.subscribe_once("ticker:BTC/USDT", Value::Null));
1024 assert!(client.send_text("{\"op\":\"subscribe\",\"channel\":\"ticker\"}".to_string()));
1025
1026 let mut lasts = Vec::new();
1029 while lasts.len() < 3 {
1030 let msg = client.next_message().await.expect("message before close");
1031 let last = crate::get_value(&msg, &Value::Str("last".into()));
1032 if let Value::Str(s) = &last {
1033 client.resolve("ticker", Value::Str(s.clone()));
1034 }
1035 if let Some(Ok(Value::Str(v))) = client.take_settled(&["ticker".to_string()]) {
1036 lasts.push(v);
1037 }
1038 }
1039 assert_eq!(lasts, vec!["100.5", "101.0", "101.5"]);
1040
1041 let subs = client.subscriptions_value();
1043 assert!(crate::runtime::is_true(&crate::get_value(
1044 &subs,
1045 &Value::Str("ticker:BTC/USDT".into())
1046 )));
1047
1048 drop_client(&url);
1049 }
1050
1051 struct TestWsCore {
1057 exchange: crate::exchange::Exchange,
1058 }
1059 impl std::ops::Deref for TestWsCore {
1060 type Target = crate::exchange::Exchange;
1061 fn deref(&self) -> &Self::Target {
1062 &self.exchange
1063 }
1064 }
1065 impl std::ops::DerefMut for TestWsCore {
1066 fn deref_mut(&mut self) -> &mut Self::Target {
1067 &mut self.exchange
1068 }
1069 }
1070 impl crate::exchange::DerivedExchange for TestWsCore {}
1071 impl crate::exchange_generated::ExchangeBase for TestWsCore {
1072 fn call_dynamic<'a>(
1073 &'a mut self,
1074 method: &'a str,
1075 args: Vec<Value>,
1076 ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Value> + Send + 'a>> {
1077 Box::pin(async move {
1078 match method {
1079 "handle_message" => {
1080 let client = args.get(0).cloned().unwrap_or(Value::Null);
1081 let message = args.get(1).cloned().unwrap_or(Value::Null);
1082 let last = crate::get_value(&message, &Value::Str("last".into()));
1083 client.resolve(&[last, Value::Str("ticker".into())]);
1085 Value::Null
1086 }
1087 _ => self.call_dynamic_base(method, args).await,
1088 }
1089 })
1090 }
1091 }
1092
1093 #[tokio::test]
1094 async fn watch_drive_loop_end_to_end() {
1095 use crate::exchange::ExchangeRuntime;
1096 let url = spawn_mock_server().await;
1097 let mut core = TestWsCore {
1098 exchange: crate::exchange::Exchange::new(None),
1099 };
1100 let result = ExchangeRuntime::watch(
1103 &mut core,
1104 Value::Str(url.clone().into()),
1105 Value::Str("ticker".into()),
1106 &[
1107 Value::Str("{\"op\":\"subscribe\",\"channel\":\"ticker\"}".into()),
1108 Value::Str("ticker".into()),
1109 Value::Null,
1110 ],
1111 )
1112 .await;
1113 assert_eq!(result, Value::Str("100.5".into()));
1115 drop_client(&url);
1116 }
1117
1118 #[tokio::test]
1126 async fn flight_elects_one_leader_and_registers_it() {
1127 let url = "flight-test-election";
1128 let c = ensure_slot(url);
1129 assert!(c.flight_begin("authenticate:future"), "first caller leads");
1130 assert!(!c.flight_begin("authenticate:future"), "second caller follows");
1131 assert!(in_op_futures(&c, "authenticate:future"));
1133 drop_client(url);
1134 }
1135
1136 #[tokio::test]
1137 async fn flight_settle_wakes_waiters_and_reopens() {
1138 let url = "flight-test-settle";
1139 let c = ensure_slot(url);
1140 assert!(c.flight_begin("auth"));
1141 c.resolve("auth", Value::Str("listen-key".into()));
1143 assert_eq!(
1144 ws_await_flight(&flight_handle(url, "auth", false)).await,
1145 Value::Str("listen-key".into())
1146 );
1147 assert_eq!(
1148 ws_await_flight(&flight_handle(url, "auth", false)).await,
1149 Value::Str("listen-key".into())
1150 );
1151 assert!(!in_op_futures(&c, "auth"));
1154 assert!(c.flight_begin("auth"), "a settled flight re-elects");
1155 drop_client(url);
1156 }
1157
1158 #[tokio::test]
1159 async fn flight_follower_waits_for_the_leader() {
1160 let url = "flight-test-wait";
1161 let c = ensure_slot(url);
1162 assert!(c.flight_begin("auth"));
1163 let settler = {
1164 let c = c.clone();
1165 tokio::spawn(async move {
1166 tokio::time::sleep(std::time::Duration::from_millis(60)).await;
1167 c.resolve("auth", Value::Str("late".into()));
1168 })
1169 };
1170 let started = std::time::Instant::now();
1171 let got = ws_await_flight(&flight_handle(url, "auth", false)).await;
1172 assert_eq!(got, Value::Str("late".into()));
1173 assert!(started.elapsed() >= std::time::Duration::from_millis(50), "waited for the leader");
1174 settler.await.unwrap();
1175 drop_client(url);
1176 }
1177
1178 #[tokio::test]
1179 async fn a_leader_never_blocks_on_its_own_flight() {
1180 let url = "flight-test-leader";
1184 let c = ensure_slot(url);
1185 let led = c.flight_begin("authenticated");
1186 assert!(led);
1187 let started = std::time::Instant::now();
1188 assert_eq!(
1189 ws_await_flight(&flight_handle(url, "authenticated", led)).await,
1190 Value::Null
1191 );
1192 assert!(started.elapsed() < std::time::Duration::from_millis(200), "returned at once");
1193 c.resolve("authenticated", Value::Bool(true));
1195 let led2 = c.flight_begin("authenticated");
1196 assert_eq!(
1197 ws_await_flight(&flight_handle(url, "authenticated", led2)).await,
1198 Value::Bool(true),
1199 "a re-lead with no new work reports the last value"
1200 );
1201 drop_client(url);
1202 }
1203
1204 #[tokio::test]
1205 async fn flight_handle_without_a_flight_returns_null() {
1206 let url = "flight-test-missing";
1209 ensure_slot(url);
1210 assert_eq!(ws_await_flight(&flight_handle(url, "nope", false)).await, Value::Null);
1211 drop_client(url);
1212 }
1213
1214 fn in_op_futures(c: &Arc<ClientState>, hash: &str) -> bool {
1216 !matches!(
1217 crate::get_value(&c.futures_value(), &Value::Str(hash.to_string().into())),
1218 Value::Null
1219 )
1220 }
1221
1222 #[tokio::test]
1223 async fn parse_helpers() {
1224 assert!(matches!(parse_text("{\"a\":1}"), Value::Dict(_)));
1226 assert_eq!(parse_text("pong"), Value::Str("pong".into()));
1227 use std::io::Write;
1229 let mut e = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
1230 e.write_all(b"{\"x\":true}").unwrap();
1231 let gz = e.finish().unwrap();
1232 assert!(matches!(parse_binary(&gz), Value::Dict(_)));
1233 }
1234
1235 #[test]
1236 fn raw_binary_frames_stay_bytes() {
1237 let frame: Vec<u8> = vec![0x10, 0x00, 0x28, 0x00, 0x01, 0x00, 0x02, 0x00, 0x41, 0x42, 0x43, 0x01];
1240 assert!(std::str::from_utf8(&frame).is_ok());
1241 assert_eq!(parse_raw_binary(&frame), crate::exchange_stubs::bytes_to_value(&frame));
1242 assert!(matches!(parse_raw_binary(b"{\"x\":true}"), Value::Dict(_)));
1244 }
1245}