montycat 0.1.7

Rust Client for Montycat - High-Performance NoSQL Database. The Fastest, Safest, and Most Elegant Database Client Ever Built in 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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
use crate::errors::MontycatClientError;
use core::fmt;
use serde::{Deserialize, Serialize};
use simd_json;

/// Represents a response from the Montycat server.
///
/// # Fields
/// - `status: bool` : Indicates if the request was successful.
/// - `payload: T` : The payload of the response, generic over type T.
/// - `error: Option<String>` : An optional error message if the request failed.
///
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MontycatResponse<T = serde_json::Value> {
    pub status: bool,
    #[serde(default)]
    pub payload: T,
    pub error: Option<String>,
}

/// Represents a streaming response from the Montycat server.
///
/// # Fields
/// - `message: Option<String>` : An optional message from the server.
/// - `status: bool` : Indicates if the request was successful.
/// - `payload: T` : The payload of the response, generic over type T.
/// - `error: Option<String>` : An optional error message if the request failed.
///
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MontycatStreamResponse<T = serde_json::Value> {
    pub message: Option<String>,
    pub status: bool,
    #[serde(default)]
    pub payload: T,
    pub error: Option<String>,
}

impl<T> MontycatResponse<T>
where
    for<'de> T: Deserialize<'de> + Clone + 'static + fmt::Debug,
{
    /// Parses the response bytes into a MontycatResponse<T>.
    ///
    /// This function handles nested JSON strings by recursively parsing them.
    /// If the payload contains JSON strings, they will be parsed into their respective structures.
    ///
    /// # Errors
    ///
    /// - Returns `MontycatClientError::ClientValueParsingError` if parsing fails at any step.
    ///
    /// # Example
    ///
    /// ```rust, ignore
    /// let response_bytes: Result<Option<Vec<u8>>, MontycatClientError> = ...;
    /// let parsed_response: MontycatResponse<Option<MyStruct>> = MontycatResponse::parse_response(response_bytes);
    /// ```
    ///
    pub fn parse_response(
        bytes: Result<Option<Vec<u8>>, MontycatClientError>,
    ) -> Result<Self, MontycatClientError> {
        let mut bytes_unwrapped: Vec<u8> = bytes?.ok_or_else(|| {
            MontycatClientError::ClientValueParsingError("No data received".into())
        })?;
        let slice: &mut [u8] = bytes_unwrapped.as_mut_slice();

        let mut response: MontycatResponse<simd_json::OwnedValue> = simd_json::from_slice(slice)
            .map_err(|e| MontycatClientError::ClientValueParsingError(e.to_string()))?;

        fn recursively_parse_json(v: simd_json::OwnedValue) -> simd_json::OwnedValue {
            match v {
                simd_json::OwnedValue::String(s) => {
                    if (s.starts_with('{') && s.ends_with('}'))
                        || (s.starts_with('[') && s.ends_with(']'))
                    {
                        let mut bytes = s.as_bytes().to_vec();
                        if let Ok(inner) =
                            simd_json::from_slice::<simd_json::OwnedValue>(bytes.as_mut_slice())
                        {
                            return recursively_parse_json(inner);
                        }
                    }

                    simd_json::OwnedValue::String(s)
                }

                simd_json::OwnedValue::Array(boxed_vec) => {
                    let vec = *boxed_vec;
                    let new_vec = vec
                        .into_iter()
                        .map(recursively_parse_json)
                        .collect::<Vec<_>>();
                    simd_json::OwnedValue::Array(Box::new(new_vec))
                }

                simd_json::OwnedValue::Object(boxed_map) => {
                    let map = *boxed_map;
                    let new_map = map
                        .into_iter()
                        .map(|(k, v)| (k, recursively_parse_json(v)))
                        .collect::<_>();
                    simd_json::OwnedValue::Object(Box::new(new_map))
                }

                other => other,
            }
        }

        let normalized_payload: simd_json::OwnedValue =
            recursively_parse_json(response.payload.clone());

        let s = simd_json::to_string(&normalized_payload)
            .map_err(|e| MontycatClientError::ClientValueParsingError(format!("{}", e)))?;

        let payload: T = serde_json::from_str(&s)
            .map_err(|e| MontycatClientError::ClientValueParsingError(format!("{}", e)))?;

        Ok(MontycatResponse {
            status: response.status,
            payload,
            error: response.error.take(),
        })
    }
}

