Skip to main content

ccxt_common/
value.rs

1// Native Rust – hand-written Value type.
2//
3// The ast-transpiler emits `Value::Map(...)`, `Value::Str(...)`, etc.
4// This module defines those variants so generated code compiles without
5// requiring serde_json macros in every file.
6//
7// At the HTTP boundary (exchange.rs) we convert between Value and
8// serde_json::Value for serialisation / deserialisation.
9
10// Value::Map uses `IndexMap` (re-exported here as `HashMap` so the rest
11// of the codebase — including transpiler-emitted `std::collections::
12// HashMap::new()` calls swapped to `indexmap::IndexMap::new()` by a
13// post-pass — keeps building literals via the same API). Insertion
14// order matters for JSON / URL-encoded payloads: exchanges like bingx /
15// digifinex / mexc reject (and the static request fixtures assert)
16// specific key orders such as `{symbol,type,side,quantity,price}`.
17pub use indexmap::IndexMap as HashMap;
18use std::borrow::Cow;
19use std::sync::Arc;
20#[cfg(feature = "engine")]
21use crate::exchange_generated::ExchangeBase;
22
23/// A dynamic value type that mirrors the CCXT JavaScript Value semantics.
24///
25/// `Dict`/`Arr` hold their containers behind an `Arc` so that `clone()` is
26/// an O(1) refcount bump instead of a deep copy — the transpiled parsers
27/// and the static-test assertions clone Values pervasively (every
28/// `safeString`/`safeNumber`, every recursion level), which dominated
29/// runtime. Mutation goes through `Arc::make_mut` (copy-on-write): it
30/// only deep-copies when the container is actually shared.
31///
32/// NOTE: the variants are named `Dict`/`Arr`, but construction uses the
33/// associated functions `Value::Map(..)` / `Value::Array(..)` /
34/// `Value::List(..)` (which wrap the `Arc`) so the ~18k transpiler-emitted
35/// `Value::Map({..})` / `Value::List(vec![..])` call sites need no change.
36/// Pattern matches use `Value::Dict(..)` / `Value::Arr(..)`.
37/// `Str` holds a `Cow<'static, str>`: transpiler-emitted string literals
38/// borrow their `&'static str` (`Value::Str("lit".into())`, zero allocation)
39/// while runtime-built strings stay owned. `clone()` on a borrowed literal
40/// is a pointer copy.
41#[derive(Debug, Clone, PartialEq)]
42pub enum Value {
43    Null,
44    Bool(bool),
45    Int(i64),
46    Float(f64),
47    Str(Cow<'static, str>),
48    Dict(Arc<HashMap<String, Value>>),
49    Arr(Arc<Vec<Value>>),
50}
51
52impl Default for Value {
53    fn default() -> Self {
54        Value::Null
55    }
56}
57
58impl Value {
59    /// Mirrors TS `Precise.reduce()`: when this Value is a
60    /// `Precise::new(...)` Map (carries the `__precise` marker), strip
61    /// trailing zeros from `integer` and bump `decimals` down to match.
62    /// Used by phemex's `to_en` after it shifts `decimals` by the
63    /// market's `valueScale`: subtracts decimals, then reduce balances
64    /// the integer side so the final `stringify_param` renders the
65    /// scaled integer correctly (`0.1` × 10^8 → `10000000`).
66    pub fn reduce(&mut self) {
67        let m = match self { Value::Dict(m) if m.contains_key("__precise") => Arc::make_mut(m), _ => return };
68        let mut decimals: i64 = match m.get("decimals") {
69            Some(Value::Int(n)) => *n,
70            _ => return,
71        };
72        let mut integer: String = match m.get("integer") {
73            Some(Value::Str(s)) => s.to_string(),
74            _ => return,
75        };
76        // Negative decimals → pad zeros onto the integer.
77        if decimals < 0 {
78            // careful: a leading '-' (negative number) stays at the front.
79            let (sign, digits) = if let Some(rest) = integer.strip_prefix('-') {
80                ("-", rest.to_string())
81            } else { ("", integer.clone()) };
82            let padded = format!("{digits}{:0<width$}", "", width = (-decimals) as usize);
83            integer = format!("{sign}{padded}");
84            decimals = 0;
85        }
86        // Trim trailing zeros while there are decimal places to consume.
87        while decimals > 0 && integer.ends_with('0') && integer.len() > 1 {
88            integer.pop();
89            decimals -= 1;
90        }
91        m.insert("integer".to_string(),  Value::Str(Cow::Owned(integer)));
92        m.insert("decimals".to_string(), Value::Int(decimals));
93    }
94
95    /// `append(item)` on an Array — pushes the item. Mirrors TS
96    /// `array.push` shape (single arg, no return).
97    ///
98    /// On a WS-cache Map (carrying a `__cacheKind` marker; see
99    /// `crate::pro::cache`) it dispatches to the per-kind logic below.
100    pub fn append(&mut self, item: Value) {
101        match self {
102            Value::Arr(a) => Arc::make_mut(a).push(item),
103            Value::Dict(m) if m.contains_key("__cacheKind") => {
104                cache_append(self, item);
105            }
106            _ => {}
107        }
108    }
109
110    /// `clear()` — resets the rolling buffer for a cache marker (or
111    /// truncates the inner array of an `Arr` value).
112    pub fn clear(&mut self) {
113        match self {
114            Value::Arr(a) => Arc::make_mut(a).clear(),
115            Value::Dict(m) if m.contains_key("__cacheKind") => {
116                if let Some(id) = cache_id_of_m(m) {
117                    with_cache_cell(id, |c| {
118                        if let Some(Value::Arr(data)) = c.get_mut("_data") { Arc::make_mut(data).clear(); }
119                        cache_reset_bookkeeping(c);
120                    });
121                } else {
122                    let m = Arc::make_mut(m);
123                    if let Some(Value::Arr(data)) = m.get_mut("_data") {
124                        Arc::make_mut(data).clear();
125                    }
126                    cache_reset_bookkeeping(m);
127                }
128            }
129            _ => {}
130        }
131    }
132
133    /// `getLimit(symbol, limit)` for the cache markers. Returns the
134    /// count of new updates since the last call (clamped by `limit`
135    /// when supplied) and arms the per-symbol / global reset flag so
136    /// the next `append` zeroes the counter.
137    pub fn get_limit(&mut self, symbol: Value, limit: Value) -> Value {
138        if matches!(self, Value::Dict(d) if d.contains_key("__cacheKind")) {
139            cache_get_limit(self, symbol, limit)
140        } else {
141            limit
142        }
143    }
144
145    /// Constructor named to match the ast-transpiler's emission shape:
146    /// `Value::List(vec![...])`. Aliases `Value::Array`. Note that this
147    /// is a function, not a variant — so pattern matches still use
148    /// `Value::Array(_)`, not `Value::List(_)`.
149    #[allow(non_snake_case)]
150    pub fn List(items: Vec<Value>) -> Value {
151        Value::Arr(Arc::new(items))
152    }
153
154    /// Construction shim — the transpiler emits `Value::Map({..IndexMap..})`
155    /// in ~18k places; this wraps the map in the `Arc` the `Dict` variant
156    /// now holds. (An associated fn, not a variant — patterns use `Dict`.)
157    #[allow(non_snake_case)]
158    pub fn Map(m: HashMap<String, Value>) -> Value {
159        Value::Dict(Arc::new(m))
160    }
161
162    /// Construction shim for `Value::Array(vec)` call sites.
163    #[allow(non_snake_case)]
164    pub fn Array(a: Vec<Value>) -> Value {
165        Value::Arr(Arc::new(a))
166    }
167
168    // ── constructors ──────────────────────────────────────────────────────────
169
170    pub fn str(s: impl Into<String>) -> Self {
171        Value::Str(Cow::Owned(s.into()))
172    }
173
174    pub fn int(n: i64) -> Self {
175        Value::Int(n)
176    }
177
178    pub fn float(f: f64) -> Self {
179        Value::Float(f)
180    }
181
182    pub fn bool(b: bool) -> Self {
183        Value::Bool(b)
184    }
185
186    pub fn map(m: HashMap<String, Value>) -> Self {
187        Value::Map(m)
188    }
189
190    pub fn array(a: Vec<Value>) -> Self {
191        Value::Array(a)
192    }
193
194    // ── type checks ───────────────────────────────────────────────────────────
195
196    pub fn is_null(&self)   -> bool { matches!(self, Value::Null) }
197    pub fn is_str(&self)    -> bool { matches!(self, Value::Str(_)) }
198    pub fn is_int(&self)    -> bool { matches!(self, Value::Int(_)) }
199    pub fn is_float(&self)  -> bool { matches!(self, Value::Float(_)) }
200    pub fn is_number(&self) -> bool { matches!(self, Value::Int(_) | Value::Float(_)) }
201    pub fn is_bool(&self)   -> bool { matches!(self, Value::Bool(_)) }
202    pub fn is_map(&self)    -> bool { matches!(self, Value::Dict(_)) }
203    pub fn is_array(&self)  -> bool { matches!(self, Value::Arr(_)) }
204    pub fn is_truthy(&self) -> bool {
205        match self {
206            Value::Null       => false,
207            Value::Bool(b)    => *b,
208            Value::Int(n)     => *n != 0,
209            Value::Float(f)   => *f != 0.0,
210            Value::Str(s)     => !s.is_empty(),
211            Value::Dict(m)    => !m.is_empty(),
212            Value::Arr(a)     => !a.is_empty(),
213        }
214    }
215
216    // ── accessors ─────────────────────────────────────────────────────────────
217
218    pub fn as_str(&self)   -> Option<&str>  { if let Value::Str(s) = self { Some(s.as_ref()) } else { None } }
219    pub fn as_i64(&self)   -> Option<i64>   { if let Value::Int(n) = self { Some(*n) } else { None } }
220    pub fn as_f64(&self)   -> Option<f64> {
221        match self {
222            Value::Float(f) => Some(*f),
223            Value::Int(n)   => Some(*n as f64),
224            _               => None,
225        }
226    }
227    pub fn as_bool(&self)  -> Option<bool>  { if let Value::Bool(b) = self { Some(*b) } else { None } }
228    pub fn as_map(&self)   -> Option<&HashMap<String, Value>> {
229        if let Value::Dict(m) = self { Some(&**m) } else { None }
230    }
231    pub fn as_array(&self) -> Option<&Vec<Value>> {
232        if let Value::Arr(a) = self { Some(&**a) } else { None }
233    }
234    /// Display text of each array element (empty for a non-array); the `Vec<String>` dispatch bridge.
235    pub fn to_str_vec(&self) -> Vec<String> {
236        match self {
237            Value::Arr(a) => a.iter().map(Value::to_string).collect(),
238            _ => Vec::new(),
239        }
240    }
241
242    /// Length of array, map, or string; 0 for everything else.
243    /// String length counts Unicode chars (matches TS `String#length`
244    /// closely enough for ASCII-only API addresses/identifiers).
245    pub fn len(&self) -> usize {
246        match self {
247            Value::Arr(a)   => a.len(),
248            // Cache handles (a book's `cache`, ArrayCache markers) are one-key
249            // marker dicts whose `.length` means the backing store. The checker
250            // lowers `typedBook.cache.length` to a bare `len()`, so unwrap here
251            // exactly as `get_array_length` does.
252            Value::Dict(m)  => book_cache_len_of(m).or_else(|| cache_len_of_marker(m)).unwrap_or(m.len()),
253            Value::Str(s)   => s.chars().count(),
254            _               => 0,
255        }
256    }
257
258    pub fn is_empty(&self) -> bool { self.len() == 0 }
259
260    // ── duck-typed method stubs that transpiled code calls on a Value ────
261    // These exist so transpiled code that calls methods on Value-typed
262    // locals (e.g. `parentRestInstance.describe()`) compiles. They return
263    // `Value::Null` and are placeholders for richer dispatch.
264
265    pub fn describe(&self) -> Value { Value::Null }
266    /// `client.url` on a ws client handle (`Value::Null` on any other Value).
267    pub fn url(&self) -> Value { get_value_k(self, "url") }
268    /// `client.reject(error, messageHash)` — stores a rejection the `watch`
269    /// drive loop delivers to the awaiting caller. Routes by the client
270    /// handle's `url` to the WS registry (no-op on a non-client Value).
271    pub fn reject(&self, args: &[Value]) -> Value {
272        crate::pro::ws_client::value_reject(self, args)
273    }
274    /// `client.resolve(value, messageHash)` — stores the resolved value the
275    /// `watch` drive loop returns. Routes by the client handle's `url`.
276    pub fn resolve(&self, args: &[Value]) -> Value {
277        crate::pro::ws_client::value_resolve(self, args)
278    }
279    /// `client.future(messageHash)` — TS's atomic check-and-insert: opens a
280    /// single-flight for the hash (or joins the open one) and hands back a
281    /// handle. Registering is the whole point — it is what makes a concurrent
282    /// caller's `messageHash in client.futures` test true, so only one of them
283    /// does the work (venue `authenticate` leader election). Await the handle
284    /// with `exchange_stubs::ws_await_flight`; the transpiler emits that
285    /// wherever the TS source awaits.
286    pub fn future(&self, args: &[Value]) -> Value {
287        self.open_flight(args.get(0).cloned().unwrap_or(Value::Null))
288    }
289    /// `client.reusable_future(messageHash)` — shared flight per hash, i.e. the
290    /// same registry and handle as `future`.
291    pub fn reusable_future(&self, msg_hash: Value) -> Value {
292        self.open_flight(msg_hash)
293    }
294    /// Shared body of `future` / `reusable_future`: open-or-join the flight on
295    /// the client this handle names, and return a handle to it. A non-client
296    /// receiver (or a non-string hash) degrades to the old pass-the-hash-back
297    /// behaviour so unrelated transpiled code keeps compiling.
298    fn open_flight(&self, msg_hash: Value) -> Value {
299        let hash = match &msg_hash {
300            Value::Str(h) => h.clone(),
301            _ => return msg_hash,
302        };
303        match crate::pro::ws_client::url_of(self) {
304            Some(url) => {
305                let led = crate::pro::ws_client::begin_flight(&url, &hash);
306                crate::pro::ws_client::flight_handle(&url, &hash, led)
307            }
308            None => msg_hash,
309        }
310    }
311    /// Field accessor: `cache.hashmap` — same as the WS Cache marker's
312    /// hashmap sub-dict. Some transpiled WS code reads this directly
313    /// via the JS field-access syntax rather than going through
314    /// `get_value`.
315    pub fn hashmap(&self) -> Value {
316        if let Value::Dict(d) = self {
317            // Cache marker: the live hashmap lives in the shared WS state store
318            // (keyed by __cache_id), not on the marker Dict. Return a copy with
319            // each symbol bucket tagged with a `__cache_backref` so that a
320            // transpiled write-back like `cache.hashmap[symbol][id] = order`
321            // (the JS reference write) persists through to the store — see
322            // try_cache_hashmap_write.
323            if let Some(id) = cache_id_of(self) {
324                let hm = with_cache_cell(id, |m| m.get("hashmap").cloned().unwrap_or(Value::Null));
325                return tag_cache_hashmap_buckets(hm, id);
326            }
327            if let Some(v) = d.get("hashmap") { return v.clone(); }
328        }
329        Value::Null
330    }
331    /// `client.send(payload)` — queues a frame on the WS connection (routed by
332    /// the client handle's `url`). No-op on a non-client Value.
333    pub fn send(&self, args: &[Value]) -> Value {
334        crate::pro::ws_client::value_send(self, args)
335    }
336    /// `client.decode_proto_msg(...)` — exchange-specific protobuf
337    /// decode helper; stubbed to `Value::Null`.
338    pub fn decode_proto_msg(&self, _args: &[Value]) -> Value { Value::Null }
339    /// `client.on_pong(...)` — WS heartbeat hook; records the pong time.
340    pub fn on_pong(&self, _args: &[Value]) -> Value {
341        crate::pro::ws_client::value_on_pong(self)
342    }
343    /// WS stub — transpiled `fn(...args)` over a Value-typed callable.
344    pub fn call(&self, _args: &[Value]) -> Value { Value::Null }
345    /// `exchange.isDictionary(value)` — transpiled tests treat `exchange`
346    /// as `Value` instead of the typed `Exchange`, so we mirror the
347    /// dict-typecheck method here.
348    pub fn is_dictionary(&self, value: Value) -> Value {
349        Value::Bool(matches!(value, Value::Dict(_)))
350    }
351    /// Lifts this snapshot's `options` + `currencies` onto a throwaway base
352    /// `Exchange` so the *transpiled* conversion methods can run against it.
353    /// The afterConstruct test transpiles its call sites with `exchange:
354    /// Value`, so these methods have to exist on `Value` — but the logic
355    /// must stay in the transpiled base, not be duplicated here.
356    #[cfg(feature = "engine")]
357    fn snapshot_as_exchange(&self) -> crate::exchange::Exchange {
358        let mut ex = crate::exchange::Exchange::new(None);
359        ex.options = crate::runtime::get_value(self, &Value::Str("options".into()));
360        ex.currencies = crate::runtime::get_value(self, &Value::Str("currencies".into()));
361        ex
362    }
363
364    /// `exchange.networkCodeToId(code, currency)` on a snapshot `Value` —
365    /// delegates to the transpiled `Exchange::network_code_to_id`.
366    pub fn network_code_to_id(&self, code: Value, args: &[Value]) -> Value {
367        #[cfg(feature = "engine")]
368        {
369            let currency = args.first().cloned().unwrap_or(Value::Null);
370            return crate::exchange::BaseCore::new(self.snapshot_as_exchange()).network_code_to_id(code, &[currency]);
371        }
372        #[cfg(not(feature = "engine"))]
373        {
374            let _ = args;
375            code
376        }
377    }
378
379    /// `exchange.networkIdToCode(networkId, currency)` on a snapshot `Value`
380    /// — delegates to the transpiled `Exchange::network_id_to_code`.
381    pub fn network_id_to_code(&self, args: &[Value]) -> Value {
382        #[cfg(feature = "engine")]
383        {
384            return crate::exchange::BaseCore::new(self.snapshot_as_exchange()).network_id_to_code(args);
385        }
386        #[cfg(not(feature = "engine"))]
387        {
388            let _ = args;
389            Value::Null
390        }
391    }
392
393    /// `exchange.extend(a, b, ...)` on a snapshot `Value` — CCXT's shallow
394    /// object merge. Pure (ignores exchange state), so it delegates to the
395    /// transpiled `Exchange::extend`. Used by the (prediction-aware) transpiled
396    /// test harness, where `exchange` is a dynamic `Value` handle.
397    pub fn extend(&self, a: Value, args: &[Value]) -> Value {
398        #[cfg(feature = "engine")]
399        {
400            return self.snapshot_as_exchange().extend(a, args);
401        }
402        #[cfg(not(feature = "engine"))]
403        {
404            let _ = args;
405            a
406        }
407    }
408
409    /// `exchange.setMarkets(markets)` on a snapshot `Value` — used by the
410    /// prediction test harness to seed event-derived markets. Delegates the
411    /// indexing to the transpiled `Exchange::set_markets`, then writes the
412    /// computed `markets`/`markets_by_id`/`symbols` back onto the `Value`
413    /// handle so later `get_value(exchange, "markets")` reads see them.
414    pub fn set_markets(&mut self, markets: Value) -> Value {
415        #[cfg(feature = "engine")]
416        {
417            // If this snapshot is backed by a live Core (`__live_id`), route to
418            // it so the Core's own `set_markets` runs — for a prediction venue
419            // that's `PredictionExchange::set_markets` (outcome→symbol aliasing +
420            // populateOutcomes), populating the outcome caches on the very
421            // instance the method dispatch uses. Without this, the prediction
422            // static request tests seed markets onto a throwaway snapshot and the
423            // live Core resolves every outcome by (re)fetching events.
424            if let Value::Dict(m) = &*self {
425                if let Some(Value::Str(id)) = m.get("__live_id") {
426                    if let Some(cb) = live_set_markets_get() {
427                        return cb(&id.clone(), markets);
428                    }
429                }
430            }
431            let mut ex = crate::exchange::BaseCore::new(self.snapshot_as_exchange());
432            let result = ex.set_markets(markets, &[]);
433            crate::runtime::add_element_to_object(self, &Value::Str("markets".into()), ex.markets.clone());
434            crate::runtime::add_element_to_object(self, &Value::Str("markets_by_id".into()), ex.markets_by_id.clone());
435            crate::runtime::add_element_to_object(self, &Value::Str("symbols".into()), ex.symbols.clone());
436            return result;
437        }
438        #[cfg(not(feature = "engine"))]
439        {
440            let _ = markets;
441            Value::Null
442        }
443    }
444    /// `side.storeArray(delta)` — insert/update/delete by price (or
445    /// by id for the indexed variant). Defined here (rather than next
446    /// to `store`) so that derived exchange code which calls
447    /// `Value::store_array` on a non-side Value still compiles as a
448    /// no-op.
449    pub fn store_array(&mut self, delta: Value) {
450        if side_kind(self).is_some() { side_store_array(self, delta); }
451    }
452    pub fn append_to_array(&self, _v: Value) {}
453
454    // ── conversion to / from serde_json ───────────────────────────────────────
455
456    pub fn to_json(&self) -> serde_json::Value {
457        match self {
458            Value::Null        => serde_json::Value::Null,
459            Value::Bool(b)     => serde_json::Value::Bool(*b),
460            Value::Int(n)      => serde_json::json!(*n),
461            Value::Float(f)    => serde_json::json!(*f),
462            Value::Str(s)      => serde_json::Value::String(s.to_string()),
463            Value::Arr(a)      => serde_json::Value::Array(a.iter().map(Value::to_json).collect()),
464            Value::Dict(m)     => {
465                // A side marker keeps its entries in the shared side store —
466                // serialize as the plain `[[price, amount], …]` array (CCXT's
467                // orderbook.bids/asks shape), matching jsonStringify(orderbook)
468                // in the other languages rather than exposing the internal side
469                // struct. The WS deep-compare unwraps markers itself, so it's
470                // unaffected.
471                if m.contains_key("__side_id") {
472                    let entries = side_entries_view(m);
473                    return serde_json::Value::Array(entries.iter().map(Value::to_json).collect());
474                }
475                // A shared book keeps its scalar meta (nonce/timestamp/…) in the
476                // book store and tags itself with internal markers — drop the
477                // markers and surface the meta so the serialized book is the
478                // clean { bids, asks, timestamp, datetime, nonce, symbol } form.
479                let is_book = m.contains_key("__book_id") || m.contains_key("__bookKind");
480                let mut obj = serde_json::Map::new();
481                for (k, v) in m.iter() {
482                    if is_book && matches!(k.as_str(), "__bookKind" | "__book_id" | "_depth") {
483                        continue;
484                    }
485                    obj.insert(k.clone(), v.to_json());
486                }
487                if let Some(Value::Int(id)) = m.get("__book_id") {
488                    for (k, v) in book_meta_snapshot(*id) { obj.insert(k, v.to_json()); }
489                }
490                // A cache marker keeps its rolling buffer in the shared cache
491                // store — surface it under `_data` for serialization.
492                if m.contains_key("__cacheKind") {
493                    let data = cache_data_snapshot(m);
494                    obj.insert("_data".to_string(),
495                        serde_json::Value::Array(data.iter().map(Value::to_json).collect()));
496                }
497                serde_json::Value::Object(obj)
498            }
499        }
500    }
501
502    pub fn from_json(v: &serde_json::Value) -> Self {
503        match v {
504            serde_json::Value::Null        => Value::Null,
505            serde_json::Value::Bool(b)     => Value::Bool(*b),
506            serde_json::Value::Number(n)   => {
507                if let Some(i) = n.as_i64()  {
508                    Value::Int(i)
509                } else if n.is_u64() {
510                    // Integer in (i64::MAX, u64::MAX] — a large order/trade/
511                    // account id. `Value::Int` is i64 and `f64` would round it,
512                    // so preserve the exact digits as a string (Go does the
513                    // same). CCXT's safe_integer/safe_number read it back as a
514                    // number when needed.
515                    Value::Str(n.to_string().into())
516                } else if let Some(f) = n.as_f64() {
517                    Value::Float(f)
518                } else {
519                    Value::Null
520                }
521            }
522            serde_json::Value::String(s)   => Value::Str(s.clone().into()),
523            serde_json::Value::Array(a)    => Value::Array(a.iter().map(Value::from_json).collect()),
524            serde_json::Value::Object(m)   => Value::Map(
525                m.iter().map(|(k, v)| (k.clone(), Value::from_json(v))).collect()
526            ),
527        }
528    }
529}
530
531impl std::fmt::Display for Value {
532    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
533        match self {
534            Value::Null        => write!(f, "null"),
535            Value::Bool(b)     => write!(f, "{b}"),
536            Value::Int(n)      => write!(f, "{n}"),
537            Value::Float(fl)   => write!(f, "{fl}"),
538            Value::Str(s)      => write!(f, "{s}"),
539            Value::Arr(a)      => write!(f, "[{} items]", a.len()),
540            Value::Dict(m)     => write!(f, "{{{}  keys}}", m.len()),
541        }
542    }
543}
544
545// ── From / Into conversions ───────────────────────────────────────────────────
546
547// Operator overloads so transpiled code's `!x`, `x && y`, `x || y` over
548// Value compile. They follow JS-style truthiness on the Value, not value
549// equality. Result type is `Value::Bool`.
550
551impl std::ops::Not for Value {
552    type Output = Value;
553    fn not(self) -> Value { Value::Bool(!self.is_truthy()) }
554}
555
556impl std::ops::Not for &Value {
557    type Output = Value;
558    fn not(self) -> Value { Value::Bool(!self.is_truthy()) }
559}
560
561impl std::ops::BitAnd for Value {
562    type Output = Value;
563    fn bitand(self, rhs: Value) -> Value {
564        Value::Bool(self.is_truthy() && rhs.is_truthy())
565    }
566}
567
568impl std::ops::BitOr for Value {
569    type Output = Value;
570    fn bitor(self, rhs: Value) -> Value {
571        Value::Bool(self.is_truthy() || rhs.is_truthy())
572    }
573}
574
575impl From<&str>    for Value { fn from(s: &str)   -> Self { Value::Str(Cow::Owned(s.to_owned())) } }
576impl From<String>  for Value { fn from(s: String) -> Self { Value::Str(Cow::Owned(s)) } }
577impl From<i64>     for Value { fn from(n: i64)    -> Self { Value::Int(n) } }
578impl From<f64>     for Value { fn from(f: f64)    -> Self { Value::Float(f) } }
579impl From<bool>    for Value { fn from(b: bool)   -> Self { Value::Bool(b) } }
580impl From<Option<i64>> for Value { fn from(n: Option<i64>) -> Self { n.map_or(Value::Null, Value::Int) } }
581impl From<Option<f64>> for Value { fn from(n: Option<f64>) -> Self { n.map_or(Value::Null, Value::Float) } }
582/// `From<ExchangeError>` makes `error.clone()` flow into `&[Value]`
583/// slices without an explicit conversion — surfaces the typed error
584/// as a `[Kind] message`-shaped string Value, matching how
585/// `runtime::panic_msg_to_error` round-trips it back into a typed
586/// `ExchangeError` for the caller.
587impl From<crate::ExchangeError> for Value {
588    fn from(e: crate::ExchangeError) -> Self {
589        Value::Str(format!("[{}] {}", e.kind, e.message).into())
590    }
591}
592impl From<HashMap<String, Value>> for Value {
593    fn from(m: HashMap<String, Value>) -> Self { Value::Map(m) }
594}
595impl From<HashMap<String, HashMap<String, Value>>> for Value {
596    fn from(m: HashMap<String, HashMap<String, Value>>) -> Self {
597        let mut out = HashMap::with_capacity(m.len());
598        for (k, v) in m {
599            out.insert(k, Value::Map(v));
600        }
601        Value::Map(out)
602    }
603}
604impl From<Vec<Value>> for Value {
605    fn from(a: Vec<Value>) -> Self { Value::Array(a) }
606}
607impl From<serde_json::Value> for Value {
608    fn from(v: serde_json::Value) -> Self { Value::from_json(&v) }
609}
610
611// ── Helper free-functions (generated code calls these) ────────────────────────
612
613/// Optional live-snapshot accessor. Installed by `ccxt_tests::live_dispatch`
614/// so reads of the heavy fields (`markets`, `markets_by_id`, `symbols`, …)
615/// on the test-runner's snapshot don't deep-clone the entire ~4k-entry
616/// markets Map on every helper invocation. When `get_value` sees a Map
617/// carrying `__live_id`, it consults this callback to resolve the key
618/// directly from the cached real `<Id>Core`. Production / non-test code
619/// leaves the callback unset and falls through to the normal map lookup.
620type LiveLookupFn = fn(id: &str, key: &str) -> Option<Value>;
621// Write-once registry: the test harness installs it from `main` before any
622// worker thread runs and nothing replaces it. One-shot cell, so every read is a
623// plain fn-pointer load with no lock and no atomic at the use site.
624static LIVE_LOOKUP: std::sync::OnceLock<LiveLookupFn> = std::sync::OnceLock::new();
625
626pub fn set_live_lookup(f: LiveLookupFn) {
627    let _ = LIVE_LOOKUP.set(f);
628}
629
630fn live_lookup_get() -> Option<LiveLookupFn> {
631    LIVE_LOOKUP.get().copied()
632}
633
634// Companion to `LiveLookupFn` but for writing: routes `exchange.setMarkets(...)`
635// on a `__live_id` snapshot to the registered *live* Core, so the Core's
636// `PredictionExchange::set_markets` override (outcome aliasing + populateOutcomes)
637// runs against the real instance the method dispatch will use. Returns the
638// resulting markets. See `Value::set_markets`.
639type LiveSetMarketsFn = fn(id: &str, markets: Value) -> Value;
640static LIVE_SET_MARKETS: std::sync::OnceLock<LiveSetMarketsFn> = std::sync::OnceLock::new();
641
642pub fn set_live_set_markets(f: LiveSetMarketsFn) {
643    let _ = LIVE_SET_MARKETS.set(f);
644}
645
646fn live_set_markets_get() -> Option<LiveSetMarketsFn> {
647    LIVE_SET_MARKETS.get().copied()
648}
649
650/// Hot-path `get_value` variant that takes the key as a `&str` directly,
651/// skipping a `Value::Str` heap allocation. Used by the `safe_*_k`
652/// fast-path readers the transpiler routes literal-key calls through.
653#[inline]
654pub fn get_value_k(obj: &Value, key: &str) -> Value {
655    if let Value::Dict(m) = obj {
656        // A shared order book keeps its scalar meta (nonce/timestamp/…) in the
657        // book store; route those through it so the safe_* helpers (which go via
658        // get_value_k) see the shared value, not the empty Dict slot.
659        if is_book_meta_key(key) {
660            if let Some(id) = book_id_of(m) { return book_meta_get(id, key); }
661        }
662        if key == "cache" {
663            if let Some(id) = book_id_of(m) { return book_cache_handle(id); }
664        }
665        if let Some(v) = m.get(key) {
666            if !matches!(v, Value::Null) {
667                return v.clone();
668            }
669        }
670        if let Some(id_val) = m.get("__live_id") {
671            if let (Value::Str(id), Some(cb)) = (id_val, live_lookup_get()) {
672                if let Some(v) = cb(id, key) { return v; }
673            }
674        }
675    }
676    Value::Null
677}
678
679/// Access a value in a map by string key, or array by integer key encoded as
680/// a `Value::Str` / `Value::Int`. Returns `Value::Null` on miss.
681pub fn get_value(obj: &Value, key: &Value) -> Value {
682    // Cache / order-book / side markers expose numeric indexing as if
683    // they were arrays — `cache[i]` reads `_data[i]`, `side[i]` reads
684    // `_entries[i]`. Handle this before the regular dict lookup so the
685    // transpiled `get_value(&cache, &Value::Int(0))` calls reach the
686    // right backing buffer.
687    // The index may arrive as an Int (`get_value(&side, &Value::Int(0))`) or as
688    // a numeric string — the `safe_*` helpers stringify their key, so
689    // `safe_value(cache, 0)` reaches here as `Str("0")`. Accept both.
690    if let Value::Dict(m) = obj {
691        let idx = match key {
692            Value::Int(i) if *i >= 0 => Some(*i as usize),
693            Value::Str(s) => s.parse::<usize>().ok(),
694            _ => None,
695        };
696        if let Some(i) = idx {
697            if let Some(id) = book_cache_id_of(m) {
698                return book_cache_at(id, i);
699            }
700            if m.contains_key("__cacheKind") {
701                return cache_at(m, i);
702            }
703            if m.contains_key("__sideKind") {
704                return side_entry_at(m, i);
705            }
706        }
707    }
708    match (obj, key) {
709        (Value::Dict(m), Value::Str(k)) => {
710            // A shared order book keeps its scalar meta (nonce/timestamp/…) in
711            // the book store so mutations propagate across clones.
712            if is_book_meta_key(k) {
713                if let Some(id) = book_id_of(m) { return book_meta_get(id, k); }
714            }
715            if k == "cache" {
716                if let Some(id) = book_id_of(m) { return book_cache_handle(id); }
717            }
718            // A cache marker's `hashmap` (bucket index) lives in the shared
719            // store cell, not the marker Dict — route the read there so a
720            // transpiled `cache.hashmap` sees live bucket state (the base-ws
721            // eviction test counts `Object.keys(cache.hashmap)`).
722            if k == "hashmap" && m.contains_key("__cacheKind") {
723                if let Some(id) = cache_id_of_m(m) {
724                    return with_cache_cell(id, |c| c.get("hashmap").cloned().unwrap_or(Value::Null));
725                }
726                return m.get("hashmap").cloned().unwrap_or(Value::Null);
727            }
728            // A client handle (`Map{url, subscriptions, futures}`) serves its
729            // subscriptions/futures live from the WS registry, so a read after a
730            // write (upbit sets subs then reads them back to build its subscribe
731            // frame) is coherent rather than a stale embedded snapshot.
732            if (k == "subscriptions" || k == "futures")
733                && m.contains_key("subscriptions") && m.contains_key("futures")
734            {
735                if let Some(Value::Str(url)) = m.get("url") {
736                    return crate::pro::ws_client::client_field_live(url, k);
737                }
738            }
739            // Snapshot value wins WHEN PRESENT AND NON-NULL. Tests that
740            // mutate `exchange.options` (e.g. kucoin broker-id test) need
741            // the snapshot view to take precedence; but `to_value`
742            // pre-populates heavy fields like `markets` with `Null`
743            // before `load_markets` runs, so we still need to fall back
744            // to the live-lookup if the snapshot value is null.
745            let snapshot_val = m.get(k.as_ref());
746            if let Some(v) = snapshot_val {
747                if !matches!(v, Value::Null) {
748                    return v.clone();
749                }
750            }
751            if let Some(id_val) = m.get("__live_id") {
752                if let (Value::Str(id), Some(cb)) = (id_val, live_lookup_get()) {
753                    if let Some(v) = cb(id, k) { return v; }
754                }
755            }
756            Value::Null
757        }
758        (Value::Arr(a), Value::Int(i)) => a.get(*i as usize).cloned().unwrap_or(Value::Null),
759        (Value::Arr(a), Value::Str(k)) => {
760            if let Ok(i) = k.parse::<usize>() {
761                a.get(i).cloned().unwrap_or(Value::Null)
762            } else {
763                Value::Null
764            }
765        }
766        // JS string indexing: `s[i]` returns the i-th character as a
767        // 1-char string (e.g. bitfinex `amountString[0] === '-'` to detect
768        // a negative). Char-based so multi-byte UTF-8 is handled.
769        (Value::Str(s), Value::Int(i)) => {
770            if *i < 0 {
771                return Value::Null;
772            }
773            match s.chars().nth(*i as usize) {
774                Some(c) => Value::Str(c.to_string().into()),
775                None    => Value::Null,
776            }
777        }
778        _ => Value::Null,
779    }
780}
781
782/// Set a key/index in a map or array value.
783pub fn set_value(obj: &mut Value, key: &Value, val: Value) {
784    match (obj, key) {
785        (Value::Dict(m), Value::Str(k)) => {
786            if try_book_meta_write(m, k, &val) { return; }
787            // Persist to the live client AND keep the local snapshot coherent so
788            // code that reads back what it just wrote (upbit builds its subscribe
789            // frame from `object_keys(client.subscriptions)`) sees the new entry.
790            try_ws_subs_write(m, k, &val);
791            try_ws_sub_field_write(m, k, &val);
792            Arc::make_mut(m).insert(k.to_string(), val);
793        }
794        (Value::Arr(a), Value::Int(i)) => {
795            let idx = *i as usize;
796            let a = Arc::make_mut(a);
797            if idx < a.len() { a[idx] = val; }
798        }
799        _ => {}
800    }
801}
802
803// ── safeXxx helpers (mirrors Exchange.ts safe helpers) ─────────────────────
804
805pub fn safe_string(obj: &Value, key: &str, default: Option<&str>) -> Option<String> {
806    let v = get_value(obj, &Value::Str(key.to_owned().into()));
807    match v {
808        Value::Str(s)  => Some(s.to_string()),
809        Value::Int(n)  => Some(n.to_string()),
810        Value::Float(f)=> Some(f.to_string()),
811        // Booleans are not strings/finite numbers → TS `safeString` returns the
812        // default for them (not "true"/"false"), same as lists/dicts.
813        Value::Null    => default.map(str::to_owned),
814        _              => default.map(str::to_owned),
815    }
816}
817
818pub fn safe_number(obj: &Value, key: &str, default: Option<f64>) -> Option<f64> {
819    let v = get_value(obj, &Value::Str(key.to_owned().into()));
820    match v {
821        Value::Float(f) => Some(f),
822        Value::Int(n)   => Some(n as f64),
823        Value::Str(s)   => s.parse::<f64>().ok().or(default),
824        _               => default,
825    }
826}
827
828pub fn safe_integer(obj: &Value, key: &str, default: Option<i64>) -> Option<i64> {
829    let v = get_value(obj, &Value::Str(key.to_owned().into()));
830    match v {
831        Value::Int(n)   => Some(n),
832        Value::Float(f) => Some(f as i64),
833        Value::Str(s)   => s.parse::<i64>().ok().or(default),
834        _               => default,
835    }
836}
837
838pub fn safe_bool(obj: &Value, key: &str, default: Option<bool>) -> Option<bool> {
839    let v = get_value(obj, &Value::Str(key.to_owned().into()));
840    match v {
841        Value::Bool(b)  => Some(b),
842        Value::Int(n)   => Some(n != 0),
843        Value::Str(s)   => match s.to_lowercase().as_str() {
844            "true" | "1" | "yes" => Some(true),
845            "false"| "0" | "no"  => Some(false),
846            _                    => default,
847        },
848        _               => default,
849    }
850}
851
852/// Recursively merges `src` into `dst`.
853/// For map/map overlaps the source fields win (deep extend).
854pub fn deep_extend(dst: Value, src: Value) -> Value {
855    match (dst, src) {
856        (Value::Dict(mut d), Value::Dict(s)) => {
857            let dm = Arc::make_mut(&mut d);
858            let sm = Arc::try_unwrap(s).unwrap_or_else(|arc| (*arc).clone());
859            for (k, v) in sm {
860                let entry = dm.shift_remove(&k).unwrap_or(Value::Null);
861                dm.insert(k, deep_extend(entry, v));
862            }
863            Value::Dict(d)
864        }
865        (_, src) => src,
866    }
867}
868
869// ────────────────────────────────────────────────────────────────────────────
870// WS cache helpers — operate on the `Value::Dict` marker maps produced by
871// `crate::pro::cache`. Logic mirrors `ts/src/base/ws/Cache.ts`.
872// ────────────────────────────────────────────────────────────────────────────
873
874fn cache_str_field(item: &Value, key: &str) -> Option<String> {
875    match item {
876        Value::Dict(d) => match d.get(key) {
877            // Coerce to the string the TS uses as an object key: exchanges send
878            // integer order ids, and JS `byId[1]` / `byId["1"]` are the same slot,
879            // so a numeric id must dedupe like its string form (else the bucket
880            // lookup and the _data removal disagree and a duplicate row leaks).
881            Some(Value::Str(s)) => Some(s.to_string()),
882            Some(Value::Int(n)) => Some(n.to_string()),
883            Some(Value::Float(f)) => Some(f.to_string()),
884            Some(Value::Bool(b)) => Some(b.to_string()),
885            _ => None,
886        },
887        _ => None,
888    }
889}
890
891/// Tag every symbol bucket of a cache hashmap copy with a `__cache_backref`
892/// = [cache_id, symbol] so a later `bucket[id] = order` write can be routed
893/// back into the shared WS state store (see `try_cache_hashmap_write`). Mirrors
894/// the JS reference semantics where `cache.hashmap[symbol]` is the live row.
895fn tag_cache_hashmap_buckets(hm: Value, id: i64) -> Value {
896    if let Value::Dict(d) = &hm {
897        let mut out: HashMap<String, Value> = HashMap::new();
898        for (sym, bucket) in d.iter() {
899            if let Value::Dict(bd) = bucket {
900                let mut nb: HashMap<String, Value> = (**bd).clone();
901                nb.insert(
902                    "__cache_backref".to_string(),
903                    Value::Arr(std::sync::Arc::new(vec![Value::Int(id), Value::Str(sym.clone().into())])),
904                );
905                out.insert(sym.clone(), Value::Dict(std::sync::Arc::new(nb)));
906            } else {
907                out.insert(sym.clone(), bucket.clone());
908            }
909        }
910        return Value::Dict(std::sync::Arc::new(out));
911    }
912    hm
913}
914
915/// When a transpiled `bucket[key] = item` write lands on a cache-hashmap bucket
916/// tagged by `tag_cache_hashmap_buckets`, persist `item` into the shared
917/// store: update `hashmap[symbol][key]` and the matching `_data` row.
918/// This is how cross-handler mutations of a cached order (fee/trades
919/// accumulation in handleMyTrade, later read by handleOrder) survive Rust's
920/// copy-on-write `Value` semantics. Returns true if a write-through happened.
921pub(crate) fn try_cache_hashmap_write(bucket: &HashMap<String, Value>, key: &str, item: &Value) -> bool {
922    let (id, sym) = match bucket.get("__cache_backref") {
923        Some(Value::Arr(a)) => match (a.first(), a.get(1)) {
924            (Some(Value::Int(id)), Some(Value::Str(s))) => (*id, s.to_string()),
925            _ => return false,
926        },
927        _ => return false,
928    };
929    let key = key.to_string();
930    let item = item.clone();
931    with_cache_cell(id, move |m| {
932        // hashmap[sym][key] = item
933        {
934            let hm = cache_dict_field_mut(m, "hashmap");
935            let b = hm.entry(sym.clone()).or_insert_with(|| Value::Map(HashMap::new()));
936            if let Value::Dict(bd) = b {
937                Arc::make_mut(bd).insert(key.clone(), item.clone());
938            }
939        }
940        // update the matching _data row (matched by symbol + id/side == key)
941        let data = cache_data_mut(m);
942        for x in data.iter_mut() {
943            if cache_str_field(x, "symbol").as_deref() == Some(sym.as_str())
944                && (cache_str_field(x, "id").as_deref() == Some(key.as_str())
945                    || cache_str_field(x, "side").as_deref() == Some(key.as_str()))
946            {
947                *x = item.clone();
948                break;
949            }
950        }
951    });
952    true
953}
954
955fn cache_kind(v: &Value) -> Option<String> {
956    match v {
957        Value::Dict(d) => match d.get("__cacheKind") {
958            Some(Value::Str(s)) => Some(s.to_string()),
959            _ => None,
960        },
961        _ => None,
962    }
963}
964
965fn cache_max_size(v: &Value) -> Option<usize> {
966    match v {
967        Value::Dict(d) => match d.get("maxSize") {
968            Some(Value::Int(n)) if *n > 0 => Some(*n as usize),
969            _ => None,
970        },
971        _ => None,
972    }
973}
974
975/// `_data` is the rolling buffer Vec for every cache kind. Returns a
976/// mutable handle to the inner Vec by going through `Arc::make_mut`.
977fn cache_data_mut(m: &mut HashMap<String, Value>) -> &mut Vec<Value> {
978    let entry = m.entry("_data".to_string()).or_insert_with(|| Value::Array(Vec::new()));
979    if let Value::Arr(a) = entry {
980        return Arc::make_mut(a);
981    }
982    *entry = Value::Array(Vec::new());
983    if let Value::Arr(a) = entry {
984        return Arc::make_mut(a);
985    }
986    unreachable!()
987}
988
989fn cache_dict_field_mut<'a>(m: &'a mut HashMap<String, Value>, key: &str) -> &'a mut HashMap<String, Value> {
990    let entry = m.entry(key.to_string()).or_insert_with(|| Value::Map(HashMap::new()));
991    if let Value::Dict(d) = entry {
992        return Arc::make_mut(d);
993    }
994    *entry = Value::Map(HashMap::new());
995    if let Value::Dict(d) = entry {
996        return Arc::make_mut(d);
997    }
998    unreachable!()
999}
1000
1001fn cache_int_field(m: &HashMap<String, Value>, key: &str) -> i64 {
1002    match m.get(key) { Some(Value::Int(n)) => *n, _ => 0 }
1003}
1004
1005fn cache_set_int(m: &mut HashMap<String, Value>, key: &str, value: i64) {
1006    m.insert(key.to_string(), Value::Int(value));
1007}
1008
1009fn cache_bool_field(m: &HashMap<String, Value>, key: &str) -> bool {
1010    matches!(m.get(key), Some(Value::Bool(true)))
1011}
1012
1013fn cache_set_bool(m: &mut HashMap<String, Value>, key: &str, value: bool) {
1014    m.insert(key.to_string(), Value::Bool(value));
1015}
1016
1017// Reset the per-kind bookkeeping that a `clear()` must drop, mirroring the TS
1018// `ArrayCache` / `ArrayCacheByTimestamp` `clear()` overrides (base/ws/Cache.ts):
1019// the keyed caches find rows through the hashmap and report new-update counts,
1020// so a `clear()` that only truncates `_data` leaves the hashmap + counters
1021// claiming rows that are gone — `getLimit()` then keeps reporting phantom
1022// updates and the next `append` merges into an orphaned reference. Only fields
1023// already present are reset (guards the bare-marker fallback path). The caller
1024// truncates `_data` separately.
1025fn cache_reset_bookkeeping(state: &mut HashMap<String, Value>) {
1026    for k in ["hashmap", "_newUpdatesBySymbol", "_seenUpdatesBySymbol", "_seenUpdatesAll",
1027              "_clearUpdatesBySymbol", "_sizeTracker"] {
1028        if state.contains_key(k) {
1029            state.insert(k.to_string(), Value::Map(HashMap::new()));
1030        }
1031    }
1032    if state.contains_key("_allNewUpdates") { cache_set_int(state, "_allNewUpdates", 0); }
1033    if state.contains_key("_newUpdates") { cache_set_int(state, "_newUpdates", 0); }
1034    if state.contains_key("_clearAllUpdates") { cache_set_bool(state, "_clearAllUpdates", false); }
1035    if state.contains_key("_clearUpdates") { cache_set_bool(state, "_clearUpdates", false); }
1036}
1037
1038// ── ArrayCache update-counter scopes ────────────────────────────────────────
1039// The keyed caches (BySymbolById / ByOutcomeById / BySymbolBySide) count the
1040// distinct second-level keys (id / side) seen since the last poll, kept in TWO
1041// independent scopes so a symbol-scoped poll and a global poll clear each other
1042// without interfering (mirrors `seenUpdatesBySymbol` / `seenUpdatesAll` in
1043// base/ws/Cache.ts). A "set" is a `Map<key2, Bool>` nested under `field[key1]`.
1044
1045// Apply a pending global-scope clear at the top of `append` (TS `clearAllUpdates`).
1046fn cache_apply_clear_all(m: &mut HashMap<String, Value>) {
1047    if cache_bool_field(m, "_clearAllUpdates") {
1048        cache_set_bool(m, "_clearAllUpdates", false);
1049        cache_set_int(m, "_allNewUpdates", 0);
1050        cache_dict_field_mut(m, "_seenUpdatesAll").clear();
1051    }
1052}
1053
1054// Take (and reset) the pending symbol-scoped clear flag for `key1`.
1055fn cache_take_symbol_clear(m: &mut HashMap<String, Value>, key1: &str) -> bool {
1056    let cs = cache_dict_field_mut(m, "_clearUpdatesBySymbol");
1057    if matches!(cs.get(key1), Some(Value::Bool(true))) {
1058        cs.insert(key1.to_string(), Value::Bool(false));
1059        true
1060    } else {
1061        false
1062    }
1063}
1064
1065// Add `key2` to the seen-set `field[key1]`; returns the resulting set size.
1066fn cache_seen_add(m: &mut HashMap<String, Value>, field: &str, key1: &str, key2: &str) -> i64 {
1067    let outer = cache_dict_field_mut(m, field);
1068    let set = outer.entry(key1.to_string()).or_insert_with(|| Value::Map(HashMap::new()));
1069    if let Value::Dict(sd) = set {
1070        let sd = Arc::make_mut(sd);
1071        sd.insert(key2.to_string(), Value::Bool(true));
1072        sd.len() as i64
1073    } else {
1074        0
1075    }
1076}
1077
1078// Size of the seen-set `field[key1]` (0 if absent).
1079fn cache_seen_size(m: &mut HashMap<String, Value>, field: &str, key1: &str) -> i64 {
1080    match cache_dict_field_mut(m, field).get(key1) {
1081        Some(Value::Dict(sd)) => sd.len() as i64,
1082        _ => 0,
1083    }
1084}
1085
1086// Empty the seen-set `field[key1]` (leaves the bucket in place).
1087fn cache_seen_clear(m: &mut HashMap<String, Value>, field: &str, key1: &str) {
1088    if let Some(Value::Dict(sd)) = cache_dict_field_mut(m, field).get_mut(key1) {
1089        Arc::make_mut(sd).clear();
1090    }
1091}
1092
1093// Remove `key2` from the seen-set `field[key1]`; returns whether it was present.
1094// Drops the outer bucket once its set is empty (TS eviction cleanup).
1095fn cache_seen_remove(m: &mut HashMap<String, Value>, field: &str, key1: &str, key2: &str) -> bool {
1096    let outer = cache_dict_field_mut(m, field);
1097    let (removed, empty) = if let Some(Value::Dict(sd)) = outer.get_mut(key1) {
1098        let sd = Arc::make_mut(sd);
1099        let removed = sd.shift_remove(key2).is_some();
1100        (removed, sd.is_empty())
1101    } else {
1102        (false, false)
1103    };
1104    if empty { outer.shift_remove(key1); }
1105    removed
1106}
1107
1108// ── Shared cache backing store ──────────────────────────────────────────────
1109// ArrayCache & friends must survive COW clones the way order-book sides do: a
1110// handler creates a cache, stores a *clone* in `self.ohlcvs[sym][tf]`, appends
1111// to the local, then re-reads the stored clone to resolve (gate watchOHLCV).
1112// With the rolling buffer + hashmap + counters kept in the Dict, the clone and
1113// the local diverge on the first append (Arc::make_mut) and the re-read is
1114// empty. So hold the whole mutable cache state (`_data`, `hashmap`, counters)
1115// in a registry keyed by a stable `__cache_id`; every COW clone shares it.
1116// ── Ws state store: one owner, channel hand-off ─────────────────────────────
1117// Every shared WS cell (cache, book, side) lives in one `WsStateStore`. The
1118// cells must outlive COW clones and task migration, so they cannot be thread
1119// local; and no lock may be held at a use site across an await. So a single
1120// owner thread holds the whole store and every other task hands it a job over a
1121// channel, then waits for the reply (`store_op`). Nothing is shared, so there is
1122// no lock to nest, poison or forget, and no cell can be read half-applied.
1123struct BookCell {
1124    meta: HashMap<String, Value>,
1125    cache: Vec<Value>,
1126}
1127
1128impl Default for BookCell {
1129    fn default() -> Self {
1130        BookCell { meta: HashMap::new(), cache: Vec::new() }
1131    }
1132}
1133
1134#[derive(Default)]
1135struct WsStateStore {
1136    caches: HashMap<i64, HashMap<String, Value>>,
1137    books: HashMap<i64, BookCell>,
1138    sides: HashMap<i64, SideCell>,
1139    last_cache_id: i64,
1140    last_book_id: i64,
1141    last_side_id: i64,
1142}
1143
1144type StoreJob = Box<dyn FnOnce(&mut WsStateStore) + Send + 'static>;
1145
1146// Marks the owner thread while a job runs: a job that calls back into the
1147// store would wait on its own reply forever, so `store_op` turns that into a
1148// panic instead of a hang.
1149thread_local! {
1150    static IN_STORE_JOB: std::cell::Cell<bool> = std::cell::Cell::new(false);
1151}
1152
1153struct InStoreJob;
1154
1155impl InStoreJob {
1156    fn enter() -> Self {
1157        IN_STORE_JOB.with(|f| f.set(true));
1158        InStoreJob
1159    }
1160}
1161
1162impl Drop for InStoreJob {
1163    fn drop(&mut self) { IN_STORE_JOB.with(|f| f.set(false)); }
1164}
1165
1166static STORE_TX: std::sync::LazyLock<tokio::sync::mpsc::UnboundedSender<StoreJob>> =
1167    std::sync::LazyLock::new(|| {
1168        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<StoreJob>();
1169        std::thread::Builder::new()
1170            .name("ccxt-ws-store".to_string())
1171            .spawn(move || {
1172                let mut store = WsStateStore::default();
1173                while let Some(job) = rx.blocking_recv() {
1174                    let _in_job = InStoreJob::enter();
1175                    job(&mut store);
1176                }
1177            })
1178            .expect("ccxt: cannot start the WS state store owner");
1179        tx
1180    });
1181
1182/// Hand `f` to the store's owner thread and return its result. The owner runs
1183/// only store jobs; a job that calls back into the store would wait on itself,
1184/// so that case panics rather than deadlocking.
1185fn store_op<R, F>(f: F) -> R
1186where
1187    R: Send + 'static,
1188    F: FnOnce(&mut WsStateStore) -> R + Send + 'static,
1189{
1190    if IN_STORE_JOB.with(|flag| flag.get()) {
1191        panic!("ccxt: WS state store job called back into the store (would deadlock)");
1192    }
1193    let (tx, rx) = std::sync::mpsc::sync_channel::<Result<R, Box<dyn std::any::Any + Send>>>(1);
1194    let job: StoreJob = Box::new(move |store: &mut WsStateStore| {
1195        let _ = tx.send(std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(store))));
1196    });
1197    if STORE_TX.send(job).is_err() {
1198        panic!("ccxt: WS state store owner is gone");
1199    }
1200    match rx.recv() {
1201        Ok(Ok(v)) => v,
1202        Ok(Err(payload)) => std::panic::resume_unwind(payload),
1203        Err(_) => panic!("ccxt: WS state store owner dropped the reply"),
1204    }
1205}
1206
1207// ── Owner thread: one writer, channel hand-off ──────────────────────────────
1208// State several tasks must reach but that no lock may guard at a use site: one
1209// plain thread owns it, callers hand it a job and wait for the reply. Nothing is
1210// shared, so there is no lock to nest, poison or forget, and no reader can see
1211// the state half-applied.
1212pub(crate) type OwnerJob<S> = Box<dyn FnOnce(&mut S) + Send + 'static>;
1213
1214pub(crate) struct OwnerThread<S> {
1215    tx: tokio::sync::mpsc::UnboundedSender<OwnerJob<S>>,
1216    owner: std::sync::OnceLock<std::thread::ThreadId>,
1217}
1218
1219impl<S: Send + 'static> OwnerThread<S> {
1220    pub(crate) fn spawn(name: &str, init: S) -> Self {
1221        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<OwnerJob<S>>();
1222        let handle = std::thread::Builder::new()
1223            .name(name.to_string())
1224            .spawn(move || {
1225                let mut state = init;
1226                while let Some(job) = rx.blocking_recv() { job(&mut state); }
1227            })
1228            .expect("ccxt: cannot start an owner thread");
1229        let owner = std::sync::OnceLock::new();
1230        let _ = owner.set(handle.thread().id());
1231        OwnerThread { tx, owner }
1232    }
1233
1234    /// Runs `f` on the owner and returns its result. A job that calls back into
1235    /// its own owner would wait on itself, so that panics instead of hanging.
1236    pub(crate) fn run<R, F>(&self, f: F) -> R
1237    where R: Send + 'static, F: FnOnce(&mut S) -> R + Send + 'static {
1238        if self.owner.get() == Some(&std::thread::current().id()) {
1239            panic!("ccxt: owner-thread job called back into its own state (would deadlock)");
1240        }
1241        let (tx, rx) = std::sync::mpsc::sync_channel::<std::thread::Result<R>>(1);
1242        self.tx.send(Box::new(move |state: &mut S| {
1243            let _ = tx.send(std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(state))));
1244        })).unwrap_or_else(|_| panic!("ccxt: owner thread is gone"));
1245        match rx.recv() {
1246            Ok(Ok(v)) => v,
1247            Ok(Err(payload)) => std::panic::resume_unwind(payload),
1248            Err(_) => panic!("ccxt: owner thread dropped the reply"),
1249        }
1250    }
1251
1252    /// Hands `f` over without waiting; a no-op once the owner is gone.
1253    pub(crate) fn post<F>(&self, f: F)
1254    where F: FnOnce(&mut S) + Send + 'static {
1255        let _ = self.tx.send(Box::new(f));
1256    }
1257}
1258
1259/// Register a cache's initial mutable state, returning its shared id.
1260pub(crate) fn alloc_cache_id(initial: HashMap<String, Value>) -> i64 {
1261    store_op(move |s| {
1262        s.last_cache_id += 1;
1263        let id = s.last_cache_id;
1264        s.caches.insert(id, initial);
1265        id
1266    })
1267}
1268
1269fn cache_id_of(v: &Value) -> Option<i64> {
1270    match v {
1271        Value::Dict(d) => match d.get("__cache_id") { Some(Value::Int(n)) => Some(*n), _ => None },
1272        _ => None,
1273    }
1274}
1275fn cache_id_of_m(m: &HashMap<String, Value>) -> Option<i64> {
1276    match m.get("__cache_id") { Some(Value::Int(n)) => Some(*n), _ => None }
1277}
1278
1279fn with_cache_cell<R>(id: i64, f: impl FnOnce(&mut HashMap<String, Value>) -> R + Send + 'static) -> R
1280where
1281    R: Send + 'static,
1282{
1283    store_op(move |s| f(s.caches.entry(id).or_default()))
1284}
1285
1286/// Snapshot a cache marker's rolling buffer (from the shared cell if it carries
1287/// a `__cache_id`, else the inline `_data` field for legacy markers).
1288fn cache_data_snapshot(m: &HashMap<String, Value>) -> Vec<Value> {
1289    if let Some(id) = cache_id_of_m(m) {
1290        return with_cache_cell(id, |c| match c.get("_data") {
1291            Some(Value::Arr(a)) => (**a).clone(),
1292            _ => Vec::new(),
1293        });
1294    }
1295    match m.get("_data") { Some(Value::Arr(a)) => (**a).clone(), _ => Vec::new() }
1296}
1297
1298fn cache_len_of(m: &HashMap<String, Value>) -> usize {
1299    if let Some(id) = cache_id_of_m(m) {
1300        return with_cache_cell(id, |c| match c.get("_data") { Some(Value::Arr(a)) => a.len(), _ => 0 });
1301    }
1302    match m.get("_data") { Some(Value::Arr(a)) => a.len(), _ => 0 }
1303}
1304
1305fn cache_at(m: &HashMap<String, Value>, i: usize) -> Value {
1306    if let Some(id) = cache_id_of_m(m) {
1307        return with_cache_cell(id, move |c| match c.get("_data") {
1308            Some(Value::Arr(a)) => a.get(i).cloned().unwrap_or(Value::Null),
1309            _ => Value::Null,
1310        });
1311    }
1312    match m.get("_data") { Some(Value::Arr(a)) => a.get(i).cloned().unwrap_or(Value::Null), _ => Value::Null }
1313}
1314
1315/// Public: cache buffer length, or None when `m` isn't a cache marker.
1316pub(crate) fn cache_len_of_marker(m: &HashMap<String, Value>) -> Option<usize> {
1317    if m.contains_key("__cacheKind") { Some(cache_len_of(m)) } else { None }
1318}
1319
1320pub(crate) fn cache_append(target: &mut Value, item: Value) {
1321    let kind = cache_kind(target).unwrap_or_default();
1322    let cap = cache_max_size(target);
1323    if let Some(id) = cache_id_of(target) {
1324        with_cache_cell(id, move |m| cache_append_inner(m, &kind, cap, item));
1325    } else if let Value::Dict(m_arc) = target {
1326        let m = Arc::make_mut(m_arc);
1327        cache_append_inner(m, &kind, cap, item);
1328    }
1329}
1330
1331fn cache_append_inner(m: &mut HashMap<String, Value>, kind: &str, cap: Option<usize>, item: Value) {
1332    {
1333        match kind {
1334            "ArrayCache" => {
1335                let data = cache_data_mut(m);
1336                if let Some(cap) = cap { if data.len() == cap { data.remove(0); } }
1337                data.push(item.clone());
1338                // Base ArrayCache counts every append (not distinct ids), per scope.
1339                cache_apply_clear_all(m);
1340                let sym = cache_str_field(&item, "symbol").unwrap_or_default();
1341                if cache_take_symbol_clear(m, &sym) {
1342                    cache_dict_field_mut(m, "_newUpdatesBySymbol").insert(sym.clone(), Value::Int(0));
1343                }
1344                {
1345                    let nubs = cache_dict_field_mut(m, "_newUpdatesBySymbol");
1346                    let cur = match nubs.get(&sym) { Some(Value::Int(n)) => *n, _ => 0 };
1347                    nubs.insert(sym, Value::Int(cur + 1));
1348                }
1349                let all = cache_int_field(m, "_allNewUpdates");
1350                cache_set_int(m, "_allNewUpdates", all + 1);
1351            }
1352            "ArrayCacheByTimestamp" => {
1353                let ts_key = match item {
1354                    Value::Arr(ref a) => match a.first() {
1355                        Some(Value::Int(n))   => n.to_string(),
1356                        Some(Value::Float(f)) => f.to_string(),
1357                        Some(Value::Str(s))   => s.to_string(),
1358                        _ => String::new(),
1359                    },
1360                    _ => String::new(),
1361                };
1362                let existing_idx = {
1363                    let hm = cache_dict_field_mut(m, "hashmap");
1364                    match hm.get(&ts_key) { Some(Value::Int(n)) => Some(*n as usize), _ => None }
1365                };
1366                if let Some(idx) = existing_idx {
1367                    let data = cache_data_mut(m);
1368                    if idx < data.len() && data[idx] != item { data[idx] = item.clone(); }
1369                } else {
1370                    // Evict if at cap; shift hashmap indices down.
1371                    let evicting = match cap { Some(c) => {
1372                        let data_len = cache_data_mut(m).len();
1373                        data_len == c
1374                    }, None => false };
1375                    if evicting {
1376                        let removed = {
1377                            let data = cache_data_mut(m);
1378                            if data.is_empty() { Value::Null } else { data.remove(0) }
1379                        };
1380                        let removed_key = match &removed {
1381                            Value::Arr(a) => match a.first() {
1382                                Some(Value::Int(n))   => n.to_string(),
1383                                Some(Value::Float(f)) => f.to_string(),
1384                                Some(Value::Str(s))   => s.to_string(),
1385                                _ => String::new(),
1386                            },
1387                            _ => String::new(),
1388                        };
1389                        let hm = cache_dict_field_mut(m, "hashmap");
1390                        hm.shift_remove(&removed_key);
1391                        for v in hm.values_mut() {
1392                            if let Value::Int(n) = v { *n = n.saturating_sub(1); }
1393                        }
1394                    }
1395                    let new_idx = {
1396                        let data = cache_data_mut(m);
1397                        let i = data.len();
1398                        data.push(item);
1399                        i
1400                    };
1401                    let hm = cache_dict_field_mut(m, "hashmap");
1402                    hm.insert(ts_key.clone(), Value::Int(new_idx as i64));
1403                }
1404                // size tracker / new updates
1405                if cache_bool_field(m, "_clearUpdates") {
1406                    cache_set_bool(m, "_clearUpdates", false);
1407                    let st = cache_dict_field_mut(m, "_sizeTracker");
1408                    st.clear();
1409                }
1410                {
1411                    let st = cache_dict_field_mut(m, "_sizeTracker");
1412                    st.insert(ts_key, Value::Bool(true));
1413                }
1414                let st_len = match m.get("_sizeTracker") {
1415                    Some(Value::Dict(d)) => d.len() as i64,
1416                    _ => 0,
1417                };
1418                cache_set_int(m, "_newUpdates", st_len);
1419            }
1420            "ArrayCacheBySymbolById" | "ArrayCacheBySymbolBySide" | "ArrayCacheByOutcomeById" => {
1421                // ArrayCacheByOutcomeById keys the outer bucket on `outcome` — prediction
1422                // markets stream several outcomes of one market that can share an order id,
1423                // so a symbol-keyed lookup would merge two distinct outcomes into one row.
1424                // The others key on `symbol`. Second level is `id` except BySymbolBySide.
1425                let key1_name = if kind == "ArrayCacheByOutcomeById" { "outcome" } else { "symbol" };
1426                let symbol = cache_str_field(&item, key1_name).unwrap_or_default();
1427                let key2_name = if kind == "ArrayCacheBySymbolBySide" { "side" } else { "id" };
1428                let key2 = cache_str_field(&item, key2_name).unwrap_or_default();
1429                let was_duplicate = {
1430                    let hm = cache_dict_field_mut(m, "hashmap");
1431                    let bucket = hm.entry(symbol.clone())
1432                        .or_insert_with(|| Value::Map(HashMap::new()));
1433                    if let Value::Dict(bd) = bucket {
1434                        Arc::make_mut(bd);
1435                    }
1436                    if let Some(Value::Dict(bd)) = hm.get(&symbol) {
1437                        bd.contains_key(&key2)
1438                    } else { false }
1439                };
1440                let item_to_store = if was_duplicate {
1441                    let merged = {
1442                        let hm = cache_dict_field_mut(m, "hashmap");
1443                        let bucket = hm.get(&symbol).cloned();
1444                        let existing = match bucket {
1445                            Some(Value::Dict(bd)) => bd.get(&key2).cloned(),
1446                            _ => None,
1447                        };
1448                        match (existing, item.clone()) {
1449                            (Some(Value::Dict(old)), Value::Dict(new_)) => {
1450                                let mut merged = (*old).clone();
1451                                for (k, v) in new_.iter() { merged.insert(k.clone(), v.clone()); }
1452                                Value::Dict(Arc::new(merged))
1453                            }
1454                            (_, new_) => new_,
1455                        }
1456                    };
1457                    {
1458                        let hm = cache_dict_field_mut(m, "hashmap");
1459                        let bucket = hm.entry(symbol.clone())
1460                            .or_insert_with(|| Value::Map(HashMap::new()));
1461                        if let Value::Dict(bd) = bucket {
1462                            Arc::make_mut(bd).insert(key2.clone(), merged.clone());
1463                        }
1464                    }
1465                    // Remove the existing slot from _data.
1466                    {
1467                        let data = cache_data_mut(m);
1468                        if let Some(pos) = data.iter().position(|x| {
1469                            cache_str_field(x, key2_name).as_deref() == Some(&key2)
1470                                && cache_str_field(x, key1_name).as_deref() == Some(&symbol)
1471                        }) { data.remove(pos); }
1472                    }
1473                    merged
1474                } else {
1475                    let hm = cache_dict_field_mut(m, "hashmap");
1476                    let bucket = hm.entry(symbol.clone())
1477                        .or_insert_with(|| Value::Map(HashMap::new()));
1478                    if let Value::Dict(bd) = bucket {
1479                        Arc::make_mut(bd).insert(key2.clone(), item.clone());
1480                    }
1481                    item.clone()
1482                };
1483                // Evict from front if at cap.
1484                let evicting = match cap { Some(c) => {
1485                    cache_data_mut(m).len() == c
1486                }, None => false };
1487                if evicting {
1488                    let removed = {
1489                        let data = cache_data_mut(m);
1490                        if data.is_empty() { Value::Null } else { data.remove(0) }
1491                    };
1492                    let r_sym = cache_str_field(&removed, key1_name).unwrap_or_default();
1493                    let r_key2 = cache_str_field(&removed, key2_name).unwrap_or_default();
1494                    {
1495                        let hm = cache_dict_field_mut(m, "hashmap");
1496                        let now_empty = if let Some(Value::Dict(bd)) = hm.get_mut(&r_sym) {
1497                            let bd = Arc::make_mut(bd);
1498                            bd.shift_remove(&r_key2);
1499                            bd.is_empty()
1500                        } else { false };
1501                        // Drop the emptied outer bucket, else a stream of short-lived
1502                        // keys leaks one empty object per key forever (mirrors TS
1503                        // `delete this.hashmap[deleteKey]` when its last id is gone).
1504                        if now_empty { hm.shift_remove(&r_sym); }
1505                    }
1506                    // The evicted key2 leaves both update scopes; a single-scope
1507                    // poller never fires the other scope's clear, so decrement the
1508                    // counts here or they would report the evicted id forever.
1509                    if cache_seen_remove(m, "_seenUpdatesBySymbol", &r_sym, &r_key2) {
1510                        let nubs = cache_dict_field_mut(m, "_newUpdatesBySymbol");
1511                        if let Some(Value::Int(n)) = nubs.get(&r_sym).cloned() {
1512                            nubs.insert(r_sym.clone(), Value::Int(n - 1));
1513                        }
1514                    }
1515                    if cache_seen_remove(m, "_seenUpdatesAll", &r_sym, &r_key2) {
1516                        let all = cache_int_field(m, "_allNewUpdates");
1517                        cache_set_int(m, "_allNewUpdates", all - 1);
1518                    }
1519                }
1520                cache_data_mut(m).push(item_to_store);
1521
1522                // Keyed caches count the distinct second-level keys (id / side)
1523                // seen per scope. Mirror ArrayCacheBySymbolById/BySymbolBySide
1524                // .append (base/ws/Cache.ts): symbol scope and global scope keep
1525                // independent seen-sets, each cleared only by its own poll.
1526                cache_apply_clear_all(m);
1527                if cache_take_symbol_clear(m, &symbol) {
1528                    cache_seen_clear(m, "_seenUpdatesBySymbol", &symbol);
1529                }
1530                let sz = cache_seen_add(m, "_seenUpdatesBySymbol", &symbol, &key2);
1531                cache_dict_field_mut(m, "_newUpdatesBySymbol").insert(symbol.clone(), Value::Int(sz));
1532                let before = cache_seen_size(m, "_seenUpdatesAll", &symbol);
1533                let after = cache_seen_add(m, "_seenUpdatesAll", &symbol, &key2);
1534                let all = cache_int_field(m, "_allNewUpdates");
1535                cache_set_int(m, "_allNewUpdates", all + (after - before));
1536            }
1537            _ => {}
1538        }
1539    }
1540}
1541
1542
1543pub(crate) fn cache_get_limit(target: &mut Value, symbol: Value, limit: Value) -> Value {
1544    let kind = cache_kind(target).unwrap_or_default();
1545    if let Some(id) = cache_id_of(target) {
1546        return with_cache_cell(id, move |m| cache_get_limit_inner(m, &kind, symbol, limit));
1547    }
1548    if let Value::Dict(m_arc) = target {
1549        let m = Arc::make_mut(m_arc);
1550        cache_get_limit_inner(m, &kind, symbol, limit)
1551    } else {
1552        limit
1553    }
1554}
1555
1556// Mirrors `ArrayCache.getLimit` (base/ws/Cache.ts). A `symbol` arg polls the
1557// symbol scope and arms its clear; `undefined` (Null) polls the global scope.
1558// The count is `undefined` only when the key was never seen — then the caller's
1559// `limit` passes through unclamped.
1560fn cache_get_limit_inner(m: &mut HashMap<String, Value>, kind: &str, symbol: Value, limit: Value) -> Value {
1561    {
1562        // `ArrayCacheByTimestamp` doesn't track per-symbol updates —
1563        // both `getLimit(undefined, …)` and `getLimit(sym, …)` return
1564        // `this.newUpdates` and arm a single global `clearUpdates` flag.
1565        if kind == "ArrayCacheByTimestamp" {
1566            let v = cache_int_field(m, "_newUpdates");
1567            cache_set_bool(m, "_clearUpdates", true);
1568            return match limit {
1569                Value::Int(l) => Value::Int(v.min(l)),
1570                _             => Value::Int(v),
1571            };
1572        }
1573        let new_updates_value: Option<i64> = match &symbol {
1574            Value::Null => {
1575                cache_set_bool(m, "_clearAllUpdates", true);
1576                Some(cache_int_field(m, "_allNewUpdates"))
1577            }
1578            Value::Str(sym) => {
1579                let v = match cache_dict_field_mut(m, "_newUpdatesBySymbol").get(sym.as_ref()) {
1580                    Some(Value::Int(n)) => Some(*n),
1581                    _ => None,
1582                };
1583                cache_dict_field_mut(m, "_clearUpdatesBySymbol")
1584                    .insert(sym.to_string(), Value::Bool(true));
1585                v
1586            }
1587            _ => None,
1588        };
1589        match (new_updates_value, &limit) {
1590            (None,    _)              => limit.clone(),
1591            (Some(v), Value::Int(l))  => Value::Int(v.min(*l)),
1592            (Some(v), _)              => Value::Int(v),
1593        }
1594    }
1595}
1596
1597// ────────────────────────────────────────────────────────────────────────────
1598// WS order-book helpers — operate on the `Value::Dict` markers from
1599// `crate::pro::order_book`. Tag layout:
1600//   * `__bookKind`  ∈ {OrderBook, IndexedOrderBook, CountedOrderBook}
1601//   * `__sideKind`  ∈ {OrderBookSide, IndexedOrderBookSide,
1602//                      CountedOrderBookSide}  (carried under `bids`/`asks`)
1603// ────────────────────────────────────────────────────────────────────────────
1604
1605fn as_f64(v: &Value) -> f64 {
1606    match v {
1607        Value::Float(f) => *f,
1608        Value::Int(n)   => *n as f64,
1609        Value::Str(s)   => s.parse().unwrap_or(0.0),
1610        _ => 0.0,
1611    }
1612}
1613
1614fn book_kind(v: &Value) -> Option<String> {
1615    match v { Value::Dict(d) => match d.get("__bookKind") {
1616        Some(Value::Str(s)) => Some(s.to_string()), _ => None,
1617    }, _ => None }
1618}
1619
1620// ────────────────────────────────────────────────────────────────────────────
1621// Shared book scalar-metadata store.
1622//
1623// Like side entries, an OrderBook's scalar fields must be shared across clones:
1624// WS handlers mutate a book pulled out of `self.orderbooks` (a COW clone) and
1625// expect the write visible on the next message — okx's per-message seqId nonce
1626// check reads the book's `nonce`, written inside `handle_order_book_message` on
1627// a clone. These fields live in a store keyed by a stable `__book_id`; bids/asks
1628// stay in the Dict (their entries are already shared via `__side_id`).
1629
1630/// Scalar book fields that live in the shared meta store (not the Dict).
1631fn is_book_meta_key(k: &str) -> bool {
1632    matches!(k, "timestamp" | "datetime" | "nonce" | "symbol" | "checksum")
1633}
1634
1635pub(crate) fn alloc_book_id() -> i64 {
1636    store_op(|s| {
1637        s.last_book_id += 1;
1638        let id = s.last_book_id;
1639        s.books.entry(id).or_default();
1640        id
1641    })
1642}
1643
1644fn book_id_of(m: &HashMap<String, Value>) -> Option<i64> {
1645    match m.get("__book_id") { Some(Value::Int(n)) => Some(*n), _ => None }
1646}
1647
1648fn book_meta_get(id: i64, k: &str) -> Value {
1649    let k = k.to_string();
1650    store_op(move |s| {
1651        s.books.get(&id).and_then(|b| b.meta.get(&k).cloned()).unwrap_or(Value::Null)
1652    })
1653}
1654
1655pub(crate) fn book_meta_set(id: i64, k: &str, v: Value) {
1656    let k = k.to_string();
1657    store_op(move |s| { s.books.entry(id).or_default().meta.insert(k, v); });
1658}
1659
1660fn book_meta_snapshot(id: i64) -> Vec<(String, Value)> {
1661    store_op(move |s| {
1662        s.books.get(&id)
1663            .map(|b| b.meta.iter().map(|(k, v)| (k.clone(), v.clone())).collect())
1664            .unwrap_or_default()
1665    })
1666}
1667
1668// A JS `OrderBook` also carries a mutable `cache` array — venues that fetch a
1669// REST/`req` snapshot buffer live deltas into `orderbook.cache` while the
1670// snapshot is in flight (binance, htx, …). Like the sides/meta, the cache must
1671// be shared across clones: `orderbook.cache.push(msg)` transpiles to
1672// `append_to_array(get_value(&book, "cache"), msg)`, and get_value returns a COW
1673// clone. So `get_value(book, "cache")` returns a lightweight handle carrying
1674// `__book_cache_id`, and length/index/append/clear route through this store.
1675
1676/// Build a cache handle for a book id (returned by `get_value(book, "cache")`).
1677fn book_cache_handle(id: i64) -> Value {
1678    let mut h = HashMap::new();
1679    h.insert("__book_cache_id".to_string(), Value::Int(id));
1680    Value::Dict(Arc::new(h))
1681}
1682
1683fn book_cache_id_of(m: &HashMap<String, Value>) -> Option<i64> {
1684    match m.get("__book_cache_id") { Some(Value::Int(n)) => Some(*n), _ => None }
1685}
1686
1687pub(crate) fn book_cache_push(id: i64, v: Value) {
1688    store_op(move |s| { s.books.entry(id).or_default().cache.push(v); });
1689}
1690
1691fn book_cache_len(id: i64) -> usize {
1692    store_op(move |s| s.books.get(&id).map(|b| b.cache.len()).unwrap_or(0))
1693}
1694
1695/// Length of a cache handle Dict's backing store, or None if `m` isn't a handle.
1696pub(crate) fn book_cache_len_of(m: &HashMap<String, Value>) -> Option<usize> {
1697    book_cache_id_of(m).map(book_cache_len)
1698}
1699
1700/// If `m` is a tagged live-subscriptions snapshot, apply `client.subscriptions
1701/// [key] = val` to the live WS client and return true.
1702pub(crate) fn try_ws_subs_write(m: &HashMap<String, Value>, key: &str, val: &Value) -> bool {
1703    if key == "__ws_subs_url" { return false; }
1704    if let Some(Value::Str(url)) = m.get("__ws_subs_url") {
1705        crate::pro::ws_client::value_subs_insert(url, key, val.clone());
1706        return true;
1707    }
1708    false
1709}
1710
1711/// If `m` is a tagged subscription dict (`__ws_sub_ref`), persist a field write
1712/// `subscription[key] = val` to the live WS client and return true.
1713pub(crate) fn try_ws_sub_field_write(m: &HashMap<String, Value>, key: &str, val: &Value) -> bool {
1714    if key == "__ws_sub_ref" { return false; }
1715    if let Some(Value::Str(subref)) = m.get("__ws_sub_ref") {
1716        crate::pro::ws_client::value_sub_field_write(subref, key, val.clone());
1717        return true;
1718    }
1719    false
1720}
1721
1722/// If `m` is a tagged live-subscriptions snapshot, apply `delete
1723/// client.subscriptions[key]` to the live WS client and return true.
1724pub(crate) fn try_ws_subs_remove(m: &HashMap<String, Value>, key: &str) -> bool {
1725    if let Some(Value::Str(url)) = m.get("__ws_subs_url") {
1726        crate::pro::ws_client::value_subs_remove(url, key);
1727        return true;
1728    }
1729    false
1730}
1731
1732/// If `obj` is a cache handle, push `v` into its store and return true.
1733pub(crate) fn try_book_cache_push(obj: &Value, v: &Value) -> bool {
1734    if let Value::Dict(m) = obj {
1735        if let Some(id) = book_cache_id_of(m) { book_cache_push(id, v.clone()); return true; }
1736    }
1737    false
1738}
1739
1740fn book_cache_at(id: i64, i: usize) -> Value {
1741    store_op(move |s| s.books.get(&id).and_then(|b| b.cache.get(i).cloned()).unwrap_or(Value::Null))
1742}
1743
1744/// Replace a book's cache contents (from `book.cache = [...]`, usually to clear).
1745pub(crate) fn book_cache_set(id: i64, items: Vec<Value>) {
1746    store_op(move |s| { s.books.entry(id).or_default().cache = items; });
1747}
1748
1749/// Snapshot a WS cache's rolling buffer as a plain array. Handles both the
1750/// `_data`-backed ArrayCache / ArrayCacheByTimestamp (trades, ohlcv, tickers)
1751/// and the registry-backed order-book cache handle. Returns `None` when `v`
1752/// isn't a cache — `to_array` then falls back to its generic Dict handling.
1753/// Without this, `to_array(cache)` would surface the cache's meta fields
1754/// (`__cacheKind`, counters, boolean flags) as if they were entries.
1755pub fn cache_entries_as_value(v: &Value) -> Option<Value> {
1756    if let Value::Dict(m) = v {
1757        if let Some(id) = book_cache_id_of(m) {
1758            let items = store_op(move |s| s.books.get(&id).map(|b| b.cache.clone()).unwrap_or_default());
1759            return Some(Value::Array(items));
1760        }
1761        if m.contains_key("__cacheKind") {
1762            return Some(Value::Array(cache_data_snapshot(m)));
1763        }
1764    }
1765    None
1766}
1767
1768/// If `m` is a shared book and `k` a meta key, write `v` to the book store and
1769/// return true (the caller should skip its own Dict insert); else false.
1770pub(crate) fn try_book_meta_write(m: &HashMap<String, Value>, k: &str, v: &Value) -> bool {
1771    if is_book_meta_key(k) {
1772        if let Some(id) = book_id_of(m) { book_meta_set(id, k, v.clone()); return true; }
1773    }
1774    // `book.cache = [...]` — replace the shared cache store (usually a clear).
1775    if k == "cache" {
1776        if let Some(id) = book_id_of(m) {
1777            let items = match v { Value::Arr(a) => a.as_ref().clone(), _ => Vec::new() };
1778            book_cache_set(id, items);
1779            return true;
1780        }
1781    }
1782    false
1783}
1784
1785/// Expand a shared book Dict into a plain Dict carrying its meta fields (for
1786/// serialization / equality). Strips `__book_id` so the result is inert.
1787pub fn book_fields_as_value(v: &Value) -> Option<Value> {
1788    match v {
1789        Value::Dict(d) if d.contains_key("__book_id") => {
1790            let mut out: HashMap<String, Value> = (**d).clone();
1791            out.shift_remove("__book_id");
1792            if let Some(Value::Int(id)) = d.get("__book_id") {
1793                for (k, val) in book_meta_snapshot(*id) { out.insert(k, val); }
1794            }
1795            Some(Value::Dict(Arc::new(out)))
1796        }
1797        _ => None,
1798    }
1799}
1800
1801// ────────────────────────────────────────────────────────────────────────────
1802// Shared side backing store.
1803//
1804// In JS an `OrderBookSide` is a mutable object; the WS handlers routinely do
1805// `const bookside = book['asks']; storeDeltas(bookside, deltas)` where the
1806// helper mutates `bookside` in place and the change is visible through `book`.
1807// Our `Value` is copy-on-write (Arc), so cloning the side Dict and mutating the
1808// clone (the transpiled `handle_deltas(side.clone(), …)` shape) would lose the
1809// writes. To restore shared mutability we keep the side's `_entries` (and the
1810// indexed-side `hashmap`) OUTSIDE the Dict, in a global store keyed by a stable
1811// `__side_id` that survives cloning. All reads and writes go through the store,
1812// so every clone of a side Dict points at the same buffer — matching JS.
1813/// One order-book level. The price sort-key is stored inline so the bisect
1814/// reads it straight from the contiguous `entries` Vec instead of chasing a
1815/// per-level `Arc<Vec<Value>>` (the scattered-allocation cache cost L1nkus
1816/// flagged). `entry` keeps the full original level Value (extra columns, string
1817/// forms) so reads, checksums and serialization stay byte-identical.
1818struct Level {
1819    price: f64,   // raw price; the sort key (bids sort on -price)
1820    entry: Value, // the full [price, amount, …] level as delivered
1821}
1822#[derive(Default)]
1823struct SideCell {
1824    entries: Vec<Level>,
1825    hashmap: HashMap<String, Value>,
1826}
1827
1828
1829/// Allocate a fresh, empty side cell and return its id.
1830fn alloc_side_id() -> i64 {
1831    store_op(|s| {
1832        s.last_side_id += 1;
1833        let id = s.last_side_id;
1834        s.sides.insert(id, SideCell::default());
1835        id
1836    })
1837}
1838
1839/// Clear (but keep) an existing side cell — used on reset so the id stays
1840/// stable across reseeds instead of leaking a new cell each time.
1841fn clear_side_cell(id: i64) {
1842    store_op(move |s| {
1843        let cell = s.sides.entry(id).or_default();
1844        cell.entries.clear();
1845        cell.hashmap.clear();
1846    });
1847}
1848
1849fn side_id_of(m: &HashMap<String, Value>) -> Option<i64> {
1850    match m.get("__side_id") { Some(Value::Int(n)) => Some(*n), _ => None }
1851}
1852
1853/// Snapshot a side's entries (clone) — for read paths (indexing, length, JSON).
1854fn side_entries_view(m: &HashMap<String, Value>) -> Vec<Value> {
1855    match side_id_of(m) {
1856        Some(id) => store_op(move |s| s.sides.get(&id)
1857            .map(|c| c.entries.iter().map(|l| l.entry.clone()).collect()).unwrap_or_default()),
1858        // Legacy fallback: a side Dict that still carries an inline `_entries`.
1859        None => match m.get("_entries") { Some(Value::Arr(a)) => a.as_ref().clone(), _ => Vec::new() },
1860    }
1861}
1862
1863fn side_entry_at(m: &HashMap<String, Value>, i: usize) -> Value {
1864    match side_id_of(m) {
1865        Some(id) => store_op(move |s| s.sides.get(&id)
1866            .and_then(|c| c.entries.get(i).map(|l| l.entry.clone())).unwrap_or(Value::Null)),
1867        None => match m.get("_entries") {
1868            Some(Value::Arr(a)) => a.get(i).cloned().unwrap_or(Value::Null), _ => Value::Null },
1869    }
1870}
1871
1872pub(crate) fn side_entries_len(m: &HashMap<String, Value>) -> usize {
1873    match side_id_of(m) {
1874        Some(id) => store_op(move |s| s.sides.get(&id).map(|c| c.entries.len()).unwrap_or(0)),
1875        None => match m.get("_entries") { Some(Value::Arr(a)) => a.len(), _ => 0 },
1876    }
1877}
1878
1879/// Hand `f` the side's cell on the store's owner thread. No-op if the side
1880/// carries no `__side_id`.
1881fn with_side_cell<R>(m: &HashMap<String, Value>, f: impl FnOnce(&mut SideCell) -> R + Send + 'static) -> Option<R>
1882where
1883    R: Send + 'static,
1884{
1885    let id = side_id_of(m)?;
1886    Some(store_op(move |s| f(s.sides.entry(id).or_default())))
1887}
1888
1889/// Public: snapshot a side marker's entries as a `Value` array, or `None` when
1890/// `v` is not a side marker. Entries live in the shared side store (not the
1891/// Dict), so callers that need the raw `[[price, size, …], …]` list — test
1892/// helpers, serializers — go through this.
1893pub fn side_entries_as_value(v: &Value) -> Option<Value> {
1894    match v {
1895        Value::Dict(d) if d.contains_key("__sideKind") => Some(Value::List(side_entries_view(d))),
1896        _ => None,
1897    }
1898}
1899
1900/// `[price, amount]` for one level row (`Value::Arr`), coercing Str/Int/Float.
1901/// Returns `None` for a short/non-numeric row so it can be dropped.
1902fn row_price_amount(row: &Value) -> Option<[f64; 2]> {
1903    let r = match row { Value::Arr(a) => a, _ => return None };
1904    let num = |cell: Option<&Value>| -> f64 {
1905        match cell {
1906            Some(Value::Float(f)) => *f,
1907            Some(Value::Int(n)) => *n as f64,
1908            Some(Value::Str(s)) => s.parse().unwrap_or(f64::NAN),
1909            _ => f64::NAN,
1910        }
1911    };
1912    let p = num(r.first());
1913    let a = num(r.get(1));
1914    if p.is_nan() || a.is_nan() { None } else { Some([p, a]) }
1915}
1916
1917/// Read a side marker's levels as `[price, amount]` pairs straight from the
1918/// shared side store — no intermediate `Value` list is materialised, so the
1919/// typed `OrderBook::from_value` decode reads the book without cloning every
1920/// level. Returns `None` when `v` is not a side marker (the caller then reads a
1921/// plain `Value::Arr`). NaN/short rows are dropped (not valid book levels).
1922pub fn side_price_amounts(v: &Value) -> Option<Vec<[f64; 2]>> {
1923    let d = match v {
1924        Value::Dict(d) if d.contains_key("__sideKind") => d,
1925        _ => return None,
1926    };
1927    let out = match side_id_of(d) {
1928        Some(id) => store_op(move |s| match s.sides.get(&id) {
1929            Some(cell) => cell.entries.iter().filter_map(|l| row_price_amount(&l.entry)).collect(),
1930            None => Vec::new(),
1931        }),
1932        None => match d.get("_entries") {
1933            Some(Value::Arr(a)) => a.iter().filter_map(row_price_amount).collect(),
1934            _ => Vec::new(),
1935        },
1936    };
1937    Some(out)
1938}
1939
1940/// Build a fresh side marker Dict backed by a new (empty) shared cell.
1941pub(crate) fn make_side_marker(side_kind: &str, is_bid: bool, depth: i64) -> Value {
1942    let sid = alloc_side_id();
1943    let mut m = HashMap::new();
1944    m.insert("__sideKind".to_string(), Value::Str(side_kind.to_string().into()));
1945    m.insert("_isBid".to_string(),     Value::Bool(is_bid));
1946    m.insert("_depth".to_string(),     Value::Int(depth));
1947    m.insert("__side_id".to_string(),  Value::Int(sid));
1948    Value::Dict(Arc::new(m))
1949}
1950
1951fn side_kind(v: &Value) -> Option<String> {
1952    match v { Value::Dict(d) => match d.get("__sideKind") {
1953        Some(Value::Str(s)) => Some(s.to_string()), _ => None,
1954    }, _ => None }
1955}
1956
1957fn side_is_bid(m: &HashMap<String, Value>) -> bool {
1958    matches!(m.get("_isBid"), Some(Value::Bool(true)))
1959}
1960
1961fn side_depth(m: &HashMap<String, Value>) -> usize {
1962    match m.get("_depth") {
1963        Some(Value::Int(n)) if *n > 0 => *n as usize,
1964        _ => usize::MAX / 2,
1965    }
1966}
1967
1968fn level_price(entries: &[Level]) -> impl Fn(usize) -> f64 + '_ {
1969    move |i: usize| entries[i].price
1970}
1971
1972fn bisect_left_by(len: usize, target: f64, is_bid: bool, get_price: impl Fn(usize) -> f64) -> usize {
1973    let mut lo = 0usize;
1974    let mut hi = len;
1975    while lo < hi {
1976        let mid = (lo + hi) / 2;
1977        let p = get_price(mid);
1978        let ip = if is_bid { -p } else { p };
1979        if ip < target { lo = mid + 1; } else { hi = mid; }
1980    }
1981    lo
1982}
1983
1984fn delta_field<T>(d: &Value, idx: usize, parse: impl Fn(&Value) -> T, default: T) -> T {
1985    match d {
1986        Value::Arr(a) => match a.get(idx) { Some(v) => parse(v), None => default },
1987        _ => default,
1988    }
1989}
1990
1991fn entry_id(entries: &[Level], i: usize) -> String {
1992    if let Value::Arr(a) = &entries[i].entry {
1993        if let Some(v) = a.get(2) {
1994            return match v {
1995                Value::Str(s) => s.to_string(),
1996                Value::Int(n) => n.to_string(),
1997                _ => String::new(),
1998            };
1999        }
2000    }
2001    String::new()
2002}
2003
2004fn side_store_array(side: &Value, delta: Value) {
2005    let kind = side_kind(side).unwrap_or_default();
2006    let m = match side { Value::Dict(d) => d.as_ref(), _ => return };
2007    let is_bid = side_is_bid(m);
2008    with_side_cell(m, move |cell| {
2009    match kind.as_str() {
2010        "OrderBookSide" => {
2011            let price = delta_field(&delta, 0, as_f64, 0.0);
2012            let size  = delta_field(&delta, 1, as_f64, 0.0);
2013            let target = if is_bid { -price } else { price };
2014            let entries = &mut cell.entries;
2015            let idx = bisect_left_by(entries.len(), target, is_bid, level_price(entries));
2016            let matches_here = idx < entries.len()
2017                && (if is_bid { -entries[idx].price } else { entries[idx].price }) == target;
2018            if size != 0.0 {
2019                if matches_here {
2020                    entries[idx] = Level { price, entry: delta };
2021                } else {
2022                    entries.insert(idx, Level { price, entry: delta });
2023                }
2024            } else if matches_here {
2025                entries.remove(idx);
2026            }
2027        }
2028        "CountedOrderBookSide" => {
2029            let price = delta_field(&delta, 0, as_f64, 0.0);
2030            let size  = delta_field(&delta, 1, as_f64, 0.0);
2031            let count = delta_field(&delta, 2, as_f64, 0.0);
2032            // JS gates a counted store on `size && count`, but some venues drive
2033            // a counted book with no numeric count in slot 2 — bitget stores
2034            // `[price, size, [rawPrice, rawSize]]` (the raw pair, for checksums).
2035            // Only treat slot 2 as a count when it's actually a number; otherwise
2036            // gate on size alone so the entry stores.
2037            let has_count = matches!(&delta,
2038                Value::Arr(a) if matches!(a.get(2), Some(Value::Int(_)) | Some(Value::Float(_))));
2039            let store_it = if has_count { size != 0.0 && count != 0.0 } else { size != 0.0 };
2040            let target = if is_bid { -price } else { price };
2041            let entries = &mut cell.entries;
2042            let idx = bisect_left_by(entries.len(), target, is_bid, level_price(entries));
2043            let matches_here = idx < entries.len()
2044                && (if is_bid { -entries[idx].price } else { entries[idx].price }) == target;
2045            if store_it {
2046                if matches_here {
2047                    entries[idx] = Level { price, entry: delta };
2048                } else {
2049                    entries.insert(idx, Level { price, entry: delta });
2050                }
2051            } else if matches_here {
2052                entries.remove(idx);
2053            }
2054        }
2055        "IndexedOrderBookSide" => {
2056            let price_opt = match &delta {
2057                Value::Arr(a) => a.first().and_then(|v| match v {
2058                    Value::Float(f) => Some(*f),
2059                    Value::Int(n)   => Some(*n as f64),
2060                    _ => None,
2061                }),
2062                _ => None,
2063            };
2064            let size = delta_field(&delta, 1, as_f64, 0.0);
2065            let id = match &delta {
2066                Value::Arr(a) => match a.get(2) {
2067                    Some(Value::Str(s)) => s.to_string(),
2068                    Some(Value::Int(n)) => n.to_string(),
2069                    _ => String::new(),
2070                },
2071                _ => String::new(),
2072            };
2073            let mut index_price = price_opt.map(|p| if is_bid { -p } else { p });
2074            let old_price_opt = {
2075                match cell.hashmap.get(&id) {
2076                    Some(Value::Float(f)) => Some(*f),
2077                    Some(Value::Int(n))   => Some(*n as f64),
2078                    _ => None,
2079                }
2080            };
2081            if size != 0.0 {
2082                if let Some(old_price) = old_price_opt {
2083                    index_price = index_price.or(Some(old_price));
2084                    if Some(old_price) == index_price {
2085                        // Find slot by walking from bisect_left
2086                        let target = old_price;
2087                        let raw = if is_bid { -old_price } else { old_price };
2088                        let entries = &mut cell.entries;
2089                        let mut idx = bisect_left_by(entries.len(), target, is_bid, level_price(entries));
2090                        while idx < entries.len() && entry_id(entries, idx) != id { idx += 1; }
2091                        if idx < entries.len() { entries[idx] = Level { price: raw, entry: delta }; }
2092                        return;
2093                    }
2094                    // Different price — remove old slot
2095                    let target = old_price;
2096                    let entries = &mut cell.entries;
2097                    let mut old_idx = bisect_left_by(entries.len(), target, is_bid, level_price(entries));
2098                    while old_idx < entries.len() && entry_id(entries, old_idx) != id { old_idx += 1; }
2099                    if old_idx < entries.len() { entries.remove(old_idx); }
2100                }
2101                let target = match index_price { Some(p) => p, None => return };
2102                let raw = if is_bid { -target } else { target };
2103                // Insert sorted with secondary id tiebreaker
2104                let entries = &mut cell.entries;
2105                let mut idx = bisect_left_by(entries.len(), target, is_bid, level_price(entries));
2106                while idx < entries.len() {
2107                    let ip = if is_bid { -entries[idx].price } else { entries[idx].price };
2108                    if ip != target { break; }
2109                    if entry_id(entries, idx) >= id { break; }
2110                    idx += 1;
2111                }
2112                entries.insert(idx, Level { price: raw, entry: delta });
2113                cell.hashmap.insert(id, Value::Float(target));
2114            } else if let Some(old_price) = old_price_opt {
2115                // Delete by id
2116                let target = old_price;
2117                let entries = &mut cell.entries;
2118                let mut idx = bisect_left_by(entries.len(), target, is_bid, level_price(entries));
2119                while idx < entries.len() && entry_id(entries, idx) != id { idx += 1; }
2120                if idx < entries.len() { entries.remove(idx); }
2121                cell.hashmap.shift_remove(&id);
2122            }
2123        }
2124        _ => {}
2125    }
2126    });
2127}
2128
2129fn side_limit(side: &Value) {
2130    let m = match side { Value::Dict(d) => d.as_ref(), _ => return };
2131    let depth = side_depth(m);
2132    with_side_cell(m, move |cell| {
2133        if cell.entries.len() > depth { cell.entries.truncate(depth); }
2134    });
2135}
2136
2137fn book_reseed_sides(book: &mut Value, snapshot: &Value) {
2138    let kind = book_kind(book).unwrap_or_default();
2139    let side_kind_str = match kind.as_str() {
2140        "IndexedOrderBook" => "IndexedOrderBookSide",
2141        "CountedOrderBook" => "CountedOrderBookSide",
2142        _                  => "OrderBookSide",
2143    };
2144    let bids_deltas = crate::get_value(snapshot, &Value::Str("bids".into()));
2145    let asks_deltas = crate::get_value(snapshot, &Value::Str("asks".into()));
2146    if let Value::Dict(book_arc) = book {
2147        let book_m = Arc::make_mut(book_arc);
2148        let depth = match book_m.get("_depth") {
2149            Some(Value::Int(n)) => *n,
2150            _ => i64::MAX / 2,
2151        };
2152        // Rebuild bids/asks. Reuse the existing side's `__side_id` (clearing its
2153        // backing cell) so repeated resets don't leak a fresh cell each time.
2154        for (side_key, deltas, is_bid) in [
2155            ("bids", &bids_deltas, true),
2156            ("asks", &asks_deltas, false),
2157        ] {
2158            let sid = match book_m.get(side_key) {
2159                Some(Value::Dict(d)) => match d.get("__side_id") {
2160                    Some(Value::Int(n)) => { clear_side_cell(*n); *n }
2161                    _ => alloc_side_id(),
2162                },
2163                _ => alloc_side_id(),
2164            };
2165            let mut m = HashMap::new();
2166            m.insert("__sideKind".to_string(),  Value::Str(side_kind_str.to_string().into()));
2167            m.insert("_isBid".to_string(),      Value::Bool(is_bid));
2168            m.insert("_depth".to_string(),      Value::Int(depth));
2169            m.insert("__side_id".to_string(),   Value::Int(sid));
2170            let side = Value::Map(m);
2171            if let Value::Arr(rows) = deltas {
2172                for row in rows.iter() {
2173                    if let Value::Arr(_) = row { side_store_array(&side, row.clone()); }
2174                }
2175            }
2176            book_m.insert(side_key.to_string(), side);
2177        }
2178    }
2179}
2180
2181pub(crate) fn book_limit(book: &mut Value) {
2182    if book_kind(book).is_none() { return; }
2183    if let Value::Dict(arc) = book {
2184        let m = Arc::make_mut(arc);
2185        if let Some(side) = m.get_mut("bids") { side_limit(side); }
2186        if let Some(side) = m.get_mut("asks") { side_limit(side); }
2187    }
2188}
2189
2190pub(crate) fn book_reset(book: &mut Value, snapshot: Value) {
2191    if book_kind(book).is_none() { return; }
2192    book_reseed_sides(book, &snapshot);
2193    let id = match book { Value::Dict(d) => book_id_of(d), _ => None };
2194    if let Some(id) = id {
2195        let ts = match crate::get_value(&snapshot, &Value::Str("timestamp".into())) {
2196            Value::Int(n)   => Some(n),
2197            Value::Float(f) => Some(f as i64),
2198            _ => None,
2199        };
2200        let dt = ts.and_then(|n| chrono::DateTime::<chrono::Utc>::from_timestamp_millis(n)
2201            .map(|t| t.to_rfc3339_opts(chrono::SecondsFormat::Millis, true)));
2202        book_meta_set(id, "timestamp", ts.map(Value::Int).unwrap_or(Value::Null));
2203        book_meta_set(id, "datetime",  dt.map(|s| Value::Str(s.into())).unwrap_or(Value::Null));
2204        book_meta_set(id, "nonce",     crate::get_value(&snapshot, &Value::Str("nonce".into())));
2205        book_meta_set(id, "symbol",    crate::get_value(&snapshot, &Value::Str("symbol".into())));
2206    }
2207}
2208
2209pub(crate) fn book_update(book: &mut Value, snapshot: Value) {
2210    if book_kind(book).is_none() { return; }
2211    // Skip stale updates.
2212    let new_nonce = match crate::get_value(&snapshot, &Value::Str("nonce".into())) {
2213        Value::Int(n) => Some(n), _ => None,
2214    };
2215    let cur_nonce = match book {
2216        Value::Dict(d) => match book_id_of(d).map(|id| book_meta_get(id, "nonce")) {
2217            Some(Value::Int(n)) => Some(n), _ => None,
2218        },
2219        _ => None,
2220    };
2221    if let (Some(n), Some(cur)) = (new_nonce, cur_nonce) {
2222        if n <= cur { return; }
2223    }
2224    book_reset(book, snapshot);
2225}
2226
2227pub(crate) fn book_store_array_side(book: &mut Value, side_key: &str, delta: Value) {
2228    if let Value::Dict(arc) = book {
2229        let m = Arc::make_mut(arc);
2230        if let Some(side) = m.get_mut(side_key) {
2231            side_store_array(side, delta);
2232        }
2233    }
2234}
2235
2236
2237// ─── Value method API exposed to the transpiled tests ─────────────────────
2238
2239impl Value {
2240    /// `book.timestamp|datetime|nonce|symbol = v` — the shared-store write for a
2241    /// tagged book, else the generic element write (same result as the helper).
2242    pub fn set_book_meta(&mut self, k: &str, v: Value) {
2243        if let Value::Dict(m) = &*self {
2244            if try_book_meta_write(m, k, &v) { return; }
2245        }
2246        crate::runtime::add_element_to_object(self, &Value::Str(k.to_string().into()), v);
2247    }
2248
2249    /// `book['bids'|'asks'|'nonce'|...]` read on an order-book-typed local: the same
2250    /// shared-store lookup `get_value` does for these keys, without the boxed key.
2251    pub fn book_field(&self, k: &str) -> Value {
2252        get_value_k(self, k)
2253    }
2254
2255    /// `book.limit()` — trim both sides to `_depth`. Returns a clone
2256    /// of `self` so transpiled `return book.limit();` lines still
2257    /// match the `-> Value` signature.
2258    pub fn limit(&mut self) -> Value {
2259        book_limit(self);
2260        self.clone()
2261    }
2262
2263    /// `book.reset(snapshot)` — wipe + reseed bids/asks + metadata.
2264    /// Returns self for the same reason as `limit()`. A bare
2265    /// `book.reset()` is also valid (matches the TS `OrderBook` shape);
2266    /// when called without a snapshot, we just rebind the existing one
2267    /// (effectively a no-op metadata refresh).
2268    pub fn reset(&mut self, snapshot: Value) -> Value {
2269        // `client.reset(error)` — a WS client handle (carries "url") rejects its
2270        // pending futures with the error; everything else is an OrderBook
2271        // snapshot reset.
2272        if matches!(&self, Value::Dict(d) if d.contains_key("url") && d.contains_key("subscriptions")) {
2273            return crate::pro::ws_client::value_reset(self, snapshot);
2274        }
2275        book_reset(self, snapshot);
2276        self.clone()
2277    }
2278    /// Zero-arg `reset()` form used by per-exchange WS code that just
2279    /// wants to clear the rolling buffers.
2280    pub fn reset0(&mut self) -> Value {
2281        book_reset(self, Value::Null);
2282        self.clone()
2283    }
2284
2285    /// `book.update(snapshot)` — same as reset but only when the
2286    /// supplied nonce moves forward.
2287    pub fn update(&mut self, snapshot: Value) -> Value {
2288        book_update(self, snapshot);
2289        self.clone()
2290    }
2291
2292    /// `side.store(price, size)` — convenience that builds a 2-element
2293    /// delta. Routed through the side's `store_array`. Only useful on a
2294    /// side marker (returned by `book['bids']`), not the book itself.
2295    pub fn store(&mut self, price: Value, size: Value) {
2296        if side_kind(self).is_some() {
2297            let delta = Value::List(vec![price, size]);
2298            side_store_array(self, delta);
2299        }
2300    }
2301
2302    /// Book-level side mutators — the transpiler rewrites side-extraction
2303    /// patterns (`let bids = book['bids']; bids.X(...)`) into calls on
2304    /// these methods so the mutation reaches the book's actual side
2305    /// dict rather than a COW-cloned copy of it.
2306    pub fn store_to_bids(&mut self, price: Value, size: Value) {
2307        let delta = Value::List(vec![price, size]);
2308        book_store_array_side(self, "bids", delta);
2309    }
2310    pub fn store_to_asks(&mut self, price: Value, size: Value) {
2311        let delta = Value::List(vec![price, size]);
2312        book_store_array_side(self, "asks", delta);
2313    }
2314    pub fn store_array_to_bids(&mut self, delta: Value) {
2315        book_store_array_side(self, "bids", delta);
2316    }
2317    pub fn store_array_to_asks(&mut self, delta: Value) {
2318        book_store_array_side(self, "asks", delta);
2319    }
2320}
2321
2322#[cfg(test)]
2323mod json_int_precision_tests {
2324    use super::Value;
2325
2326    #[test]
2327    fn preserves_large_u64_ids_losslessly() {
2328        // 12345678901234567890 > i64::MAX but ≤ u64::MAX — must not round.
2329        let v: serde_json::Value = serde_json::from_str(r#"{"id": 12345678901234567890}"#).unwrap();
2330        let parsed = Value::from_json(&v);
2331        let id = crate::runtime::get_value(&parsed, &Value::Str("id".into()));
2332        assert_eq!(id, Value::Str("12345678901234567890".into()));
2333    }
2334
2335    #[test]
2336    fn small_ints_stay_ints_floats_stay_floats() {
2337        let v: serde_json::Value = serde_json::from_str(r#"{"a": 42, "b": -7, "c": 1.5}"#).unwrap();
2338        let p = Value::from_json(&v);
2339        assert_eq!(crate::runtime::get_value(&p, &Value::Str("a".into())), Value::Int(42));
2340        assert_eq!(crate::runtime::get_value(&p, &Value::Str("b".into())), Value::Int(-7));
2341        assert_eq!(crate::runtime::get_value(&p, &Value::Str("c".into())), Value::Float(1.5));
2342    }
2343}
2344
2345#[cfg(test)]
2346mod value_len_tests {
2347    use super::*;
2348
2349    #[test]
2350    fn len_of_book_cache_handle_reports_backing_store() {
2351        // `typedBook.cache.length` lowers to `Value::len()` on the handle dict;
2352        // it must report the registry-backed store, not the handle's one key.
2353        let id = -424242; // private id, never handed out to a registered book
2354        let handle = book_cache_handle(id);
2355        assert_eq!(handle.len(), 0);
2356        book_cache_push(id, Value::Int(1));
2357        book_cache_push(id, Value::Int(2));
2358        assert_eq!(handle.len(), 2);
2359    }
2360
2361    #[test]
2362    fn len_of_plain_dict_still_counts_keys() {
2363        let mut m = HashMap::new();
2364        m.insert("a".to_string(), Value::Int(1));
2365        m.insert("b".to_string(), Value::Int(2));
2366        assert_eq!(Value::Dict(Arc::new(m)).len(), 2);
2367    }
2368
2369    #[test]
2370    fn store_serves_concurrent_writers_over_the_channel() {
2371        // Every mutation is a job on the store's owner thread; concurrent
2372        // callers must neither lose a write nor deadlock on each other.
2373        let id = alloc_book_id();
2374        let mut hs = Vec::new();
2375        for _ in 0..4 {
2376            hs.push(std::thread::spawn(move || {
2377                for i in 0..64i64 { book_cache_push(id, Value::Int(i)); }
2378            }));
2379        }
2380        for h in hs { h.join().unwrap(); }
2381        assert_eq!(book_cache_len(id), 256);
2382    }
2383
2384    #[test]
2385    fn store_panic_reaches_the_caller_and_leaves_the_owner_alive() {
2386        let hit = std::panic::catch_unwind(|| {
2387            let _: () = store_op(|_s: &mut WsStateStore| panic!("boom"));
2388        })
2389        .is_err();
2390        assert!(hit);
2391        // The owner catches job panics, so a dead store must not follow.
2392        let id = alloc_book_id();
2393        book_cache_push(id, Value::Int(1));
2394        assert_eq!(book_cache_len(id), 1);
2395    }
2396
2397    #[test]
2398    fn nested_store_op_panics_instead_of_deadlocking() {
2399        // A job must not re-enter the store: the owner would wait on itself.
2400        let hit = std::panic::catch_unwind(|| {
2401            store_op(|_s: &mut WsStateStore| { let _ = alloc_book_id(); });
2402        })
2403        .is_err();
2404        assert!(hit);
2405        // The owner survives the rejected nesting and keeps serving.
2406        let id = alloc_book_id();
2407        book_cache_push(id, Value::Int(7));
2408        assert_eq!(book_cache_len(id), 1);
2409    }
2410}