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
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) {
364 self.resolved.lock().unwrap().clear();
365 self.rejections.lock().unwrap().clear();
366 self.subscriptions.lock().unwrap().clear();
367 self.futures.lock().unwrap().clear();
368 self.flights.lock().unwrap().clear();
369 }
370
371 pub fn reset_with_error(&self, error: Value) {
380 let hashes: Vec<String> = self.futures.lock().unwrap().iter().cloned().collect();
381 for h in &hashes {
382 if self.resolved.lock().unwrap().contains_key(h) {
383 continue;
384 }
385 self.reject(h, error.clone());
386 }
387 self.futures.lock().unwrap().clear();
388 }
389
390 pub fn subscriptions_value(&self) -> Value {
396 let subs = self.subscriptions.lock().unwrap();
397 let mut m = indexmap::IndexMap::new();
398 m.insert("__ws_subs_url".to_string(), Value::Str(self.url.clone().into()));
399 for (h, sub) in subs.iter() {
400 let tagged = match sub {
405 Value::Dict(d) => {
406 let mut inner = (**d).clone();
407 inner.insert("__ws_sub_ref".to_string(),
408 Value::Str(format!("{}\u{1}{}", self.url, h).into()));
409 Value::Dict(std::sync::Arc::new(inner))
410 }
411 other => other.clone(),
412 };
413 m.insert(h.clone(), tagged);
414 }
415 Value::Map(m)
416 }
417
418 pub fn set_subscription_field(&self, hash: &str, key: &str, val: Value) {
421 let mut subs = self.subscriptions.lock().unwrap();
422 match subs.get_mut(hash) {
423 Some(Value::Dict(d)) => { std::sync::Arc::make_mut(d).insert(key.to_string(), val); }
424 _ => {
425 let mut inner = indexmap::IndexMap::new();
426 inner.insert(key.to_string(), val);
427 subs.insert(hash.to_string(), Value::Dict(std::sync::Arc::new(inner)));
428 }
429 }
430 }
431
432 pub fn futures_value(&self) -> Value {
434 let f = self.futures.lock().unwrap();
435 let mut m = indexmap::IndexMap::new();
436 for h in f.iter() {
437 let mut fh = indexmap::IndexMap::new();
441 fh.insert("url".to_string(), Value::Str(self.url.clone().into()));
442 fh.insert("__ws_future_hash".to_string(), Value::Str(h.clone().into()));
443 m.insert(h.clone(), Value::Map(fh));
444 }
445 Value::Map(m)
446 }
447}
448
449pub fn get_client(url: &str) -> Option<Arc<ClientState>> {
451 let reg = REGISTRY.lock().unwrap();
452 reg.get(url).filter(|c| !c.is_closed()).cloned()
453}
454
455pub fn value_subs_insert(url: &str, key: &str, val: Value) {
458 if let Some(c) = get_client(url) { c.set_subscription(key, val); }
459}
460
461pub fn value_subs_remove(url: &str, key: &str) {
463 if let Some(c) = get_client(url) { c.subscriptions.lock().unwrap().remove(key); }
464}
465
466pub fn value_sub_field_write(subref: &str, key: &str, val: Value) {
469 if let Some((url, hash)) = subref.split_once('\u{1}') {
470 if let Some(c) = get_client(url) { c.set_subscription_field(hash, key, val); }
471 }
472}
473
474async fn connect_via_proxy(
480 url: &str,
481 proxy: &str,
482) -> Result<tokio_tungstenite::WebSocketStream<
483 tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>, String> {
484 use tokio::io::{AsyncReadExt, AsyncWriteExt};
485 let target = url::Url::parse(url).map_err(|e| format!("[NetworkError] ws url {url}: {e}"))?;
486 let host = target.host_str().ok_or_else(|| format!("[NetworkError] ws url {url} has no host"))?;
487 let port = target.port_or_known_default().unwrap_or(443);
488 let p = url::Url::parse(proxy).map_err(|e| format!("[NetworkError] ws proxy {proxy}: {e}"))?;
489 let p_host = p.host_str().ok_or_else(|| format!("[NetworkError] ws proxy {proxy} has no host"))?;
490 let p_port = p.port_or_known_default().unwrap_or(8080);
491 let mut stream = tokio::net::TcpStream::connect((p_host, p_port))
492 .await
493 .map_err(|e| format!("[NetworkError] ws proxy connect {proxy}: {e}"))?;
494 let connect = format!(
495 "CONNECT {host}:{port} HTTP/1.1\r\nHost: {host}:{port}\r\nProxy-Connection: Keep-Alive\r\n\r\n"
496 );
497 stream
498 .write_all(connect.as_bytes())
499 .await
500 .map_err(|e| format!("[NetworkError] ws proxy CONNECT {proxy}: {e}"))?;
501 let mut head = Vec::new();
502 let mut byte = [0u8; 1];
503 while !head.ends_with(b"\r\n\r\n") {
504 let n = stream
505 .read(&mut byte)
506 .await
507 .map_err(|e| format!("[NetworkError] ws proxy CONNECT {proxy}: {e}"))?;
508 if n == 0 {
509 return Err(format!("[NetworkError] ws proxy {proxy} closed during CONNECT"));
510 }
511 head.push(byte[0]);
512 if head.len() > 8192 {
513 return Err(format!("[NetworkError] ws proxy {proxy} sent an oversized CONNECT reply"));
514 }
515 }
516 let status = String::from_utf8_lossy(&head);
517 let first = status.lines().next().unwrap_or_default();
518 if !first.contains(" 200") {
519 return Err(format!("[NetworkError] ws proxy {proxy} refused CONNECT: {first}"));
520 }
521 let (ws, _resp) = tokio_tungstenite::client_async_tls(url, stream)
522 .await
523 .map_err(|e| format!("[NetworkError] ws connect {url} via {proxy}: {e}"))?;
524 Ok(ws)
525}
526
527pub async fn ensure_client(url: &str, proxy: Option<String>) -> Result<Arc<ClientState>, String> {
528 let state = ensure_slot(url);
529 if *state.connected.lock().unwrap() {
530 return Ok(state);
531 }
532 let gate_holder = state.clone();
535 let _gate = gate_holder.connect_gate.lock().await;
536 if *state.connected.lock().unwrap() {
537 return Ok(state);
538 }
539 let ws = match proxy.as_deref().filter(|p| !p.is_empty()) {
540 Some(p) => connect_via_proxy(url, p).await?,
541 None => {
542 let (ws, _resp) = tokio_tungstenite::connect_async(url)
543 .await
544 .map_err(|e| format!("[NetworkError] ws connect {url}: {e}"))?;
545 ws
546 }
547 };
548 let (mut write, mut read) = ws.split();
549 let mut rx = state.pending_rx.lock().unwrap().take()
550 .ok_or_else(|| format!("[NetworkError] ws {url} slot has no writer channel"))?;
551 *state.last_pong_ms.lock().unwrap() = now_ms();
552
553 tokio::spawn(async move {
555 while let Some(msg) = rx.recv().await {
556 if write.send(msg).await.is_err() {
557 break;
558 }
559 }
560 let _ = write.close().await;
561 });
562
563 let st = state.clone();
565 tokio::spawn(async move {
566 while let Some(frame) = read.next().await {
567 match frame {
568 Ok(Message::Text(t)) => st.push_incoming(parse_text(&t)),
569 Ok(Message::Binary(b)) => st.push_incoming(parse_binary(&b)),
570 Ok(Message::Pong(_)) => st.on_pong(),
571 Ok(Message::Ping(_)) => {}
573 Ok(Message::Close(_)) | Err(_) => break,
574 _ => {}
575 }
576 }
577 *st.connected.lock().unwrap() = false;
578 *st.closed.lock().unwrap() = true;
579 st.notify.notify_waiters();
580 });
581
582 let st2 = state.clone();
585 tokio::spawn(async move {
586 let mut iv = tokio::time::interval(std::time::Duration::from_secs(30));
587 iv.tick().await; loop {
589 iv.tick().await;
590 if st2.is_closed() {
591 break;
592 }
593 if st2.outgoing.send(Message::Ping(Vec::new())).is_err() {
594 break;
595 }
596 }
597 });
598
599 *state.connected.lock().unwrap() = true;
600 Ok(state)
601}
602
603pub fn client_field_live(url: &str, field: &str) -> Value {
607 match get_client(url) {
608 Some(c) if field == "futures" => c.futures_value(),
609 Some(c) => c.subscriptions_value(),
610 None => Value::Map(indexmap::IndexMap::new()),
611 }
612}
613
614fn ensure_slot(url: &str) -> Arc<ClientState> {
617 let mut reg = REGISTRY.lock().unwrap();
618 if let Some(c) = reg.get(url) {
619 if !c.is_closed() {
620 return c.clone();
621 }
622 }
623 let (tx, rx) = mpsc::unbounded_channel::<Message>();
624 let state = Arc::new(ClientState {
625 url: url.to_string(),
626 outgoing: tx,
627 pending_rx: Mutex::new(Some(rx)),
628 connect_gate: tokio::sync::Mutex::new(()),
629 incoming: Mutex::new(VecDeque::new()),
630 notify: Notify::new(),
631 resolved: Mutex::new(HashMap::new()),
632 rejections: Mutex::new(HashMap::new()),
633 subscriptions: Mutex::new(HashMap::new()),
634 futures: Mutex::new(HashSet::new()),
635 flights: Mutex::new(HashMap::new()),
636 connected: Mutex::new(false),
637 closed: Mutex::new(false),
638 last_pong_ms: Mutex::new(now_ms()),
639 mock: Mutex::new(false),
640 mock_sent: Mutex::new(Vec::new()),
641 ws_test_completed: Mutex::new(false),
642 });
643 reg.insert(url.to_string(), state.clone());
644 state
645}
646
647pub fn drop_client(url: &str) {
649 REGISTRY.lock().unwrap().remove(url);
650}
651
652pub fn mock_setup(url: &str) {
664 let c = ensure_slot(url);
665 c.reset();
666 c.mock_enable();
667 c.mock_sent.lock().unwrap().clear();
668 c.incoming.lock().unwrap().clear();
672 *c.ws_test_completed.lock().unwrap() = false;
673}
674pub fn mock_inject(url: &str, msg: Value) {
675 if let Some(c) = get_client(url) { c.mock_inject(msg); }
676}
677pub fn mock_sent_messages(url: &str) -> Value {
678 match get_client(url) { Some(c) => c.mock_sent_value(), None => Value::Array(vec![]) }
679}
680pub fn mock_has_pending_futures(url: &str) -> bool {
681 get_client(url).map(|c| c.has_pending_futures()).unwrap_or(false)
682}
683pub fn mock_has_queued_messages(url: &str) -> bool {
684 get_client(url).map(|c| c.has_queued_messages()).unwrap_or(false)
685}
686pub fn mock_mark_completed(url: &str) {
687 if let Some(c) = get_client(url) { c.mark_ws_test_completed(); }
688}
689pub fn mock_is_completed(url: &str) -> bool {
690 get_client(url).map(|c| c.is_ws_test_completed()).unwrap_or(true)
691}
692pub fn mock_reject_futures(url: &str) {
693 if let Some(c) = get_client(url) {
694 c.reject_pending_futures(Value::Str(
695 "[ExchangeError] static ws test: the injected messages did not resolve the watch future".to_string().into()));
696 }
697}
698
699pub fn client_value(url: &str) -> Value {
703 let c = ensure_slot(url);
706 let mut m = indexmap::IndexMap::new();
707 m.insert("url".to_string(), Value::Str(url.to_string().into()));
708 m.insert("subscriptions".to_string(), c.subscriptions_value());
709 m.insert("futures".to_string(), c.futures_value());
710 Value::Map(m)
711}
712
713pub fn begin_flight(url: &str, hash: &str) -> bool {
718 ensure_slot(url).flight_begin(hash)
719}
720
721
722pub fn flight_handle(url: &str, hash: &str, led: bool) -> Value {
727 let mut m = indexmap::IndexMap::new();
728 m.insert("url".to_string(), Value::Str(url.to_string().into()));
729 m.insert("__ws_flight_hash".to_string(), Value::Str(hash.to_string().into()));
730 m.insert("__ws_flight_led".to_string(), Value::Bool(led));
736 Value::Map(m)
737}
738
739fn flight_hash_of(handle: &Value) -> Option<String> {
742 for key in ["__ws_flight_hash", "__ws_future_hash"] {
743 if let Value::Str(h) = crate::get_value(handle, &Value::Str(key.to_string().into())) {
744 return Some(h.to_string());
745 }
746 }
747 None
748}
749
750pub async fn ws_await_flight(handle: &Value) -> Value {
757 let (url, hash) = match (url_of(handle), flight_hash_of(handle)) {
758 (Some(u), Some(h)) => (u, h),
759 _ => return Value::Null,
760 };
761 let client = match get_client(&url) {
762 Some(c) => c,
763 None => return Value::Null,
764 };
765 let settled = client.flight_peek(&hash);
766 let led = matches!(
771 crate::get_value(handle, &Value::Str("__ws_flight_led".into())),
772 Value::Bool(true)
773 );
774 if led || !client.flight_is_open(&hash) {
775 return match settled {
776 Some(Ok(v)) => v,
777 Some(Err(e)) => panic!(
778 "{}",
779 match &e {
780 Value::Str(s) => s.clone(),
781 v => crate::runtime::stringify_param(v).into(),
782 }
783 ),
784 None => Value::Null,
788 };
789 }
790 let budget = if client.is_mock() {
791 std::time::Duration::from_millis(1500)
792 } else {
793 std::time::Duration::from_secs(60)
794 };
795 let deadline = tokio::time::Instant::now() + budget;
796 loop {
797 let notified = client.notify.notified();
800 if let Some(res) = client.flight_peek(&hash) {
801 return match res {
802 Ok(v) => v,
803 Err(e) => panic!(
804 "{}",
805 match &e {
806 Value::Str(s) => s.clone(),
807 v => crate::runtime::stringify_param(v).into(),
808 }
809 ),
810 };
811 }
812 if !client.flight_is_open(&hash) {
813 return Value::Null;
815 }
816 if tokio::time::timeout_at(deadline, notified).await.is_err() {
817 panic!(
818 "[NetworkError] timed out waiting for the in-flight '{}' on {}",
819 hash, url
820 );
821 }
822 }
823}
824
825pub fn url_of(client: &Value) -> Option<String> {
827 match crate::get_value(client, &Value::Str("url".into())) {
828 Value::Str(s) => Some(s.to_string()),
829 _ => None,
830 }
831}
832
833fn hash_str(v: &Value) -> Option<String> {
834 match v {
835 Value::Str(s) => Some(s.to_string()),
836 _ => None,
837 }
838}
839
840pub fn value_resolve(client: &Value, args: &[Value]) -> Value {
842 let value = args.get(0).cloned().unwrap_or(Value::Null);
843 if let Some(hash) = future_hash_of(client) {
846 if let Some(url) = url_of(client) {
847 if let Some(c) = get_client(&url) { c.resolve(&hash, value.clone()); }
848 }
849 return value;
850 }
851 if let (Some(url), Some(hash)) = (url_of(client), args.get(1).and_then(hash_str)) {
852 if let Some(c) = get_client(&url) {
853 c.resolve(&hash, value.clone());
854 }
855 }
856 value
857}
858
859fn future_hash_of(client: &Value) -> Option<String> {
861 match crate::get_value(client, &Value::Str("__ws_future_hash".into())) {
862 Value::Str(s) => Some(s.to_string()),
863 _ => None,
864 }
865}
866
867pub fn value_reject(client: &Value, args: &[Value]) -> Value {
869 let err = args.get(0).cloned().unwrap_or(Value::Null);
870 if let Some(hash) = future_hash_of(client) {
872 if let Some(url) = url_of(client) {
873 if let Some(c) = get_client(&url) { c.reject(&hash, err.clone()); }
874 }
875 return err;
876 }
877 if let Some(url) = url_of(client) {
878 if let Some(c) = get_client(&url) {
879 match args.get(1).and_then(hash_str) {
880 Some(hash) => c.reject(&hash, err.clone()),
881 None => {
883 let hashes: Vec<String> = c.futures.lock().unwrap().iter().cloned().collect();
884 for h in hashes {
885 c.reject(&h, err.clone());
886 }
887 }
888 }
889 }
890 }
891 err
892}
893
894pub fn value_send(client: &Value, args: &[Value]) -> Value {
896 if let Some(url) = url_of(client) {
897 if let Some(c) = get_client(&url) {
898 let payload = match args.get(0) {
899 Some(Value::Str(s)) => s.to_string(),
900 Some(v) => v.to_json().to_string(),
901 None => String::new().into(),
902 };
903 c.send_text(payload);
904 }
905 }
906 Value::Null
907}
908
909pub fn value_reset(client: &Value, error: Value) -> Value {
913 if let Some(url) = url_of(client) {
914 if let Some(c) = get_client(&url) {
915 if matches!(error, Value::Null) {
916 c.reset();
917 } else {
918 c.reset_with_error(error);
919 }
920 }
921 }
922 Value::Null
923}
924
925pub fn value_on_pong(client: &Value) -> Value {
927 if let Some(url) = url_of(client) {
928 if let Some(c) = get_client(&url) {
929 c.on_pong();
930 }
931 }
932 Value::Null
933}
934
935#[cfg(test)]
936mod tests {
937 use super::*;
938 use tokio_tungstenite::tungstenite::Message as WsMessage;
939
940 async fn spawn_mock_server() -> String {
945 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
946 let addr = listener.local_addr().unwrap();
947 tokio::spawn(async move {
948 if let Ok((stream, _)) = listener.accept().await {
949 let mut ws = tokio_tungstenite::accept_async(stream).await.unwrap();
950 if let Some(Ok(WsMessage::Text(sub))) = ws.next().await {
952 assert!(sub.contains("subscribe"), "expected subscribe, got {sub}");
953 }
954 for px in ["100.5", "101.0", "101.5"] {
956 let msg = format!("{{\"channel\":\"ticker\",\"symbol\":\"BTC/USDT\",\"last\":\"{px}\"}}");
957 ws.send(WsMessage::Text(msg)).await.unwrap();
958 }
959 tokio::time::sleep(std::time::Duration::from_millis(50)).await;
961 let _ = ws.close(None).await;
962 }
963 });
964 format!("ws://{addr}")
965 }
966
967 #[test]
973 fn value_reset_rejects_pending_futures() {
974 let url = "ws://reset-with-error.test";
975 mock_setup(url);
976 let client = get_client(url).expect("mock client");
977 client.note_futures(&["pending".to_string(), "delivered".to_string()]);
978 client.resolve("delivered", Value::Str("payload".into()));
979
980 let handle = client_value(url);
981 let error = Value::Str("[InvalidNonce] gap detected".into());
982 value_reset(&handle, error.clone());
983
984 assert_eq!(
986 client.take_settled(&["pending".to_string()]),
987 Some(Err(error))
988 );
989 assert_eq!(
991 client.take_settled(&["delivered".to_string()]),
992 Some(Ok(Value::Str("payload".into())))
993 );
994 assert!(!client.has_pending_futures());
995
996 client.note_futures(&["pending2".to_string()]);
998 value_reset(&handle, Value::Null);
999 assert_eq!(client.take_settled(&["pending2".to_string()]), None);
1000 assert!(!client.has_pending_futures());
1001
1002 drop_client(url);
1003 }
1004
1005 #[tokio::test]
1006 async fn transport_roundtrip() {
1007 let url = spawn_mock_server().await;
1008 let client = ensure_client(&url, None).await.expect("connect");
1009
1010 assert!(client.subscribe_once("ticker:BTC/USDT", Value::Null));
1012 assert!(!client.subscribe_once("ticker:BTC/USDT", Value::Null));
1013 assert!(client.send_text("{\"op\":\"subscribe\",\"channel\":\"ticker\"}".to_string()));
1014
1015 let mut lasts = Vec::new();
1018 while lasts.len() < 3 {
1019 let msg = client.next_message().await.expect("message before close");
1020 let last = crate::get_value(&msg, &Value::Str("last".into()));
1021 if let Value::Str(s) = &last {
1022 client.resolve("ticker", Value::Str(s.clone()));
1023 }
1024 if let Some(Ok(Value::Str(v))) = client.take_settled(&["ticker".to_string()]) {
1025 lasts.push(v);
1026 }
1027 }
1028 assert_eq!(lasts, vec!["100.5", "101.0", "101.5"]);
1029
1030 let subs = client.subscriptions_value();
1032 assert!(crate::runtime::is_true(&crate::get_value(
1033 &subs,
1034 &Value::Str("ticker:BTC/USDT".into())
1035 )));
1036
1037 drop_client(&url);
1038 }
1039
1040 struct TestWsCore {
1046 exchange: crate::exchange::Exchange,
1047 }
1048 impl std::ops::Deref for TestWsCore {
1049 type Target = crate::exchange::Exchange;
1050 fn deref(&self) -> &Self::Target {
1051 &self.exchange
1052 }
1053 }
1054 impl std::ops::DerefMut for TestWsCore {
1055 fn deref_mut(&mut self) -> &mut Self::Target {
1056 &mut self.exchange
1057 }
1058 }
1059 impl crate::exchange::DerivedExchange for TestWsCore {}
1060 impl crate::exchange_generated::ExchangeBase for TestWsCore {
1061 fn call_dynamic<'a>(
1062 &'a mut self,
1063 method: &'a str,
1064 args: Vec<Value>,
1065 ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Value> + Send + 'a>> {
1066 Box::pin(async move {
1067 match method {
1068 "handle_message" => {
1069 let client = args.get(0).cloned().unwrap_or(Value::Null);
1070 let message = args.get(1).cloned().unwrap_or(Value::Null);
1071 let last = crate::get_value(&message, &Value::Str("last".into()));
1072 client.resolve(&[last, Value::Str("ticker".into())]);
1074 Value::Null
1075 }
1076 _ => self.call_dynamic_base(method, args).await,
1077 }
1078 })
1079 }
1080 }
1081
1082 #[tokio::test]
1083 async fn watch_drive_loop_end_to_end() {
1084 use crate::exchange::ExchangeRuntime;
1085 let url = spawn_mock_server().await;
1086 let mut core = TestWsCore {
1087 exchange: crate::exchange::Exchange::new(None),
1088 };
1089 let result = ExchangeRuntime::watch(
1092 &mut core,
1093 Value::Str(url.clone().into()),
1094 Value::Str("ticker".into()),
1095 &[
1096 Value::Str("{\"op\":\"subscribe\",\"channel\":\"ticker\"}".into()),
1097 Value::Str("ticker".into()),
1098 Value::Null,
1099 ],
1100 )
1101 .await;
1102 assert_eq!(result, Value::Str("100.5".into()));
1104 drop_client(&url);
1105 }
1106
1107 #[tokio::test]
1115 async fn flight_elects_one_leader_and_registers_it() {
1116 let url = "flight-test-election";
1117 let c = ensure_slot(url);
1118 assert!(c.flight_begin("authenticate:future"), "first caller leads");
1119 assert!(!c.flight_begin("authenticate:future"), "second caller follows");
1120 assert!(in_op_futures(&c, "authenticate:future"));
1122 drop_client(url);
1123 }
1124
1125 #[tokio::test]
1126 async fn flight_settle_wakes_waiters_and_reopens() {
1127 let url = "flight-test-settle";
1128 let c = ensure_slot(url);
1129 assert!(c.flight_begin("auth"));
1130 c.resolve("auth", Value::Str("listen-key".into()));
1132 assert_eq!(
1133 ws_await_flight(&flight_handle(url, "auth", false)).await,
1134 Value::Str("listen-key".into())
1135 );
1136 assert_eq!(
1137 ws_await_flight(&flight_handle(url, "auth", false)).await,
1138 Value::Str("listen-key".into())
1139 );
1140 assert!(!in_op_futures(&c, "auth"));
1143 assert!(c.flight_begin("auth"), "a settled flight re-elects");
1144 drop_client(url);
1145 }
1146
1147 #[tokio::test]
1148 async fn flight_follower_waits_for_the_leader() {
1149 let url = "flight-test-wait";
1150 let c = ensure_slot(url);
1151 assert!(c.flight_begin("auth"));
1152 let settler = {
1153 let c = c.clone();
1154 tokio::spawn(async move {
1155 tokio::time::sleep(std::time::Duration::from_millis(60)).await;
1156 c.resolve("auth", Value::Str("late".into()));
1157 })
1158 };
1159 let started = std::time::Instant::now();
1160 let got = ws_await_flight(&flight_handle(url, "auth", false)).await;
1161 assert_eq!(got, Value::Str("late".into()));
1162 assert!(started.elapsed() >= std::time::Duration::from_millis(50), "waited for the leader");
1163 settler.await.unwrap();
1164 drop_client(url);
1165 }
1166
1167 #[tokio::test]
1168 async fn a_leader_never_blocks_on_its_own_flight() {
1169 let url = "flight-test-leader";
1173 let c = ensure_slot(url);
1174 let led = c.flight_begin("authenticated");
1175 assert!(led);
1176 let started = std::time::Instant::now();
1177 assert_eq!(
1178 ws_await_flight(&flight_handle(url, "authenticated", led)).await,
1179 Value::Null
1180 );
1181 assert!(started.elapsed() < std::time::Duration::from_millis(200), "returned at once");
1182 c.resolve("authenticated", Value::Bool(true));
1184 let led2 = c.flight_begin("authenticated");
1185 assert_eq!(
1186 ws_await_flight(&flight_handle(url, "authenticated", led2)).await,
1187 Value::Bool(true),
1188 "a re-lead with no new work reports the last value"
1189 );
1190 drop_client(url);
1191 }
1192
1193 #[tokio::test]
1194 async fn flight_handle_without_a_flight_returns_null() {
1195 let url = "flight-test-missing";
1198 ensure_slot(url);
1199 assert_eq!(ws_await_flight(&flight_handle(url, "nope", false)).await, Value::Null);
1200 drop_client(url);
1201 }
1202
1203 fn in_op_futures(c: &Arc<ClientState>, hash: &str) -> bool {
1205 !matches!(
1206 crate::get_value(&c.futures_value(), &Value::Str(hash.to_string().into())),
1207 Value::Null
1208 )
1209 }
1210
1211 #[tokio::test]
1212 async fn parse_helpers() {
1213 assert!(matches!(parse_text("{\"a\":1}"), Value::Dict(_)));
1215 assert_eq!(parse_text("pong"), Value::Str("pong".into()));
1216 use std::io::Write;
1218 let mut e = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
1219 e.write_all(b"{\"x\":true}").unwrap();
1220 let gz = e.finish().unwrap();
1221 assert!(matches!(parse_binary(&gz), Value::Dict(_)));
1222 }
1223}