reddb-io-server 1.2.0

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
//! Minimal JSON parser and serializer with zero dependencies.
//! Implements a subset of JSON sufficient for MCP message handling.

use std::fmt;

/// Simplified JSON value representation.
#[derive(Clone, Debug, PartialEq)]
pub enum JsonValue {
    Null,
    Bool(bool),
    Number(f64),
    String(String),
    Array(Vec<JsonValue>),
    Object(Vec<(String, JsonValue)>),
}

impl JsonValue {
    /// Returns the value as string reference if it is a string.
    pub fn as_str(&self) -> Option<&str> {
        match self {
            JsonValue::String(s) => Some(s.as_str()),
            _ => None,
        }
    }

    /// Returns the value as f64 if it is a number.
    pub fn as_f64(&self) -> Option<f64> {
        match self {
            JsonValue::Number(n) => Some(*n),
            _ => None,
        }
    }

    /// Returns the value as boolean.
    pub fn as_bool(&self) -> Option<bool> {
        match self {
            JsonValue::Bool(b) => Some(*b),
            _ => None,
        }
    }

    /// Returns the value as array.
    pub fn as_array(&self) -> Option<&[JsonValue]> {
        match self {
            JsonValue::Array(items) => Some(items.as_slice()),
            _ => None,
        }
    }

    /// Returns the value as mutable array.
    pub fn as_array_mut(&mut self) -> Option<&mut Vec<JsonValue>> {
        match self {
            JsonValue::Array(items) => Some(items),
            _ => None,
        }
    }

    /// Returns the object entries if the value is an object.
    pub fn as_object(&self) -> Option<&[(String, JsonValue)]> {
        match self {
            JsonValue::Object(entries) => Some(entries.as_slice()),
            _ => None,
        }
    }

    /// Returns a mutable reference to the object entries.
    pub fn as_object_mut(&mut self) -> Option<&mut Vec<(String, JsonValue)>> {
        match self {
            JsonValue::Object(entries) => Some(entries),
            _ => None,
        }
    }

    /// Retrieves field value from object by key.
    pub fn get(&self, key: &str) -> Option<&JsonValue> {
        if let JsonValue::Object(entries) = self {
            for (k, v) in entries {
                if k == key {
                    return Some(v);
                }
            }
        }
        None
    }

    /// Retrieves mutable field value from object by key.
    pub fn get_mut(&mut self, key: &str) -> Option<&mut JsonValue> {
        if let JsonValue::Object(entries) = self {
            for (k, v) in entries.iter_mut() {
                if k == key {
                    return Some(v);
                }
            }
        }
        None
    }

    /// Convenience constructor for JSON objects.
    pub fn object(entries: Vec<(String, JsonValue)>) -> JsonValue {
        JsonValue::Object(entries)
    }

    /// Convenience constructor for JSON arrays.
    pub fn array(items: Vec<JsonValue>) -> JsonValue {
        JsonValue::Array(items)
    }

    /// Serializes the value into a compact JSON string.
    ///
    /// **Deprecation note (ADR 0010 / issue #177):** the canonical
    /// JSON encoder for serialization-boundary-sensitive paths
    /// (audit log, HelloAck, PayloadReply, anything reaching a
    /// downstream parser) is `crate::serde_json::Value::escape_string`
    /// using `to_string_compact`. This local encoder is correct after
    /// the F-01 hotfix (#181) but is not the canonical owner; new
    /// audit / wire emission code should not call it. Existing MCP
    /// JSON-RPC callers may keep using it pending a follow-up
    /// retirement slice.
    #[deprecated(
        note = "Use crate::serde_json::Value::to_string_compact for boundary emission; see ADR 0010 / issue #177"
    )]
    pub fn to_json_string(&self) -> String {
        let mut out = String::new();
        self.write_json(&mut out);
        out
    }

    fn write_json(&self, out: &mut String) {
        match self {
            JsonValue::Null => out.push_str("null"),
            JsonValue::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
            JsonValue::Number(n) => {
                if n.fract() == 0.0 {
                    out.push_str(&format!("{}", *n as i64));
                } else {
                    out.push_str(&format!("{}", n));
                }
            }
            JsonValue::String(s) => {
                out.push('"');
                for ch in s.chars() {
                    match ch {
                        '"' => out.push_str("\\\""),
                        '\\' => out.push_str("\\\\"),
                        '\n' => out.push_str("\\n"),
                        '\r' => out.push_str("\\r"),
                        '\t' => out.push_str("\\t"),
                        c if c.is_control() => {
                            out.push_str(&format!("\\u{:04x}", c as u32));
                        }
                        c => out.push(c),
                    }
                }
                out.push('"');
            }
            JsonValue::Array(items) => {
                out.push('[');
                for (idx, item) in items.iter().enumerate() {
                    if idx > 0 {
                        out.push(',');
                    }
                    item.write_json(out);
                }
                out.push(']');
            }
            JsonValue::Object(entries) => {
                out.push('{');
                for (idx, (key, value)) in entries.iter().enumerate() {
                    if idx > 0 {
                        out.push(',');
                    }
                    JsonValue::String(key.clone()).write_json(out);
                    out.push(':');
                    value.write_json(out);
                }
                out.push('}');
            }
        }
    }
}

