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 (TS `client.reset`),
360    /// e.g. after a reconnect so stale hashes don't resolve new waiters.
361    pub fn reset(&self) {
362        self.resolved.lock().unwrap().clear();
363        self.rejections.lock().unwrap().clear();
364        self.subscriptions.lock().unwrap().clear();
365        self.futures.lock().unwrap().clear();
366        self.flights.lock().unwrap().clear();
367    }
368
369    /// Snapshot of `subscriptions` as a `Value::Map { hash: subscription }` —
370    /// the shape the transpiled `get_value(&client, "subscriptions")` reads.
371    /// Tagged with `__ws_subs_url` so that writes performed on the snapshot
372    /// (`client.subscriptions[chanId] = …`, common in bitfinex/chan-id venues)
373    /// route back to this live `ClientState` instead of a discarded clone.
374    pub fn subscriptions_value(&self) -> Value {
375        let subs = self.subscriptions.lock().unwrap();
376        let mut m = indexmap::IndexMap::new();
377        m.insert("__ws_subs_url".to_string(), Value::Str(self.url.clone()));
378        for (h, sub) in subs.iter() {
379            // Tag each subscription DICT with a back-reference so a field write
380            // on it (`subscription['receivedSnapshot'] = true`) persists to this
381            // live client — venues mutate a subscription retrieved from
382            // client.subscriptions and rely on JS object identity.
383            let tagged = match sub {
384                Value::Dict(d) => {
385                    let mut inner = (**d).clone();
386                    inner.insert("__ws_sub_ref".to_string(),
387                        Value::Str(format!("{}\u{1}{}", self.url, h)));
388                    Value::Dict(std::sync::Arc::new(inner))
389                }
390                other => other.clone(),
391            };
392            m.insert(h.clone(), tagged);
393        }
394        Value::Map(m)
395    }
396
397    /// Set a field on a stored subscription dict (`client.subscriptions[hash]
398    /// [key] = val`). Creates the entry if missing.
399    pub fn set_subscription_field(&self, hash: &str, key: &str, val: Value) {
400        let mut subs = self.subscriptions.lock().unwrap();
401        match subs.get_mut(hash) {
402            Some(Value::Dict(d)) => { std::sync::Arc::make_mut(d).insert(key.to_string(), val); }
403            _ => {
404                let mut inner = indexmap::IndexMap::new();
405                inner.insert(key.to_string(), val);
406                subs.insert(hash.to_string(), Value::Dict(std::sync::Arc::new(inner)));
407            }
408        }
409    }
410
411    /// Snapshot of `futures` as a `Value::Map { hash: true }`.
412    pub fn futures_value(&self) -> Value {
413        let f = self.futures.lock().unwrap();
414        let mut m = indexmap::IndexMap::new();
415        for h in f.iter() {
416            // Each entry is a future *handle* carrying the url + its own hash, so
417            // transpiled `client.futures[hash].resolve(x)` (bitget/cryptocom auth)
418            // routes back to this ClientState — see value_resolve/value_reject.
419            let mut fh = indexmap::IndexMap::new();
420            fh.insert("url".to_string(), Value::Str(self.url.clone()));
421            fh.insert("__ws_future_hash".to_string(), Value::Str(h.clone()));
422            m.insert(h.clone(), Value::Map(fh));
423        }
424        Value::Map(m)
425    }
426}
427
428/// Get the existing client for `url`, or `None` if not yet connected.
429pub fn get_client(url: &str) -> Option<Arc<ClientState>> {
430    let reg = REGISTRY.lock().unwrap();
431    reg.get(url).filter(|c| !c.is_closed()).cloned()
432}
433
434/// `client.subscriptions[key] = val` written on a tagged snapshot — persist it
435/// to the live client so subsequent `handle_message` snapshots see it.
436pub fn value_subs_insert(url: &str, key: &str, val: Value) {
437    if let Some(c) = get_client(url) { c.set_subscription(key, val); }
438}
439
440/// `delete client.subscriptions[key]` on a tagged snapshot.
441pub fn value_subs_remove(url: &str, key: &str) {
442    if let Some(c) = get_client(url) { c.subscriptions.lock().unwrap().remove(key); }
443}
444
445/// `client.subscriptions[hash][key] = val` written on a tagged subscription
446/// dict (carrying `__ws_sub_ref` = "url\u{1}hash").
447pub fn value_sub_field_write(subref: &str, key: &str, val: Value) {
448    if let Some((url, hash)) = subref.split_once('\u{1}') {
449        if let Some(c) = get_client(url) { c.set_subscription_field(hash, key, val); }
450    }
451}
452
453/// Ensure a live connection to `url`, connecting (and spawning the reader /
454/// writer / keep-alive tasks) if needed. Idempotent per URL.
455/// Open an HTTP CONNECT tunnel to `proxy` and hand the raw stream to
456/// tungstenite. `connect_async` has no proxy support of its own, so a venue
457/// reached through `wsProxy` / `wssProxy` has to be dialed this way.
458async fn connect_via_proxy(
459    url: &str,
460    proxy: &str,
461) -> Result<tokio_tungstenite::WebSocketStream<
462        tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>, String> {
463    use tokio::io::{AsyncReadExt, AsyncWriteExt};
464    let target = url::Url::parse(url).map_err(|e| format!("[NetworkError] ws url {url}: {e}"))?;
465    let host = target.host_str().ok_or_else(|| format!("[NetworkError] ws url {url} has no host"))?;
466    let port = target.port_or_known_default().unwrap_or(443);
467    let p = url::Url::parse(proxy).map_err(|e| format!("[NetworkError] ws proxy {proxy}: {e}"))?;
468    let p_host = p.host_str().ok_or_else(|| format!("[NetworkError] ws proxy {proxy} has no host"))?;
469    let p_port = p.port_or_known_default().unwrap_or(8080);
470    let mut stream = tokio::net::TcpStream::connect((p_host, p_port))
471        .await
472        .map_err(|e| format!("[NetworkError] ws proxy connect {proxy}: {e}"))?;
473    let connect = format!(
474        "CONNECT {host}:{port} HTTP/1.1\r\nHost: {host}:{port}\r\nProxy-Connection: Keep-Alive\r\n\r\n"
475    );
476    stream
477        .write_all(connect.as_bytes())
478        .await
479        .map_err(|e| format!("[NetworkError] ws proxy CONNECT {proxy}: {e}"))?;
480    let mut head = Vec::new();
481    let mut byte = [0u8; 1];
482    while !head.ends_with(b"\r\n\r\n") {
483        let n = stream
484            .read(&mut byte)
485            .await
486            .map_err(|e| format!("[NetworkError] ws proxy CONNECT {proxy}: {e}"))?;
487        if n == 0 {
488            return Err(format!("[NetworkError] ws proxy {proxy} closed during CONNECT"));
489        }
490        head.push(byte[0]);
491        if head.len() > 8192 {
492            return Err(format!("[NetworkError] ws proxy {proxy} sent an oversized CONNECT reply"));
493        }
494    }
495    let status = String::from_utf8_lossy(&head);
496    let first = status.lines().next().unwrap_or_default();
497    if !first.contains(" 200") {
498        return Err(format!("[NetworkError] ws proxy {proxy} refused CONNECT: {first}"));
499    }
500    let (ws, _resp) = tokio_tungstenite::client_async_tls(url, stream)
501        .await
502        .map_err(|e| format!("[NetworkError] ws connect {url} via {proxy}: {e}"))?;
503    Ok(ws)
504}
505
506pub async fn ensure_client(url: &str, proxy: Option<String>) -> Result<Arc<ClientState>, String> {
507    let state = ensure_slot(url);
508    if *state.connected.lock().unwrap() {
509        return Ok(state);
510    }
511    // Serialize connect; re-check under the gate (another task may have just
512    // connected this slot). Lock via a cloned Arc so `state` stays movable.
513    let gate_holder = state.clone();
514    let _gate = gate_holder.connect_gate.lock().await;
515    if *state.connected.lock().unwrap() {
516        return Ok(state);
517    }
518    let ws = match proxy.as_deref().filter(|p| !p.is_empty()) {
519        Some(p) => connect_via_proxy(url, p).await?,
520        None => {
521            let (ws, _resp) = tokio_tungstenite::connect_async(url)
522                .await
523                .map_err(|e| format!("[NetworkError] ws connect {url}: {e}"))?;
524            ws
525        }
526    };
527    let (mut write, mut read) = ws.split();
528    let mut rx = state.pending_rx.lock().unwrap().take()
529        .ok_or_else(|| format!("[NetworkError] ws {url} slot has no writer channel"))?;
530    *state.last_pong_ms.lock().unwrap() = now_ms();
531
532    // Writer task: drain the outgoing queue to the socket.
533    tokio::spawn(async move {
534        while let Some(msg) = rx.recv().await {
535            if write.send(msg).await.is_err() {
536                break;
537            }
538        }
539        let _ = write.close().await;
540    });
541
542    // Reader task: decode frames → incoming queue.
543    let st = state.clone();
544    tokio::spawn(async move {
545        while let Some(frame) = read.next().await {
546            match frame {
547                Ok(Message::Text(t)) => st.push_incoming(parse_text(&t)),
548                Ok(Message::Binary(b)) => st.push_incoming(parse_binary(&b)),
549                Ok(Message::Pong(_)) => st.on_pong(),
550                // tungstenite answers Ping frames with Pong automatically.
551                Ok(Message::Ping(_)) => {}
552                Ok(Message::Close(_)) | Err(_) => break,
553                _ => {}
554            }
555        }
556        *st.connected.lock().unwrap() = false;
557        *st.closed.lock().unwrap() = true;
558        st.notify.notify_waiters();
559    });
560
561    // Keep-alive: an unsolicited Ping every 30s; the peer's Pong updates
562    // last_pong. (Full miss-count RequestTimeout handling is a later refinement.)
563    let st2 = state.clone();
564    tokio::spawn(async move {
565        let mut iv = tokio::time::interval(std::time::Duration::from_secs(30));
566        iv.tick().await; // first tick fires immediately; skip it
567        loop {
568            iv.tick().await;
569            if st2.is_closed() {
570                break;
571            }
572            if st2.outgoing.send(Message::Ping(Vec::new())).is_err() {
573                break;
574            }
575        }
576    });
577
578    *state.connected.lock().unwrap() = true;
579    Ok(state)
580}
581
582/// Live read of a client handle's `subscriptions` / `futures` field, straight
583/// from the registry so a read after a write (upbit builds its subscribe frame
584/// from subscriptions it just set) is coherent, not a stale embedded snapshot.
585pub fn client_field_live(url: &str, field: &str) -> Value {
586    match get_client(url) {
587        Some(c) if field == "futures" => c.futures_value(),
588        Some(c) => c.subscriptions_value(),
589        None => Value::Map(indexmap::IndexMap::new()),
590    }
591}
592
593/// Get-or-create the registry slot for `url` WITHOUT connecting the socket, so
594/// `client.subscriptions` written before `watch()` connects still persist.
595fn ensure_slot(url: &str) -> Arc<ClientState> {
596    let mut reg = REGISTRY.lock().unwrap();
597    if let Some(c) = reg.get(url) {
598        if !c.is_closed() {
599            return c.clone();
600        }
601    }
602    let (tx, rx) = mpsc::unbounded_channel::<Message>();
603    let state = Arc::new(ClientState {
604        url: url.to_string(),
605        outgoing: tx,
606        pending_rx: Mutex::new(Some(rx)),
607        connect_gate: tokio::sync::Mutex::new(()),
608        incoming: Mutex::new(VecDeque::new()),
609        notify: Notify::new(),
610        resolved: Mutex::new(HashMap::new()),
611        rejections: Mutex::new(HashMap::new()),
612        subscriptions: Mutex::new(HashMap::new()),
613        futures: Mutex::new(HashSet::new()),
614        flights: Mutex::new(HashMap::new()),
615        connected: Mutex::new(false),
616        closed: Mutex::new(false),
617        last_pong_ms: Mutex::new(now_ms()),
618        mock: Mutex::new(false),
619        mock_sent: Mutex::new(Vec::new()),
620        ws_test_completed: Mutex::new(false),
621    });
622    reg.insert(url.to_string(), state.clone());
623    state
624}
625
626/// Remove (and thereby drop / disconnect) the client for `url`.
627pub fn drop_client(url: &str) {
628    REGISTRY.lock().unwrap().remove(url);
629}
630
631// ── `Value`-handle bridge ────────────────────────────────────────────────────
632//
633// The transpiled `handle_message(&mut self, client: Value, message: Value)`
634// receives a *client* as a `Value`. We model it as `Value::Map { "url": <url>,
635// "subscriptions": <snapshot>, "futures": <snapshot> }`. The `Value` methods
636// `resolve`/`reject`/`send`/… (in value.rs) extract `url` and route here.
637
638// ── Static-WS-test mock transport (url-keyed façade over ClientState) ────────
639
640/// `setupWsMockTransport(url)` — register a connected, socket-less client whose
641/// sends are captured. Clears any prior state so each fixture starts fresh.
642pub fn mock_setup(url: &str) {
643    let c = ensure_slot(url);
644    c.reset();
645    c.mock_enable();
646    c.mock_sent.lock().unwrap().clear();
647    // Discard any messages left unconsumed by a prior test on the same URL (e.g.
648    // a heartbeat a watchTrades drive loop returned past before reading) so they
649    // don't leak an extra handler dispatch / sent frame into the next test.
650    c.incoming.lock().unwrap().clear();
651    *c.ws_test_completed.lock().unwrap() = false;
652}
653pub fn mock_inject(url: &str, msg: Value) {
654    if let Some(c) = get_client(url) { c.mock_inject(msg); }
655}
656pub fn mock_sent_messages(url: &str) -> Value {
657    match get_client(url) { Some(c) => c.mock_sent_value(), None => Value::Array(vec![]) }
658}
659pub fn mock_has_pending_futures(url: &str) -> bool {
660    get_client(url).map(|c| c.has_pending_futures()).unwrap_or(false)
661}
662pub fn mock_has_queued_messages(url: &str) -> bool {
663    get_client(url).map(|c| c.has_queued_messages()).unwrap_or(false)
664}
665pub fn mock_mark_completed(url: &str) {
666    if let Some(c) = get_client(url) { c.mark_ws_test_completed(); }
667}
668pub fn mock_is_completed(url: &str) -> bool {
669    get_client(url).map(|c| c.is_ws_test_completed()).unwrap_or(true)
670}
671pub fn mock_reject_futures(url: &str) {
672    if let Some(c) = get_client(url) {
673        c.reject_pending_futures(Value::Str(
674            "[ExchangeError] static ws test: the injected messages did not resolve the watch future".to_string()));
675    }
676}
677
678/// Build the client-handle `Value` passed to `handle_message`: the URL plus
679/// live snapshots of `subscriptions` / `futures` (the fields venues read via
680/// `get_value(&client, "subscriptions")`).
681pub fn client_value(url: &str) -> Value {
682    // Pre-register the slot so subscriptions written on this handle (before the
683    // socket connects) persist and read back — upbit-style subscribe building.
684    let c = ensure_slot(url);
685    let mut m = indexmap::IndexMap::new();
686    m.insert("url".to_string(), Value::Str(url.to_string()));
687    m.insert("subscriptions".to_string(), c.subscriptions_value());
688    m.insert("futures".to_string(), c.futures_value());
689    Value::Map(m)
690}
691
692/// Open-or-join the single-flight for `hash` on `url`, creating the registry
693/// slot if the client has not been dialed yet (venue `authenticate` parks its
694/// flights on a never-dialed pseudo-url, because the real user-data url embeds
695/// the credential the flight is fetching).
696pub fn begin_flight(url: &str, hash: &str) -> bool {
697    ensure_slot(url).flight_begin(hash)
698}
699
700
701/// The `Value` a `client.future ()` / `client.reusableFuture ()` call hands
702/// back: enough to find the flight again (its client's url + the hash). TS
703/// returns a real Future object; a `Value` can't hold one, so the port returns
704/// a handle and `ws_await_flight` does the awaiting.
705pub fn flight_handle(url: &str, hash: &str, led: bool) -> Value {
706    let mut m = indexmap::IndexMap::new();
707    m.insert("url".to_string(), Value::Str(url.to_string()));
708    m.insert("__ws_flight_hash".to_string(), Value::Str(hash.to_string()));
709    // Whether the call that produced this handle opened the flight. A leader
710    // settles its own flight (and TS's `await future` resolves the instant it
711    // does), so it must never block on itself — including when the venue
712    // decides, after taking the lead, that there is no work to do because it
713    // is already subscribed (bitget's `authenticate`).
714    m.insert("__ws_flight_led".to_string(), Value::Bool(led));
715    Value::Map(m)
716}
717
718/// The hash a flight handle refers to. Accepts the `futures_value ()` handle
719/// shape too, so `client.futures[hash]` entries can be awaited as well.
720fn flight_hash_of(handle: &Value) -> Option<String> {
721    for key in ["__ws_flight_hash", "__ws_future_hash"] {
722        if let Value::Str(h) = crate::get_value(handle, &Value::Str(key.to_string())) {
723            return Some(h);
724        }
725    }
726    None
727}
728
729/// Await a flight handle — the port of TS's `await client.future (hash)` and
730/// of the trailing `await future` a single-flight leader runs after settling.
731///
732/// Returns the resolved value; a rejected flight panics with the error, which
733/// is how the port rethrows (the drive loop does the same with `take_settled`).
734/// A handle that names no flight returns `Value::Null` rather than hanging.
735pub async fn ws_await_flight(handle: &Value) -> Value {
736    let (url, hash) = match (url_of(handle), flight_hash_of(handle)) {
737        (Some(u), Some(h)) => (u, h),
738        _ => return Value::Null,
739    };
740    let client = match get_client(&url) {
741        Some(c) => c,
742        None => return Value::Null,
743    };
744    let settled = client.flight_peek(&hash);
745    // The leader: its own `client.resolve ()` has already run by the time it
746    // reaches its trailing await, so take the value and go. Waiting here would
747    // deadlock the (common) case where the venue took the lead and then found
748    // it had nothing to do.
749    let led = matches!(
750        crate::get_value(handle, &Value::Str("__ws_flight_led".to_string())),
751        Value::Bool(true)
752    );
753    if led || !client.flight_is_open(&hash) {
754        return match settled {
755            Some(Ok(v)) => v,
756            Some(Err(e)) => panic!(
757                "{}",
758                match &e {
759                    Value::Str(s) => s.clone(),
760                    v => crate::runtime::stringify_param(v),
761                }
762            ),
763            // A flight that never opened is not an error — the value it would
764            // have carried is already in the venue's own cache, which is what
765            // the caller reads next.
766            None => Value::Null,
767        };
768    }
769    let budget = if client.is_mock() {
770        std::time::Duration::from_millis(1500)
771    } else {
772        std::time::Duration::from_secs(60)
773    };
774    let deadline = tokio::time::Instant::now() + budget;
775    loop {
776        // Create the wakeup before peeking, so a settle racing this loop is
777        // never missed (same pattern as `next_message`).
778        let notified = client.notify.notified();
779        if let Some(res) = client.flight_peek(&hash) {
780            return match res {
781                Ok(v) => v,
782                Err(e) => panic!(
783                    "{}",
784                    match &e {
785                        Value::Str(s) => s.clone(),
786                        v => crate::runtime::stringify_param(v),
787                    }
788                ),
789            };
790        }
791        if !client.flight_is_open(&hash) {
792            // Closed without a value (reset between fixture cases).
793            return Value::Null;
794        }
795        if tokio::time::timeout_at(deadline, notified).await.is_err() {
796            panic!(
797                "[NetworkError] timed out waiting for the in-flight '{}' on {}",
798                hash, url
799            );
800        }
801    }
802}
803
804/// Extract the `url` from a client-handle `Value` (`Map{"url": ...}`).
805pub fn url_of(client: &Value) -> Option<String> {
806    match crate::get_value(client, &Value::Str("url".to_string())) {
807        Value::Str(s) => Some(s),
808        _ => None,
809    }
810}
811
812fn hash_str(v: &Value) -> Option<String> {
813    match v {
814        Value::Str(s) => Some(s.clone()),
815        _ => None,
816    }
817}
818
819/// `client.resolve(value, messageHash)` routed by URL. Returns `value`.
820pub fn value_resolve(client: &Value, args: &[Value]) -> Value {
821    let value = args.get(0).cloned().unwrap_or(Value::Null);
822    // `client.futures[hash].resolve(value)` — the future handle carries its own
823    // hash, so there is no second arg. Resolve that hash.
824    if let Some(hash) = future_hash_of(client) {
825        if let Some(url) = url_of(client) {
826            if let Some(c) = get_client(&url) { c.resolve(&hash, value.clone()); }
827        }
828        return value;
829    }
830    if let (Some(url), Some(hash)) = (url_of(client), args.get(1).and_then(hash_str)) {
831        if let Some(c) = get_client(&url) {
832            c.resolve(&hash, value.clone());
833        }
834    }
835    value
836}
837
838/// Extract the hash a future handle (`client.futures[hash]`) resolves/rejects.
839fn future_hash_of(client: &Value) -> Option<String> {
840    match crate::get_value(client, &Value::Str("__ws_future_hash".to_string())) {
841        Value::Str(s) => Some(s),
842        _ => None,
843    }
844}
845
846/// `client.reject(error, messageHash)` routed by URL.
847pub fn value_reject(client: &Value, args: &[Value]) -> Value {
848    let err = args.get(0).cloned().unwrap_or(Value::Null);
849    // `client.futures[hash].reject(error)` — future handle carries its own hash.
850    if let Some(hash) = future_hash_of(client) {
851        if let Some(url) = url_of(client) {
852            if let Some(c) = get_client(&url) { c.reject(&hash, err.clone()); }
853        }
854        return err;
855    }
856    if let Some(url) = url_of(client) {
857        if let Some(c) = get_client(&url) {
858            match args.get(1).and_then(hash_str) {
859                Some(hash) => c.reject(&hash, err.clone()),
860                // reject with no hash → reject every pending future.
861                None => {
862                    let hashes: Vec<String> = c.futures.lock().unwrap().iter().cloned().collect();
863                    for h in hashes {
864                        c.reject(&h, err.clone());
865                    }
866                }
867            }
868        }
869    }
870    err
871}
872
873/// `client.send(message)` routed by URL. Serialises non-string payloads to JSON.
874pub fn value_send(client: &Value, args: &[Value]) -> Value {
875    if let Some(url) = url_of(client) {
876        if let Some(c) = get_client(&url) {
877            let payload = match args.get(0) {
878                Some(Value::Str(s)) => s.clone(),
879                Some(v) => v.to_json().to_string(),
880                None => String::new(),
881            };
882            c.send_text(payload);
883        }
884    }
885    Value::Null
886}
887
888/// `client.reset(...)` routed by URL.
889pub fn value_reset(client: &Value) -> Value {
890    if let Some(url) = url_of(client) {
891        if let Some(c) = get_client(&url) {
892            c.reset();
893        }
894    }
895    Value::Null
896}
897
898/// `client.on_pong(...)` routed by URL.
899pub fn value_on_pong(client: &Value) -> Value {
900    if let Some(url) = url_of(client) {
901        if let Some(c) = get_client(&url) {
902            c.on_pong();
903        }
904    }
905    Value::Null
906}
907
908#[cfg(test)]
909mod tests {
910    use super::*;
911    use tokio_tungstenite::tungstenite::Message as WsMessage;
912
913    // A minimal mock exchange WS server: accepts one connection, waits for a
914    // subscribe frame, then streams a few JSON "ticker" messages. Proves the
915    // full connect → send(subscribe) → receive → parse → resolve round-trip
916    // without touching a live venue.
917    async fn spawn_mock_server() -> String {
918        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
919        let addr = listener.local_addr().unwrap();
920        tokio::spawn(async move {
921            if let Ok((stream, _)) = listener.accept().await {
922                let mut ws = tokio_tungstenite::accept_async(stream).await.unwrap();
923                // Wait for the client's subscribe frame.
924                if let Some(Ok(WsMessage::Text(sub))) = ws.next().await {
925                    assert!(sub.contains("subscribe"), "expected subscribe, got {sub}");
926                }
927                // Stream three ticker updates.
928                for px in ["100.5", "101.0", "101.5"] {
929                    let msg = format!("{{\"channel\":\"ticker\",\"symbol\":\"BTC/USDT\",\"last\":\"{px}\"}}");
930                    ws.send(WsMessage::Text(msg)).await.unwrap();
931                }
932                // Give the client time to drain before closing.
933                tokio::time::sleep(std::time::Duration::from_millis(50)).await;
934                let _ = ws.close(None).await;
935            }
936        });
937        format!("ws://{addr}")
938    }
939
940    #[tokio::test]
941    async fn transport_roundtrip() {
942        let url = spawn_mock_server().await;
943        let client = ensure_client(&url, None).await.expect("connect");
944
945        // Send a subscribe frame once (idempotent per hash).
946        assert!(client.subscribe_once("ticker:BTC/USDT", Value::Null));
947        assert!(!client.subscribe_once("ticker:BTC/USDT", Value::Null));
948        assert!(client.send_text("{\"op\":\"subscribe\",\"channel\":\"ticker\"}".to_string()));
949
950        // Drive: pull each inbound message, mimic handle_message resolving the
951        // "ticker" hash, and collect the resolved values.
952        let mut lasts = Vec::new();
953        while lasts.len() < 3 {
954            let msg = client.next_message().await.expect("message before close");
955            let last = crate::get_value(&msg, &Value::Str("last".to_string()));
956            if let Value::Str(s) = &last {
957                client.resolve("ticker", Value::Str(s.clone()));
958            }
959            if let Some(Ok(Value::Str(v))) = client.take_settled(&["ticker".to_string()]) {
960                lasts.push(v);
961            }
962        }
963        assert_eq!(lasts, vec!["100.5", "101.0", "101.5"]);
964
965        // Field snapshots the transpiled code reads off the client handle.
966        let subs = client.subscriptions_value();
967        assert!(crate::runtime::is_true(&crate::get_value(
968            &subs,
969            &Value::Str("ticker:BTC/USDT".to_string())
970        )));
971
972        drop_client(&url);
973    }
974
975    // A minimal Core whose `handle_message` resolves the "ticker" hash with the
976    // inbound message's `last` field — exactly what a real venue's
977    // handle_message does. Lets us drive the *actual* `watch()` runtime end to
978    // end (connect → subscribe → frame → dispatch_to_derived("handle_message")
979    // → resolve → return) against the mock server, independent of venue quirks.
980    struct TestWsCore {
981        exchange: crate::exchange::Exchange,
982    }
983    impl std::ops::Deref for TestWsCore {
984        type Target = crate::exchange::Exchange;
985        fn deref(&self) -> &Self::Target {
986            &self.exchange
987        }
988    }
989    impl std::ops::DerefMut for TestWsCore {
990        fn deref_mut(&mut self) -> &mut Self::Target {
991            &mut self.exchange
992        }
993    }
994    impl crate::exchange::DerivedExchange for TestWsCore {}
995    impl crate::exchange_generated::ExchangeBase for TestWsCore {
996        fn call_dynamic<'a>(
997            &'a mut self,
998            method: &'a str,
999            args: Vec<Value>,
1000        ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Value> + Send + 'a>> {
1001            Box::pin(async move {
1002                match method {
1003                    "handle_message" => {
1004                        let client = args.get(0).cloned().unwrap_or(Value::Null);
1005                        let message = args.get(1).cloned().unwrap_or(Value::Null);
1006                        let last = crate::get_value(&message, &Value::Str("last".to_string()));
1007                        // `client.resolve(value, messageHash)` — routes to the registry.
1008                        client.resolve(&[last, Value::Str("ticker".to_string())]);
1009                        Value::Null
1010                    }
1011                    _ => self.call_dynamic_base(method, args).await,
1012                }
1013            })
1014        }
1015    }
1016
1017    #[tokio::test]
1018    async fn watch_drive_loop_end_to_end() {
1019        use crate::exchange::ExchangeRuntime;
1020        let url = spawn_mock_server().await;
1021        let mut core = TestWsCore {
1022            exchange: crate::exchange::Exchange::new(None),
1023        };
1024        // Drive the real base `watch()`: connect, send subscribe, read frames,
1025        // dispatch each to handle_message, return once "ticker" resolves.
1026        let result = ExchangeRuntime::watch(
1027            &mut core,
1028            Value::Str(url.clone()),
1029            Value::Str("ticker".to_string()),
1030            &[
1031                Value::Str("{\"op\":\"subscribe\",\"channel\":\"ticker\"}".to_string()),
1032                Value::Str("ticker".to_string()),
1033                Value::Null,
1034            ],
1035        )
1036        .await;
1037        // First streamed ticker.
1038        assert_eq!(result, Value::Str("100.5".to_string()));
1039        drop_client(&url);
1040    }
1041
1042    // ── single-flight (client.future / client.reusableFuture) ───────────────
1043    //
1044    // The venue `authenticate` idiom: the first caller leads and fetches the
1045    // credential, concurrent callers join the flight and wake when it settles.
1046    // Regression cover for the port's original no-op `future()` stub, where
1047    // every caller led and nobody waited.
1048
1049    #[tokio::test]
1050    async fn flight_elects_one_leader_and_registers_it() {
1051        let url = "flight-test-election";
1052        let c = ensure_slot(url);
1053        assert!(c.flight_begin("authenticate:future"), "first caller leads");
1054        assert!(!c.flight_begin("authenticate:future"), "second caller follows");
1055        // The follower's `messageHash in client.futures` test must see it.
1056        assert!(in_op_futures(&c, "authenticate:future"));
1057        drop_client(url);
1058    }
1059
1060    #[tokio::test]
1061    async fn flight_settle_wakes_waiters_and_reopens() {
1062        let url = "flight-test-settle";
1063        let c = ensure_slot(url);
1064        assert!(c.flight_begin("auth"));
1065        // Every waiter observes the value — settling must not consume it.
1066        c.resolve("auth", Value::Str("listen-key".to_string()));
1067        assert_eq!(
1068            ws_await_flight(&flight_handle(url, "auth", false)).await,
1069            Value::Str("listen-key".to_string())
1070        );
1071        assert_eq!(
1072            ws_await_flight(&flight_handle(url, "auth", false)).await,
1073            Value::Str("listen-key".to_string())
1074        );
1075        // Settled ⇒ cleared from `futures`, so the next cycle re-leads rather
1076        // than parking every caller on the follower branch forever.
1077        assert!(!in_op_futures(&c, "auth"));
1078        assert!(c.flight_begin("auth"), "a settled flight re-elects");
1079        drop_client(url);
1080    }
1081
1082    #[tokio::test]
1083    async fn flight_follower_waits_for_the_leader() {
1084        let url = "flight-test-wait";
1085        let c = ensure_slot(url);
1086        assert!(c.flight_begin("auth"));
1087        let settler = {
1088            let c = c.clone();
1089            tokio::spawn(async move {
1090                tokio::time::sleep(std::time::Duration::from_millis(60)).await;
1091                c.resolve("auth", Value::Str("late".to_string()));
1092            })
1093        };
1094        let started = std::time::Instant::now();
1095        let got = ws_await_flight(&flight_handle(url, "auth", false)).await;
1096        assert_eq!(got, Value::Str("late".to_string()));
1097        assert!(started.elapsed() >= std::time::Duration::from_millis(50), "waited for the leader");
1098        settler.await.unwrap();
1099        drop_client(url);
1100    }
1101
1102    #[tokio::test]
1103    async fn a_leader_never_blocks_on_its_own_flight() {
1104        // A venue can take the lead and then find it has nothing to do — bitget
1105        // re-`authenticate`s on an already-subscribed client. Its trailing
1106        // `await future` must return, not wait for a settle that never comes.
1107        let url = "flight-test-leader";
1108        let c = ensure_slot(url);
1109        let led = c.flight_begin("authenticated");
1110        assert!(led);
1111        let started = std::time::Instant::now();
1112        assert_eq!(
1113            ws_await_flight(&flight_handle(url, "authenticated", led)).await,
1114            Value::Null
1115        );
1116        assert!(started.elapsed() < std::time::Duration::from_millis(200), "returned at once");
1117        // Having led once and settled, the value is still there for a re-await.
1118        c.resolve("authenticated", Value::Bool(true));
1119        let led2 = c.flight_begin("authenticated");
1120        assert_eq!(
1121            ws_await_flight(&flight_handle(url, "authenticated", led2)).await,
1122            Value::Bool(true),
1123            "a re-lead with no new work reports the last value"
1124        );
1125        drop_client(url);
1126    }
1127
1128    #[tokio::test]
1129    async fn flight_handle_without_a_flight_returns_null() {
1130        // Never-opened flight: return rather than hang, the value the caller
1131        // wanted is already in the venue's own cache.
1132        let url = "flight-test-missing";
1133        ensure_slot(url);
1134        assert_eq!(ws_await_flight(&flight_handle(url, "nope", false)).await, Value::Null);
1135        drop_client(url);
1136    }
1137
1138    /// The transpiled follower test, `messageHash in client.futures`.
1139    fn in_op_futures(c: &Arc<ClientState>, hash: &str) -> bool {
1140        !matches!(
1141            crate::get_value(&c.futures_value(), &Value::Str(hash.to_string())),
1142            Value::Null
1143        )
1144    }
1145
1146    #[tokio::test]
1147    async fn parse_helpers() {
1148        // JSON text → dict; non-JSON → Value::Str.
1149        assert!(matches!(parse_text("{\"a\":1}"), Value::Dict(_)));
1150        assert_eq!(parse_text("pong"), Value::Str("pong".to_string()));
1151        // gzip binary → parsed JSON.
1152        use std::io::Write;
1153        let mut e = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
1154        e.write_all(b"{\"x\":true}").unwrap();
1155        let gz = e.finish().unwrap();
1156        assert!(matches!(parse_binary(&gz), Value::Dict(_)));
1157    }
1158}