1use std::cmp::Ordering;
4use std::collections::BTreeMap;
5use std::fmt;
6
7use serde::de::Error as _;
8use serde::{Deserialize, Deserializer, Serialize, Serializer};
9use serde_json::Value;
10
11use crate::error::{Error, ErrorCode};
12
13#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
15#[serde(rename_all = "lowercase")]
16pub enum Mode {
17 #[default]
18 Live,
19 Confirmed,
20}
21
22#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
26pub enum From {
27 #[default]
28 Live,
29 Cursor {
30 cursor: String,
31 engine: Option<String>,
32 },
33 Time(String),
34}
35
36pub type StartFrom = From;
39
40impl Serialize for From {
41 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
42 #[derive(Serialize)]
43 struct CursorFrom<'a> {
44 cursor: &'a str,
45 #[serde(skip_serializing_if = "Option::is_none")]
46 engine: Option<&'a str>,
47 }
48 #[derive(Serialize)]
49 struct TimeFrom<'a> {
50 time: &'a str,
51 }
52 match self {
53 From::Live => serializer.serialize_str("live"),
54 From::Cursor { cursor, engine } => CursorFrom { cursor, engine: engine.as_deref() }.serialize(serializer),
55 From::Time(time) => TimeFrom { time }.serialize(serializer),
56 }
57 }
58}
59
60impl<'de> Deserialize<'de> for From {
61 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
62 #[derive(Deserialize)]
63 #[serde(untagged)]
64 enum Wire {
65 Name(String),
66 Cursor { cursor: String, engine: Option<String> },
67 Time { time: String },
68 }
69 match Wire::deserialize(deserializer)? {
70 Wire::Name(name) if name == "live" => Ok(From::Live),
71 Wire::Name(name) => Err(D::Error::custom(format!("unknown start point {name:?}: expected \"live\", {{cursor}} or {{time}}"))),
72 Wire::Cursor { cursor, engine } => Ok(From::Cursor { cursor, engine }),
73 Wire::Time { time } => Ok(From::Time(time)),
74 }
75 }
76}
77
78macro_rules! string_enum {
80 ($(#[$meta:meta])* $name:ident { $($variant:ident => $text:literal,)* }) => {
81 $(#[$meta])*
82 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
83 #[non_exhaustive]
84 pub enum $name {
85 $($variant,)*
86 Other(String),
87 }
88
89 impl $name {
90 pub fn as_str(&self) -> &str {
91 match self {
92 $($name::$variant => $text,)*
93 $name::Other(text) => text,
94 }
95 }
96 }
97
98 impl fmt::Display for $name {
99 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100 f.write_str(self.as_str())
101 }
102 }
103
104 impl Serialize for $name {
105 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
106 serializer.serialize_str(self.as_str())
107 }
108 }
109
110 impl<'de> Deserialize<'de> for $name {
111 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
112 let text = String::deserialize(deserializer)?;
113 Ok(match text.as_str() {
114 $($text => $name::$variant,)*
115 _ => $name::Other(text),
116 })
117 }
118 }
119 };
120}
121
122string_enum! {
123 SourceState {
125 Live => "live",
126 Warming => "warming",
127 SourceDelayed => "source_delayed",
128 SourceDown => "source_down",
129 MarketClosed => "market_closed",
130 }
131}
132
133string_enum! {
134 ResetReason {
136 Roll => "roll",
137 CursorExpired => "cursor_expired",
138 EntitlementChanged => "entitlement_changed",
139 EngineChange => "engine_change",
140 }
141}
142
143string_enum! {
144 NoticeKind {
148 Reconnect => "reconnect",
149 Maintenance => "maintenance",
150 MaintenanceCancelled => "maintenance-cancelled",
151 }
152}
153
154#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
156#[serde(rename_all = "camelCase")]
157pub struct MaintenanceWindow {
158 pub id: String,
159 pub starts_at: String,
160 pub ends_at: String,
161 pub message: String,
162}
163
164#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
166pub struct Item<T = Value> {
167 pub id: String,
168 #[serde(rename = "final")]
169 pub is_final: bool,
170 pub ts: String,
171 pub data: T,
172}
173
174#[derive(Debug, Clone, Copy)]
176pub struct CloseCode;
177
178impl CloseCode {
179 pub const NORMAL: u16 = 1000;
180 pub const PROTOCOL_ERROR: u16 = 1002;
181 pub const BINARY_NOT_SUPPORTED: u16 = 1003;
182 pub const INVALID_UTF8: u16 = 1007;
183 pub const RATE_LIMITED: u16 = 1008;
184 pub const MESSAGE_TOO_BIG: u16 = 1009;
185 pub const INTERNAL_ERROR: u16 = 1011;
186 pub const SERVICE_RESTART: u16 = 1012;
187 pub const TRY_AGAIN_LATER: u16 = 1013;
188 pub const UNAUTHORIZED: u16 = 4001;
189 pub const FORBIDDEN: u16 = 4003;
190 pub const SLOW_CONSUMER: u16 = 4008;
191 pub const TOO_MANY_CONNECTIONS: u16 = 4029;
192 pub const CLIENT_RECONNECT: u16 = 4000;
194}
195
196fn cursor_parts(cursor: &str) -> Result<[u32; 3], Error> {
198 let invalid = || {
199 Error::new(
200 ErrorCode::InvalidParameters,
201 format!(
202 "Invalid cursor {}: expected <utcDay>.<rank>.<k>, unsigned 32-bit decimal integers without leading zeros",
203 Value::from(cursor)
204 ),
205 )
206 };
207 let mut parts = cursor.split('.');
208 let mut out = [0u32; 3];
209 for slot in &mut out {
210 let part = parts.next().ok_or_else(invalid)?;
211 let digits = !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit());
212 if !digits || (part.len() > 1 && part.starts_with('0')) {
213 return Err(invalid());
214 }
215 *slot = part.parse().map_err(|_| invalid())?;
216 }
217 if parts.next().is_some() {
218 return Err(invalid());
219 }
220 Ok(out)
221}
222
223pub fn compare_cursors(a: &str, b: &str) -> Result<Ordering, Error> {
226 Ok(cursor_parts(a)?.cmp(&cursor_parts(b)?))
227}
228
229#[derive(Debug, Serialize)]
231#[serde(tag = "t", rename_all = "lowercase")]
232pub(crate) enum ClientMessage<'a> {
233 Auth { token: &'a str },
234 Subscribe { sub: &'a str, instrument: &'a str, indicator: &'a str, params: &'a Value, mode: Mode, from: &'a From },
235 Unsubscribe { sub: &'a str },
236 Ping,
237}
238
239#[derive(Debug, Deserialize)]
241#[serde(tag = "t", rename_all = "lowercase")]
242pub(crate) enum ServerMessage {
243 Subscribed {
244 sub: String,
245 topic: String,
246 instrument: String,
247 #[serde(rename = "tickSizeNanos")]
248 tick_size_nanos: String,
249 engine: String,
250 },
251 Snapshot {
252 sub: String,
253 cursor: String,
254 items: Vec<Item>,
255 },
256 Upsert {
257 sub: String,
258 cursor: String,
259 id: String,
260 #[serde(rename = "final")]
261 is_final: bool,
262 ts: String,
263 #[serde(default)]
264 data: Value,
265 },
266 Remove {
267 sub: String,
268 cursor: String,
269 id: String,
270 #[serde(rename = "final")]
271 is_final: bool,
272 ts: String,
273 },
274 Status {
275 sub: String,
276 state: SourceState,
277 #[serde(rename = "lagMs")]
278 lag_ms: u64,
279 },
280 Reset {
281 sub: String,
282 reason: ResetReason,
283 },
284 Error {
285 #[serde(default)]
286 sub: Option<String>,
287 code: String,
288 message: String,
289 },
290 Hb {
291 #[serde(default)]
292 cursors: BTreeMap<String, String>,
293 },
294 Notice {
295 kind: NoticeKind,
296 #[serde(default)]
297 id: Option<String>,
298 #[serde(rename = "effectiveAt", default)]
299 effective_at: Option<String>,
300 #[serde(rename = "endsAt", default)]
301 ends_at: Option<String>,
302 #[serde(default)]
303 message: Option<String>,
304 },
305 Pong,
306 #[serde(other)]
307 Unknown,
308}