reddb-io-server 1.1.2

RedDB server-side engine: storage, runtime, replication, MCP, AI, and the gRPC/HTTP/RedWire/PG-wire dispatchers. Re-exported by the umbrella `reddb` crate.
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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
use crate::utils::json::{parse_json, JsonValue};
use std::collections::{BTreeMap, HashMap};
use std::fmt;
use std::ops::{Index, IndexMut};

pub type Map<K, V> = BTreeMap<K, V>;

#[derive(Debug, Clone, PartialEq)]
pub enum Value {
    Null,
    Bool(bool),
    Number(f64),
    String(String),
    Array(Vec<Value>),
    Object(Map<String, Value>),
}

impl fmt::Display for Value {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.to_string_compact())
    }
}

impl Value {
    pub fn as_str(&self) -> Option<&str> {
        match self {
            Value::String(s) => Some(s.as_str()),
            _ => None,
        }
    }

    pub fn as_f64(&self) -> Option<f64> {
        match self {
            Value::Number(n) => Some(*n),
            _ => None,
        }
    }

    pub fn as_i64(&self) -> Option<i64> {
        match self {
            Value::Number(n) => Some(*n as i64),
            _ => None,
        }
    }

    pub fn as_u64(&self) -> Option<u64> {
        match self {
            Value::Number(n) if *n >= 0.0 => Some(*n as u64),
            _ => None,
        }
    }

    pub fn as_bool(&self) -> Option<bool> {
        match self {
            Value::Bool(b) => Some(*b),
            _ => None,
        }
    }

    pub fn as_array(&self) -> Option<&[Value]> {
        match self {
            Value::Array(values) => Some(values.as_slice()),
            _ => None,
        }
    }

    pub fn as_object(&self) -> Option<&Map<String, Value>> {
        match self {
            Value::Object(map) => Some(map),
            _ => None,
        }
    }

    pub fn get(&self, key: &str) -> Option<&Value> {
        if let Value::Object(map) = self {
            map.get(key)
        } else {
            None
        }
    }

    pub fn to_string_compact(&self) -> String {
        let mut out = String::new();
        self.write_compact(&mut out);
        out
    }

    pub fn to_string_pretty(&self) -> String {
        let mut out = String::new();
        self.write_pretty(&mut out, 0);
        out
    }

    fn write_compact(&self, out: &mut String) {
        match self {
            Value::Null => out.push_str("null"),
            Value::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
            Value::Number(n) => {
                if n.fract() == 0.0 {
                    out.push_str(&format!("{}", *n as i64));
                } else {
                    out.push_str(&format!("{}", n));
                }
            }
            Value::String(s) => {
                out.push('"');
                out.push_str(&escape_string(s));
                out.push('"');
            }
            Value::Array(values) => {
                out.push('[');
                for (idx, value) in values.iter().enumerate() {
                    if idx > 0 {
                        out.push(',');
                    }
                    value.write_compact(out);
                }
                out.push(']');
            }
            Value::Object(map) => {
                out.push('{');
                for (idx, (key, value)) in map.iter().enumerate() {
                    if idx > 0 {
                        out.push(',');
                    }
                    out.push('"');
                    out.push_str(&escape_string(key));
                    out.push('"');
                    out.push(':');
                    value.write_compact(out);
                }
                out.push('}');
            }
        }
    }

    fn write_pretty(&self, out: &mut String, indent: usize) {
        match self {
            Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => {
                out.push_str(&self.to_string_compact());
            }
            Value::Array(values) => {
                out.push('[');
                if !values.is_empty() {
                    out.push('\n');
                    for (idx, value) in values.iter().enumerate() {
                        if idx > 0 {
                            out.push_str(",\n");
                        }
                        out.push_str(&"  ".repeat(indent + 1));
                        value.write_pretty(out, indent + 1);
                    }
                    out.push('\n');
                    out.push_str(&"  ".repeat(indent));
                }
                out.push(']');
            }
            Value::Object(map) => {
                out.push('{');
                if !map.is_empty() {
                    out.push('\n');
                    for (idx, (key, value)) in map.iter().enumerate() {
                        if idx > 0 {
                            out.push_str(",\n");
                        }
                        out.push_str(&"  ".repeat(indent + 1));
                        out.push('"');
                        out.push_str(&escape_string(key));
                        out.push_str("\": ");
                        value.write_pretty(out, indent + 1);
                    }
                    out.push('\n');
                    out.push_str(&"  ".repeat(indent));
                }
                out.push('}');
            }
        }
    }
}