impl From<&str> for JsonValue {
    fn from(value: &str) -> JsonValue {
        JsonValue::String(value.to_string())
    }
}

impl From<String> for JsonValue {
    fn from(value: String) -> JsonValue {
        JsonValue::String(value)
    }
}

impl From<bool> for JsonValue {
    fn from(value: bool) -> JsonValue {
        JsonValue::Bool(value)
    }
}

impl From<f64> for JsonValue {
    fn from(value: f64) -> JsonValue {
        JsonValue::Number(value)
    }
}

impl From<i64> for JsonValue {
    fn from(value: i64) -> JsonValue {
        JsonValue::Number(value as f64)
    }
}

impl From<usize> for JsonValue {
    fn from(value: usize) -> JsonValue {
        JsonValue::Number(value as f64)
    }
}

impl fmt::Display for JsonValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Internal route — Display is the legacy entry point and
        // routes through the (now deprecated for boundary use)
        // `to_json_string`. Silence the warning here so the lint
        // surfaces only at external call sites.
        #[allow(deprecated)]
        let s = self.to_json_string();
        write!(f, "{s}")
    }
}

/// Parser for JSON strings into [`JsonValue`].
pub struct JsonParser<'a> {
    input: &'a [u8],
    pos: usize,
}

impl<'a> JsonParser<'a> {
    /// Creates a new parser from input slice.
    pub fn new(input: &'a str) -> Self {
        Self {
            input: input.as_bytes(),
            pos: 0,
        }
    }

    /// Parses a JSON value from the current position.
    pub fn parse_value(&mut self) -> Result<JsonValue, String> {
        self.skip_whitespace();
        if self.eof() {
            return Err("unexpected end of input".to_string());
        }
        let ch = self.current_char();
        match ch {
            b'n' => self.parse_null(),
            b't' | b'f' => self.parse_bool(),
            b'-' | b'0'..=b'9' => self.parse_number(),
            b'"' => self.parse_string().map(JsonValue::String),
            b'[' => self.parse_array(),
            b'{' => self.parse_object(),
            _ => Err(format!("unexpected character '{}'", ch as char)),
        }
    }

    fn parse_null(&mut self) -> Result<JsonValue, String> {
        self.expect_bytes(b"null")?;
        Ok(JsonValue::Null)
    }

    fn parse_bool(&mut self) -> Result<JsonValue, String> {
        if self.matches_bytes(b"true") {
            self.pos += 4;
            Ok(JsonValue::Bool(true))
        } else if self.matches_bytes(b"false") {
            self.pos += 5;
            Ok(JsonValue::Bool(false))
        } else {
            Err("invalid boolean literal".to_string())
        }
    }

    fn parse_number(&mut self) -> Result<JsonValue, String> {
        let start = self.pos;
        if self.current_char() == b'-' {
            self.pos += 1;
        }
        if self.eof() {
            return Err("invalid number literal".to_string());
        }

        match self.current_char() {
            b'0' => {
                self.pos += 1;
            }
            b'1'..=b'9' => {
                self.pos += 1;
                while !self.eof() && self.current_char().is_ascii_digit() {
                    self.pos += 1;
                }
            }
            _ => return Err("invalid number literal".to_string()),
        }

        if !self.eof() && self.current_char() == b'.' {
            self.pos += 1;
            if self.eof() || !self.current_char().is_ascii_digit() {
                return Err("invalid number literal".to_string());
            }
            while !self.eof() && self.current_char().is_ascii_digit() {
                self.pos += 1;
            }
        }

        if !self.eof() && (self.current_char() == b'e' || self.current_char() == b'E') {
            self.pos += 1;
            if !self.eof() && (self.current_char() == b'+' || self.current_char() == b'-') {
                self.pos += 1;
            }
            if self.eof() || !self.current_char().is_ascii_digit() {
                return Err("invalid number literal".to_string());
            }
            while !self.eof() && self.current_char().is_ascii_digit() {
                self.pos += 1;
            }
        }

        let slice = &self.input[start..self.pos];
        let s = std::str::from_utf8(slice).map_err(|_| "invalid UTF-8 in number".to_string())?;
        let value = s
            .parse::<f64>()
            .map_err(|_| "failed to parse number".to_string())?;
        Ok(JsonValue::Number(value))
    }

