rustis 0.23.0

Redis async driver for Rust
Documentation
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
use serde::{
    Deserialize,
    de::{self},
    ser::{self, Serialize},
};

/// Wrapper type that converts a Rust value from and to a Redis bulk string holding JSON.
///
/// This is useful for storing and retrieving structured data as JSON.
/// Typically used with commands like `GET` / `SET`, `HGET` / `HSET`, or any
/// command taking or returning a bulk string.
///
/// A key that may be missing must be read as `Option<Json<T>>`: a nil reply is
/// not a JSON document.
///
/// `Json(&value)` borrows and `Json(value)` moves — both serialize identically,
/// since `&T` is itself `Serialize`.
///
/// `T` needs no schema: `Json<serde_json::Value>` stores and reads back an
/// untyped document. The wrapper is what makes the document one bulk string —
/// a bare [`serde_json::Value`] passed as an argument is serialized like any
/// other Rust value, so a map becomes one argument per key and per value, and
/// an array one argument per element.
///
/// ```rust
/// # use rustis::{client::Client, commands::StringCommands, resp::Json, Result};
/// # #[tokio::main]
/// # async fn main() -> Result<()> {
/// # let client = Client::connect("127.0.0.1:6379").await?;
/// let document = serde_json::json!({ "id": 12, "name": "foo" });
/// client.set("user:123", Json(&document)).await?;
/// let Json(read_back): Json<serde_json::Value> = client.get("user:123").await?;
///
/// assert_eq!(document, read_back);
/// # Ok(())
/// # }
/// ```
///
/// # Example
/// ```rust
/// use rustis::{
///     client::Client,
///     commands::{FlushingMode, ServerCommands, StringCommands},
///     resp::Json,
///     Result
/// };
///
/// #[derive(Debug, PartialEq, serde::Deserialize, serde::Serialize)]
/// struct User {
///     id: u32,
///     name: String,
/// }
///
/// #[tokio::main]
/// async fn main() -> Result<()> {
///     let client = Client::connect("127.0.0.1:6379").await?;
///     client.flushall(FlushingMode::Sync).await?;
///     let user1 = User { id: 12, name: "foo".to_string() };
///     client.set("user:123", Json(&user1)).await?;
///     let Json(user2): Json<User> = client.get("user:123").await?;
///
///     assert_eq!(user1, user2);
///     Ok(())
/// }
/// ```
#[derive(Debug, Clone)]
#[must_use]
pub struct Json<T>(pub T);

impl<T> Json<T> {
    /// Returns the wrapped value.
    pub fn into_inner(self) -> T {
        self.0
    }
}

const TRANSIENT_INPUT: &str = "`Json<T>` needs data borrowed from the connection buffer, and this \
                               deserializer supplied owned data; use `serde_json` directly";

impl<'de, T> Deserialize<'de> for Json<T>
where
    T: Deserialize<'de>,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        use std::{fmt, marker::PhantomData};

        struct Visitor<T> {
            phantom: PhantomData<T>,
        }

        impl<'de, T> de::Visitor<'de> for Visitor<T>
        where
            T: Deserialize<'de>,
        {
            type Value = Json<T>;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("a JSON-encoded bulk string")
            }

            // `deserialize_any` routes a nil reply here, where serde's own
            // message would be `invalid type: Option`. The reply shape the
            // caller got and the type they need are both worth naming.
            fn visit_none<E>(self) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Err(de::Error::custom(
                    "the reply is nil: a key that may be missing must be read as \
                     `Option<Json<T>>`, not `Json<T>`",
                ))
            }

            fn visit_unit<E>(self) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                self.visit_none()
            }

            fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Err(de::Error::custom(format!(
                    "expected a JSON-encoded bulk string, got the integer reply {v}"
                )))
            }

            fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Err(de::Error::custom(format!(
                    "expected a JSON-encoded bulk string, got the integer reply {v}"
                )))
            }

            fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Err(de::Error::custom(format!(
                    "expected a JSON-encoded bulk string, got the double reply {v}"
                )))
            }

            fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Err(de::Error::custom(format!(
                    "expected a JSON-encoded bulk string, got the boolean reply {v}"
                )))
            }

            // `T: Deserialize<'de>` may borrow from the input, which data owned
            // by the deserializer does not outlive. Accepting these would force
            // `T: DeserializeOwned` and rule out borrowing types, so they are
            // diagnosed rather than supported.
            fn visit_str<E>(self, _v: &str) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Err(de::Error::custom(TRANSIENT_INPUT))
            }

            fn visit_string<E>(self, _v: String) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Err(de::Error::custom(TRANSIENT_INPUT))
            }

            fn visit_bytes<E>(self, _v: &[u8]) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Err(de::Error::custom(TRANSIENT_INPUT))
            }

            fn visit_byte_buf<E>(self, _v: Vec<u8>) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Err(de::Error::custom(TRANSIENT_INPUT))
            }

            fn visit_borrowed_bytes<E>(self, v: &'de [u8]) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                let value: T = serde_json::from_slice(v).map_err(|e| {
                    de::Error::custom(format!(
                        "Cannot deserialize from json (borrowed bytes): {}",
                        e
                    ))
                })?;
                Ok(Json(value))
            }

            fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                let value: T = serde_json::from_str(v).map_err(|e| {
                    de::Error::custom(format!(
                        "Cannot deserialize from json (borrowed str): {}",
                        e
                    ))
                })?;
                Ok(Json(value))
            }
        }

        deserializer.deserialize_any(Visitor {
            phantom: PhantomData,
        })
    }
}

