hypercall_client/indicative.rs
1//! Decoding `indicative_market_data` frames, batched or not.
2#![expect(
3 clippy::result_large_err,
4 reason = "decoders return the crate's established unboxed public ClientError"
5)]
6//!
7//! [`crate::WsClient::subscribe_indicative_market_data`] subscribes to
8//! `indicative_market_data_v2`, whose `IndicativeMarketDataBatch` frames each
9//! hold several rows oldest first. With batching disabled, or against a server
10//! that predates the v2 channel, it uses `indicative_market_data`, where each
11//! row arrives as its own `IndicativeMarketData` frame. The helpers here return the rows in delivery order either way, so
12//! applying them in order gives the same per-instrument state regardless of
13//! framing.
14//!
15//! ```rust
16//! use hypercall_client::indicative::decode_indicative_rows;
17//!
18//! let frame = r#"{"type":"IndicativeMarketDataBatch","flushed_at":2,"updates":[
19//! {"instrument":"BTC-20261002-87000-C","best_bid":"14.79","best_ask":"133.88",
20//! "num_providers":1,"published_at":1,"timestamp":1}]}"#;
21//! let rows = decode_indicative_rows(frame).unwrap().expect("indicative frame");
22//! assert_eq!(rows[0].instrument, "BTC-20261002-87000-C");
23//! ```
24
25use crate::error::Result;
26use hypercall_sdk_types::ws_protocol::{WsIndicativeMarketData, WsMessage};
27
28/// Rows carried by one server message, or `None` if it is not indicative
29/// market data.
30pub fn indicative_rows(message: WsMessage) -> Option<Vec<WsIndicativeMarketData>> {
31 match message {
32 WsMessage::IndicativeMarketData(row) => Some(vec![row]),
33 WsMessage::IndicativeMarketDataBatch(batch) => Some(batch.updates),
34 _ => None,
35 }
36}
37
38/// Decode one text frame and return its indicative rows, or `None` for any
39/// other message type.
40///
41/// Frames come from the network, so they are decoded with Serde, whose
42/// default recursion limit rejects hostile nesting (the repository JSON
43/// policy: Serde incoming, Sonic outgoing).
44pub fn decode_indicative_rows(frame: &str) -> Result<Option<Vec<WsIndicativeMarketData>>> {
45 let message: WsMessage = serde_json::from_str(frame)?;
46 Ok(indicative_rows(message))
47}
48
49/// [`decode_indicative_rows`] for a message already collected by
50/// [`crate::WsClient`] (see [`crate::WsClient::get_messages`]).
51pub fn indicative_rows_from_value(
52 value: &sonic_rs::Value,
53) -> Result<Option<Vec<WsIndicativeMarketData>>> {
54 // Re-encode and decode through the same guarded Serde path rather than
55 // converting the Sonic value directly.
56 decode_indicative_rows(&sonic_rs::to_string(value)?)
57}
58
59#[cfg(test)]
60#[path = "indicative_test.rs"]
61mod tests;