fn escape_string(input: &str) -> String {
    // RFC 8259 §7: all control bytes (U+0000..U+001F), `"`, and `\` MUST be escaped.
    // Previous version silently dropped control bytes other than \n \r \t — see
    // F-01 in docs/security/serialization-boundary-audit-2026-05-06.md and
    // ADR 0010 (serialization-boundary discipline).
    use std::fmt::Write as _;
    let mut out = String::with_capacity(input.len());
    for ch in input.chars() {
        match ch {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            '\u{08}' => out.push_str("\\b"),
            '\u{0C}' => out.push_str("\\f"),
            c if (c as u32) < 0x20 => {
                let _ = write!(out, "\\u{:04x}", c as u32);
            }
            c => out.push(c),
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    fn encode(s: &str) -> String {
        Value::String(s.to_string()).to_string_compact()
    }

    /// Every byte 0x00..0x20 must produce a valid JSON string that round-trips
    /// through a real JSON parser preserving the original byte.
    #[test]
    fn escape_string_handles_every_control_byte() {
        for byte in 0x00u8..0x20 {
            let original: String = std::char::from_u32(byte as u32).unwrap().to_string();
            let encoded = encode(&original);
            // Must parse back to the exact same byte (NOT silently dropped).
            let parsed: String = from_str(&encoded).unwrap_or_else(|err| {
                panic!("byte 0x{byte:02x} encoded as {encoded:?} failed to parse: {err}")
            });
            assert_eq!(
                parsed, original,
                "byte 0x{byte:02x} did not round-trip (encoded={encoded:?})"
            );
        }
    }

    #[test]
    fn escape_string_handles_standard_escapes() {
        assert_eq!(encode("\""), "\"\\\"\"");
        assert_eq!(encode("\\"), "\"\\\\\"");
        assert_eq!(encode("\n"), "\"\\n\"");
        assert_eq!(encode("\r"), "\"\\r\"");
        assert_eq!(encode("\t"), "\"\\t\"");
        assert_eq!(encode("\u{08}"), "\"\\b\"");
        assert_eq!(encode("\u{0C}"), "\"\\f\"");
    }

    #[test]
    fn escape_string_handles_mixed_payload() {
        let input = "name=\"x\"\n\\path\t\x01end";
        let encoded = encode(input);
        let parsed: String = from_str(&encoded).expect("mixed payload must parse");
        assert_eq!(parsed, input);
    }

    /// Regression test for F-01: the "self-disagreeing audit log" exploit.
    /// An attacker writes audit data containing \x01. The old encoder
    /// silently dropped \x01, so a downstream auditor that re-parses the
    /// JSONL would see a different record than what was emitted. The fix
    /// must encode \x01 as  so it survives the round trip.
    #[test]
    fn audit_log_preserves_low_control_bytes() {
        let payload = "collection\x01name\x07with\x1fbells";
        let encoded = encode(payload);

        // Encoded form must contain explicit \u escapes — NOT raw control bytes,
        // NOT silent drops.
        assert!(
            encoded.contains("\\u0001"),
            "expected \\u0001 escape in {encoded:?}"
        );
        assert!(
            encoded.contains("\\u0007"),
            "expected \\u0007 escape in {encoded:?}"
        );
        assert!(
            encoded.contains("\\u001f"),
            "expected \\u001f escape in {encoded:?}"
        );
        assert!(
            !encoded.contains('\x01'),
            "raw \\x01 must not appear in encoded output"
        );

        // Round trip through the in-house parser must reproduce the original bytes.
        let parsed: String = from_str(&encoded).expect("audit payload must parse");
        assert_eq!(parsed, payload);
    }
}

impl From<JsonValue> for Value {
    fn from(value: JsonValue) -> Self {
        match value {
            JsonValue::Null => Value::Null,
            JsonValue::Bool(b) => Value::Bool(b),
            JsonValue::Number(n) => Value::Number(n),
            JsonValue::String(s) => Value::String(s),
            JsonValue::Array(values) => Value::Array(values.into_iter().map(Value::from).collect()),
            JsonValue::Object(entries) => {
                let mut map = Map::new();
                for (k, v) in entries {
                    map.insert(k, Value::from(v));
                }
                Value::Object(map)
            }
        }
    }
}

impl Index<&str> for Value {
    type Output = Value;

    fn index(&self, key: &str) -> &Self::Output {
        static NULL: Value = Value::Null;
        match self {
            Value::Object(map) => map.get(key).unwrap_or(&NULL),
            _ => &NULL,
        }
    }
}

impl IndexMut<&str> for Value {
    fn index_mut(&mut self, key: &str) -> &mut Self::Output {
        match self {
            Value::Object(map) => map.entry(key.to_string()).or_insert(Value::Null),
            _ => {
                *self = Value::Object(Map::new());
                match self {
                    Value::Object(map) => map.entry(key.to_string()).or_insert(Value::Null),
                    _ => unreachable!(),
                }
            }
        }
    }
}

pub trait JsonEncode {
    fn to_json_value(&self) -> Value;
}

impl<T: JsonEncode + ?Sized> JsonEncode for &T {
    fn to_json_value(&self) -> Value {
        (*self).to_json_value()
    }
}

pub trait JsonDecode: Sized {
    fn from_json_value(value: Value) -> Result<Self, String>;
}

impl JsonEncode for Value {
    fn to_json_value(&self) -> Value {
        self.clone()
    }
}

impl JsonDecode for Value {
    fn from_json_value(value: Value) -> Result<Self, String> {
        Ok(value)
    }
}

impl JsonEncode for bool {
    fn to_json_value(&self) -> Value {
        Value::Bool(*self)
    }
}

impl JsonEncode for i64 {
    fn to_json_value(&self) -> Value {
        Value::Number(*self as f64)
    }
}

impl JsonEncode for i32 {
    fn to_json_value(&self) -> Value {
        Value::Number(*self as f64)
    }
}

impl JsonEncode for u8 {
    fn to_json_value(&self) -> Value {
        Value::Number(*self as f64)
    }
}

impl JsonEncode for u16 {
    fn to_json_value(&self) -> Value {
        Value::Number(*self as f64)
    }
}

impl JsonEncode for u32 {
    fn to_json_value(&self) -> Value {
        Value::Number(*self as f64)
    }
}

impl JsonEncode for u64 {
    fn to_json_value(&self) -> Value {
        Value::Number(*self as f64)
    }
}

impl JsonEncode for usize {
    fn to_json_value(&self) -> Value {
        Value::Number(*self as f64)
    }
}

impl JsonEncode for f64 {
    fn to_json_value(&self) -> Value {
        Value::Number(*self)
    }
}

impl JsonEncode for f32 {
    fn to_json_value(&self) -> Value {
        Value::Number(*self as f64)
    }
}

impl JsonEncode for String {
    fn to_json_value(&self) -> Value {
        Value::String(self.clone())
    }
}

impl JsonEncode for &str {
    fn to_json_value(&self) -> Value {
        Value::String(self.to_string())
    }
}

impl<'a> JsonEncode for std::borrow::Cow<'a, str> {
    fn to_json_value(&self) -> Value {
        Value::String(self.to_string())
    }
}

impl<T: JsonEncode> JsonEncode for Vec<T> {
    fn to_json_value(&self) -> Value {
        Value::Array(self.iter().map(|v| v.to_json_value()).collect())
    }
}

impl<T: JsonEncode> JsonEncode for [T] {
    fn to_json_value(&self) -> Value {
        Value::Array(self.iter().map(|v| v.to_json_value()).collect())
    }
}

impl<T: JsonEncode> JsonEncode for Option<T> {
    fn to_json_value(&self) -> Value {
        match self {
            Some(value) => value.to_json_value(),
            None => Value::Null,
        }
    }
}

impl<const N: usize> JsonEncode for [u8; N] {
    fn to_json_value(&self) -> Value {
        Value::Array(self.iter().map(|b| Value::Number(*b as f64)).collect())
    }
}

impl<T: JsonEncode> JsonEncode for HashMap<String, T> {
    fn to_json_value(&self) -> Value {
        let mut map = Map::new();
        for (k, v) in self {
            map.insert(k.clone(), v.to_json_value());
        }
        Value::Object(map)
    }
}

impl JsonDecode for String {
    fn from_json_value(value: Value) -> Result<Self, String> {
        match value {
            Value::String(s) => Ok(s),
            _ => Err("expected string".to_string()),
        }
    }
}

impl JsonDecode for bool {
    fn from_json_value(value: Value) -> Result<Self, String> {
        match value {
            Value::Bool(b) => Ok(b),
            _ => Err("expected bool".to_string()),
        }
    }
}

impl JsonDecode for u8 {
    fn from_json_value(value: Value) -> Result<Self, String> {
        match value {
            Value::Number(n) => Ok(n as u8),
            _ => Err("expected number".to_string()),
        }
    }
}

impl JsonDecode for u16 {
    fn from_json_value(value: Value) -> Result<Self, String> {
        match value {
            Value::Number(n) => Ok(n as u16),
            _ => Err("expected number".to_string()),
        }
    }
}

impl JsonDecode for u32 {
    fn from_json_value(value: Value) -> Result<Self, String> {
        match value {
            Value::Number(n) => Ok(n as u32),
            _ => Err("expected number".to_string()),
        }
    }
}

impl JsonDecode for u64 {
    fn from_json_value(value: Value) -> Result<Self, String> {
        match value {
            Value::Number(n) => Ok(n as u64),
            _ => Err("expected number".to_string()),
        }
    }
}

impl JsonDecode for usize {
    fn from_json_value(value: Value) -> Result<Self, String> {
        match value {
            Value::Number(n) => Ok(n as usize),
            _ => Err("expected number".to_string()),
        }
    }
}

impl JsonDecode for i64 {
    fn from_json_value(value: Value) -> Result<Self, String> {
        match value {
            Value::Number(n) => Ok(n as i64),
            _ => Err("expected number".to_string()),
        }
    }
}

impl JsonDecode for i32 {
    fn from_json_value(value: Value) -> Result<Self, String> {
        match value {
            Value::Number(n) => Ok(n as i32),
            _ => Err("expected number".to_string()),
        }
    }
}

impl JsonDecode for f32 {
    fn from_json_value(value: Value) -> Result<Self, String> {
        match value {
            Value::Number(n) => Ok(n as f32),
            _ => Err("expected number".to_string()),
        }
    }
}

impl<T: JsonDecode> JsonDecode for Vec<T> {
    fn from_json_value(value: Value) -> Result<Self, String> {
        match value {
            Value::Array(values) => values.into_iter().map(T::from_json_value).collect(),
            _ => Err("expected array".to_string()),
        }
    }
}

impl<T: JsonDecode> JsonDecode for HashMap<String, T> {
    fn from_json_value(value: Value) -> Result<Self, String> {
        match value {
            Value::Object(map) => map
                .into_iter()
                .map(|(k, v)| Ok((k, T::from_json_value(v)?)))
                .collect(),
            _ => Err("expected object".to_string()),
        }
    }
}

impl<T: JsonDecode> JsonDecode for Option<T> {
    fn from_json_value(value: Value) -> Result<Self, String> {
        match value {
            Value::Null => Ok(None),
            other => Ok(Some(T::from_json_value(other)?)),
        }
    }
}

impl<const N: usize> JsonDecode for [u8; N] {
    fn from_json_value(value: Value) -> Result<Self, String> {
        match value {
            Value::Array(values) => {
                if values.len() != N {
                    return Err("invalid array length".to_string());
                }
                let mut out = [0u8; N];
                for (idx, val) in values.into_iter().enumerate() {
                    out[idx] = u8::from_json_value(val)?;
                }
                Ok(out)
            }
            _ => Err("expected array".to_string()),
        }
    }
}

pub fn to_value<T: JsonEncode + ?Sized>(value: &T) -> Value {
    value.to_json_value()
}

pub fn to_string<T: JsonEncode + ?Sized>(value: &T) -> Result<String, String> {
    Ok(to_value(value).to_string_compact())
}

pub fn to_string_pretty<T: JsonEncode + ?Sized>(value: &T) -> Result<String, String> {
    Ok(to_value(value).to_string_pretty())
}

pub fn to_vec<T: JsonEncode + ?Sized>(value: &T) -> Result<Vec<u8>, String> {
    Ok(to_string(value)?.into_bytes())
}

pub fn from_str<T: JsonDecode>(input: &str) -> Result<T, String> {
    let value = parse_json(input).map(Value::from)?;
    T::from_json_value(value)
}

pub fn from_slice<T: JsonDecode>(input: &[u8]) -> Result<T, String> {
    let s = std::str::from_utf8(input).map_err(|e| e.to_string())?;
    from_str(s)
}

pub fn from_value<T: JsonDecode>(value: Value) -> Result<T, String> {
    T::from_json_value(value)
}

#[macro_export]
macro_rules! json {
    (null) => {
        $crate::serde_json::Value::Null
    };
    ([ $( $elem:expr ),* $(,)? ]) => {
        $crate::serde_json::Value::Array(vec![ $( $crate::json!($elem) ),* ])
    };
    ({ $( $key:literal : $value:expr ),* $(,)? }) => {{
        let mut map = $crate::serde_json::Map::new();
        $( map.insert($key.to_string(), $crate::json!($value)); )*
        $crate::serde_json::Value::Object(map)
    }};
    ($other:expr) => {
        $crate::serde_json::to_value(&$other)
    };
}

pub use crate::json;