repe 2.6.0

Rust implementation of the REPE RPC protocol (JSON-focused)
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
use crate::constants::{BodyFormat, ErrorCode, HEADER_SIZE, QueryFormat};
use crate::error::RepeError;
use crate::header::Header;
use beve::{Error as BeveError, from_slice as beve_from_slice, to_vec as beve_to_vec};
use std::io::{self, Write};

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Message {
    pub header: Header,
    pub query: Vec<u8>,
    pub body: Vec<u8>,
}

impl Message {
    pub fn new(header: Header, query: Vec<u8>, body: Vec<u8>) -> Result<Self, RepeError> {
        if header.query_length != query.len() as u64 || header.body_length != body.len() as u64 {
            return Err(RepeError::LengthMismatch {
                expected: HEADER_SIZE as u64 + header.query_length + header.body_length,
                got: HEADER_SIZE as u64 + query.len() as u64 + body.len() as u64,
            });
        }
        Ok(Self {
            header,
            query,
            body,
        })
    }

    pub fn builder() -> MessageBuilder {
        MessageBuilder::default()
    }

    pub fn to_vec(&self) -> Vec<u8> {
        let mut out = Vec::with_capacity(HEADER_SIZE + self.query.len() + self.body.len());
        out.extend_from_slice(&self.header.encode());
        if !self.query.is_empty() {
            out.extend_from_slice(&self.query);
        }
        if !self.body.is_empty() {
            out.extend_from_slice(&self.body);
        }
        out
    }

    /// Wire size of the serialized message: `HEADER_SIZE + query.len() + body.len()`.
    /// O(1); does not serialize.
    pub fn serialized_len(&self) -> usize {
        HEADER_SIZE + self.query.len() + self.body.len()
    }

    /// Write the message to `w` without allocating an intermediate frame buffer.
    ///
    /// Equivalent to `w.write_all(&self.to_vec())` byte-for-byte, but emits the
    /// header, query, and body in three writes instead of building a single
    /// owned `Vec<u8>`. Useful when the body is large (e.g. multi-MiB chunks).
    pub fn write_to<W: Write>(&self, w: &mut W) -> io::Result<()> {
        w.write_all(&self.header.encode())?;
        if !self.query.is_empty() {
            w.write_all(&self.query)?;
        }
        if !self.body.is_empty() {
            w.write_all(&self.body)?;
        }
        Ok(())
    }

    pub fn from_slice(buf: &[u8]) -> Result<Self, RepeError> {
        if buf.len() < HEADER_SIZE {
            return Err(RepeError::InvalidHeaderLength(buf.len()));
        }
        let header = Header::decode(&buf[..HEADER_SIZE])?;
        let expected = HEADER_SIZE + header.query_length as usize + header.body_length as usize;
        if buf.len() < expected {
            return Err(RepeError::BufferTooSmall {
                need: expected,
                have: buf.len(),
            });
        }
        let mut o = HEADER_SIZE;
        let query = buf[o..o + header.query_length as usize].to_vec();
        o += header.query_length as usize;
        let body = buf[o..o + header.body_length as usize].to_vec();
        Self::new(header, query, body)
    }

    pub fn from_slice_exact(buf: &[u8]) -> Result<Self, RepeError> {
        let message = Self::from_slice(buf)?;
        let expected = HEADER_SIZE + message.query.len() + message.body.len();
        if buf.len() != expected {
            return Err(RepeError::LengthMismatch {
                expected: expected as u64,
                got: buf.len() as u64,
            });
        }
        Ok(message)
    }

    pub fn is_error(&self) -> bool {
        self.header.ec != ErrorCode::Ok as u32
    }

    pub fn error_code(&self) -> Option<ErrorCode> {
        ErrorCode::try_from(self.header.ec).ok()
    }

    pub fn error_message_utf8(&self) -> Option<String> {
        if !self.is_error() {
            return None;
        }
        Some(String::from_utf8_lossy(&self.body).into_owned())
    }

