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()),
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
139impl ClientState {
140 fn push_incoming(&self, v: Value) {
141 self.incoming.lock().unwrap().push_back(v);
142 self.notify.notify_waiters();
143 }
144
145 pub async fn next_message(&self) -> Option<Value> {
149 let mock = *self.mock.lock().unwrap();
150 loop {
151 let notified = self.notify.notified();
152 if let Some(v) = self.incoming.lock().unwrap().pop_front() {
153 return Some(v);
154 }
155 if *self.closed.lock().unwrap() {
156 return None;
157 }
158 if mock {
159 if tokio::time::timeout(std::time::Duration::from_millis(1500), notified).await.is_err() {
164 return None;
165 }
166 } else {
167 notified.await;
168 }
169 }
170 }
171
172 pub fn resolve(&self, hash: &str, value: Value) {
179 self.flight_settle(hash, Ok(value.clone()));
180 self.resolved.lock().unwrap().insert(hash.to_string(), value);
181 self.notify.notify_waiters();
182 }
183
184 pub fn reject(&self, hash: &str, err: Value) {
187 self.flight_settle(hash, Err(err.clone()));
188 self.rejections.lock().unwrap().insert(hash.to_string(), err);
189 self.notify.notify_waiters();
190 }
191
192 pub fn take_settled(&self, hashes: &[String]) -> Option<Result<Value, Value>> {
195 {
196 let mut rj = self.rejections.lock().unwrap();
197 for h in hashes {
198 if let Some(e) = rj.remove(h) {
199 return Some(Err(e));
200 }
201 }
202 }
203 let mut r = self.resolved.lock().unwrap();
204 for h in hashes {
205 if let Some(v) = r.remove(h) {
206 return Some(Ok(v));
207 }
208 }
209 None
210 }
211
212 pub fn note_futures(&self, hashes: &[String]) {
215 let mut f = self.futures.lock().unwrap();
216 for h in hashes {
217 f.insert(h.clone());
218 }
219 }
220
221 pub fn flight_begin(&self, hash: &str) -> bool {
230 let mut fl = self.flights.lock().unwrap();
231 match fl.get_mut(hash) {
232 Some(slot) if slot.open => false,
234 Some(slot) => {
237 slot.open = true;
238 self.futures.lock().unwrap().insert(hash.to_string());
239 true
240 }
241 None => {
242 fl.insert(hash.to_string(), FlightSlot { open: true, settled: None });
243 self.futures.lock().unwrap().insert(hash.to_string());
244 true
245 }
246 }
247 }
248
249 pub fn flight_peek(&self, hash: &str) -> Option<Result<Value, Value>> {
252 self.flights.lock().unwrap().get(hash).and_then(|s| s.settled.clone())
253 }
254
255 pub fn flight_is_open(&self, hash: &str) -> bool {
257 self.flights.lock().unwrap().get(hash).map(|s| s.open).unwrap_or(false)
258 }
259
260 pub fn flight_settle(&self, hash: &str, res: Result<Value, Value>) -> bool {
264 {
265 let mut fl = self.flights.lock().unwrap();
266 match fl.get_mut(hash) {
267 Some(slot) if slot.open => {
268 slot.open = false;
269 slot.settled = Some(res);
270 }
271 _ => return false,
272 }
273 }
274 self.futures.lock().unwrap().remove(hash);
277 self.notify.notify_waiters();
278 true
279 }
280
281 pub fn subscribe_once(&self, subscribe_hash: &str, subscription: Value) -> bool {
285 let mut subs = self.subscriptions.lock().unwrap();
286 if subs.contains_key(subscribe_hash) {
287 return false;
288 }
289 let stored = if matches!(subscription, Value::Null) {
290 Value::Bool(true)
291 } else {
292 subscription
293 };
294 subs.insert(subscribe_hash.to_string(), stored);
295 true
296 }
297
298 pub fn set_subscription(&self, subscribe_hash: &str, subscription: Value) {
301 self.subscriptions.lock().unwrap().insert(subscribe_hash.to_string(), subscription);
302 }
303
304 pub fn is_subscribed(&self, subscribe_hash: &str) -> bool {
305 self.subscriptions.lock().unwrap().contains_key(subscribe_hash)
306 }
307
308 pub fn send_text(&self, s: String) -> bool {
309 if std::env::var("CCXT_WS_DEBUG").is_ok() { eprintln!("[wssend] {}", s.chars().take(200).collect::<String>()); }
310 if *self.mock.lock().unwrap() {
313 self.mock_sent.lock().unwrap().push(parse_text(&s));
314 return true;
315 }
316 self.outgoing.send(Message::Text(s)).is_ok()
317 }
318
319 pub fn mock_enable(&self) {
322 *self.mock.lock().unwrap() = true;
323 *self.connected.lock().unwrap() = true;
324 }
325 pub fn mock_inject(&self, msg: Value) {
327 self.incoming.lock().unwrap().push_back(msg);
328 self.notify.notify_one();
329 }
330 pub fn is_mock(&self) -> bool { *self.mock.lock().unwrap() }
331 pub fn mock_sent_value(&self) -> Value {
333 Value::Array(self.mock_sent.lock().unwrap().clone())
334 }
335 pub fn has_pending_futures(&self) -> bool {
336 !self.futures.lock().unwrap().is_empty()
337 }
338 pub fn has_queued_messages(&self) -> bool {
340 !self.incoming.lock().unwrap().is_empty()
341 }
342 pub fn mark_ws_test_completed(&self) { *self.ws_test_completed.lock().unwrap() = true; }
343 pub fn is_ws_test_completed(&self) -> bool { *self.ws_test_completed.lock().unwrap() }
344 pub fn reject_pending_futures(&self, err: Value) {
347 let hashes: Vec<String> = self.futures.lock().unwrap().iter().cloned().collect();
348 for h in hashes { self.reject(&h, err.clone()); }
349 }
350
351 pub fn is_closed(&self) -> bool {
352 *self.closed.lock().unwrap()
353 }
354
355 pub fn on_pong(&self) {
356 *self.last_pong_ms.lock().unwrap() = now_ms();
357 }
358
359 pub fn reset(&self) {
362 self.resolved.lock().unwrap().clear();
363 self.rejections.lock().unwrap().clear();
364 self.subscriptions.lock().unwrap().clear();
365 self.futures.lock().unwrap().clear();
366 self.flights.lock().unwrap().clear();
367 }
368
369 pub fn subscriptions_value(&self) -> Value {
375 let subs = self.subscriptions.lock().unwrap();
376 let mut m = indexmap::IndexMap::new();
377 m.insert("__ws_subs_url".to_string(), Value::Str(self.url.clone()));
378 for (h, sub) in subs.iter() {
379 let tagged = match sub {
384 Value::Dict(d) => {
385 let mut inner = (**d).clone();
386 inner.insert("__ws_sub_ref".to_string(),
387 Value::Str(format!("{}\u{1}{}", self.url, h)));
388 Value::Dict(std::sync::Arc::new(inner))
389 }
390 other => other.clone(),
391 };
392 m.insert(h.clone(), tagged);
393 }
394 Value::Map(m)
395 }
396
397 pub fn set_subscription_field(&self, hash: &str, key: &str, val: Value) {
400 let mut subs = self.subscriptions.lock().unwrap();
401 match subs.get_mut(hash) {
402 Some(Value::Dict(d)) => { std::sync::Arc::make_mut(d).insert(key.to_string(), val); }
403 _ => {
404 let mut inner = indexmap::IndexMap::new();
405 inner.insert(key.to_string(), val);
406 subs.insert(hash.to_string(), Value::Dict(std::sync::Arc::new(inner)));
407 }
408 }
409 }
410
411 pub fn futures_value(&self) -> Value {
413 let f = self.futures.lock().unwrap();
414 let mut m = indexmap::IndexMap::new();
415 for h in f.iter() {
416 let mut fh = indexmap::IndexMap::new();
420 fh.insert("url".to_string(), Value::Str(self.url.clone()));
421 fh.insert("__ws_future_hash".to_string(), Value::Str(h.clone()));
422 m.insert(h.clone(), Value::Map(fh));
423 }
424 Value::Map(m)
425 }
426}
427
428pub fn get_client(url: &str) -> Option<Arc<ClientState>> {
430 let reg = REGISTRY.lock().unwrap();
431 reg.get(url).filter(|c| !c.is_closed()).cloned()
432}
433
434pub fn value_subs_insert(url: &str, key: &str, val: Value) {
437 if let Some(c) = get_client(url) { c.set_subscription(key, val); }
438}
439
440pub fn value_subs_remove(url: &str, key: &str) {
442 if let Some(c) = get_client(url) { c.subscriptions.lock().unwrap().remove(key); }
443}
444
445pub fn value_sub_field_write(subref: &str, key: &str, val: Value) {
448 if let Some((url, hash)) = subref.split_once('\u{1}') {
449 if let Some(c) = get_client(url) { c.set_subscription_field(hash, key, val); }
450 }
451}
452
453async fn connect_via_proxy(
459 url: &str,
460 proxy: &str,
461) -> Result<tokio_tungstenite::WebSocketStream<
462 tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>, String> {
463 use tokio::io::{AsyncReadExt, AsyncWriteExt};
464 let target = url::Url::parse(url).map_err(|e| format!("[NetworkError] ws url {url}: {e}"))?;
465 let host = target.host_str().ok_or_else(|| format!("[NetworkError] ws url {url} has no host"))?;
466 let port = target.port_or_known_default().unwrap_or(443);
467 let p = url::Url::parse(proxy).map_err(|e| format!("[NetworkError] ws proxy {proxy}: {e}"))?;
468 let p_host = p.host_str().ok_or_else(|| format!("[NetworkError] ws proxy {proxy} has no host"))?;
469 let p_port = p.port_or_known_default().unwrap_or(8080);
470 let mut stream = tokio::net::TcpStream::connect((p_host, p_port))
471 .await
472 .map_err(|e| format!("[NetworkError] ws proxy connect {proxy}: {e}"))?;
473 let connect = format!(
474 "CONNECT {host}:{port} HTTP/1.1\r\nHost: {host}:{port}\r\nProxy-Connection: Keep-Alive\r\n\r\n"
475 );
476 stream
477 .write_all(connect.as_bytes())
478 .await
479 .map_err(|e| format!("[NetworkError] ws proxy CONNECT {proxy}: {e}"))?;
480 let mut head = Vec::new();
481 let mut byte = [0u8; 1];
482 while !head.ends_with(b"\r\n\r\n") {
483 let n = stream
484 .read(&mut byte)
485 .await
486 .map_err(|e| format!("[NetworkError] ws proxy CONNECT {proxy}: {e}"))?;
487 if n == 0 {
488 return Err(format!("[NetworkError] ws proxy {proxy} closed during CONNECT"));
489 }
490 head.push(byte[0]);
491 if head.len() > 8192 {
492 return Err(format!("[NetworkError] ws proxy {proxy} sent an oversized CONNECT reply"));
493 }
494 }
495 let status = String::from_utf8_lossy(&head);
496 let first = status.lines().next().unwrap_or_default();
497 if !first.contains(" 200") {
498 return Err(format!("[NetworkError] ws proxy {proxy} refused CONNECT: {first}"));
499 }
500 let (ws, _resp) = tokio_tungstenite::client_async_tls(url, stream)
501 .await
502 .map_err(|e| format!("[NetworkError] ws connect {url} via {proxy}: {e}"))?;
503 Ok(ws)
504}
505
506pub async fn ensure_client(url: &str, proxy: Option<String>) -> Result<Arc<ClientState>, String> {
507 let state = ensure_slot(url);
508 if *state.connected.lock().unwrap() {
509 return Ok(state);
510 }
511 let gate_holder = state.clone();
514 let _gate = gate_holder.connect_gate.lock().await;
515 if *state.connected.lock().unwrap() {
516 return Ok(state);
517 }
518 let ws = match proxy.as_deref().filter(|p| !p.is_empty()) {
519 Some(p) => connect_via_proxy(url, p).await?,
520 None => {
521 let (ws, _resp) = tokio_tungstenite::connect_async(url)
522 .await
523 .map_err(|e| format!("[NetworkError] ws connect {url}: {e}"))?;
524 ws
525 }
526 };
527 let (mut write, mut read) = ws.split();
528 let mut rx = state.pending_rx.lock().unwrap().take()
529 .ok_or_else(|| format!("[NetworkError] ws {url} slot has no writer channel"))?;
530 *state.last_pong_ms.lock().unwrap() = now_ms();
531
532 tokio::spawn(async move {
534 while let Some(msg) = rx.recv().await {
535 if write.send(msg).await.is_err() {
536 break;
537 }
538 }
539 let _ = write.close().await;
540 });
541
542 let st = state.clone();
544 tokio::spawn(async move {
545 while let Some(frame) = read.next().await {
546 match frame {
547 Ok(Message::Text(t)) => st.push_incoming(parse_text(&t)),
548 Ok(Message::Binary(b)) => st.push_incoming(parse_binary(&b)),
549 Ok(Message::Pong(_)) => st.on_pong(),
550 Ok(Message::Ping(_)) => {}
552 Ok(Message::Close(_)) | Err(_) => break,
553 _ => {}
554 }
555 }
556 *st.connected.lock().unwrap() = false;
557 *st.closed.lock().unwrap() = true;
558 st.notify.notify_waiters();
559 });
560
561 let st2 = state.clone();
564 tokio::spawn(async move {
565 let mut iv = tokio::time::interval(std::time::Duration::from_secs(30));
566 iv.tick().await; loop {
568 iv.tick().await;
569 if st2.is_closed() {
570 break;
571 }
572 if st2.outgoing.send(Message::Ping(Vec::new())).is_err() {
573 break;
574 }
575 }
576 });
577
578 *state.connected.lock().unwrap() = true;
579 Ok(state)
580}
581
582pub fn client_field_live(url: &str, field: &str) -> Value {
586 match get_client(url) {
587 Some(c) if field == "futures" => c.futures_value(),
588 Some(c) => c.subscriptions_value(),
589 None => Value::Map(indexmap::IndexMap::new()),
590 }
591}
592
593fn ensure_slot(url: &str) -> Arc<ClientState> {
596 let mut reg = REGISTRY.lock().unwrap();
597 if let Some(c) = reg.get(url) {
598 if !c.is_closed() {
599 return c.clone();
600 }
601 }
602 let (tx, rx) = mpsc::unbounded_channel::<Message>();
603 let state = Arc::new(ClientState {
604 url: url.to_string(),
605 outgoing: tx,
606 pending_rx: Mutex::new(Some(rx)),
607 connect_gate: tokio::sync::Mutex::new(()),
608 incoming: Mutex::new(VecDeque::new()),
609 notify: Notify::new(),
610 resolved: Mutex::new(HashMap::new()),
611 rejections: Mutex::new(HashMap::new()),
612 subscriptions: Mutex::new(HashMap::new()),
613 futures: Mutex::new(HashSet::new()),
614 flights: Mutex::new(HashMap::new()),
615 connected: Mutex::new(false),
616 closed: Mutex::new(false),
617 last_pong_ms: Mutex::new(now_ms()),
618 mock: Mutex::new(false),
619 mock_sent: Mutex::new(Vec::new()),
620 ws_test_completed: Mutex::new(false),
621 });
622 reg.insert(url.to_string(), state.clone());
623 state
624}
625
626pub fn drop_client(url: &str) {
628 REGISTRY.lock().unwrap().remove(url);
629}
630
631pub fn mock_setup(url: &str) {
643 let c = ensure_slot(url);
644 c.reset();
645 c.mock_enable();
646 c.mock_sent.lock().unwrap().clear();
647 c.incoming.lock().unwrap().clear();
651 *c.ws_test_completed.lock().unwrap() = false;
652}
653pub fn mock_inject(url: &str, msg: Value) {
654 if let Some(c) = get_client(url) { c.mock_inject(msg); }
655}
656pub fn mock_sent_messages(url: &str) -> Value {
657 match get_client(url) { Some(c) => c.mock_sent_value(), None => Value::Array(vec![]) }
658}
659pub fn mock_has_pending_futures(url: &str) -> bool {
660 get_client(url).map(|c| c.has_pending_futures()).unwrap_or(false)
661}
662pub fn mock_has_queued_messages(url: &str) -> bool {
663 get_client(url).map(|c| c.has_queued_messages()).unwrap_or(false)
664}
665pub fn mock_mark_completed(url: &str) {
666 if let Some(c) = get_client(url) { c.mark_ws_test_completed(); }
667}
668pub fn mock_is_completed(url: &str) -> bool {
669 get_client(url).map(|c| c.is_ws_test_completed()).unwrap_or(true)
670}
671pub fn mock_reject_futures(url: &str) {
672 if let Some(c) = get_client(url) {
673 c.reject_pending_futures(Value::Str(
674 "[ExchangeError] static ws test: the injected messages did not resolve the watch future".to_string()));
675 }
676}
677
678pub fn client_value(url: &str) -> Value {
682 let c = ensure_slot(url);
685 let mut m = indexmap::IndexMap::new();
686 m.insert("url".to_string(), Value::Str(url.to_string()));
687 m.insert("subscriptions".to_string(), c.subscriptions_value());
688 m.insert("futures".to_string(), c.futures_value());
689 Value::Map(m)
690}
691
692pub fn begin_flight(url: &str, hash: &str) -> bool {
697 ensure_slot(url).flight_begin(hash)
698}
699
700
701pub fn flight_handle(url: &str, hash: &str, led: bool) -> Value {
706 let mut m = indexmap::IndexMap::new();
707 m.insert("url".to_string(), Value::Str(url.to_string()));
708 m.insert("__ws_flight_hash".to_string(), Value::Str(hash.to_string()));
709 m.insert("__ws_flight_led".to_string(), Value::Bool(led));
715 Value::Map(m)
716}
717
718fn flight_hash_of(handle: &Value) -> Option<String> {
721 for key in ["__ws_flight_hash", "__ws_future_hash"] {
722 if let Value::Str(h) = crate::get_value(handle, &Value::Str(key.to_string())) {
723 return Some(h);
724 }
725 }
726 None
727}
728
729pub async fn ws_await_flight(handle: &Value) -> Value {
736 let (url, hash) = match (url_of(handle), flight_hash_of(handle)) {
737 (Some(u), Some(h)) => (u, h),
738 _ => return Value::Null,
739 };
740 let client = match get_client(&url) {
741 Some(c) => c,
742 None => return Value::Null,
743 };
744 let settled = client.flight_peek(&hash);
745 let led = matches!(
750 crate::get_value(handle, &Value::Str("__ws_flight_led".to_string())),
751 Value::Bool(true)
752 );
753 if led || !client.flight_is_open(&hash) {
754 return match settled {
755 Some(Ok(v)) => v,
756 Some(Err(e)) => panic!(
757 "{}",
758 match &e {
759 Value::Str(s) => s.clone(),
760 v => crate::runtime::stringify_param(v),
761 }
762 ),
763 None => Value::Null,
767 };
768 }
769 let budget = if client.is_mock() {
770 std::time::Duration::from_millis(1500)
771 } else {
772 std::time::Duration::from_secs(60)
773 };
774 let deadline = tokio::time::Instant::now() + budget;
775 loop {
776 let notified = client.notify.notified();
779 if let Some(res) = client.flight_peek(&hash) {
780 return match res {
781 Ok(v) => v,
782 Err(e) => panic!(
783 "{}",
784 match &e {
785 Value::Str(s) => s.clone(),
786 v => crate::runtime::stringify_param(v),
787 }
788 ),
789 };
790 }
791 if !client.flight_is_open(&hash) {
792 return Value::Null;
794 }
795 if tokio::time::timeout_at(deadline, notified).await.is_err() {
796 panic!(
797 "[NetworkError] timed out waiting for the in-flight '{}' on {}",
798 hash, url
799 );
800 }
801 }
802}
803
804pub fn url_of(client: &Value) -> Option<String> {
806 match crate::get_value(client, &Value::Str("url".to_string())) {
807 Value::Str(s) => Some(s),
808 _ => None,
809 }
810}
811
812fn hash_str(v: &Value) -> Option<String> {
813 match v {
814 Value::Str(s) => Some(s.clone()),
815 _ => None,
816 }
817}
818
819pub fn value_resolve(client: &Value, args: &[Value]) -> Value {
821 let value = args.get(0).cloned().unwrap_or(Value::Null);
822 if let Some(hash) = future_hash_of(client) {
825 if let Some(url) = url_of(client) {
826 if let Some(c) = get_client(&url) { c.resolve(&hash, value.clone()); }
827 }
828 return value;
829 }
830 if let (Some(url), Some(hash)) = (url_of(client), args.get(1).and_then(hash_str)) {
831 if let Some(c) = get_client(&url) {
832 c.resolve(&hash, value.clone());
833 }
834 }
835 value
836}
837
838fn future_hash_of(client: &Value) -> Option<String> {
840 match crate::get_value(client, &Value::Str("__ws_future_hash".to_string())) {
841 Value::Str(s) => Some(s),
842 _ => None,
843 }
844}
845
846pub fn value_reject(client: &Value, args: &[Value]) -> Value {
848 let err = args.get(0).cloned().unwrap_or(Value::Null);
849 if let Some(hash) = future_hash_of(client) {
851 if let Some(url) = url_of(client) {
852 if let Some(c) = get_client(&url) { c.reject(&hash, err.clone()); }
853 }
854 return err;
855 }
856 if let Some(url) = url_of(client) {
857 if let Some(c) = get_client(&url) {
858 match args.get(1).and_then(hash_str) {
859 Some(hash) => c.reject(&hash, err.clone()),
860 None => {
862 let hashes: Vec<String> = c.futures.lock().unwrap().iter().cloned().collect();
863 for h in hashes {
864 c.reject(&h, err.clone());
865 }
866 }
867 }
868 }
869 }
870 err
871}
872
873pub fn value_send(client: &Value, args: &[Value]) -> Value {
875 if let Some(url) = url_of(client) {
876 if let Some(c) = get_client(&url) {
877 let payload = match args.get(0) {
878 Some(Value::Str(s)) => s.clone(),
879 Some(v) => v.to_json().to_string(),
880 None => String::new(),
881 };
882 c.send_text(payload);
883 }
884 }
885 Value::Null
886}
887
888pub fn value_reset(client: &Value) -> Value {
890 if let Some(url) = url_of(client) {
891 if let Some(c) = get_client(&url) {
892 c.reset();
893 }
894 }
895 Value::Null
896}
897
898pub fn value_on_pong(client: &Value) -> Value {
900 if let Some(url) = url_of(client) {
901 if let Some(c) = get_client(&url) {
902 c.on_pong();
903 }
904 }
905 Value::Null
906}
907
908#[cfg(test)]
909mod tests {
910 use super::*;
911 use tokio_tungstenite::tungstenite::Message as WsMessage;
912
913 async fn spawn_mock_server() -> String {
918 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
919 let addr = listener.local_addr().unwrap();
920 tokio::spawn(async move {
921 if let Ok((stream, _)) = listener.accept().await {
922 let mut ws = tokio_tungstenite::accept_async(stream).await.unwrap();
923 if let Some(Ok(WsMessage::Text(sub))) = ws.next().await {
925 assert!(sub.contains("subscribe"), "expected subscribe, got {sub}");
926 }
927 for px in ["100.5", "101.0", "101.5"] {
929 let msg = format!("{{\"channel\":\"ticker\",\"symbol\":\"BTC/USDT\",\"last\":\"{px}\"}}");
930 ws.send(WsMessage::Text(msg)).await.unwrap();
931 }
932 tokio::time::sleep(std::time::Duration::from_millis(50)).await;
934 let _ = ws.close(None).await;
935 }
936 });
937 format!("ws://{addr}")
938 }
939
940 #[tokio::test]
941 async fn transport_roundtrip() {
942 let url = spawn_mock_server().await;
943 let client = ensure_client(&url, None).await.expect("connect");
944
945 assert!(client.subscribe_once("ticker:BTC/USDT", Value::Null));
947 assert!(!client.subscribe_once("ticker:BTC/USDT", Value::Null));
948 assert!(client.send_text("{\"op\":\"subscribe\",\"channel\":\"ticker\"}".to_string()));
949
950 let mut lasts = Vec::new();
953 while lasts.len() < 3 {
954 let msg = client.next_message().await.expect("message before close");
955 let last = crate::get_value(&msg, &Value::Str("last".to_string()));
956 if let Value::Str(s) = &last {
957 client.resolve("ticker", Value::Str(s.clone()));
958 }
959 if let Some(Ok(Value::Str(v))) = client.take_settled(&["ticker".to_string()]) {
960 lasts.push(v);
961 }
962 }
963 assert_eq!(lasts, vec!["100.5", "101.0", "101.5"]);
964
965 let subs = client.subscriptions_value();
967 assert!(crate::runtime::is_true(&crate::get_value(
968 &subs,
969 &Value::Str("ticker:BTC/USDT".to_string())
970 )));
971
972 drop_client(&url);
973 }
974
975 struct TestWsCore {
981 exchange: crate::exchange::Exchange,
982 }
983 impl std::ops::Deref for TestWsCore {
984 type Target = crate::exchange::Exchange;
985 fn deref(&self) -> &Self::Target {
986 &self.exchange
987 }
988 }
989 impl std::ops::DerefMut for TestWsCore {
990 fn deref_mut(&mut self) -> &mut Self::Target {
991 &mut self.exchange
992 }
993 }
994 impl crate::exchange::DerivedExchange for TestWsCore {}
995 impl crate::exchange_generated::ExchangeBase for TestWsCore {
996 fn call_dynamic<'a>(
997 &'a mut self,
998 method: &'a str,
999 args: Vec<Value>,
1000 ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Value> + Send + 'a>> {
1001 Box::pin(async move {
1002 match method {
1003 "handle_message" => {
1004 let client = args.get(0).cloned().unwrap_or(Value::Null);
1005 let message = args.get(1).cloned().unwrap_or(Value::Null);
1006 let last = crate::get_value(&message, &Value::Str("last".to_string()));
1007 client.resolve(&[last, Value::Str("ticker".to_string())]);
1009 Value::Null
1010 }
1011 _ => self.call_dynamic_base(method, args).await,
1012 }
1013 })
1014 }
1015 }
1016
1017 #[tokio::test]
1018 async fn watch_drive_loop_end_to_end() {
1019 use crate::exchange::ExchangeRuntime;
1020 let url = spawn_mock_server().await;
1021 let mut core = TestWsCore {
1022 exchange: crate::exchange::Exchange::new(None),
1023 };
1024 let result = ExchangeRuntime::watch(
1027 &mut core,
1028 Value::Str(url.clone()),
1029 Value::Str("ticker".to_string()),
1030 &[
1031 Value::Str("{\"op\":\"subscribe\",\"channel\":\"ticker\"}".to_string()),
1032 Value::Str("ticker".to_string()),
1033 Value::Null,
1034 ],
1035 )
1036 .await;
1037 assert_eq!(result, Value::Str("100.5".to_string()));
1039 drop_client(&url);
1040 }
1041
1042 #[tokio::test]
1050 async fn flight_elects_one_leader_and_registers_it() {
1051 let url = "flight-test-election";
1052 let c = ensure_slot(url);
1053 assert!(c.flight_begin("authenticate:future"), "first caller leads");
1054 assert!(!c.flight_begin("authenticate:future"), "second caller follows");
1055 assert!(in_op_futures(&c, "authenticate:future"));
1057 drop_client(url);
1058 }
1059
1060 #[tokio::test]
1061 async fn flight_settle_wakes_waiters_and_reopens() {
1062 let url = "flight-test-settle";
1063 let c = ensure_slot(url);
1064 assert!(c.flight_begin("auth"));
1065 c.resolve("auth", Value::Str("listen-key".to_string()));
1067 assert_eq!(
1068 ws_await_flight(&flight_handle(url, "auth", false)).await,
1069 Value::Str("listen-key".to_string())
1070 );
1071 assert_eq!(
1072 ws_await_flight(&flight_handle(url, "auth", false)).await,
1073 Value::Str("listen-key".to_string())
1074 );
1075 assert!(!in_op_futures(&c, "auth"));
1078 assert!(c.flight_begin("auth"), "a settled flight re-elects");
1079 drop_client(url);
1080 }
1081
1082 #[tokio::test]
1083 async fn flight_follower_waits_for_the_leader() {
1084 let url = "flight-test-wait";
1085 let c = ensure_slot(url);
1086 assert!(c.flight_begin("auth"));
1087 let settler = {
1088 let c = c.clone();
1089 tokio::spawn(async move {
1090 tokio::time::sleep(std::time::Duration::from_millis(60)).await;
1091 c.resolve("auth", Value::Str("late".to_string()));
1092 })
1093 };
1094 let started = std::time::Instant::now();
1095 let got = ws_await_flight(&flight_handle(url, "auth", false)).await;
1096 assert_eq!(got, Value::Str("late".to_string()));
1097 assert!(started.elapsed() >= std::time::Duration::from_millis(50), "waited for the leader");
1098 settler.await.unwrap();
1099 drop_client(url);
1100 }
1101
1102 #[tokio::test]
1103 async fn a_leader_never_blocks_on_its_own_flight() {
1104 let url = "flight-test-leader";
1108 let c = ensure_slot(url);
1109 let led = c.flight_begin("authenticated");
1110 assert!(led);
1111 let started = std::time::Instant::now();
1112 assert_eq!(
1113 ws_await_flight(&flight_handle(url, "authenticated", led)).await,
1114 Value::Null
1115 );
1116 assert!(started.elapsed() < std::time::Duration::from_millis(200), "returned at once");
1117 c.resolve("authenticated", Value::Bool(true));
1119 let led2 = c.flight_begin("authenticated");
1120 assert_eq!(
1121 ws_await_flight(&flight_handle(url, "authenticated", led2)).await,
1122 Value::Bool(true),
1123 "a re-lead with no new work reports the last value"
1124 );
1125 drop_client(url);
1126 }
1127
1128 #[tokio::test]
1129 async fn flight_handle_without_a_flight_returns_null() {
1130 let url = "flight-test-missing";
1133 ensure_slot(url);
1134 assert_eq!(ws_await_flight(&flight_handle(url, "nope", false)).await, Value::Null);
1135 drop_client(url);
1136 }
1137
1138 fn in_op_futures(c: &Arc<ClientState>, hash: &str) -> bool {
1140 !matches!(
1141 crate::get_value(&c.futures_value(), &Value::Str(hash.to_string())),
1142 Value::Null
1143 )
1144 }
1145
1146 #[tokio::test]
1147 async fn parse_helpers() {
1148 assert!(matches!(parse_text("{\"a\":1}"), Value::Dict(_)));
1150 assert_eq!(parse_text("pong"), Value::Str("pong".to_string()));
1151 use std::io::Write;
1153 let mut e = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
1154 e.write_all(b"{\"x\":true}").unwrap();
1155 let gz = e.finish().unwrap();
1156 assert!(matches!(parse_binary(&gz), Value::Dict(_)));
1157 }
1158}