Skip to main content

ccxt_base/pro/
cache.rs

1// CCXT-pro Cache types — Value-shaped facades.
2//
3// Reflects the TS classes (`ArrayCache`, `ArrayCacheByTimestamp`,
4// `ArrayCacheBySymbolById`, `ArrayCacheBySymbolBySide`) into Rust as
5// unit-struct factories that return `Value::Dict` "marker maps". The
6// marker carries a `__cacheKind` tag, an optional `maxSize` cap, an
7// ordered `_data` Vec for the rolling buffer, plus per-class
8// bookkeeping fields (`_hashmap`, `_new_updates_by_symbol`, …).
9//
10// All append/clear/getLimit/length/indexing logic lives in
11// `Value::*` methods (see `value.rs` and `runtime.rs`) — the
12// transpiled tests in `rust/tests/base_ws/test.cache.rs` call those
13// methods directly on the Value-typed locals the transpiler emits
14// (`cache.append(...)`, `cache.get_limit(...)`, `cache.clear()`,
15// `cache[i]`, `get_array_length(&cache)`).
16
17use crate::Value;
18use indexmap::IndexMap;
19
20/// Cache kind tag stored at `__cacheKind` inside the marker map.
21/// Drives the dispatch in `Value::append`.
22pub const KIND_ARRAY_CACHE:              &str = "ArrayCache";
23pub const KIND_ARRAY_CACHE_BY_TIMESTAMP: &str = "ArrayCacheByTimestamp";
24pub const KIND_ARRAY_CACHE_BY_SYMBOL_ID: &str = "ArrayCacheBySymbolById";
25pub const KIND_ARRAY_CACHE_BY_SYMBOL_SIDE: &str = "ArrayCacheBySymbolBySide";
26// Prediction-market cache: like BySymbolById but keys the outer bucket on
27// `outcome` (several outcomes of one market can share an order id), so it needs
28// a distinct tag or the append dispatch merges two outcomes into one row.
29pub const KIND_ARRAY_CACHE_BY_OUTCOME_ID: &str = "ArrayCacheByOutcomeById";
30
31/// Internal constructor: builds the marker `Value::Dict` with default
32/// bookkeeping fields. Per-kind overrides flip specific fields after.
33fn new_marker(kind: &str, max_size: Value) -> Value {
34    // The mutable rolling buffer + hashmap + counters live in the shared cache
35    // registry (keyed by __cache_id) so COW clones of the marker share them —
36    // see value::CACHE_STORE. The marker Dict keeps only the immutable tags.
37    let mut state: IndexMap<String, Value> = IndexMap::new();
38    state.insert("_data".to_string(),             Value::Array(Vec::new()));
39    state.insert("hashmap".to_string(),           Value::Map(IndexMap::new()));
40    state.insert("_newUpdatesBySymbol".to_string(),   Value::Map(IndexMap::new()));
41    // Two independent distinct-key seen-sets: the symbol-scoped poll and the
42    // global poll each clear only their own scope (see value::cache_seen_*).
43    state.insert("_seenUpdatesBySymbol".to_string(),  Value::Map(IndexMap::new()));
44    state.insert("_seenUpdatesAll".to_string(),       Value::Map(IndexMap::new()));
45    state.insert("_clearUpdatesBySymbol".to_string(), Value::Map(IndexMap::new()));
46    state.insert("_allNewUpdates".to_string(),    Value::Int(0));
47    state.insert("_clearAllUpdates".to_string(),  Value::Bool(false));
48    // Per-timestamp cache fields (default zero/empty; unused by the other kinds).
49    state.insert("_sizeTracker".to_string(),      Value::Map(IndexMap::new()));
50    state.insert("_newUpdates".to_string(),       Value::Int(0));
51    state.insert("_clearUpdates".to_string(),     Value::Bool(false));
52    let id = crate::value::alloc_cache_id(state);
53    let mut m = IndexMap::new();
54    m.insert("__cacheKind".to_string(),       Value::Str(kind.to_string().into()));
55    m.insert("__cache_id".to_string(),        Value::Int(id));
56    m.insert("maxSize".to_string(),           max_size);
57    Value::Map(m)
58}
59
60// ─── public factories ─────────────────────────────────────────────────────
61
62pub struct ArrayCache;
63impl ArrayCache {
64    /// `new ArrayCache(maxSize?)` → marker map. `maxSize` is held as a
65    /// `Value::Int` or `Value::Null` (matches the JS `undefined` semantics).
66    pub fn new(max_size: Value) -> Value {
67        new_marker(KIND_ARRAY_CACHE, max_size)
68    }
69}
70
71pub struct ArrayCacheByTimestamp;
72impl ArrayCacheByTimestamp {
73    pub fn new(max_size: Value) -> Value {
74        new_marker(KIND_ARRAY_CACHE_BY_TIMESTAMP, max_size)
75    }
76}
77
78pub struct ArrayCacheBySymbolById;
79impl ArrayCacheBySymbolById {
80    pub fn new(max_size: Value) -> Value {
81        new_marker(KIND_ARRAY_CACHE_BY_SYMBOL_ID, max_size)
82    }
83}
84
85pub struct ArrayCacheBySymbolBySide;
86impl ArrayCacheBySymbolBySide {
87    pub fn new(max_size: Value) -> Value {
88        new_marker(KIND_ARRAY_CACHE_BY_SYMBOL_SIDE, max_size)
89    }
90}
91
92/// Prediction-market analogue of `ArrayCacheBySymbolById`, keyed by outcome id
93/// instead of symbol id. Behaviourally identical for the cache marker, so it
94/// reuses the same kind.
95pub struct ArrayCacheByOutcomeById;
96impl ArrayCacheByOutcomeById {
97    pub fn new(max_size: Value) -> Value {
98        new_marker(KIND_ARRAY_CACHE_BY_OUTCOME_ID, max_size)
99    }
100}