    pub fn query_utf8(&self) -> String {
        match self.query_str() {
            Ok(s) => s.to_owned(),
            Err(_) => String::from_utf8_lossy(&self.query).into_owned(),
        }
    }

    pub fn query_str(&self) -> Result<&str, std::str::Utf8Error> {
        std::str::from_utf8(&self.query)
    }

    pub fn body_utf8(&self) -> String {
        String::from_utf8_lossy(&self.body).into_owned()
    }

    pub fn json_body<T: serde::de::DeserializeOwned>(&self) -> Result<T, RepeError> {
        match BodyFormat::try_from(self.header.body_format) {
            Ok(BodyFormat::Json) => Ok(serde_json::from_slice(&self.body)?),
            Ok(BodyFormat::Utf8) | Ok(BodyFormat::RawBinary) | Ok(BodyFormat::Beve) | Err(_) => {
                let io_err =
                    std::io::Error::new(std::io::ErrorKind::InvalidData, "body_format is not JSON");
                Err(RepeError::Json(serde_json::Error::io(io_err)))
            }
        }
    }

    pub fn beve_body<T: serde::de::DeserializeOwned>(&self) -> Result<T, RepeError> {
        match BodyFormat::try_from(self.header.body_format) {
            Ok(BodyFormat::Beve) => Ok(beve_from_slice(&self.body)?),
            Ok(BodyFormat::Json) | Ok(BodyFormat::Utf8) | Ok(BodyFormat::RawBinary) | Err(_) => {
                Err(RepeError::from(BeveError::msg("body_format is not BEVE")))
            }
        }
    }
}

/// Borrowing view over a serialized REPE message.
///
/// Unlike [`Message::from_slice`], which copies the query and body out of the
/// caller's buffer, `MessageView` keeps both as borrowed slices of the input.
/// Useful when a large body (e.g. a multi-MiB chunk) will be deserialized with
/// `serde_bytes::Bytes<'a>` so the bulk payload stays borrowed end-to-end.
///
/// The `header` is decoded by value because it's only 48 bytes and downstream
/// code typically wants the parsed fields rather than the raw header bytes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MessageView<'a> {
    pub header: Header,
    pub query: &'a [u8],
    pub body: &'a [u8],
}

impl<'a> MessageView<'a> {
    /// Parse a `MessageView` from `buf`. The returned view borrows from `buf`;
    /// no copies are made.
    pub fn from_slice(buf: &'a [u8]) -> Result<Self, RepeError> {
        if buf.len() < HEADER_SIZE {
            return Err(RepeError::InvalidHeaderLength(buf.len()));
        }
        let header = Header::decode(&buf[..HEADER_SIZE])?;
        let expected = HEADER_SIZE + header.query_length as usize + header.body_length as usize;
        if buf.len() < expected {
            return Err(RepeError::BufferTooSmall {
                need: expected,
                have: buf.len(),
            });
        }
        let q_start = HEADER_SIZE;
        let q_end = q_start + header.query_length as usize;
        let b_end = q_end + header.body_length as usize;
        Ok(Self {
            header,
            query: &buf[q_start..q_end],
            body: &buf[q_end..b_end],
        })
    }