impl<T> MontycatStreamResponse<T>
where
    for<'de> T: Deserialize<'de> + Clone + 'static + fmt::Debug,
{
    /// Parses the response bytes into a MontycatStreamResponse<T>.
    ///
    /// This function handles nested JSON strings by recursively parsing them.
    /// If the payload contains JSON strings, they will be parsed into their respective structures.
    ///
    /// # Errors
    ///
    /// If the response cannot be parsed, an error will be returned.
    ///
    /// # Example
    ///
    /// ```rust, ignore
    /// let response_bytes: &mut [u8] = ...;
    /// let parsed_response: MontycatStreamResponse<Option<MyStruct>> = MontycatStreamResponse::parse_response(response_bytes);
    /// ```
    ///
    pub fn parse_response(bytes: &mut [u8]) -> Result<Self, MontycatClientError> {
        let mut response: MontycatStreamResponse<simd_json::OwnedValue> =
            simd_json::from_slice(bytes)
                .map_err(|e| MontycatClientError::ClientValueParsingError(e.to_string()))?;

        fn recursively_parse_json(v: simd_json::OwnedValue) -> simd_json::OwnedValue {
            match v {
                simd_json::OwnedValue::String(s) => {
                    if (s.starts_with('{') && s.ends_with('}'))
                        || (s.starts_with('[') && s.ends_with(']'))
                    {
                        let mut bytes = s.as_bytes().to_vec();
                        if let Ok(inner) =
                            simd_json::from_slice::<simd_json::OwnedValue>(bytes.as_mut_slice())
                        {
                            return recursively_parse_json(inner);
                        }
                    }

                    simd_json::OwnedValue::String(s)
                }

                simd_json::OwnedValue::Array(boxed_vec) => {
                    let vec = *boxed_vec;
                    let new_vec = vec
                        .into_iter()
                        .map(recursively_parse_json)
                        .collect::<Vec<_>>();
                    simd_json::OwnedValue::Array(Box::new(new_vec))
                }

                simd_json::OwnedValue::Object(boxed_map) => {
                    let map = *boxed_map;
                    let new_map = map
                        .into_iter()
                        .map(|(k, v)| (k, recursively_parse_json(v)))
                        .collect::<_>();
                    simd_json::OwnedValue::Object(Box::new(new_map))
                }

                other => other,
            }
        }

        let normalized_payload: simd_json::OwnedValue =
            recursively_parse_json(response.payload.clone());

        let s = simd_json::to_string(&normalized_payload)
            .map_err(|e| MontycatClientError::ClientValueParsingError(format!("{}", e)))?;

        let payload: T = serde_json::from_str(&s)
            .map_err(|e| MontycatClientError::ClientValueParsingError(format!("{}", e)))?;

        Ok(MontycatStreamResponse {
            status: response.status,
            message: response.message.take(),
            payload,
            error: response.error.take(),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde::{Deserialize, Serialize};

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

    // ===== MontycatResponse Tests =====

    #[test]
    fn test_montycat_response_parse_simple_success() {
        let json_str = r#"{"status":true,"payload":"test_value","error":null}"#;
        let bytes = Ok(Some(json_str.as_bytes().to_vec()));

        let response: MontycatResponse<String> = MontycatResponse::parse_response(bytes).unwrap();

        assert!(response.status);
        assert_eq!(response.payload, "test_value");
        assert_eq!(response.error, None);
    }

    #[test]
    fn test_montycat_response_parse_with_error() {
        let json_str = r#"{"status":false,"payload":null,"error":"Something went wrong"}"#;
        let bytes = Ok(Some(json_str.as_bytes().to_vec()));

        let response: MontycatResponse<Option<String>> =
            MontycatResponse::parse_response(bytes).unwrap();

        assert!(!response.status);
        assert_eq!(response.payload, None);
        assert_eq!(response.error, Some("Something went wrong".to_string()));
    }

    #[test]
    fn test_montycat_response_parse_struct() {
        let json_str = r#"{"status":true,"payload":{"id":1,"name":"test"},"error":null}"#;
        let bytes = Ok(Some(json_str.as_bytes().to_vec()));

        let response: MontycatResponse<TestStruct> =
            MontycatResponse::parse_response(bytes).unwrap();

        assert!(response.status);
        assert_eq!(response.payload.id, 1);
        assert_eq!(response.payload.name, "test");
    }

    #[test]
    fn test_montycat_response_parse_nested_json_string() {
        let json_str =
            r#"{"status":true,"payload":"{\"id\":42,\"name\":\"nested\"}","error":null}"#;
        let bytes = Ok(Some(json_str.as_bytes().to_vec()));

        let response: MontycatResponse<TestStruct> =
            MontycatResponse::parse_response(bytes).unwrap();

        assert!(response.status);
        assert_eq!(response.payload.id, 42);
        assert_eq!(response.payload.name, "nested");
    }

    #[test]
    fn test_montycat_response_parse_array() {
        let json_str = r#"{"status":true,"payload":[{"id":1,"name":"first"},{"id":2,"name":"second"}],"error":null}"#;
        let bytes = Ok(Some(json_str.as_bytes().to_vec()));

        let response: MontycatResponse<Vec<TestStruct>> =
            MontycatResponse::parse_response(bytes).unwrap();

        assert!(response.status);
        assert_eq!(response.payload.len(), 2);
        assert_eq!(response.payload[0].id, 1);
        assert_eq!(response.payload[1].name, "second");
    }

    #[test]
    fn test_montycat_response_parse_option_some() {
        let json_str = r#"{"status":true,"payload":{"id":99,"name":"optional"},"error":null}"#;
        let bytes = Ok(Some(json_str.as_bytes().to_vec()));

        let response: MontycatResponse<Option<TestStruct>> =
            MontycatResponse::parse_response(bytes).unwrap();

        assert!(response.status);
        assert!(response.payload.is_some());
        assert_eq!(response.payload.unwrap().id, 99);
    }

    #[test]
    fn test_montycat_response_parse_option_none() {
        let json_str = r#"{"status":true,"payload":null,"error":null}"#;
        let bytes = Ok(Some(json_str.as_bytes().to_vec()));

        let response: MontycatResponse<Option<TestStruct>> =
            MontycatResponse::parse_response(bytes).unwrap();

        assert!(response.status);
        assert!(response.payload.is_none());
    }

    #[test]
    fn test_montycat_response_parse_error_no_data() {
        let bytes: Result<Option<Vec<u8>>, MontycatClientError> = Ok(None);

        let result: Result<MontycatResponse<String>, MontycatClientError> =
            MontycatResponse::parse_response(bytes);

        assert!(result.is_err());
        if let Err(e) = result {
            assert!(e.message().contains("No data received"));
        }
    }

    #[test]
    fn test_montycat_response_parse_error_invalid_json() {
        let invalid_json = b"not valid json";
        let bytes = Ok(Some(invalid_json.to_vec()));

        let result: Result<MontycatResponse<String>, MontycatClientError> =
            MontycatResponse::parse_response(bytes);

        assert!(result.is_err());
    }

    #[test]
    fn test_montycat_response_parse_error_propagation() {
        let bytes: Result<Option<Vec<u8>>, MontycatClientError> = Err(
            MontycatClientError::ClientEngineError("Connection failed".to_string()),
        );

        let result: Result<MontycatResponse<String>, MontycatClientError> =
            MontycatResponse::parse_response(bytes);

        assert!(result.is_err());
        if let Err(e) = result {
            assert_eq!(e.message(), "Connection failed");
        }
    }

    // ===== MontycatStreamResponse Tests =====

    #[test]
    fn test_montycat_stream_response_parse_simple() {
        let json_str =
            r#"{"message":"Processing","status":true,"payload":"stream_data","error":null}"#;
        let mut bytes = json_str.as_bytes().to_vec();

        let response: MontycatStreamResponse<String> =
            MontycatStreamResponse::parse_response(bytes.as_mut_slice()).unwrap();
        assert!(response.status);
        assert_eq!(response.message, Some("Processing".to_string()));
        assert_eq!(response.payload, "stream_data");
        assert_eq!(response.error, None);
    }

    #[test]
    fn test_montycat_stream_response_parse_with_error() {
        let json_str = r#"{"message":null,"status":false,"payload":null,"error":"Stream error"}"#;
        let mut bytes = json_str.as_bytes().to_vec();

        let response: MontycatStreamResponse<Option<String>> =
            MontycatStreamResponse::parse_response(bytes.as_mut_slice()).unwrap();

        assert!(!response.status);
        assert_eq!(response.message, None);
        assert_eq!(response.error, Some("Stream error".to_string()));
    }

    #[test]
    fn test_montycat_stream_response_parse_struct() {
        let json_str = r#"{"message":"Data ready","status":true,"payload":{"id":123,"name":"streamed"},"error":null}"#;
        let mut bytes = json_str.as_bytes().to_vec();

        let response: MontycatStreamResponse<TestStruct> =
            MontycatStreamResponse::parse_response(bytes.as_mut_slice()).unwrap();

        assert!(response.status);
        assert_eq!(response.message, Some("Data ready".to_string()));
        assert_eq!(response.payload.id, 123);
        assert_eq!(response.payload.name, "streamed");
    }

    #[test]
    fn test_montycat_stream_response_parse_nested_json() {
        let json_str = r#"{"message":"Nested data","status":true,"payload":"{\"id\":77,\"name\":\"nested_stream\"}","error":null}"#;
        let mut bytes = json_str.as_bytes().to_vec();

        let response: MontycatStreamResponse<TestStruct> =
            MontycatStreamResponse::parse_response(bytes.as_mut_slice()).unwrap();

        assert!(response.status);
        assert_eq!(response.payload.id, 77);
        assert_eq!(response.payload.name, "nested_stream");
    }

    #[test]
    fn test_montycat_stream_response_parse_invalid_json() {
        let invalid_json = b"not valid json";

        let result: Result<MontycatStreamResponse<String>, MontycatClientError> =
            MontycatStreamResponse::parse_response(invalid_json.to_vec().as_mut_slice());

        assert!(result.is_err());
    }

    #[test]
    fn test_montycat_stream_response_no_message() {
        let json_str = r#"{"status":true,"payload":"data","error":null}"#;
        let mut bytes = json_str.as_bytes().to_vec();

        let response: MontycatStreamResponse<String> =
            MontycatStreamResponse::parse_response(bytes.as_mut_slice()).unwrap();

        assert!(response.status);
        assert_eq!(response.message, None);
        assert_eq!(response.payload, "data");
    }

    #[test]
    fn test_recursive_json_parsing_deeply_nested() {
        let json_str = r#"{"status":true,"payload":"[{\"id\":1,\"name\":\"item1\"},{\"id\":2,\"name\":\"item2\"}]","error":null}"#;
        let bytes = json_str.as_bytes().to_vec();

        let response: MontycatResponse<Vec<TestStruct>> =
            MontycatResponse::parse_response(Ok(Some(bytes))).unwrap();

        assert!(response.status);
        assert_eq!(response.payload.len(), 2);
        assert_eq!(response.payload[0].id, 1);
        assert_eq!(response.payload[1].name, "item2");
    }
}