Skip to main content

df_hyperliquid_core/live/frame/
read.rs

1//! Reading one text frame ([`decode`]): its channel names the type its data reads into. A frame
2//! that does not read is a [`BadFrame`], naming the channel when it got that far.
3
4use std::{borrow::Cow, fmt};
5
6use crate::client::ExchangeResponse;
7use crate::live::{Ack, Answer, Frame, Method, Reply};
8use crate::utils::Json;
9use serde::Deserialize;
10use serde_json::value::RawValue;
11
12use super::one_pass::{channel_of, decode_in_one, is_plain, plain};
13
14/// A frame that did not read: the channel it named, when it got that far, and why.
15#[derive(Debug, Clone, PartialEq, Eq)]
16#[non_exhaustive]
17pub struct BadFrame {
18    /// The channel the frame named; `None` when it did not get that far.
19    pub channel: Option<String>,
20    /// Why it did not read.
21    pub detail: String,
22}
23
24impl fmt::Display for BadFrame {
25    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26        match &self.channel {
27            Some(channel) => write!(f, "a `{channel}` frame did not read: {}", self.detail),
28            None => write!(f, "not a frame: {}", self.detail),
29        }
30    }
31}
32
33impl std::error::Error for BadFrame {}
34
35#[derive(Deserialize)]
36struct Head<'a> {
37    #[serde(borrow)]
38    channel: Cow<'a, str>,
39    #[serde(default, borrow)]
40    data: Option<&'a RawValue>,
41}
42
43#[derive(Deserialize)]
44struct RawAck<'a> {
45    method: Method,
46    #[serde(borrow)]
47    subscription: &'a RawValue,
48}
49
50#[derive(Deserialize)]
51struct RawReply<'a> {
52    id: u64,
53    #[serde(borrow)]
54    response: RawResponse<'a>,
55}
56
57#[derive(Deserialize)]
58struct RawResponse<'a> {
59    #[serde(rename = "type", borrow)]
60    kind: Cow<'a, str>,
61    #[serde(borrow)]
62    payload: &'a RawValue,
63}
64
65#[derive(Deserialize)]
66struct RawInfo<'a> {
67    #[serde(rename = "type")]
68    kind: String,
69    #[serde(default, borrow)]
70    data: Option<&'a RawValue>,
71}
72
73/// Reads one text frame. `l2Book`, `trades` and `bbo` in the venue's own compact layout are read
74/// straight from the text. Other frames are read in one pass when they are
75/// `{"channel":..,"data":..}` in that order with nothing else, as the venue writes every data frame.
76/// Anything else, and every frame that does not read, is read in two passes (the frame with its
77/// data kept as written, then the data), which gives the same frame or says why not.
78pub fn decode(text: &str) -> Result<Frame, BadFrame> {
79    if let Some(frame) = super::hot::read(text) {
80        return Ok(frame);
81    }
82    if channel_of(text).is_some_and(is_plain)
83        && let Ok(frame) = decode_in_one(text)
84    {
85        return Ok(frame);
86    }
87    decode_in_two(text)
88}
89
90/// Whether [`decode`] reads `text` with its direct reader: an `l2Book`, `trades` or `bbo` frame in
91/// the venue's compact layout. For the live suite, which checks that the venue still writes that
92/// layout: behind the `__test-internals` feature, outside the crate's API and its semver promise.
93/// It reads the frame again, so it is not for every frame of a running program.
94#[cfg(feature = "__test-internals")]
95#[doc(hidden)]
96#[must_use]
97pub fn reads_directly(text: &str) -> bool {
98    super::hot::read(text).is_some()
99}
100
101/// Two passes: the frame with its data kept as written, then the data read for its channel. Reads
102/// every frame [`decode`] takes and names the reason for one it does not.
103pub(crate) fn decode_in_two(text: &str) -> Result<Frame, BadFrame> {
104    let head: Head<'_> = serde_json::from_str(text)
105        .map_err(|error| BadFrame { channel: None, detail: format!("{error} in {}", shown(text)) })?;
106    let channel = head.channel.as_ref();
107    let data = head.data.map(RawValue::get);
108    let typed = Typed { channel, data };
109    Ok(match channel {
110        "pong" => Frame::Pong,
111        "subscriptionResponse" => {
112            let ack: RawAck<'_> = typed.read()?;
113            let echo = Json::parse(ack.subscription.get()).map_err(|error| typed.fail(error.to_string()))?;
114            Frame::Ack(Ack { method: ack.method, echo })
115        }
116        "post" => Frame::Post(typed.reply()?),
117        "outcomeMetaUpdates" => {
118            Frame::OutcomeMetaUpdates(Json::parse(typed.data()?).map_err(|error| typed.fail(error.to_string()))?)
119        }
120        other => match typed.plain() {
121            Some(frame) => frame?,
122            None => Frame::Other { channel: other.to_owned(), data: data.unwrap_or_default().to_owned() },
123        },
124    })
125}
126
127/// A frame's data, read for the channel that named it.
128struct Typed<'a> {
129    channel: &'a str,
130    data: Option<&'a str>,
131}
132
133impl<'a> Typed<'a> {
134    fn fail(&self, detail: String) -> BadFrame {
135        BadFrame { channel: Some(self.channel.to_owned()), detail }
136    }
137
138    fn data(&self) -> Result<&'a str, BadFrame> {
139        self.data.ok_or_else(|| self.fail("no data".to_owned()))
140    }
141
142    fn read<T: Deserialize<'a>>(&self) -> Result<T, BadFrame> {
143        let data = self.data()?;
144        serde_json::from_str(data).map_err(|error| self.fail(format!("{error} in {}", shown(data))))
145    }
146
147    /// The data of a channel [`plain`] knows, read as `serde_json::from_str` would; `None` for
148    /// any other channel.
149    fn plain(&self) -> Option<Result<Frame, BadFrame>> {
150        if !is_plain(self.channel) {
151            return None;
152        }
153        let data = match self.data() {
154            Ok(data) => data,
155            Err(error) => return Some(Err(error)),
156        };
157        let mut de = serde_json::Deserializer::from_str(data);
158        let frame = plain(self.channel, &mut de)?.and_then(|frame| de.end().map(|()| frame));
159        Some(frame.map_err(|error| self.fail(format!("{error} in {}", shown(data)))))
160    }
161
162    fn reply(&self) -> Result<Reply, BadFrame> {
163        let data = self.data()?;
164        let reply: RawReply<'_> =
165            serde_json::from_str(data).map_err(|error| self.fail(format!("{error} in {}", shown(data))))?;
166        let payload = reply.response.payload.get();
167        let answer = match reply.response.kind.as_ref() {
168            "info" => {
169                let info: RawInfo<'_> = serde_json::from_str(payload).map_err(|error| self.fail(error.to_string()))?;
170                Answer::Info { kind: info.kind, data: info.data.map_or("null", RawValue::get).to_owned() }
171            }
172            "action" => Answer::Action(ExchangeResponse::parse(payload).map_err(|error| self.fail(error.to_string()))?),
173            "error" => Answer::Error(serde_json::from_str(payload).map_err(|error| self.fail(error.to_string()))?),
174            other => return Err(self.fail(format!("a post answered as `{other}`"))),
175        };
176        Ok(Reply { id: reply.id, answer })
177    }
178}
179
180/// The start of a text, for an error message.
181fn shown(text: &str) -> String {
182    let start: String = text.chars().take(160).collect();
183    match start.len() < text.len() {
184        true => format!("{start}..."),
185        false => start,
186    }
187}
188
189#[cfg(test)]
190#[path = "tests/read.rs"]
191mod tests;