    /// View the query as a `&str`. Errors if the query is not valid UTF-8.
    pub fn query_str(&self) -> Result<&'a str, std::str::Utf8Error> {
        std::str::from_utf8(self.query)
    }
}

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

    #[test]
    fn json_body_non_json_errors() {
        let msg = Message::builder()
            .id(1)
            .query_str("/q")
            .query_format(QueryFormat::JsonPointer)
            .body_utf8("not json")
            .build();
        let err = msg.json_body::<serde_json::Value>().unwrap_err();
        matches!(err, RepeError::Json(_));
    }

    #[derive(Serialize, Deserialize, Debug, PartialEq)]
    struct Pair {
        a: i32,
        b: i32,
    }

    #[test]
    fn create_response_json_and_utf8() {
        let req = Message::builder()
            .id(5)
            .query_str("/sum")
            .query_format(QueryFormat::JsonPointer)
            .body_json(&Pair { a: 1, b: 2 })
            .unwrap()
            .build();

        // JSON body
        let resp_json =
            create_response(&req, serde_json::json!({"ok": true}), BodyFormat::Json).unwrap();
        assert_eq!(resp_json.header.id, 5);
        assert_eq!(resp_json.header.ec, ErrorCode::Ok as u32);
        assert_eq!(resp_json.header.body_format, BodyFormat::Json as u16);

        // UTF8 body (stringified JSON)
        let resp_utf8 =
            create_response(&req, serde_json::json!([1, 2, 3]), BodyFormat::Utf8).unwrap();
        assert_eq!(resp_utf8.header.body_format, BodyFormat::Utf8 as u16);
        assert!(std::str::from_utf8(&resp_utf8.body).unwrap().contains("1"));
    }

    #[test]
    fn message_from_slice_truncated_returns_buffer_too_small() {
        let msg = Message::builder()
            .id(10)
            .query_str("/a")
            .query_format(QueryFormat::JsonPointer)
            .body_utf8("payload")
            .build();
        let mut bytes = msg.to_vec();
        let full_len = bytes.len();
        bytes.truncate(bytes.len() - 1);
        match Message::from_slice(&bytes).unwrap_err() {
            RepeError::BufferTooSmall { need, have } => {
                assert_eq!(need, full_len);
                assert_eq!(have, full_len - 1);
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[test]
    fn message_from_slice_exact_rejects_trailing_bytes() {
        let msg = Message::builder()
            .id(11)
            .query_str("/a")
            .query_format(QueryFormat::JsonPointer)
            .body_utf8("payload")
            .build();
        let mut bytes = msg.to_vec();
        bytes.extend_from_slice(&[0xAA, 0xBB]);

        match Message::from_slice_exact(&bytes).unwrap_err() {
            RepeError::LengthMismatch { expected, got } => {
                assert_eq!(expected, msg.to_vec().len() as u64);
                assert_eq!(got, bytes.len() as u64);
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[test]
    fn create_response_beve_serializes_body() {
        let req = Message::builder()
            .id(3)
            .query_str("/noop")
            .query_format(QueryFormat::JsonPointer)
            .body_utf8("{}");
        let req = req.build();

        let resp =
            create_response(&req, serde_json::json!({"ignored": true}), BodyFormat::Beve).unwrap();
        assert_eq!(resp.header.id, req.header.id);
        assert_eq!(resp.query, req.query);
        assert!(!resp.body.is_empty());
        assert_eq!(resp.header.body_format, BodyFormat::Beve as u16);

        let value: serde_json::Value = resp.beve_body().unwrap();
        assert_eq!(value["ignored"], true);
    }

    #[test]
    fn create_response_propagates_serialization_error() {
        struct Fails;

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

        let req = Message::builder()
            .id(12)
            .query_str("/bad")
            .query_format(QueryFormat::JsonPointer)
            .body_utf8("{}");
        let req = req.build();

        let err = create_response(&req, Fails, BodyFormat::Json).unwrap_err();
        matches!(err, RepeError::Json(_));
    }

    #[test]
    fn body_beve_roundtrip() {
        #[derive(Serialize, Deserialize, Debug, PartialEq)]
        struct Data {
            x: i32,
            y: String,
        }

        let msg = Message::builder()
            .id(7)
            .query_str("/d")
            .query_format(QueryFormat::JsonPointer)
            .body_beve(&Data {
                x: 10,
                y: "ok".into(),
            })
            .unwrap()
            .build();

        assert_eq!(msg.header.body_format, BodyFormat::Beve as u16);
        let decoded: Data = msg.beve_body().unwrap();
        assert_eq!(
            decoded,
            Data {
                x: 10,
                y: "ok".into()
            }
        );
    }

    #[test]
    fn message_view_from_slice_borrows() {
        let msg = Message::builder()
            .id(7)
            .query_str("/echo")
            .query_format(QueryFormat::JsonPointer)
            .body_bytes(vec![1u8, 2, 3, 4])
            .body_format(BodyFormat::RawBinary)
            .build();
        let bytes = msg.to_vec();

        let view = MessageView::from_slice(&bytes).unwrap();
        assert_eq!(view.header, msg.header);
        assert_eq!(view.query, msg.query.as_slice());
        assert_eq!(view.body, msg.body.as_slice());

        // Verify the slices point inside `bytes`, not into a fresh allocation.
        let bytes_start = bytes.as_ptr() as usize;
        let bytes_end = bytes_start + bytes.len();
        let q_addr = view.query.as_ptr() as usize;
        let b_addr = view.body.as_ptr() as usize;
        assert!(q_addr >= bytes_start && q_addr <= bytes_end);
        assert!(b_addr >= bytes_start && b_addr <= bytes_end);

        assert_eq!(view.query_str().unwrap(), "/echo");
    }

    #[test]
    fn message_view_truncated_returns_buffer_too_small() {
        let msg = Message::builder()
            .id(1)
            .query_str("/x")
            .query_format(QueryFormat::JsonPointer)
            .body_utf8("payload")
            .build();
        let mut bytes = msg.to_vec();
        let full_len = bytes.len();
        bytes.truncate(bytes.len() - 1);
        match MessageView::from_slice(&bytes).unwrap_err() {
            RepeError::BufferTooSmall { need, have } => {
                assert_eq!(need, full_len);
                assert_eq!(have, full_len - 1);
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[test]
    fn write_to_matches_to_vec() {
        let msg = Message::builder()
            .id(42)
            .query_str("/collect/file_chunk")
            .query_format(QueryFormat::JsonPointer)
            .body_bytes(vec![0xDEu8; 1024])
            .body_format(BodyFormat::Beve)
            .build();

        let expected = msg.to_vec();
        let mut got = Vec::new();
        msg.write_to(&mut got).expect("write_to");
        assert_eq!(got, expected);
        assert_eq!(msg.serialized_len(), expected.len());
    }

    #[test]
    fn write_to_handles_empty_query_and_body() {
        let msg = Message::builder().id(1).build();
        let expected = msg.to_vec();
        let mut got = Vec::new();
        msg.write_to(&mut got).expect("write_to");
        assert_eq!(got, expected);
        assert_eq!(msg.serialized_len(), expected.len());
    }

    #[test]
    fn beve_body_non_beve_errors() {
        let msg = Message::builder()
            .id(2)
            .query_str("/a")
            .query_format(QueryFormat::JsonPointer)
            .body_utf8("text")
            .build();

        let err = msg.beve_body::<serde_json::Value>().unwrap_err();
        matches!(err, RepeError::Beve(_));
    }

    #[test]
    fn builder_format_code_methods_set_explicit_codes() {
        let msg = Message::builder()
            .id(9)
            .query_str("/raw")
            .query_format_code(0x7777)
            .body_bytes(vec![1, 2, 3])
            .body_format_code(0x8888)
            .build();

        assert_eq!(msg.header.query_format, 0x7777);
        assert_eq!(msg.header.body_format, 0x8888);
    }
}

#[derive(Default)]
pub struct MessageBuilder {
    id: u64,
    query: Vec<u8>,
    body: Vec<u8>,
    query_format: u16,
    body_format: u16,
    notify: bool,
    ec: u32,
}

impl MessageBuilder {
    pub fn id(mut self, id: u64) -> Self {
        self.id = id;
        self
    }
    pub fn notify(mut self, notify: bool) -> Self {
        self.notify = notify;
        self
    }
    pub fn error_code(mut self, ec: ErrorCode) -> Self {
        self.ec = ec as u32;
        self
    }
    pub fn query_format(mut self, f: QueryFormat) -> Self {
        self.query_format = u16::from(f);
        self
    }
    pub fn query_format_code(mut self, format_code: u16) -> Self {
        self.query_format = format_code;
        self
    }
    pub fn body_format(mut self, f: BodyFormat) -> Self {
        self.body_format = u16::from(f);
        self
    }
    pub fn body_format_code(mut self, format_code: u16) -> Self {
        self.body_format = format_code;
        self
    }
    pub fn query_bytes(mut self, q: impl Into<Vec<u8>>) -> Self {
        self.query = q.into();
        self
    }
    pub fn query_str(mut self, q: &str) -> Self {
        self.query = q.as_bytes().to_vec();
        self
    }
    pub fn body_bytes(mut self, b: impl Into<Vec<u8>>) -> Self {
        self.body = b.into();
        self
    }
    pub fn body_utf8(mut self, s: &str) -> Self {
        self.body = s.as_bytes().to_vec();
        self.body_format = BodyFormat::Utf8 as u16;
        self
    }
    pub fn body_json<T: serde::Serialize>(mut self, v: &T) -> Result<Self, RepeError> {
        self.body = serde_json::to_vec(v)?;
        self.body_format = BodyFormat::Json as u16;
        Ok(self)
    }

    pub fn body_beve<T: serde::Serialize>(mut self, v: &T) -> Result<Self, RepeError> {
        self.body = beve_to_vec(v)?;
        self.body_format = BodyFormat::Beve as u16;
        Ok(self)
    }

    pub fn build(self) -> Message {
        let mut header = Header::new();
        header.id = self.id;
        header.query_length = self.query.len() as u64;
        header.body_length = self.body.len() as u64;
        header.length = HEADER_SIZE as u64 + header.query_length + header.body_length;
        header.query_format = if self.query_format == 0 {
            QueryFormat::RawBinary as u16
        } else {
            self.query_format
        };
        header.body_format = if self.body_format == 0 {
            BodyFormat::RawBinary as u16
        } else {
            self.body_format
        };
        header.notify = if self.notify { 1 } else { 0 };
        header.ec = self.ec;
        Message {
            header,
            query: self.query,
            body: self.body,
        }
    }
}

pub fn create_error_message(code: ErrorCode, msg: impl AsRef<str>) -> Message {
    let body = msg.as_ref().as_bytes().to_vec();
    Message::builder()
        .error_code(code)
        .body_bytes(body)
        .body_format(BodyFormat::Utf8)
        .build()
}

pub fn create_error_response_like(
    request: &Message,
    code: ErrorCode,
    msg: impl AsRef<str>,
) -> Message {
    let mut err = create_error_message(code, msg.as_ref());
    err.header.id = request.header.id;
    err.query = request.query.clone();
    err.header.query_length = err.query.len() as u64;
    err.header.length = HEADER_SIZE as u64 + err.header.query_length + err.header.body_length;
    err
}

pub fn create_response(
    request: &Message,
    result: impl serde::Serialize,
    body_format: BodyFormat,
) -> Result<Message, RepeError> {
    let mut builder = Message::builder()
        .id(request.header.id)
        .query_bytes(request.query.clone())
        .query_format(
            QueryFormat::try_from(request.header.query_format).unwrap_or(QueryFormat::RawBinary),
        )
        .error_code(ErrorCode::Ok);
    builder = match body_format {
        BodyFormat::Json => builder.body_json(&result)?,
        BodyFormat::Utf8 => {
            let s = serde_json::to_string(&result)?; // convenience: stringify
            builder.body_utf8(&s)
        }
        BodyFormat::RawBinary => {
            // Serialize JSON then treat as bytes; callers wanting true raw should supply bytes.
            let v = serde_json::to_vec(&result)?;
            builder.body_bytes(v).body_format(BodyFormat::RawBinary)
        }
        BodyFormat::Beve => builder.body_beve(&result)?,
    };
    Ok(builder.build())
}