    fn parse_string(&mut self) -> Result<String, String> {
        self.expect_char(b'"')?;
        let mut result = String::new();
        while !self.eof() {
            let ch = self.current_char();
            match ch {
                b'"' => {
                    self.pos += 1;
                    return Ok(result);
                }
                b'\\' => {
                    self.pos += 1;
                    if self.eof() {
                        return Err("unexpected end of input in escape".to_string());
                    }
                    let esc = self.current_char();
                    self.pos += 1;
                    match esc {
                        b'"' => result.push('"'),
                        b'\\' => result.push('\\'),
                        b'/' => result.push('/'),
                        b'b' => result.push('\x08'),
                        b'f' => result.push('\x0c'),
                        b'n' => result.push('\n'),
                        b'r' => result.push('\r'),
                        b't' => result.push('\t'),
                        b'u' => {
                            // RFC 8259 §7: `\uXXXX` covers code points in
                            // the BMP. Code points above U+FFFF (e.g. emoji,
                            // U+1F4A9 PILE OF POO) are represented in JSON
                            // as a UTF-16 surrogate pair `💩` and
                            // MUST be decoded as one Unicode scalar.
                            let code = self.parse_unicode_escape()?;
                            if (0xD800..=0xDBFF).contains(&code) {
                                // High surrogate — must be followed by a
                                // `\uXXXX` low surrogate.
                                if self.pos + 2 > self.input.len()
                                    || self.input[self.pos] != b'\\'
                                    || self.input[self.pos + 1] != b'u'
                                {
                                    return Err(
                                        "expected low surrogate after high surrogate".to_string()
                                    );
                                }
                                self.pos += 2;
                                let low = self.parse_unicode_escape()?;
                                if !(0xDC00..=0xDFFF).contains(&low) {
                                    return Err("invalid low surrogate".to_string());
                                }
                                let scalar = 0x10000 + (((code - 0xD800) << 10) | (low - 0xDC00));
                                if let Some(chr) = char::from_u32(scalar) {
                                    result.push(chr);
                                } else {
                                    return Err("invalid unicode escape".to_string());
                                }
                            } else if (0xDC00..=0xDFFF).contains(&code) {
                                return Err(
                                    "unexpected low surrogate without preceding high surrogate"
                                        .to_string(),
                                );
                            } else if let Some(chr) = char::from_u32(code) {
                                result.push(chr);
                            } else {
                                return Err("invalid unicode escape".to_string());
                            }
                        }
                        _ => return Err("invalid escape sequence".to_string()),
                    }
                }
                _ if ch < 0x80 => {
                    // ASCII fast path: byte == codepoint.
                    self.pos += 1;
                    result.push(ch as char);
                }
                _ => {
                    // Multi-byte UTF-8 sequence. The parser's input came
                    // from `&str` (validated UTF-8 at JsonParser::new), so
                    // a complete codepoint starts here. Decoding byte-by-
                    // byte via `ch as char` would map each continuation
                    // byte to a Latin-1 codepoint, producing mojibake (the
                    // root cause of issue #191 — `é` → `é`, `🦀` → four
                    // garbled chars). Instead, lift a full codepoint out
                    // of the underlying UTF-8 stream.
                    let next = std::str::from_utf8(&self.input[self.pos..])
                        .map_err(|_| "invalid utf-8 in string body".to_string())?
                        .chars()
                        .next()
                        .ok_or_else(|| "unterminated string literal".to_string())?;
                    self.pos += next.len_utf8();
                    result.push(next);
                }
            }
        }
        Err("unterminated string literal".to_string())
    }

