Skip to main content

ccxt_base/pro/
ws_client.rs

1//! WebSocket transport for the pro (`watch*`) API.
2//!
3//! This is the Rust port of the runtime side of `ts/src/base/ws/{Client,WsClient}.ts`.
4//! The transpiled `pro/<id>.rs` exchanges call — via the base `watch()` /
5//! `watch_multiple()` — into a *client* object keyed by URL that:
6//!   * owns the live `tokio-tungstenite` connection (one per URL),
7//!   * exposes `resolve` / `reject` / `future` / `send` so the venue's
8//!     `handle_message` can push parsed data back to the awaiting `watch`,
9//!   * tracks `subscriptions` (so a subscribe frame is sent once per hash),
10//!   * runs ping/pong keep-alive.
11//!
12//! Ownership model (why this is a global registry, not a field on `Exchange`):
13//! the base `watch()` borrows `&mut self` to drive `handle_message`, which
14//! itself needs the client. Keeping the connection + futures in a process-wide
15//! registry keyed by URL (behind its own locks) keeps it disjoint from the
16//! `&mut Exchange` borrow, so the drive loop can read the next frame and call
17//! `handle_message(self, client, msg)` without aliasing.
18
19#![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
31/// Per-connection state. Lives in [`REGISTRY`] behind an `Arc`, so both the
32/// background reader/writer tasks and the `watch` drive loop share it.
33pub struct ClientState {
34    pub url: String,
35    /// Frames queued for the writer task → socket.
36    outgoing: mpsc::UnboundedSender<Message>,
37    /// Receiver half held until the socket connects (a slot is pre-registered
38    /// before connecting so `client.subscriptions` writes persist — upbit builds
39    /// its subscribe frame from subscriptions set before the socket is up). The
40    /// writer task takes this on connect.
41    pending_rx: Mutex<Option<mpsc::UnboundedReceiver<Message>>>,
42    /// Serializes the (async) connect so concurrent `ensure_client`s for a
43    /// pre-registered slot don't open two sockets.
44    connect_gate: tokio::sync::Mutex<()>,
45    /// Parsed inbound messages awaiting dispatch to `handle_message`.
46    incoming: Mutex<VecDeque<Value>>,
47    /// Woken on: new inbound message, a resolve/reject, or close.
48    notify: Notify,
49    /// messageHash → resolved value (set by `handle_message` via `resolve`).
50    resolved: Mutex<HashMap<String, Value>>,
51    /// messageHash → error (set by `reject`; delivered before/instead of value).
52    rejections: Mutex<HashMap<String, Value>>,
53    /// subscribeHash → subscription object (TS `client.subscriptions[hash]`).
54    /// A subscribe frame is sent only the first time a hash is inserted.
55    subscriptions: Mutex<HashMap<String, Value>>,
56    /// messageHashes some `watch` call is currently waiting on. Mirrors TS
57    /// `client.futures` (read by a few venues' `handle_message`).
58    futures: Mutex<HashSet<String>>,
59    /// In-flight single-flight slots keyed by messageHash — the registry behind
60    /// TS's `client.future ()` / `client.reusableFuture ()` leader election
61    /// (binance/bybit/kucoin/... `authenticate`). Separate from `resolved`
62    /// because a flight has *many* waiters (all of whom must observe the
63    /// settled value, not consume it) and because settling one must also clear
64    /// its `futures` entry so the NEXT cycle can elect a fresh leader.
65    flights: Mutex<HashMap<String, FlightSlot>>,
66    connected: Mutex<bool>,
67    closed: Mutex<bool>,
68    last_pong_ms: Mutex<i64>,
69    /// Static-WS-test mock transport. When `mock` is set, `send_text` records the
70    /// (JSON-parsed) outgoing frame into `mock_sent` instead of relying on a
71    /// socket, and no real connection is ever opened. `ws_test_completed` is the
72    /// watch side's done-flag the frame injector's rejection loop polls.
73    mock: Mutex<bool>,
74    mock_sent: Mutex<Vec<Value>>,
75    ws_test_completed: Mutex<bool>,
76}
77
78/// One single-flight slot. `settled` stays populated after the flight closes so
79/// waiters that poll late still observe the result, and so a caller that
80/// re-awaits a hash nobody is working on any more gets the last value instead
81/// of blocking (TS's already-resolved Future). `open` is what a concurrent
82/// caller joins.
83#[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
92/// Monotonic-ish wall clock in ms. `SystemTime` is fine here (keep-alive only).
93fn 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
100/// Decode a text frame into a `Value` — JSON when it parses, else a raw string
101/// (some venues send bare `"pong"` etc. that `handle_message` matches on).
102fn 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
109/// Decode a binary frame: try raw-inflate then gzip (the two schemes venues
110/// use), fall back to the bytes as UTF-8. Then parse as text.
111fn parse_binary(b: &[u8]) -> Value {
112    use std::io::Read;
113    // gzip
114    {
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    // raw deflate (no zlib header)
122    {
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    // Uncompressed and valid UTF-8 → parse as text/JSON (covers venues that
130    // send plain-JSON frames over the binary opcode).
131    if let Ok(s) = std::str::from_utf8(b) {
132        return parse_text(s);
133    }
134    // Genuine binary payload (e.g. mexc protobuf): carry the raw bytes through
135    // as the port's byte-array form so `isBinaryMessage`/`decodeProtoMsg` see them.
136    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    /// Await the next inbound message. `None` once the socket is closed and
146    /// the backlog is drained. Uses the create-future-before-check pattern so
147    /// a resolve/push racing the await is never lost.
148    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                // Static WS test: the mock queue is fed by the frame injector.
160                // If nothing arrives within a short window the fixture is
161                // finished (or under-feeds this watch) — stop instead of
162                // blocking the drive loop forever, so the test completes.
163                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    /// Store a resolved value for `hash` (TS `client.resolve`). Also settles an
173    /// open single-flight on the same hash: TS's `client.resolve ()` settles
174    /// the future AND removes it from `client.futures`, which is what lets the
175    /// next cycle elect a fresh leader. Both paths run — a hash can in
176    /// principle be someone's flight and someone else's `watch`, and only the
177    /// waiter that exists will read its side.
178    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    /// Store an error for `hash` (TS `client.reject`), settling an open
185    /// single-flight on the same hash — see `resolve`.
186    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    /// If any of `hashes` has a resolved value or rejection, remove and return
193    /// it (`Ok` for value, `Err` for rejection). Rejections take priority.
194    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    /// Register interest in `hashes` (TS `client.future`). Returns true if the
213    /// subscribe frame still needs sending for `subscribe_hash`.
214    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    /// Open a single-flight for `hash`, or join one already in progress. `true`
222    /// means this caller is the leader and must do the work; `false` means a
223    /// flight is already open and the caller should wait on it.
224    ///
225    /// The insert into `futures` is what makes the transpiled
226    /// `if (messageHash in client.futures)` follower test observable, and it
227    /// happens under the same lock as the check — this is TS's documented
228    /// "atomic check-and-insert".
229    pub fn flight_begin(&self, hash: &str) -> bool {
230        let mut fl = self.flights.lock().unwrap();
231        match fl.get_mut(hash) {
232            // Open flight — join it as a follower.
233            Some(slot) if slot.open => false,
234            // Closed: re-open, keeping the last value for anyone who re-awaits
235            // without new work being done.
236            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    /// The flight's last outcome, if it has one. Does NOT consume it: every
250    /// waiter must be able to observe the same result.
251    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    /// Whether a flight for `hash` exists and is still open.
256    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    /// Settle an open flight and wake its waiters. Returns false (and does
261    /// nothing) when `hash` names no open flight, so `resolve`/`reject` can
262    /// fall through to their normal watch-hash behaviour.
263    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        // Clear the `futures` entry as part of settling, mirroring TS: the
275        // flight is over, so the next cycle must elect a fresh leader.
276        self.futures.lock().unwrap().remove(hash);
277        self.notify.notify_waiters();
278        true
279    }
280
281    /// Record `subscribe_hash` → `subscription`; returns true the first time
282    /// (so the caller sends the subscribe frame exactly once). Mirrors TS
283    /// `client.subscriptions[subscribeHash] = subscription || true`.
284    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    /// Directly set a subscription entry (TS `client.subscriptions[h] = x`
299    /// written from `handle_message`).
300    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        // Static-WS-test mock transport: record the frame (JSON-parsed, like the
311        // TS `client.connection.send` stub) instead of hitting a socket.
312        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    /// Enable the mock transport: mark connected (so `ensure_client` never opens
320    /// a socket) and route `send_text` to the capture buffer.
321    pub fn mock_enable(&self) {
322        *self.mock.lock().unwrap() = true;
323        *self.connected.lock().unwrap() = true;
324    }
325    /// Injected inbound frame → the same queue the socket reader feeds.
326    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    /// The captured outgoing frames as a `Value::List`.
332    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    /// Whether the mock inbound queue still holds un-consumed frames.
339    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    /// Reject every pending future so a fixture whose frames don't resolve the
345    /// watch fails (with a message) rather than hanging the drive loop.
346    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    /// Drop resolved/rejected/subscription/future state,
360    /// e.g. after a reconnect so stale hashes don't resolve new waiters.
361    /// Internal wipe only — the transpiled `client.reset(error)` goes through
362    /// `reset_with_error` below, which delivers the error first.
363    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    /// TS `client.reset(error)` — reject every pending future/flight with the
372    /// error so waiters fail fast instead of hanging, then drop the pending
373    /// future state. Mirrors the js/php/c#/go/java/python clients: rejections
374    /// are kept (they carry the error to the waiters), delivered-but-not-taken
375    /// `resolved` values are kept (in TS an already-resolved future is settled
376    /// — `reject` on it is a no-op — so its waiter still gets the value), and
377    /// subscriptions are left to the caller — the TS `Client.reset` does not
378    /// clear them either.
379    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    /// Snapshot of `subscriptions` as a `Value::Map { hash: subscription }` —
391    /// the shape the transpiled `get_value(&client, "subscriptions")` reads.
392    /// Tagged with `__ws_subs_url` so that writes performed on the snapshot
393    /// (`client.subscriptions[chanId] = …`, common in bitfinex/chan-id venues)
394    /// route back to this live `ClientState` instead of a discarded clone.
395    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()));
399        for (h, sub) in subs.iter() {
400            // Tag each subscription DICT with a back-reference so a field write
401            // on it (`subscription['receivedSnapshot'] = true`) persists to this
402            // live client — venues mutate a subscription retrieved from
403            // client.subscriptions and rely on JS object identity.
404            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)));
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    /// Set a field on a stored subscription dict (`client.subscriptions[hash]
419    /// [key] = val`). Creates the entry if missing.
420    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    /// Snapshot of `futures` as a `Value::Map { hash: true }`.
433    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            // Each entry is a future *handle* carrying the url + its own hash, so
438            // transpiled `client.futures[hash].resolve(x)` (bitget/cryptocom auth)
439            // routes back to this ClientState — see value_resolve/value_reject.
440            let mut fh = indexmap::IndexMap::new();
441            fh.insert("url".to_string(), Value::Str(self.url.clone()));
442            fh.insert("__ws_future_hash".to_string(), Value::Str(h.clone()));
443            m.insert(h.clone(), Value::Map(fh));
444        }
445        Value::Map(m)
446    }
447}
448
449/// Get the existing client for `url`, or `None` if not yet connected.
450pub 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
455/// `client.subscriptions[key] = val` written on a tagged snapshot — persist it
456/// to the live client so subsequent `handle_message` snapshots see it.
457pub 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
461/// `delete client.subscriptions[key]` on a tagged snapshot.
462pub fn value_subs_remove(url: &str, key: &str) {
463    if let Some(c) = get_client(url) { c.subscriptions.lock().unwrap().remove(key); }
464}
465
466/// `client.subscriptions[hash][key] = val` written on a tagged subscription
467/// dict (carrying `__ws_sub_ref` = "url\u{1}hash").
468pub 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
474/// Ensure a live connection to `url`, connecting (and spawning the reader /
475/// writer / keep-alive tasks) if needed. Idempotent per URL.
476/// Open an HTTP CONNECT tunnel to `proxy` and hand the raw stream to
477/// tungstenite. `connect_async` has no proxy support of its own, so a venue
478/// reached through `wsProxy` / `wssProxy` has to be dialed this way.
479async 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    // Serialize connect; re-check under the gate (another task may have just
533    // connected this slot). Lock via a cloned Arc so `state` stays movable.
534    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    // Writer task: drain the outgoing queue to the socket.
554    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    // Reader task: decode frames → incoming queue.
564    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                // tungstenite answers Ping frames with Pong automatically.
572                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    // Keep-alive: an unsolicited Ping every 30s; the peer's Pong updates
583    // last_pong. (Full miss-count RequestTimeout handling is a later refinement.)
584    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; // first tick fires immediately; skip it
588        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
603/// Live read of a client handle's `subscriptions` / `futures` field, straight
604/// from the registry so a read after a write (upbit builds its subscribe frame
605/// from subscriptions it just set) is coherent, not a stale embedded snapshot.
606pub 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
614/// Get-or-create the registry slot for `url` WITHOUT connecting the socket, so
615/// `client.subscriptions` written before `watch()` connects still persist.
616fn 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
647/// Remove (and thereby drop / disconnect) the client for `url`.
648pub fn drop_client(url: &str) {
649    REGISTRY.lock().unwrap().remove(url);
650}
651
652// ── `Value`-handle bridge ────────────────────────────────────────────────────
653//
654// The transpiled `handle_message(&mut self, client: Value, message: Value)`
655// receives a *client* as a `Value`. We model it as `Value::Map { "url": <url>,
656// "subscriptions": <snapshot>, "futures": <snapshot> }`. The `Value` methods
657// `resolve`/`reject`/`send`/… (in value.rs) extract `url` and route here.
658
659// ── Static-WS-test mock transport (url-keyed façade over ClientState) ────────
660
661/// `setupWsMockTransport(url)` — register a connected, socket-less client whose
662/// sends are captured. Clears any prior state so each fixture starts fresh.
663pub 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    // Discard any messages left unconsumed by a prior test on the same URL (e.g.
669    // a heartbeat a watchTrades drive loop returned past before reading) so they
670    // don't leak an extra handler dispatch / sent frame into the next test.
671    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()));
696    }
697}
698
699/// Build the client-handle `Value` passed to `handle_message`: the URL plus
700/// live snapshots of `subscriptions` / `futures` (the fields venues read via
701/// `get_value(&client, "subscriptions")`).
702pub fn client_value(url: &str) -> Value {
703    // Pre-register the slot so subscriptions written on this handle (before the
704    // socket connects) persist and read back — upbit-style subscribe building.
705    let c = ensure_slot(url);
706    let mut m = indexmap::IndexMap::new();
707    m.insert("url".to_string(), Value::Str(url.to_string()));
708    m.insert("subscriptions".to_string(), c.subscriptions_value());
709    m.insert("futures".to_string(), c.futures_value());
710    Value::Map(m)
711}
712
713/// Open-or-join the single-flight for `hash` on `url`, creating the registry
714/// slot if the client has not been dialed yet (venue `authenticate` parks its
715/// flights on a never-dialed pseudo-url, because the real user-data url embeds
716/// the credential the flight is fetching).
717pub fn begin_flight(url: &str, hash: &str) -> bool {
718    ensure_slot(url).flight_begin(hash)
719}
720
721
722/// The `Value` a `client.future ()` / `client.reusableFuture ()` call hands
723/// back: enough to find the flight again (its client's url + the hash). TS
724/// returns a real Future object; a `Value` can't hold one, so the port returns
725/// a handle and `ws_await_flight` does the awaiting.
726pub 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()));
729    m.insert("__ws_flight_hash".to_string(), Value::Str(hash.to_string()));
730    // Whether the call that produced this handle opened the flight. A leader
731    // settles its own flight (and TS's `await future` resolves the instant it
732    // does), so it must never block on itself — including when the venue
733    // decides, after taking the lead, that there is no work to do because it
734    // is already subscribed (bitget's `authenticate`).
735    m.insert("__ws_flight_led".to_string(), Value::Bool(led));
736    Value::Map(m)
737}
738
739/// The hash a flight handle refers to. Accepts the `futures_value ()` handle
740/// shape too, so `client.futures[hash]` entries can be awaited as well.
741fn 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())) {
744            return Some(h);
745        }
746    }
747    None
748}
749
750/// Await a flight handle — the port of TS's `await client.future (hash)` and
751/// of the trailing `await future` a single-flight leader runs after settling.
752///
753/// Returns the resolved value; a rejected flight panics with the error, which
754/// is how the port rethrows (the drive loop does the same with `take_settled`).
755/// A handle that names no flight returns `Value::Null` rather than hanging.
756pub 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    // The leader: its own `client.resolve ()` has already run by the time it
767    // reaches its trailing await, so take the value and go. Waiting here would
768    // deadlock the (common) case where the venue took the lead and then found
769    // it had nothing to do.
770    let led = matches!(
771        crate::get_value(handle, &Value::Str("__ws_flight_led".to_string())),
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),
782                }
783            ),
784            // A flight that never opened is not an error — the value it would
785            // have carried is already in the venue's own cache, which is what
786            // the caller reads next.
787            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        // Create the wakeup before peeking, so a settle racing this loop is
798        // never missed (same pattern as `next_message`).
799        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),
808                    }
809                ),
810            };
811        }
812        if !client.flight_is_open(&hash) {
813            // Closed without a value (reset between fixture cases).
814            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
825/// Extract the `url` from a client-handle `Value` (`Map{"url": ...}`).
826pub fn url_of(client: &Value) -> Option<String> {
827    match crate::get_value(client, &Value::Str("url".to_string())) {
828        Value::Str(s) => Some(s),
829        _ => None,
830    }
831}
832
833fn hash_str(v: &Value) -> Option<String> {
834    match v {
835        Value::Str(s) => Some(s.clone()),
836        _ => None,
837    }
838}
839
840/// `client.resolve(value, messageHash)` routed by URL. Returns `value`.
841pub fn value_resolve(client: &Value, args: &[Value]) -> Value {
842    let value = args.get(0).cloned().unwrap_or(Value::Null);
843    // `client.futures[hash].resolve(value)` — the future handle carries its own
844    // hash, so there is no second arg. Resolve that hash.
845    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
859/// Extract the hash a future handle (`client.futures[hash]`) resolves/rejects.
860fn future_hash_of(client: &Value) -> Option<String> {
861    match crate::get_value(client, &Value::Str("__ws_future_hash".to_string())) {
862        Value::Str(s) => Some(s),
863        _ => None,
864    }
865}
866
867/// `client.reject(error, messageHash)` routed by URL.
868pub fn value_reject(client: &Value, args: &[Value]) -> Value {
869    let err = args.get(0).cloned().unwrap_or(Value::Null);
870    // `client.futures[hash].reject(error)` — future handle carries its own hash.
871    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                // reject with no hash → reject every pending future.
882                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
894/// `client.send(message)` routed by URL. Serialises non-string payloads to JSON.
895pub 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.clone(),
900                Some(v) => v.to_json().to_string(),
901                None => String::new(),
902            };
903            c.send_text(payload);
904        }
905    }
906    Value::Null
907}
908
909/// `client.reset(...)` routed by URL. An arg-less `client.reset()` reaches
910/// here with `Value::Null` — there is no error to deliver, so fall back to
911/// the internal wipe rather than rejecting every waiter with a null error.
912pub 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
925/// `client.on_pong(...)` routed by URL.
926pub 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    // A minimal mock exchange WS server: accepts one connection, waits for a
941    // subscribe frame, then streams a few JSON "ticker" messages. Proves the
942    // full connect → send(subscribe) → receive → parse → resolve round-trip
943    // without touching a live venue.
944    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                // Wait for the client's subscribe frame.
951                if let Some(Ok(WsMessage::Text(sub))) = ws.next().await {
952                    assert!(sub.contains("subscribe"), "expected subscribe, got {sub}");
953                }
954                // Stream three ticker updates.
955                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                // Give the client time to drain before closing.
960                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    // The transpiled `client.reset(error)` path (`value_reset` →
968    // `reset_with_error`): a pending watch hash must observe the error (not
969    // hang), a delivered-but-not-taken value must survive the reset, and an
970    // arg-less `client.reset()` (error = `Value::Null`) must fall back to the
971    // silent wipe instead of rejecting waiters with a null error.
972    #[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".to_string()));
979
980        let handle = client_value(url);
981        let error = Value::Str("[InvalidNonce] gap detected".to_string());
982        value_reset(&handle, error.clone());
983
984        // The pending waiter fails fast with the reset error…
985        assert_eq!(
986            client.take_settled(&["pending".to_string()]),
987            Some(Err(error))
988        );
989        // …while the already-delivered value still reaches its waiter.
990        assert_eq!(
991            client.take_settled(&["delivered".to_string()]),
992            Some(Ok(Value::Str("payload".to_string())))
993        );
994        assert!(!client.has_pending_futures());
995
996        // Arg-less reset: silent wipe, nothing settled with a null error.
997        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        // Send a subscribe frame once (idempotent per hash).
1011        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        // Drive: pull each inbound message, mimic handle_message resolving the
1016        // "ticker" hash, and collect the resolved values.
1017        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".to_string()));
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        // Field snapshots the transpiled code reads off the client handle.
1031        let subs = client.subscriptions_value();
1032        assert!(crate::runtime::is_true(&crate::get_value(
1033            &subs,
1034            &Value::Str("ticker:BTC/USDT".to_string())
1035        )));
1036
1037        drop_client(&url);
1038    }
1039
1040    // A minimal Core whose `handle_message` resolves the "ticker" hash with the
1041    // inbound message's `last` field — exactly what a real venue's
1042    // handle_message does. Lets us drive the *actual* `watch()` runtime end to
1043    // end (connect → subscribe → frame → dispatch_to_derived("handle_message")
1044    // → resolve → return) against the mock server, independent of venue quirks.
1045    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".to_string()));
1072                        // `client.resolve(value, messageHash)` — routes to the registry.
1073                        client.resolve(&[last, Value::Str("ticker".to_string())]);
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        // Drive the real base `watch()`: connect, send subscribe, read frames,
1090        // dispatch each to handle_message, return once "ticker" resolves.
1091        let result = ExchangeRuntime::watch(
1092            &mut core,
1093            Value::Str(url.clone()),
1094            Value::Str("ticker".to_string()),
1095            &[
1096                Value::Str("{\"op\":\"subscribe\",\"channel\":\"ticker\"}".to_string()),
1097                Value::Str("ticker".to_string()),
1098                Value::Null,
1099            ],
1100        )
1101        .await;
1102        // First streamed ticker.
1103        assert_eq!(result, Value::Str("100.5".to_string()));
1104        drop_client(&url);
1105    }
1106
1107    // ── single-flight (client.future / client.reusableFuture) ───────────────
1108    //
1109    // The venue `authenticate` idiom: the first caller leads and fetches the
1110    // credential, concurrent callers join the flight and wake when it settles.
1111    // Regression cover for the port's original no-op `future()` stub, where
1112    // every caller led and nobody waited.
1113
1114    #[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        // The follower's `messageHash in client.futures` test must see it.
1121        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        // Every waiter observes the value — settling must not consume it.
1131        c.resolve("auth", Value::Str("listen-key".to_string()));
1132        assert_eq!(
1133            ws_await_flight(&flight_handle(url, "auth", false)).await,
1134            Value::Str("listen-key".to_string())
1135        );
1136        assert_eq!(
1137            ws_await_flight(&flight_handle(url, "auth", false)).await,
1138            Value::Str("listen-key".to_string())
1139        );
1140        // Settled ⇒ cleared from `futures`, so the next cycle re-leads rather
1141        // than parking every caller on the follower branch forever.
1142        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".to_string()));
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".to_string()));
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        // A venue can take the lead and then find it has nothing to do — bitget
1170        // re-`authenticate`s on an already-subscribed client. Its trailing
1171        // `await future` must return, not wait for a settle that never comes.
1172        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        // Having led once and settled, the value is still there for a re-await.
1183        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        // Never-opened flight: return rather than hang, the value the caller
1196        // wanted is already in the venue's own cache.
1197        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    /// The transpiled follower test, `messageHash in client.futures`.
1204    fn in_op_futures(c: &Arc<ClientState>, hash: &str) -> bool {
1205        !matches!(
1206            crate::get_value(&c.futures_value(), &Value::Str(hash.to_string())),
1207            Value::Null
1208        )
1209    }
1210
1211    #[tokio::test]
1212    async fn parse_helpers() {
1213        // JSON text → dict; non-JSON → Value::Str.
1214        assert!(matches!(parse_text("{\"a\":1}"), Value::Dict(_)));
1215        assert_eq!(parse_text("pong"), Value::Str("pong".to_string()));
1216        // gzip binary → parsed JSON.
1217        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}