#![allow(dead_code)]
use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::{Arc, Mutex};
use futures::{SinkExt, StreamExt};
use once_cell::sync::Lazy;
use tokio::sync::{mpsc, Notify};
use tokio_tungstenite::tungstenite::Message;
use crate::Value;
pub struct ClientState {
pub url: String,
outgoing: mpsc::UnboundedSender<Message>,
pending_rx: Mutex<Option<mpsc::UnboundedReceiver<Message>>>,
connect_gate: tokio::sync::Mutex<()>,
incoming: Mutex<VecDeque<Value>>,
notify: Notify,
resolved: Mutex<HashMap<String, Value>>,
rejections: Mutex<HashMap<String, Value>>,
subscriptions: Mutex<HashMap<String, Value>>,
futures: Mutex<HashSet<String>>,
flights: Mutex<HashMap<String, FlightSlot>>,
connected: Mutex<bool>,
closed: Mutex<bool>,
last_pong_ms: Mutex<i64>,
mock: Mutex<bool>,
mock_sent: Mutex<Vec<Value>>,
ws_test_completed: Mutex<bool>,
}
#[derive(Clone)]
struct FlightSlot {
open: bool,
settled: Option<Result<Value, Value>>,
}
static REGISTRY: Lazy<Mutex<HashMap<String, Arc<ClientState>>>> =
Lazy::new(|| Mutex::new(HashMap::new()));
fn now_ms() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as i64)
.unwrap_or(0)
}
fn parse_text(t: &str) -> Value {
match serde_json::from_str::<serde_json::Value>(t) {
Ok(j) => Value::from_json(&j),
Err(_) => Value::Str(t.to_string()),
}
}
fn parse_binary(b: &[u8]) -> Value {
use std::io::Read;
{
let mut d = flate2::read::GzDecoder::new(b);
let mut s = String::new();
if d.read_to_string(&mut s).is_ok() && !s.is_empty() {
return parse_text(&s);
}
}
{
let mut d = flate2::read::DeflateDecoder::new(b);
let mut s = String::new();
if d.read_to_string(&mut s).is_ok() && !s.is_empty() {
return parse_text(&s);
}
}
if let Ok(s) = std::str::from_utf8(b) {
return parse_text(s);
}
crate::exchange_stubs::bytes_to_value(b)
}
impl ClientState {
fn push_incoming(&self, v: Value) {
self.incoming.lock().unwrap().push_back(v);
self.notify.notify_waiters();
}
pub async fn next_message(&self) -> Option<Value> {
let mock = *self.mock.lock().unwrap();
loop {
let notified = self.notify.notified();
if let Some(v) = self.incoming.lock().unwrap().pop_front() {
return Some(v);
}
if *self.closed.lock().unwrap() {
return None;
}
if mock {
if tokio::time::timeout(std::time::Duration::from_millis(1500), notified).await.is_err() {
return None;
}
} else {
notified.await;
}
}
}
pub fn resolve(&self, hash: &str, value: Value) {
self.flight_settle(hash, Ok(value.clone()));
self.resolved.lock().unwrap().insert(hash.to_string(), value);
self.notify.notify_waiters();
}
pub fn reject(&self, hash: &str, err: Value) {
self.flight_settle(hash, Err(err.clone()));
self.rejections.lock().unwrap().insert(hash.to_string(), err);
self.notify.notify_waiters();
}
pub fn take_settled(&self, hashes: &[String]) -> Option<Result<Value, Value>> {
{
let mut rj = self.rejections.lock().unwrap();
for h in hashes {
if let Some(e) = rj.remove(h) {
return Some(Err(e));
}
}
}
let mut r = self.resolved.lock().unwrap();
for h in hashes {
if let Some(v) = r.remove(h) {
return Some(Ok(v));
}
}
None
}
pub fn note_futures(&self, hashes: &[String]) {
let mut f = self.futures.lock().unwrap();
for h in hashes {
f.insert(h.clone());
}
}
pub fn flight_begin(&self, hash: &str) -> bool {
let mut fl = self.flights.lock().unwrap();
match fl.get_mut(hash) {
Some(slot) if slot.open => false,
Some(slot) => {
slot.open = true;
self.futures.lock().unwrap().insert(hash.to_string());
true
}
None => {
fl.insert(hash.to_string(), FlightSlot { open: true, settled: None });
self.futures.lock().unwrap().insert(hash.to_string());
true
}
}
}
pub fn flight_peek(&self, hash: &str) -> Option<Result<Value, Value>> {
self.flights.lock().unwrap().get(hash).and_then(|s| s.settled.clone())
}
pub fn flight_is_open(&self, hash: &str) -> bool {
self.flights.lock().unwrap().get(hash).map(|s| s.open).unwrap_or(false)
}
pub fn flight_settle(&self, hash: &str, res: Result<Value, Value>) -> bool {
{
let mut fl = self.flights.lock().unwrap();
match fl.get_mut(hash) {
Some(slot) if slot.open => {
slot.open = false;
slot.settled = Some(res);
}
_ => return false,
}
}
self.futures.lock().unwrap().remove(hash);
self.notify.notify_waiters();
true
}
pub fn subscribe_once(&self, subscribe_hash: &str, subscription: Value) -> bool {
let mut subs = self.subscriptions.lock().unwrap();
if subs.contains_key(subscribe_hash) {
return false;
}
let stored = if matches!(subscription, Value::Null) {
Value::Bool(true)
} else {
subscription
};
subs.insert(subscribe_hash.to_string(), stored);
true
}
pub fn set_subscription(&self, subscribe_hash: &str, subscription: Value) {
self.subscriptions.lock().unwrap().insert(subscribe_hash.to_string(), subscription);
}
pub fn is_subscribed(&self, subscribe_hash: &str) -> bool {
self.subscriptions.lock().unwrap().contains_key(subscribe_hash)
}
pub fn send_text(&self, s: String) -> bool {
if std::env::var("CCXT_WS_DEBUG").is_ok() { eprintln!("[wssend] {}", s.chars().take(200).collect::<String>()); }
if *self.mock.lock().unwrap() {
self.mock_sent.lock().unwrap().push(parse_text(&s));
return true;
}
self.outgoing.send(Message::Text(s)).is_ok()
}
pub fn mock_enable(&self) {
*self.mock.lock().unwrap() = true;
*self.connected.lock().unwrap() = true;
}
pub fn mock_inject(&self, msg: Value) {
self.incoming.lock().unwrap().push_back(msg);
self.notify.notify_one();
}
pub fn is_mock(&self) -> bool { *self.mock.lock().unwrap() }
pub fn mock_sent_value(&self) -> Value {
Value::Array(self.mock_sent.lock().unwrap().clone())
}
pub fn has_pending_futures(&self) -> bool {
!self.futures.lock().unwrap().is_empty()
}
pub fn has_queued_messages(&self) -> bool {
!self.incoming.lock().unwrap().is_empty()
}
pub fn mark_ws_test_completed(&self) { *self.ws_test_completed.lock().unwrap() = true; }
pub fn is_ws_test_completed(&self) -> bool { *self.ws_test_completed.lock().unwrap() }
pub fn reject_pending_futures(&self, err: Value) {
let hashes: Vec<String> = self.futures.lock().unwrap().iter().cloned().collect();
for h in hashes { self.reject(&h, err.clone()); }
}
pub fn is_closed(&self) -> bool {
*self.closed.lock().unwrap()
}
pub fn on_pong(&self) {
*self.last_pong_ms.lock().unwrap() = now_ms();
}
pub fn reset(&self) {
self.resolved.lock().unwrap().clear();
self.rejections.lock().unwrap().clear();
self.subscriptions.lock().unwrap().clear();
self.futures.lock().unwrap().clear();
self.flights.lock().unwrap().clear();
}
pub fn subscriptions_value(&self) -> Value {
let subs = self.subscriptions.lock().unwrap();
let mut m = indexmap::IndexMap::new();
m.insert("__ws_subs_url".to_string(), Value::Str(self.url.clone()));
for (h, sub) in subs.iter() {
let tagged = match sub {
Value::Dict(d) => {
let mut inner = (**d).clone();
inner.insert("__ws_sub_ref".to_string(),
Value::Str(format!("{}\u{1}{}", self.url, h)));
Value::Dict(std::sync::Arc::new(inner))
}
other => other.clone(),
};
m.insert(h.clone(), tagged);
}
Value::Map(m)
}
pub fn set_subscription_field(&self, hash: &str, key: &str, val: Value) {
let mut subs = self.subscriptions.lock().unwrap();
match subs.get_mut(hash) {
Some(Value::Dict(d)) => { std::sync::Arc::make_mut(d).insert(key.to_string(), val); }
_ => {
let mut inner = indexmap::IndexMap::new();
inner.insert(key.to_string(), val);
subs.insert(hash.to_string(), Value::Dict(std::sync::Arc::new(inner)));
}
}
}
pub fn futures_value(&self) -> Value {
let f = self.futures.lock().unwrap();
let mut m = indexmap::IndexMap::new();
for h in f.iter() {
let mut fh = indexmap::IndexMap::new();
fh.insert("url".to_string(), Value::Str(self.url.clone()));
fh.insert("__ws_future_hash".to_string(), Value::Str(h.clone()));
m.insert(h.clone(), Value::Map(fh));
}
Value::Map(m)
}
}
pub fn get_client(url: &str) -> Option<Arc<ClientState>> {
let reg = REGISTRY.lock().unwrap();
reg.get(url).filter(|c| !c.is_closed()).cloned()
}
pub fn value_subs_insert(url: &str, key: &str, val: Value) {
if let Some(c) = get_client(url) { c.set_subscription(key, val); }
}
pub fn value_subs_remove(url: &str, key: &str) {
if let Some(c) = get_client(url) { c.subscriptions.lock().unwrap().remove(key); }
}
pub fn value_sub_field_write(subref: &str, key: &str, val: Value) {
if let Some((url, hash)) = subref.split_once('\u{1}') {
if let Some(c) = get_client(url) { c.set_subscription_field(hash, key, val); }
}
}
async fn connect_via_proxy(
url: &str,
proxy: &str,
) -> Result<tokio_tungstenite::WebSocketStream<
tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>, String> {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let target = url::Url::parse(url).map_err(|e| format!("[NetworkError] ws url {url}: {e}"))?;
let host = target.host_str().ok_or_else(|| format!("[NetworkError] ws url {url} has no host"))?;
let port = target.port_or_known_default().unwrap_or(443);
let p = url::Url::parse(proxy).map_err(|e| format!("[NetworkError] ws proxy {proxy}: {e}"))?;
let p_host = p.host_str().ok_or_else(|| format!("[NetworkError] ws proxy {proxy} has no host"))?;
let p_port = p.port_or_known_default().unwrap_or(8080);
let mut stream = tokio::net::TcpStream::connect((p_host, p_port))
.await
.map_err(|e| format!("[NetworkError] ws proxy connect {proxy}: {e}"))?;
let connect = format!(
"CONNECT {host}:{port} HTTP/1.1\r\nHost: {host}:{port}\r\nProxy-Connection: Keep-Alive\r\n\r\n"
);
stream
.write_all(connect.as_bytes())
.await
.map_err(|e| format!("[NetworkError] ws proxy CONNECT {proxy}: {e}"))?;
let mut head = Vec::new();
let mut byte = [0u8; 1];
while !head.ends_with(b"\r\n\r\n") {
let n = stream
.read(&mut byte)
.await
.map_err(|e| format!("[NetworkError] ws proxy CONNECT {proxy}: {e}"))?;
if n == 0 {
return Err(format!("[NetworkError] ws proxy {proxy} closed during CONNECT"));
}
head.push(byte[0]);
if head.len() > 8192 {
return Err(format!("[NetworkError] ws proxy {proxy} sent an oversized CONNECT reply"));
}
}
let status = String::from_utf8_lossy(&head);
let first = status.lines().next().unwrap_or_default();
if !first.contains(" 200") {
return Err(format!("[NetworkError] ws proxy {proxy} refused CONNECT: {first}"));
}
let (ws, _resp) = tokio_tungstenite::client_async_tls(url, stream)
.await
.map_err(|e| format!("[NetworkError] ws connect {url} via {proxy}: {e}"))?;
Ok(ws)
}
pub async fn ensure_client(url: &str, proxy: Option<String>) -> Result<Arc<ClientState>, String> {
let state = ensure_slot(url);
if *state.connected.lock().unwrap() {
return Ok(state);
}
let gate_holder = state.clone();
let _gate = gate_holder.connect_gate.lock().await;
if *state.connected.lock().unwrap() {
return Ok(state);
}
let ws = match proxy.as_deref().filter(|p| !p.is_empty()) {
Some(p) => connect_via_proxy(url, p).await?,
None => {
let (ws, _resp) = tokio_tungstenite::connect_async(url)
.await
.map_err(|e| format!("[NetworkError] ws connect {url}: {e}"))?;
ws
}
};
let (mut write, mut read) = ws.split();
let mut rx = state.pending_rx.lock().unwrap().take()
.ok_or_else(|| format!("[NetworkError] ws {url} slot has no writer channel"))?;
*state.last_pong_ms.lock().unwrap() = now_ms();
tokio::spawn(async move {
while let Some(msg) = rx.recv().await {
if write.send(msg).await.is_err() {
break;
}
}
let _ = write.close().await;
});
let st = state.clone();
tokio::spawn(async move {
while let Some(frame) = read.next().await {
match frame {
Ok(Message::Text(t)) => st.push_incoming(parse_text(&t)),
Ok(Message::Binary(b)) => st.push_incoming(parse_binary(&b)),
Ok(Message::Pong(_)) => st.on_pong(),
Ok(Message::Ping(_)) => {}
Ok(Message::Close(_)) | Err(_) => break,
_ => {}
}
}
*st.connected.lock().unwrap() = false;
*st.closed.lock().unwrap() = true;
st.notify.notify_waiters();
});
let st2 = state.clone();
tokio::spawn(async move {
let mut iv = tokio::time::interval(std::time::Duration::from_secs(30));
iv.tick().await; loop {
iv.tick().await;
if st2.is_closed() {
break;
}
if st2.outgoing.send(Message::Ping(Vec::new())).is_err() {
break;
}
}
});
*state.connected.lock().unwrap() = true;
Ok(state)
}
pub fn client_field_live(url: &str, field: &str) -> Value {
match get_client(url) {
Some(c) if field == "futures" => c.futures_value(),
Some(c) => c.subscriptions_value(),
None => Value::Map(indexmap::IndexMap::new()),
}
}
fn ensure_slot(url: &str) -> Arc<ClientState> {
let mut reg = REGISTRY.lock().unwrap();
if let Some(c) = reg.get(url) {
if !c.is_closed() {
return c.clone();
}
}
let (tx, rx) = mpsc::unbounded_channel::<Message>();
let state = Arc::new(ClientState {
url: url.to_string(),
outgoing: tx,
pending_rx: Mutex::new(Some(rx)),
connect_gate: tokio::sync::Mutex::new(()),
incoming: Mutex::new(VecDeque::new()),
notify: Notify::new(),
resolved: Mutex::new(HashMap::new()),
rejections: Mutex::new(HashMap::new()),
subscriptions: Mutex::new(HashMap::new()),
futures: Mutex::new(HashSet::new()),
flights: Mutex::new(HashMap::new()),
connected: Mutex::new(false),
closed: Mutex::new(false),
last_pong_ms: Mutex::new(now_ms()),
mock: Mutex::new(false),
mock_sent: Mutex::new(Vec::new()),
ws_test_completed: Mutex::new(false),
});
reg.insert(url.to_string(), state.clone());
state
}
pub fn drop_client(url: &str) {
REGISTRY.lock().unwrap().remove(url);
}
pub fn mock_setup(url: &str) {
let c = ensure_slot(url);
c.reset();
c.mock_enable();
c.mock_sent.lock().unwrap().clear();
c.incoming.lock().unwrap().clear();
*c.ws_test_completed.lock().unwrap() = false;
}
pub fn mock_inject(url: &str, msg: Value) {
if let Some(c) = get_client(url) { c.mock_inject(msg); }
}
pub fn mock_sent_messages(url: &str) -> Value {
match get_client(url) { Some(c) => c.mock_sent_value(), None => Value::Array(vec![]) }
}
pub fn mock_has_pending_futures(url: &str) -> bool {
get_client(url).map(|c| c.has_pending_futures()).unwrap_or(false)
}
pub fn mock_has_queued_messages(url: &str) -> bool {
get_client(url).map(|c| c.has_queued_messages()).unwrap_or(false)
}
pub fn mock_mark_completed(url: &str) {
if let Some(c) = get_client(url) { c.mark_ws_test_completed(); }
}
pub fn mock_is_completed(url: &str) -> bool {
get_client(url).map(|c| c.is_ws_test_completed()).unwrap_or(true)
}
pub fn mock_reject_futures(url: &str) {
if let Some(c) = get_client(url) {
c.reject_pending_futures(Value::Str(
"[ExchangeError] static ws test: the injected messages did not resolve the watch future".to_string()));
}
}
pub fn client_value(url: &str) -> Value {
let c = ensure_slot(url);
let mut m = indexmap::IndexMap::new();
m.insert("url".to_string(), Value::Str(url.to_string()));
m.insert("subscriptions".to_string(), c.subscriptions_value());
m.insert("futures".to_string(), c.futures_value());
Value::Map(m)
}
pub fn begin_flight(url: &str, hash: &str) -> bool {
ensure_slot(url).flight_begin(hash)
}
pub fn flight_handle(url: &str, hash: &str, led: bool) -> Value {
let mut m = indexmap::IndexMap::new();
m.insert("url".to_string(), Value::Str(url.to_string()));
m.insert("__ws_flight_hash".to_string(), Value::Str(hash.to_string()));
m.insert("__ws_flight_led".to_string(), Value::Bool(led));
Value::Map(m)
}
fn flight_hash_of(handle: &Value) -> Option<String> {
for key in ["__ws_flight_hash", "__ws_future_hash"] {
if let Value::Str(h) = crate::get_value(handle, &Value::Str(key.to_string())) {
return Some(h);
}
}
None
}
pub async fn ws_await_flight(handle: &Value) -> Value {
let (url, hash) = match (url_of(handle), flight_hash_of(handle)) {
(Some(u), Some(h)) => (u, h),
_ => return Value::Null,
};
let client = match get_client(&url) {
Some(c) => c,
None => return Value::Null,
};
let settled = client.flight_peek(&hash);
let led = matches!(
crate::get_value(handle, &Value::Str("__ws_flight_led".to_string())),
Value::Bool(true)
);
if led || !client.flight_is_open(&hash) {
return match settled {
Some(Ok(v)) => v,
Some(Err(e)) => panic!(
"{}",
match &e {
Value::Str(s) => s.clone(),
v => crate::runtime::stringify_param(v),
}
),
None => Value::Null,
};
}
let budget = if client.is_mock() {
std::time::Duration::from_millis(1500)
} else {
std::time::Duration::from_secs(60)
};
let deadline = tokio::time::Instant::now() + budget;
loop {
let notified = client.notify.notified();
if let Some(res) = client.flight_peek(&hash) {
return match res {
Ok(v) => v,
Err(e) => panic!(
"{}",
match &e {
Value::Str(s) => s.clone(),
v => crate::runtime::stringify_param(v),
}
),
};
}
if !client.flight_is_open(&hash) {
return Value::Null;
}
if tokio::time::timeout_at(deadline, notified).await.is_err() {
panic!(
"[NetworkError] timed out waiting for the in-flight '{}' on {}",
hash, url
);
}
}
}
pub fn url_of(client: &Value) -> Option<String> {
match crate::get_value(client, &Value::Str("url".to_string())) {
Value::Str(s) => Some(s),
_ => None,
}
}
fn hash_str(v: &Value) -> Option<String> {
match v {
Value::Str(s) => Some(s.clone()),
_ => None,
}
}
pub fn value_resolve(client: &Value, args: &[Value]) -> Value {
let value = args.get(0).cloned().unwrap_or(Value::Null);
if let Some(hash) = future_hash_of(client) {
if let Some(url) = url_of(client) {
if let Some(c) = get_client(&url) { c.resolve(&hash, value.clone()); }
}
return value;
}
if let (Some(url), Some(hash)) = (url_of(client), args.get(1).and_then(hash_str)) {
if let Some(c) = get_client(&url) {
c.resolve(&hash, value.clone());
}
}
value
}
fn future_hash_of(client: &Value) -> Option<String> {
match crate::get_value(client, &Value::Str("__ws_future_hash".to_string())) {
Value::Str(s) => Some(s),
_ => None,
}
}
pub fn value_reject(client: &Value, args: &[Value]) -> Value {
let err = args.get(0).cloned().unwrap_or(Value::Null);
if let Some(hash) = future_hash_of(client) {
if let Some(url) = url_of(client) {
if let Some(c) = get_client(&url) { c.reject(&hash, err.clone()); }
}
return err;
}
if let Some(url) = url_of(client) {
if let Some(c) = get_client(&url) {
match args.get(1).and_then(hash_str) {
Some(hash) => c.reject(&hash, err.clone()),
None => {
let hashes: Vec<String> = c.futures.lock().unwrap().iter().cloned().collect();
for h in hashes {
c.reject(&h, err.clone());
}
}
}
}
}
err
}
pub fn value_send(client: &Value, args: &[Value]) -> Value {
if let Some(url) = url_of(client) {
if let Some(c) = get_client(&url) {
let payload = match args.get(0) {
Some(Value::Str(s)) => s.clone(),
Some(v) => v.to_json().to_string(),
None => String::new(),
};
c.send_text(payload);
}
}
Value::Null
}
pub fn value_reset(client: &Value) -> Value {
if let Some(url) = url_of(client) {
if let Some(c) = get_client(&url) {
c.reset();
}
}
Value::Null
}
pub fn value_on_pong(client: &Value) -> Value {
if let Some(url) = url_of(client) {
if let Some(c) = get_client(&url) {
c.on_pong();
}
}
Value::Null
}
#[cfg(test)]
mod tests {
use super::*;
use tokio_tungstenite::tungstenite::Message as WsMessage;
async fn spawn_mock_server() -> String {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
if let Ok((stream, _)) = listener.accept().await {
let mut ws = tokio_tungstenite::accept_async(stream).await.unwrap();
if let Some(Ok(WsMessage::Text(sub))) = ws.next().await {
assert!(sub.contains("subscribe"), "expected subscribe, got {sub}");
}
for px in ["100.5", "101.0", "101.5"] {
let msg = format!("{{\"channel\":\"ticker\",\"symbol\":\"BTC/USDT\",\"last\":\"{px}\"}}");
ws.send(WsMessage::Text(msg)).await.unwrap();
}
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
let _ = ws.close(None).await;
}
});
format!("ws://{addr}")
}
#[tokio::test]
async fn transport_roundtrip() {
let url = spawn_mock_server().await;
let client = ensure_client(&url, None).await.expect("connect");
assert!(client.subscribe_once("ticker:BTC/USDT", Value::Null));
assert!(!client.subscribe_once("ticker:BTC/USDT", Value::Null));
assert!(client.send_text("{\"op\":\"subscribe\",\"channel\":\"ticker\"}".to_string()));
let mut lasts = Vec::new();
while lasts.len() < 3 {
let msg = client.next_message().await.expect("message before close");
let last = crate::get_value(&msg, &Value::Str("last".to_string()));
if let Value::Str(s) = &last {
client.resolve("ticker", Value::Str(s.clone()));
}
if let Some(Ok(Value::Str(v))) = client.take_settled(&["ticker".to_string()]) {
lasts.push(v);
}
}
assert_eq!(lasts, vec!["100.5", "101.0", "101.5"]);
let subs = client.subscriptions_value();
assert!(crate::runtime::is_true(&crate::get_value(
&subs,
&Value::Str("ticker:BTC/USDT".to_string())
)));
drop_client(&url);
}
struct TestWsCore {
exchange: crate::exchange::Exchange,
}
impl std::ops::Deref for TestWsCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &Self::Target {
&self.exchange
}
}
impl std::ops::DerefMut for TestWsCore {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.exchange
}
}
impl crate::exchange::DerivedExchange for TestWsCore {}
impl crate::exchange_generated::ExchangeBase for TestWsCore {
fn call_dynamic<'a>(
&'a mut self,
method: &'a str,
args: Vec<Value>,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = Value> + Send + 'a>> {
Box::pin(async move {
match method {
"handle_message" => {
let client = args.get(0).cloned().unwrap_or(Value::Null);
let message = args.get(1).cloned().unwrap_or(Value::Null);
let last = crate::get_value(&message, &Value::Str("last".to_string()));
client.resolve(&[last, Value::Str("ticker".to_string())]);
Value::Null
}
_ => self.call_dynamic_base(method, args).await,
}
})
}
}
#[tokio::test]
async fn watch_drive_loop_end_to_end() {
use crate::exchange::ExchangeRuntime;
let url = spawn_mock_server().await;
let mut core = TestWsCore {
exchange: crate::exchange::Exchange::new(None),
};
let result = ExchangeRuntime::watch(
&mut core,
Value::Str(url.clone()),
Value::Str("ticker".to_string()),
&[
Value::Str("{\"op\":\"subscribe\",\"channel\":\"ticker\"}".to_string()),
Value::Str("ticker".to_string()),
Value::Null,
],
)
.await;
assert_eq!(result, Value::Str("100.5".to_string()));
drop_client(&url);
}
#[tokio::test]
async fn flight_elects_one_leader_and_registers_it() {
let url = "flight-test-election";
let c = ensure_slot(url);
assert!(c.flight_begin("authenticate:future"), "first caller leads");
assert!(!c.flight_begin("authenticate:future"), "second caller follows");
assert!(in_op_futures(&c, "authenticate:future"));
drop_client(url);
}
#[tokio::test]
async fn flight_settle_wakes_waiters_and_reopens() {
let url = "flight-test-settle";
let c = ensure_slot(url);
assert!(c.flight_begin("auth"));
c.resolve("auth", Value::Str("listen-key".to_string()));
assert_eq!(
ws_await_flight(&flight_handle(url, "auth", false)).await,
Value::Str("listen-key".to_string())
);
assert_eq!(
ws_await_flight(&flight_handle(url, "auth", false)).await,
Value::Str("listen-key".to_string())
);
assert!(!in_op_futures(&c, "auth"));
assert!(c.flight_begin("auth"), "a settled flight re-elects");
drop_client(url);
}
#[tokio::test]
async fn flight_follower_waits_for_the_leader() {
let url = "flight-test-wait";
let c = ensure_slot(url);
assert!(c.flight_begin("auth"));
let settler = {
let c = c.clone();
tokio::spawn(async move {
tokio::time::sleep(std::time::Duration::from_millis(60)).await;
c.resolve("auth", Value::Str("late".to_string()));
})
};
let started = std::time::Instant::now();
let got = ws_await_flight(&flight_handle(url, "auth", false)).await;
assert_eq!(got, Value::Str("late".to_string()));
assert!(started.elapsed() >= std::time::Duration::from_millis(50), "waited for the leader");
settler.await.unwrap();
drop_client(url);
}
#[tokio::test]
async fn a_leader_never_blocks_on_its_own_flight() {
let url = "flight-test-leader";
let c = ensure_slot(url);
let led = c.flight_begin("authenticated");
assert!(led);
let started = std::time::Instant::now();
assert_eq!(
ws_await_flight(&flight_handle(url, "authenticated", led)).await,
Value::Null
);
assert!(started.elapsed() < std::time::Duration::from_millis(200), "returned at once");
c.resolve("authenticated", Value::Bool(true));
let led2 = c.flight_begin("authenticated");
assert_eq!(
ws_await_flight(&flight_handle(url, "authenticated", led2)).await,
Value::Bool(true),
"a re-lead with no new work reports the last value"
);
drop_client(url);
}
#[tokio::test]
async fn flight_handle_without_a_flight_returns_null() {
let url = "flight-test-missing";
ensure_slot(url);
assert_eq!(ws_await_flight(&flight_handle(url, "nope", false)).await, Value::Null);
drop_client(url);
}
fn in_op_futures(c: &Arc<ClientState>, hash: &str) -> bool {
!matches!(
crate::get_value(&c.futures_value(), &Value::Str(hash.to_string())),
Value::Null
)
}
#[tokio::test]
async fn parse_helpers() {
assert!(matches!(parse_text("{\"a\":1}"), Value::Dict(_)));
assert_eq!(parse_text("pong"), Value::Str("pong".to_string()));
use std::io::Write;
let mut e = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
e.write_all(b"{\"x\":true}").unwrap();
let gz = e.finish().unwrap();
assert!(matches!(parse_binary(&gz), Value::Dict(_)));
}
}