aboutsummaryrefslogtreecommitdiff
path: root/crates/arti-rpc-client-core/src/msgs/request.rs
blob: 2cee05b3ad21276856b1573b1055004325cbc2cf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
//! Support for encoding and decoding RPC Requests.
//!
//! There are several types in this module:
//!
//! - [`Request`] is for requests that are generated from within this crate,
//!   to implement authentication, negotiation, and other functionality.
//! - `ParsedRequestFields` (internal) is for a request we've completely validated,
//!   with all of its fields present.
//! - [`ValidatedRequest`] is for a string that we have validated as a request.

use std::sync::Arc;

use serde::{Deserialize, Serialize};

/// Alias for a Map as used by the serde_json.
pub(crate) type JsonMap = serde_json::Map<String, serde_json::Value>;

use crate::conn::ProtoError;

use super::{AnyRequestId, JsonAnyObj, ObjectId};

/// An outbound request that we have generated from within this crate.
///
/// It lacks a required `id` field (since we will generate one when sending it),
/// and it allows any Serialize for its `params`.
#[derive(Serialize, Debug)]
// Testing only. Don't implement Deserialize here; this is not the type you should parse into!
#[cfg_attr(test, derive(Eq, PartialEq, Deserialize))]
#[allow(clippy::missing_docs_in_private_items)] // Fields are as for ParsedRequest.
pub(crate) struct Request<T> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) id: Option<AnyRequestId>,
    pub(crate) obj: ObjectId,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) meta: Option<RequestMeta>,
    pub(crate) method: String,
    pub(crate) params: T,
}