    fn parse_unicode_escape(&mut self) -> Result<u32, String> {
        if self.pos + 4 > self.input.len() {
            return Err("invalid unicode escape".to_string());
        }
        let mut value = 0u32;
        for _ in 0..4 {
            let ch = self.current_char();
            self.pos += 1;
            value <<= 4;
            value |= match ch {
                b'0'..=b'9' => (ch - b'0') as u32,
                b'a'..=b'f' => (ch - b'a' + 10) as u32,
                b'A'..=b'F' => (ch - b'A' + 10) as u32,
                _ => return Err("invalid unicode escape".to_string()),
            };
        }
        Ok(value)
    }

    fn parse_array(&mut self) -> Result<JsonValue, String> {
        self.expect_char(b'[')?;
        let mut items = Vec::new();
        self.skip_whitespace();
        if self.peek_char() == Some(b']') {
            self.pos += 1;
            return Ok(JsonValue::Array(items));
        }
        loop {
            let value = self.parse_value()?;
            items.push(value);
            self.skip_whitespace();
            match self.peek_char() {
                Some(b',') => {
                    self.pos += 1;
                }
                Some(b']') => {
                    self.pos += 1;
                    break;
                }
                _ => return Err("expected ',' or ']' in array".to_string()),
            }
        }
        Ok(JsonValue::Array(items))
    }

    fn parse_object(&mut self) -> Result<JsonValue, String> {
        self.expect_char(b'{')?;
        let mut entries = Vec::new();
        self.skip_whitespace();
        if self.peek_char() == Some(b'}') {
            self.pos += 1;
            return Ok(JsonValue::Object(entries));
        }
        loop {
            self.skip_whitespace();
            let key = self.parse_string()?;
            self.skip_whitespace();
            self.expect_char(b':')?;
            let value = self.parse_value()?;
            entries.push((key, value));
            self.skip_whitespace();
            match self.peek_char() {
                Some(b',') => {
                    self.pos += 1;
                }
                Some(b'}') => {
                    self.pos += 1;
                    break;
                }
                _ => return Err("expected ',' or '}' in object".to_string()),
            }
        }
        Ok(JsonValue::Object(entries))
    }

    fn skip_whitespace(&mut self) {
        while !self.eof() {
            match self.current_char() {
                b' ' | b'\n' | b'\r' | b'\t' => self.pos += 1,
                _ => break,
            }
        }
    }

    fn expect_bytes(&mut self, expected: &[u8]) -> Result<(), String> {
        if self.remaining().starts_with(expected) {
            self.pos += expected.len();
            Ok(())
        } else {
            Err("unexpected token".to_string())
        }
    }

    fn matches_bytes(&self, expected: &[u8]) -> bool {
        self.remaining().starts_with(expected)
    }

    fn expect_char(&mut self, expected: u8) -> Result<(), String> {
        if self.peek_char() == Some(expected) {
            self.pos += 1;
            Ok(())
        } else {
            Err(format!("expected '{}'", expected as char))
        }
    }

    fn peek_char(&self) -> Option<u8> {
        if self.pos >= self.input.len() {
            None
        } else {
            Some(self.input[self.pos])
        }
    }

    fn current_char(&self) -> u8 {
        self.input[self.pos]
    }

    fn remaining(&self) -> &[u8] {
        &self.input[self.pos..]
    }

    fn eof(&self) -> bool {
        self.pos >= self.input.len()
    }
}

/// Parses the provided JSON string into a [`JsonValue`].
pub fn parse_json(input: &str) -> Result<JsonValue, String> {
    let mut parser = JsonParser::new(input);
    let value = parser.parse_value()?;
    parser.skip_whitespace();
    if parser.eof() {
        Ok(value)
    } else {
        Err("unexpected trailing data".to_string())
    }
}

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

    #[test]
    fn parse_simple_object() {
        let json = r#"{"name":"reddb","active":true,"count":3}"#;
        let value = parse_json(json).unwrap();
        let obj = value.as_object().unwrap();
        assert_eq!(obj.len(), 3);
    }

    #[test]
    fn parse_nested_array() {
        let json = r#"{"items":[1,2,{"flag":false}]}"#;
        let value = parse_json(json).unwrap();
        assert!(value.get("items").unwrap().as_array().is_some());
    }

    #[test]
    fn stringify_roundtrip() {
        let json = r#"{"message":"hello","value":42}"#;
        let value = parse_json(json).unwrap();
        #[allow(deprecated)]
        let output = value.to_json_string();
        assert!(output.contains("hello"));
    }
}