Skip to main content

taba/rpc/
wire.rs

1//! Rust <-> TypeScript.
2
3use alloc::{
4    boxed::Box,
5    string::{String, ToString},
6    vec::Vec,
7};
8
9use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
10use serde_json::value::RawValue;
11
12use super::SessionId;
13use crate::{Input, Output, typescript::Shape};
14
15/// A [Safe JavaScript Number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger#description) <code>2<sup>53</sup> – 1</code>.
16///
17/// Never above <code>[Number.MAX_SAFE_INTEGER](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER) 2<sup>53</sup> – 1</code>.
18#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
19pub struct SafeInteger(u64);
20
21impl SafeInteger {
22    /// <code>[Number.MAX_SAFE_INTEGER](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER) 2<sup>53</sup> – 1</code>.
23    const MAX: u64 = (1 << 53) - 1;
24
25    /// The next integer, or this one again at the max.
26    pub(crate) fn saturating_next(self) -> Self {
27        Self((self.0 + 1).min(Self::MAX))
28    }
29}
30
31impl Serialize for SafeInteger {
32    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
33        serializer.serialize_u64(self.0) // we enforce the max at creation
34    }
35}
36
37impl<'de> Deserialize<'de> for SafeInteger {
38    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
39        match u64::deserialize(deserializer)? {
40            x if x <= Self::MAX => Ok(SafeInteger(x)),
41            x => Err(de::Error::custom(format_args!("{x} > `Number.MAX_SAFE_INTEGER`"))),
42        }
43    }
44}
45
46impl Output for SafeInteger {
47    const __SHAPE: Shape = Shape::Number;
48}
49
50impl Input for SafeInteger {
51    const __SHAPE: Shape = Shape::Number;
52}
53
54/// Requests from TypeScript.
55///
56/// `value` comes last for [`RawValue`]'s deferred parsing.
57#[derive(Debug, Deserialize, Input)]
58#[serde(tag = "kind", content = "value", rename_all = "lowercase")]
59pub enum Message {
60    /// Answered once.
61    Call(SafeInteger, String, Box<RawValue>),
62
63    /// Answered once per [`Next`](Self::Next).
64    Subscribe(SafeInteger, String, Box<RawValue>),
65
66    /// Pulls one value.
67    Next(SafeInteger),
68
69    /// Abort a call or subscription's task.
70    Cancel(SafeInteger),
71}
72
73/// A session's [`Message`]s, in the order TypeScript sent them.
74#[derive(Debug, Deserialize, Input)]
75pub struct Batch(pub(crate) SessionId, pub(crate) Vec<Message>);
76
77/// What a poll returns.
78#[derive(Debug, Serialize, Output)]
79pub struct Frame {
80    /// Its message's id.
81    pub(crate) id: SafeInteger,
82
83    /// Beside `id` on the wire.
84    #[serde(flatten)]
85    pub(crate) kind: Kind,
86}
87
88/// What a frame tells TypeScript.
89#[derive(Debug, Serialize, Output)]
90#[serde(tag = "kind", content = "value", rename_all = "lowercase")]
91pub enum Kind {
92    /// A handler's `Ok`.
93    Value(Box<RawValue>),
94
95    /// A handler's `Err`, which no frame follows.
96    Error(Box<RawValue>),
97
98    /// After a stream's last value.
99    End,
100
101    /// [`taba`](crate)'s own failure, rejected in TypeScript.
102    Reject(Rejection),
103}
104
105impl Kind {
106    /// Reject as [`Rejection::Unknown`].
107    pub fn unknown(name: String) -> Self {
108        Kind::Reject(Rejection::Unknown(name))
109    }
110
111    /// Reject as [`Rejection::Invalid`].
112    pub fn invalid(error: serde_json::Error) -> Self {
113        Kind::Reject(Rejection::Invalid(error.to_string()))
114    }
115
116    /// Reject as [`Rejection::Unencodable`].
117    pub fn unencodable(error: serde_json::Error) -> Self {
118        Kind::Reject(Rejection::Unencodable(error.to_string()))
119    }
120}
121
122/// Why [`taba`](crate) rejected a request.
123#[derive(Debug, Serialize, Output)]
124#[serde(tag = "kind", content = "value", rename_all = "lowercase")]
125pub enum Rejection {
126    /// No procedure by this name answers the request.
127    Unknown(String),
128
129    /// A request serde can't parse, and why.
130    Invalid(String),
131
132    /// A handler's result serde can't encode, and why.
133    Unencodable(String),
134
135    /// A handler's panic.
136    Panic(String),
137}
138
139#[cfg(test)]
140mod tests {
141    use alloc::vec::Vec;
142
143    use serde_json::value::RawValue;
144
145    use super::{Frame, Kind, Message, Rejection, SafeInteger};
146
147    /// [`Number.MAX_SAFE_INTEGER`]'s example.
148    ///
149    /// [`Number.MAX_SAFE_INTEGER`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER
150    #[test]
151    fn max_safe_integer() {
152        let x = SafeInteger::MAX + 1;
153        let y = SafeInteger::MAX + 2;
154
155        insta::assert_snapshot!(SafeInteger::MAX, @"9007199254740991");
156        insta::assert_snapshot!(x, @"9007199254740992");
157        insta::assert_snapshot!(x as f64 == y as f64, @"true"); // Rust is also IEEE 754
158
159        let max: SafeInteger = serde_json::from_str("9007199254740991").unwrap();
160        insta::assert_snapshot!(serde_json::to_string(&max).unwrap(), @"9007199254740991");
161        insta::assert_snapshot!(serde_json::to_string(&max.saturating_next()).unwrap(), @"9007199254740991");
162
163        let error = serde_json::from_str::<SafeInteger>("9007199254740992").unwrap_err();
164        insta::assert_snapshot!(error, @"9007199254740992 > `Number.MAX_SAFE_INTEGER`");
165    }
166
167    #[test]
168    fn every_message_kind() {
169        let batch = r#"[
170            {"kind":"call","value":[7,"buy",{"generator":"drill"}]},
171            {"kind":"subscribe","value":[8,"resources",{"resource":"ore"}]},
172            {"kind":"next","value":8},
173            {"kind":"cancel","value":8}
174        ]"#;
175        let batch: Vec<Message> = serde_json::from_str(batch).unwrap();
176        insta::assert_debug_snapshot!(batch, @r#"
177        [
178            Call(
179                SafeInteger(
180                    7,
181                ),
182                "buy",
183                RawValue(
184                    {"generator":"drill"},
185                ),
186            ),
187            Subscribe(
188                SafeInteger(
189                    8,
190                ),
191                "resources",
192                RawValue(
193                    {"resource":"ore"},
194                ),
195            ),
196            Next(
197                SafeInteger(
198                    8,
199                ),
200            ),
201            Cancel(
202                SafeInteger(
203                    8,
204                ),
205            ),
206        ]
207        "#);
208    }
209
210    #[test]
211    fn every_frame_kind() {
212        let json = |json: &str| RawValue::from_string(json.into()).unwrap();
213        let frames = [
214            Frame { id: SafeInteger(0), kind: Kind::Value(json("4")) },
215            Frame { id: SafeInteger(1), kind: Kind::Error(json(r#""not enough ore""#)) },
216            Frame { id: SafeInteger(2), kind: Kind::End },
217            Frame { id: SafeInteger(3), kind: Kind::Reject(Rejection::Unknown("sell".into())) },
218            Frame {
219                id: SafeInteger(4),
220                kind: Kind::Reject(Rejection::Invalid("trailing comma".into())),
221            },
222            Frame {
223                id: SafeInteger(5),
224                kind: Kind::Reject(Rejection::Unencodable("key must be a string".into())),
225            },
226            Frame {
227                id: SafeInteger(6),
228                kind: Kind::Reject(Rejection::Panic("the mine flooded".into())),
229            },
230        ];
231        let frames = frames.map(|frame| serde_json::to_string(&frame).unwrap());
232        insta::assert_snapshot!(frames.join("\n"), @r#"
233        {"id":0,"kind":"value","value":4}
234        {"id":1,"kind":"error","value":"not enough ore"}
235        {"id":2,"kind":"end"}
236        {"id":3,"kind":"reject","value":{"kind":"unknown","value":"sell"}}
237        {"id":4,"kind":"reject","value":{"kind":"invalid","value":"trailing comma"}}
238        {"id":5,"kind":"reject","value":{"kind":"unencodable","value":"key must be a string"}}
239        {"id":6,"kind":"reject","value":{"kind":"panic","value":"the mine flooded"}}
240        "#);
241    }
242}