/// An error that has prevented us from validating an request.
#[derive(Clone, Debug, thiserror::Error)]
#[non_exhaustive]
pub enum InvalidRequestError {
    /// We failed to turn the request into any kind of json.
    #[error("Request was not valid Json")]
    InvalidJson(#[source] Arc<serde_json::Error>),
    /// We got the request into json, but we couldn't find the fields we wanted.
    #[error("Request's fields were invalid or missing")]
    InvalidFormat(#[source] Arc<serde_json::Error>),
    /// We validated the request, but couldn't re-encode it.
    #[error("Unable to re-encode or format request")]
    ReencodeFailed(#[source] Arc<serde_json::Error>),
}

impl<T: Serialize> Request<T> {
    /// Construct a new outbound Request.
    pub(crate) fn new(obj: ObjectId, method: impl Into<String>, params: T) -> Self {
        Self {
            id: None,
            obj,
            meta: Default::default(),
            method: method.into(),
            params,
        }
    }
    /// Try to encode this request as a String.
    ///
    /// The string may not yet be a valid request; it might need to get an ID assigned.
    pub(crate) fn encode(&self) -> Result<String, ProtoError> {
        serde_json::to_string(self).map_err(|e| ProtoError::CouldNotEncode(Arc::new(e)))
    }
}

/// A request in its decoded (or unencoded) format.
///
/// We use this type to validate outbound requests from the application.
#[derive(Deserialize, Debug)]
// Don't implement Serialize here; this is not for generating requests!
#[allow(dead_code)] // The fields here are only used for validating serde objects.
struct ParsedRequestFields {
    /// The identifier for this request.
    ///
    /// Used to match a request with its responses.
    id: AnyRequestId,
    /// The ID for the object to which this request is addressed.
    ///
    /// (Every request goes to a single object.)
    obj: ObjectId,
    /// Additional information for Arti about how to handle the request.
    #[serde(skip_serializing_if = "Option::is_none")]
    meta: Option<RequestMeta>,
    /// The name of the method to invoke.
    method: String,
    /// Parameters to pass to the method.
    params: JsonAnyObj,
}

/// A known-valid request, encoded as a string (in a single line, with a terminating newline).
#[derive(derive_more::AsRef, Debug, Clone)]
pub(crate) struct ValidatedRequest {
    /// The message itself, as encoded.
    #[as_ref]
    msg: String,
    /// The ID for this request.
    id: AnyRequestId,
}

impl ValidatedRequest {
    /// Return the Id associated with this request.
    pub(crate) fn id(&self) -> &AnyRequestId {
        &self.id
    }

    /// Try to construct a validated request from a `serde_json::Value`.
    fn from_json_value(val: serde_json::Value) -> Result<Self, InvalidRequestError> {
        let mut msg = serde_json::to_string(&val)
            .map_err(|e| InvalidRequestError::ReencodeFailed(Arc::new(e)))?;
        debug_assert!(!msg.contains('\n'));
        msg.push('\n');

        let req: ParsedRequestFields = serde_json::from_value(val)
            .map_err(|e| InvalidRequestError::InvalidFormat(Arc::new(e)))?;
        let id = req.id;

        Ok(ValidatedRequest { id, msg })
    }

    /// Try to construct a validated request using `s`.
    // TODO nb: Expose or remove.
    #[allow(dead_code)]
    pub(crate) fn from_string_strict(s: &str) -> Result<Self, InvalidRequestError> {
        let value: serde_json::Value =
            serde_json::from_str(s).map_err(|e| InvalidRequestError::InvalidJson(Arc::new(e)))?;
        Self::from_json_value(value)
    }

    /// Try to construct a ValidatedRequest from the string in `s`.
    ///
    /// If it has no `id`, add one using `id_generator`.
    pub(crate) fn from_string_loose<F>(
        s: &str,
        id_generator: F,
    ) -> Result<Self, InvalidRequestError>
    where
        F: FnOnce() -> AnyRequestId,
    {
        let mut value: serde_json::Value =
            serde_json::from_str(s).map_err(|e| InvalidRequestError::InvalidJson(Arc::new(e)))?;

        if let Some(obj) = value.as_object_mut() {
            obj.entry("id")
                .or_insert_with(|| id_generator().into_json_value());
        }

        Self::from_json_value(value)
    }
}

/// Crate-internal: The "meta" field in a request.
#[derive(Deserialize, Serialize, Debug, Default)]
#[cfg_attr(test, derive(Eq, PartialEq))]
pub(crate) struct RequestMeta {
    /// If true, the application wants to receive incremental updates
    /// about the request that it sent.
    ///
    /// (Default: false)
    #[serde(default)]
    pub(crate) updates: bool,
    /// Any unrecognized fields that we received from the user.
    /// (We re-encode these in case the user knows about fields that we don't.)
    #[serde(flatten)]
    pub(crate) unrecognized_fields: JsonMap,
}

/// A helper to return unique Request identifiers.
///
/// All identifiers are prefixed with `"!aut o!--"`:
/// if you don't use that string in your own IDs,
/// you won't have any collisions.
#[derive(Debug, Default)]
pub(crate) struct IdGenerator {
    /// The number
    next_id: u64,
}

impl IdGenerator {
    /// Return a previously unyielded identifier.
    pub(crate) fn next_id(&mut self) -> AnyRequestId {
        let id = self.next_id;
        self.next_id += 1;
        format!("!auto!--{id}").into()
    }
}

#[cfg(test)]
mod test {
    // @@ begin test lint list maintained by maint/add_warning @@
    #![allow(clippy::bool_assert_comparison)]
    #![allow(clippy::clone_on_copy)]
    #![allow(clippy::dbg_macro)]
    #![allow(clippy::mixed_attributes_style)]
    #![allow(clippy::print_stderr)]
    #![allow(clippy::print_stdout)]
    #![allow(clippy::single_char_pattern)]
    #![allow(clippy::unwrap_used)]
    #![allow(clippy::unchecked_time_subtraction)]
    #![allow(clippy::useless_vec)]
    #![allow(clippy::needless_pass_by_value)]
    #![allow(clippy::string_slice)] // See arti#2571
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->

    impl ParsedRequestFields {
        /// Return true if this request is asking for updates.
        fn updates_requested(&self) -> bool {
            self.meta.as_ref().map(|m| m.updates).unwrap_or(false)
        }
    }

    use crate::util::assert_same_json;

    use super::*;
    const REQ1: &str = r#"{"id":7, "obj": "hi", "meta": {"updates": true}, "method":"twiddle", "params":{"stuff": "nonsense"} }"#;
    const REQ2: &str = r#"{"id":"fred", "obj": "hi", "method":"twiddle", "params":{} }"#;
    const REQ3: &str =
        r#"{"id":"fred", "obj": "hi", "method":"twiddle", "params":{},"unrecognized":"waffles"}"#;

    #[test]
    fn parse_requests() {
        let req1: ParsedRequestFields = serde_json::from_str(REQ1).unwrap();
        assert_eq!(req1.id, 7.into());
        assert_eq!(req1.obj.as_ref(), "hi");
        assert_eq!(req1.updates_requested(), true);
        assert_eq!(req1.method, "twiddle");

        let req2: ParsedRequestFields = serde_json::from_str(REQ2).unwrap();
        assert_eq!(req2.id, "fred".to_string().into());
        assert_eq!(req2.obj.as_ref(), "hi");
        assert_eq!(req2.updates_requested(), false);
        assert_eq!(req2.method, "twiddle");

        let _req3: ParsedRequestFields = serde_json::from_str(REQ2).unwrap();
    }

    #[test]
    fn reencode_requests() {
        for r in [REQ1, REQ2, REQ3] {
            let val1 = ValidatedRequest::from_string_strict(r).unwrap();
            let val2 = ValidatedRequest::from_string_loose(r, || panic!()).unwrap();

            assert_same_json!(val1.as_ref(), val2.as_ref());
            assert_same_json!(val1.as_ref(), r);
        }
    }

    #[test]
    fn bad_requests() {
        for text in [
            // not an object.
            "123",
            // missing most parts.
            r#"{"id":12,}"#,
            // no id.
            r#"{"obj":"hi", "method":"twiddle", "params":{"stuff":"nonsense"}}"#,
            // no params
            r#"{"obj":"hi", "id": 7, "method":"twiddle"}"#,
            // bad params type
            r#"{"obj":"hi", "id": 7, "method":"twiddle", "params": []}"#,
            // weird obj.
            r#"{"obj":7, "id": 7, "method":"twiddle", "params":{"stuff":"nonsense"}}"#,
            // weird id.
            r#"{"obj":"hi", "id": [], "method":"twiddle", "params":{"stuff":"nonsense"}}"#,
            // weird method
            r#"{"obj":"hi", "id": 7, "method":6", "params":{"stuff":"nonsense"}}"#,
        ] {
            let r: Result<ParsedRequestFields, _> = serde_json::from_str(dbg!(text));
            assert!(r.is_err());
        }
    }

    #[test]
    fn fix_requests() {
        let no_id = r#"{"obj":"hi", "method":"twiddle", "params":{"stuff":"nonsense"}}"#;
        let validated = ValidatedRequest::from_string_loose(no_id, || 7.into()).unwrap();
        let expected_with_id =
            r#"{"id": 7, "obj":"hi", "method":"twiddle", "params":{"stuff":"nonsense"}}"#;
        assert_same_json!(validated.as_ref(), expected_with_id);
    }

    #[test]
    fn preserve_fields() {
        let orig = r#"
            {"obj":"hi",
             "meta": { "updates": true, "waffles": "yesplz" },
             "method":"twiddle",
             "params":{"stuff":"nonsense"},
             "explosions": -70
            }"#;
        let validated = ValidatedRequest::from_string_loose(orig, || 77.into()).unwrap();
        let expected_with_id = r#"
            {"id":77,
            "obj":"hi",
            "meta": { "updates": true, "waffles": "yesplz" },
            "method":"twiddle",
            "params":{"stuff":"nonsense"},
            "explosions": -70
            }"#;
        assert_same_json!(validated.as_ref(), expected_with_id);
    }

    #[test]
    fn ok_request_encode() {
        let expected_encoded_request =
            r#"{"obj":"connection","method":"arti:get_rpc_proxy_info","params":"123"}"#;
        let obj_id = ObjectId::connection_id();
        let encoded_request = Request::new(obj_id, "arti:get_rpc_proxy_info", "123")
            .encode()
            .unwrap();
        assert_eq!(expected_encoded_request, encoded_request);
    }

    // This should not be possible
    #[test]
    fn err_request_encode() {
        struct FailingSerialization;

        impl serde::Serialize for FailingSerialization {
            fn serialize<S>(&self, _serializer: S) -> Result<S::Ok, S::Error>
            where
                S: serde::Serializer,
            {
                Err(serde::ser::Error::custom(
                    "Intentional serialization failure",
                ))
            }
        }

        let obj_id = ObjectId::connection_id();
        let failing_request = Request::new(obj_id, "arti:get_rpc_proxy_info", FailingSerialization);

        let err = failing_request.encode().unwrap_err();
        assert!(matches!(err, ProtoError::CouldNotEncode(_)));
    }
}