impl<T> Serialize for Json<T>
where
    T: Serialize,
{
    /// A value that cannot be rendered as JSON fails the command: the error
    /// travels through the command builder's deferred error slot and surfaces
    /// from the awaited command, before anything is sent. An argument that
    /// cannot be written must never be replaced by an empty one, which would
    /// store an absent value under the caller's key and report success.
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let bytes = serde_json::to_vec(&self.0)
            .map_err(|e| ser::Error::custom(format!("Cannot serialize to json: {e}")))?;
        serializer.serialize_bytes(&bytes)
    }
}

#[cfg(test)]
mod tests {
    #![allow(
        clippy::unwrap_used,
        clippy::expect_used,
        clippy::panic,
        clippy::unreachable,
        clippy::indexing_slicing,
        reason = "test code: a panic is how a test reports failure"
    )]
    use super::Json;
    use crate::{
        ClientError, Error, ErrorKind,
        resp::{Command, FastPathCommandBuilder, RespBuf, cmd},
    };
    use serde::{Deserialize, Serialize};
    use std::collections::BTreeMap;

    #[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
    struct Person {
        id: u32,
        name: String,
    }

    fn person() -> Person {
        Person {
            id: 12,
            name: "Foo".to_string(),
        }
    }

    /// A value whose `Serialize` impl always fails, standing in for any user type
    /// `serde_json` cannot render.
    struct FailingSerialize;
    impl Serialize for FailingSerialize {
        fn serialize<S: serde::Serializer>(&self, _: S) -> Result<S::Ok, S::Error> {
            Err(serde::ser::Error::custom("boom"))
        }
    }

    fn serialization_error_of(mut command: Command) -> Option<Error> {
        command.take_serialization_error()
    }

    #[test]
    fn a_failing_serialize_fails_the_command() {
        let mut command: Command = FastPathCommandBuilder::set("key", Json(&FailingSerialize));
        let error = command.take_serialization_error();
        assert!(
            matches!(error.as_ref().map(Error::kind), Some(ErrorKind::Client(ClientError::SerdeSerialize(m))) if m.contains("Cannot serialize to json")),
            "unexpected error: {error:?}"
        );
    }

    #[test]
    fn a_serde_json_error_reaches_the_caller() {
        // A map with non-string keys is a real `serde_json` failure, not a
        // synthetic one.
        let map: BTreeMap<(u8, u8), u8> = BTreeMap::from([((1, 2), 3)]);
        let command: Command = FastPathCommandBuilder::set("key", Json(&map));
        let error = serialization_error_of(command).expect("a deferred serialization error");
        assert!(matches!(
            error.kind(),
            ErrorKind::Client(ClientError::SerdeSerialize(_))
        ));
    }

    #[test]
    fn an_unserializable_value_is_never_written_as_an_empty_argument() {
        // A failing argument must leave the command incomplete and carrying the
        // error. An empty argument in the value's place would make Redis store
        // an absent value under the caller's key, and the call would report
        // success.
        let mut command: Command = FastPathCommandBuilder::set("key", Json(&FailingSerialize));
        assert!(command.take_serialization_error().is_some());
        assert_eq!(1, command.num_args());
        assert_eq!(Some(&b"key"[..]), command.get_arg(0).as_deref());
    }

    #[test]
    fn the_generic_builder_defers_the_same_error() {
        let command: Command = cmd("SET").key("key").arg(Json(&FailingSerialize)).into();
        let error = serialization_error_of(command).expect("a deferred serialization error");
        assert!(matches!(
            error.kind(),
            ErrorKind::Client(ClientError::SerdeSerialize(_))
        ));
    }

    #[test]
    fn a_serializable_value_becomes_one_json_argument() {
        let mut command: Command = FastPathCommandBuilder::set("key", Json(&person()));
        assert!(command.take_serialization_error().is_none());
        assert_eq!(2, command.num_args());
        assert_eq!(
            Some(&br#"{"id":12,"name":"Foo"}"#[..]),
            command.get_arg(1).as_deref()
        );
    }

    #[test]
    fn a_borrowed_value_serializes_like_an_owned_one() {
        // `&T` is itself `Serialize`, so the wrapper covers both spellings.
        let person = person();
        let borrowed: Command = FastPathCommandBuilder::set("key", Json(&person));
        let owned: Command = FastPathCommandBuilder::set("key", Json(person.clone()));

        assert_eq!(borrowed.get_arg(1), owned.get_arg(1));
    }

    #[test]
    fn a_bulk_string_reply_deserializes() {
        let resp = RespBuf::from_slice(b"$22\r\n{\"id\":12,\"name\":\"Foo\"}\r\n");
        let Json(deserialized): Json<Person> = resp.to().unwrap();
        assert_eq!(person(), deserialized);
    }

    #[test]
    fn a_simple_string_reply_deserializes() {
        let resp = RespBuf::from_slice(b"+{\"id\":12,\"name\":\"Foo\"}\r\n");
        let Json(deserialized): Json<Person> = resp.to().unwrap();
        assert_eq!(person(), deserialized);
    }

    #[test]
    fn a_nil_reply_points_at_option_json() {
        let resp = RespBuf::from_slice(b"_\r\n");
        let error = resp.to::<Json<Person>>().unwrap_err();
        assert!(
            error.to_string().contains("Option<Json<T>>"),
            "unexpected error: {error}"
        );
        assert!(resp.to::<Option<Json<Person>>>().unwrap().is_none());
    }

    #[test]
    fn an_integer_reply_is_named_in_the_error() {
        let resp = RespBuf::from_slice(b":12\r\n");
        let error = resp.to::<Json<Person>>().unwrap_err();
        assert!(
            error.to_string().contains("integer"),
            "unexpected error: {error}"
        );
    }

    #[test]
    fn malformed_json_reports_the_serde_json_message() {
        let resp = RespBuf::from_slice(b"$3\r\nnot\r\n");
        let error = resp.to::<Json<Person>>().unwrap_err();
        assert!(
            error.to_string().contains("Cannot deserialize from json"),
            "unexpected error: {error}"
        );
    }

    #[test]
    fn a_json_value_becomes_one_json_argument() {
        let value = serde_json::json!({ "id": 12, "name": "Foo" });
        let mut command: Command = FastPathCommandBuilder::set("key", Json(&value));
        assert!(command.take_serialization_error().is_none());
        assert_eq!(2, command.num_args());
        assert_eq!(
            Some(&br#"{"id":12,"name":"Foo"}"#[..]),
            command.get_arg(1).as_deref()
        );
    }

    #[test]
    fn a_bulk_string_reply_deserializes_into_a_json_value() {
        let resp = RespBuf::from_slice(b"$22\r\n{\"id\":12,\"name\":\"Foo\"}\r\n");
        let Json(value): Json<serde_json::Value> = resp.to().unwrap();
        assert_eq!(serde_json::json!({ "id": 12, "name": "Foo" }), value);
    }

    #[test]
    fn into_inner_returns_the_wrapped_value() {
        assert_eq!(person(), Json(person()).into_inner());
    }
}