sierradb-server 0.3.1

SierraDB server - distributed event store server with Redis RESP3 protocol
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
use std::collections::HashSet;
use std::fmt;

use combine::error::{StreamError, Tracked};
use combine::parser::choice::or;
use combine::stream::{ResetStream, StreamErrorFor, StreamOnce};
use combine::{ParseError, Parser, Positioned, attempt, choice, easy, satisfy_map};
use redis_protocol::resp3::types::{BytesFrame, VerbatimStringFormat};
use sierradb::StreamId;
use sierradb::bucket::PartitionId;
use sierradb_protocol::{ErrorCode, ExpectedVersion};
use uuid::Uuid;

use crate::request::{PartitionSelector, RangeValue};

#[derive(Debug, PartialEq)]
pub struct FrameStreamErrors<'a> {
    errors: easy::Errors<&'a BytesFrame, &'a [BytesFrame], usize>,
}

impl<'a> ParseError<&'a BytesFrame, &'a [BytesFrame], usize> for FrameStreamErrors<'a> {
    type StreamError = easy::Error<&'a BytesFrame, &'a [BytesFrame]>;

    fn empty(position: usize) -> Self {
        FrameStreamErrors {
            errors: easy::Errors::empty(position),
        }
    }

    fn set_position(&mut self, position: usize) {
        self.errors.set_position(position);
    }

    fn add(&mut self, err: Self::StreamError) {
        self.errors.add(err);
    }

    fn set_expected<F>(self_: &mut Tracked<Self>, info: Self::StreamError, f: F)
    where
        F: FnOnce(&mut Tracked<Self>),
    {
        let start = self_.error.errors.errors.len();
        f(self_);
        // Replace all expected errors that were added from the previous add_error
        // with this expected error
        let mut i = 0;
        self_.error.errors.errors.retain(|e| {
            if i < start {
                i += 1;
                true
            } else {
                !matches!(*e, easy::Error::Expected(_))
            }
        });
        self_.error.errors.add(info);
    }

    fn is_unexpected_end_of_input(&self) -> bool {
        self.errors.is_unexpected_end_of_input()
    }

    fn into_other<T>(self) -> T
    where
        T: ParseError<&'a BytesFrame, &'a [BytesFrame], usize>,
    {
        self.errors.into_other()
    }
}

fn frame_kind(frame: &BytesFrame) -> &'static str {
    match frame {
        BytesFrame::BlobString { .. } => "string",
        BytesFrame::BlobError { .. } => "error",
        BytesFrame::SimpleString { .. } => "string",
        BytesFrame::SimpleError { .. } => "error",
        BytesFrame::Boolean { .. } => "boolean",
        BytesFrame::Null => "null",
        BytesFrame::Number { .. } => "number",
        BytesFrame::Double { .. } => "double",
        BytesFrame::BigNumber { .. } => "number",
        BytesFrame::VerbatimString { .. } => "string",
        BytesFrame::Array { .. } => "array",
        BytesFrame::Map { .. } => "map",
        BytesFrame::Set { .. } => "set",
        BytesFrame::Push { .. } => "push",
        BytesFrame::Hello { .. } => "hello",
        BytesFrame::ChunkedString(_) => "chunk",
    }
}

fn display_error<'a>(
    f: &mut fmt::Formatter<'_>,
    err: &easy::Error<&'a BytesFrame, &'a [BytesFrame]>,
) -> fmt::Result {
    match err {
        easy::Error::Unexpected(info) => display_info(f, info),
        easy::Error::Expected(info) => display_info(f, info),
        easy::Error::Message(info) => display_info(f, info),
        easy::Error::Other(error) => write!(f, "{error}"),
    }
}

fn display_info<'a>(
    f: &mut fmt::Formatter<'_>,
    info: &easy::Info<&'a BytesFrame, &'a [BytesFrame]>,
) -> fmt::Result {
    match info {
        easy::Info::Token(token) => write!(f, "{}", frame_kind(token)),
        easy::Info::Range(range) => {
            for (i, frame) in range.iter().enumerate() {
                if i < range.len() - 1 {
                    write!(f, "{}, ", frame_kind(frame))?;
                } else {
                    write!(f, "{}", frame_kind(frame))?;
                }
            }
            Ok(())
        }
        easy::Info::Owned(msg) => write!(f, "{msg}"),
        easy::Info::Static(msg) => write!(f, "{msg}"),
    }
}

impl<'a> fmt::Display for FrameStreamErrors<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} ", ErrorCode::InvalidArg)?;

        // First print the token that we did not expect
        // There should really just be one unexpected message at this point though we
        // print them all to be safe
        let unexpected = self
            .errors
            .errors
            .iter()
            .filter(|e| matches!(**e, easy::Error::Unexpected(_)));
        let mut has_unexpected = false;
        for err in unexpected {
            if !has_unexpected {
                write!(f, "unexpected ")?;
            }
            has_unexpected = true;
            display_error(f, err)?;
        }

        // Then we print out all the things that were expected in a comma separated list
        // 'Expected 'a', 'expression' or 'let'
        let iter = || {
            self.errors.errors.iter().filter_map(|err| match *err {
                easy::Error::Expected(ref err) => Some(err),
                _ => None,
            })
        };
        let expected_count = iter().count();
        for (i, message) in iter().enumerate() {
            if has_unexpected {
                write!(f, ": ")?;
                has_unexpected = false;
            }
            let s = match i {
                0 => "expected",
                _ if i < expected_count - 1 => ",",
                // Last expected message to be written
                _ => " or",
            };
            write!(f, "{s} ")?;
            display_info(f, message)?;
        }
        // If there are any generic messages we print them out last
        let messages = self
            .errors
            .errors
            .iter()
            .filter(|e| matches!(**e, easy::Error::Message(_) | easy::Error::Other(_)));
        for (i, err) in messages.enumerate() {
            if i == 0 && expected_count != 0 {
                write!(f, ": ")?;
            }
            display_error(f, err)?;
        }
        Ok(())
    }
}

// Implement the Stream trait for &[BytesFrame]
#[derive(Clone, Debug, PartialEq)]
pub struct FrameStream<'a> {
    frames: &'a [BytesFrame],
    position: usize,
}

impl<'a> StreamOnce for FrameStream<'a> {
    type Error = FrameStreamErrors<'a>;
    type Position = usize;
    type Range = &'a [BytesFrame];
    type Token = &'a BytesFrame;

    fn uncons(&mut self) -> Result<Self::Token, StreamErrorFor<Self>> {
        match self.frames.split_first() {
            Some((first, rest)) => {
                self.frames = rest;
                self.position += 1;
                Ok(first)
            }
            None => Err(easy::Error::end_of_input()),
        }
    }

    fn is_partial(&self) -> bool {
        false
    }
}

impl<'a> ResetStream for FrameStream<'a> {
    type Checkpoint = (usize, &'a [BytesFrame]);

    fn checkpoint(&self) -> Self::Checkpoint {
        (self.position, self.frames)
    }

    fn reset(&mut self, checkpoint: Self::Checkpoint) -> Result<(), Self::Error> {
        self.position = checkpoint.0;
        self.frames = checkpoint.1;
        Ok(())
    }
}

impl<'a> Positioned for FrameStream<'a> {
    fn position(&self) -> Self::Position {
        self.position
    }
}

// Helper function to create a FrameStream
pub fn frame_stream(frames: &'_ [BytesFrame]) -> FrameStream<'_> {
    FrameStream {
        frames,
        position: 0,
    }
}

// Basic frame parsers using regular functions instead of the parser! macro
pub fn string<'a>() -> impl Parser<FrameStream<'a>, Output = &'a str> + 'a {
    satisfy_map(|frame: &'a BytesFrame| match frame {
        BytesFrame::BlobString { data, .. }
        | BytesFrame::SimpleString { data, .. }
        | BytesFrame::VerbatimString {
            data,
            format: VerbatimStringFormat::Text,
            ..
        } => str::from_utf8(data).ok(),
        _ => None,
    })
    .expected("string")
}

pub fn data<'a>() -> impl Parser<FrameStream<'a>, Output = &'a [u8]> + 'a {
    satisfy_map(|frame: &'a BytesFrame| match frame {
        BytesFrame::BlobString { data, .. }
        | BytesFrame::SimpleString { data, .. }
        | BytesFrame::VerbatimString {
            data,
            format: VerbatimStringFormat::Text,
            ..
        } => Some(&**data),
        _ => None,
    })
    .expected("string or bytes")
}

pub fn data_owned<'a>() -> impl Parser<FrameStream<'a>, Output = Vec<u8>> + 'a {
    data().map(ToOwned::to_owned)
}

pub fn keyword<'a>(kw: &'static str) -> impl Parser<FrameStream<'a>, Output = &'a str> + 'a {
    debug_assert_eq!(kw, kw.to_uppercase(), "keywords should be uppercase");
    satisfy_map(move |frame: &'a BytesFrame| match frame {
        BytesFrame::BlobString { data, .. }
        | BytesFrame::SimpleString { data, .. }
        | BytesFrame::VerbatimString {
            data,
            format: VerbatimStringFormat::Text,
            ..
        } => str::from_utf8(data).ok().and_then(|s| {
            if s.to_uppercase() == kw {
                Some(s)
            } else {
                None
            }
        }),
        _ => None,
    })
    .expected(kw)
}

pub fn number_u64<'a>() -> impl Parser<FrameStream<'a>, Output = u64> + 'a {
    satisfy_map(|frame: &'a BytesFrame| match frame {
        BytesFrame::BlobString { data, .. }
        | BytesFrame::SimpleString { data, .. }
        | BytesFrame::BigNumber { data, .. }
        | BytesFrame::VerbatimString {
            data,
            format: VerbatimStringFormat::Text,
            ..
        } => str::from_utf8(data).ok().and_then(|s| s.parse().ok()),
        BytesFrame::Number { data, .. } => (*data).try_into().ok(),
        _ => None,
    })
    .expected("number")
}

pub fn number_u64_min<'a>(min: u64) -> impl Parser<FrameStream<'a>, Output = u64> + 'a {
    number_u64().and_then(move |n| {
        if n < min {
            Err(easy::Error::message_format(format!(
                "number {n} must not be less than {min}"
            )))
        } else {
            Ok(n)
        }
    })
}

pub fn number_i64<'a>() -> impl Parser<FrameStream<'a>, Output = i64> + 'a {
    satisfy_map(|frame: &'a BytesFrame| match frame {
        BytesFrame::BlobString { data, .. }
        | BytesFrame::SimpleString { data, .. }
        | BytesFrame::BigNumber { data, .. }
        | BytesFrame::VerbatimString {
            data,
            format: VerbatimStringFormat::Text,
            ..
        } => str::from_utf8(data).ok().and_then(|s| s.parse().ok()),
        BytesFrame::Number { data, .. } => Some(*data),
        _ => None,
    })
    .expected("number")
}

pub fn number_u32<'a>() -> impl Parser<FrameStream<'a>, Output = u32> + 'a {
    satisfy_map(|frame: &'a BytesFrame| match frame {
        BytesFrame::BlobString { data, .. }
        | BytesFrame::SimpleString { data, .. }
        | BytesFrame::BigNumber { data, .. }
        | BytesFrame::VerbatimString {
            data,
            format: VerbatimStringFormat::Text,
            ..
        } => str::from_utf8(data).ok().and_then(|s| s.parse().ok()),
        BytesFrame::Number { data, .. } => (*data).try_into().ok(),
        _ => None,
    })
    .expected("number")
}

pub fn partition_id<'a>() -> impl Parser<FrameStream<'a>, Output = PartitionId> + 'a {
    satisfy_map(|frame: &'a BytesFrame| match frame {
        BytesFrame::BlobString { data, .. }
        | BytesFrame::SimpleString { data, .. }
        | BytesFrame::BigNumber { data, .. }
        | BytesFrame::VerbatimString {
            data,
            format: VerbatimStringFormat::Text,
            ..
        } => str::from_utf8(data).ok().and_then(|s| s.parse().ok()),
        BytesFrame::Number { data, .. } => (*data).try_into().ok(),
        _ => None,
    })
    .expected("partition id")
}

fn uuid<'a>(expected: &'static str) -> impl Parser<FrameStream<'a>, Output = Uuid> + 'a {
    string()
        .and_then(move |s| {
            Uuid::parse_str(s.trim())
                .map_err(|_| easy::Error::message_format(format!("invalid {expected}")))
        })
        .expected(expected)
}

pub fn event_id<'a>() -> impl Parser<FrameStream<'a>, Output = Uuid> + 'a {
    uuid("event id")
}

pub fn partition_key<'a>() -> impl Parser<FrameStream<'a>, Output = Uuid> + 'a {
    uuid("partition key")
}

pub fn subscription_id<'a>() -> impl Parser<FrameStream<'a>, Output = Uuid> + 'a {
    uuid("subscription id")
}

pub fn expected_version<'a>() -> impl Parser<FrameStream<'a>, Output = ExpectedVersion> + 'a {
    let exact = number_u64().map(ExpectedVersion::Exact);

    let keyword = choice((
        keyword("ANY").map(|_| ExpectedVersion::Any),
        keyword("EXISTS").map(|_| ExpectedVersion::Exists),
        keyword("EMPTY").map(|_| ExpectedVersion::Empty),
    ));

    exact
        .or(keyword)
        .message("expected version number or 'any', 'exists', 'empty'")
}

pub fn range_value<'a>() -> impl Parser<FrameStream<'a>, Output = RangeValue> + 'a {
    choice!(
        keyword("-").map(|_| RangeValue::Start),
        keyword("+").map(|_| RangeValue::End),
        number_u64().map(RangeValue::Value)
    )
    .expected("range value (-, +, or number)")
}

pub fn partition_selector<'a>() -> impl Parser<FrameStream<'a>, Output = PartitionSelector> + 'a {
    or(
        attempt(partition_key().map(PartitionSelector::ByKey)),
        partition_id().map(PartitionSelector::ById),
    )
    .expected("partition id or key")
}

pub fn all_selector<'a>() -> impl Parser<FrameStream<'a>, Output = char> + 'a {
    keyword("*").map(|_| '*')
}

pub fn partition_ids<'a>() -> impl Parser<FrameStream<'a>, Output = HashSet<PartitionId>> + 'a {
    satisfy_map(|frame: &'a BytesFrame| {
        match frame {
            BytesFrame::BlobString { data, .. }
            | BytesFrame::SimpleString { data, .. }
            | BytesFrame::VerbatimString {
                data,
                format: VerbatimStringFormat::Text,
                ..
            } => {
                let data = str::from_utf8(data).ok()?;

                // Otherwise try comma-separated list
                data.split(',')
                    .map(|part| part.trim().parse::<PartitionId>())
                    .collect::<Result<_, _>>()
                    .ok()
            }
            BytesFrame::BigNumber { data, .. } => {
                // Handle Number frames directly
                let id: PartitionId = str::from_utf8(data).ok()?.parse().ok()?;
                Some(HashSet::from_iter([id]))
            }
            BytesFrame::Number { data, .. } => {
                // Handle Number frames directly
                let id: PartitionId = (*data).try_into().ok()?;
                Some(HashSet::from_iter([id]))
            }
            _ => None,
        }
    })
    .expected("comma-separated partition ids")
}

// <p1>=<s1>
pub fn partition_id_sequence<'a>() -> impl Parser<FrameStream<'a>, Output = (PartitionId, u64)> + 'a
{
    satisfy_map(|frame: &'a BytesFrame| match frame {
        BytesFrame::BlobString { data, .. }
        | BytesFrame::SimpleString { data, .. }
        | BytesFrame::VerbatimString {
            data,
            format: VerbatimStringFormat::Text,
            ..
        } => {
            let (partition_id, sequence) = str::from_utf8(data).ok()?.split_once('=')?;
            let partition_id: PartitionId = partition_id.parse().ok()?;
            let sequence: u64 = sequence.parse().ok()?;
            Some((partition_id, sequence))
        }
        _ => None,
    })
    .expected("partition id sequence value")
}

// <s1>=<v1>
pub fn stream_id_version<'a>() -> impl Parser<FrameStream<'a>, Output = (StreamId, u64)> + 'a {
    string()
        .and_then(|s| {
            let (stream_id, version) = s
                .split_once('=')
                .ok_or_else(|| easy::Error::message_format("missing `=` in stream id version"))?;
            let stream_id = StreamId::new(stream_id).map_err(easy::Error::message_format)?;
            let version: u64 = version
                .parse()
                .map_err(|_| easy::Error::message_format("invalid stream id version number"))?;
            Ok::<_, easy::Error<_, _>>((stream_id, version))
        })
        .expected("stream id version value")
}

pub fn stream_id<'a>() -> impl Parser<FrameStream<'a>, Output = StreamId> + 'a {
    string()
        .and_then(|s| StreamId::new(s).map_err(easy::Error::message_format))
        .expected("stream id")
}

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

    #[test]
    fn test_string_parser() {
        let frames = vec![BytesFrame::SimpleString {
            data: b"GET".to_vec().into(),
            attributes: None,
        }];

        let stream = frame_stream(&frames);
        let result = string().parse(stream);
        assert!(result.is_ok());
        let (parsed, _) = result.unwrap();
        assert_eq!(parsed, "GET");
    }

    #[test]
    fn test_keyword_parser() {
        let frames = vec![BytesFrame::SimpleString {
            data: b"PARTITION_KEY".to_vec().into(),
            attributes: None,
        }];

        let stream = frame_stream(&frames);
        let (parsed, _) = keyword("PARTITION_KEY").parse(stream).unwrap();
        assert_eq!(parsed, "PARTITION_KEY");
    }

    #[test]
    fn test_partition_id_parser() {
        let frames = vec![BytesFrame::Number {
            data: 10,
            attributes: None,
        }];

        let stream = frame_stream(&frames);
        let (parsed, _) = partition_id().parse(stream).unwrap();
        assert_eq!(parsed, 10);

        let frames = vec![BytesFrame::SimpleString {
            data: b"10".to_vec().into(),
            attributes: None,
        }];

        let stream = frame_stream(&frames);
        let (parsed, _) = partition_id().parse(stream).unwrap();
        assert_eq!(parsed, 10);
    }

    #[test]
    fn test_partition_ids_parser() {
        let frames = vec![BytesFrame::Number {
            data: 10,
            attributes: None,
        }];

        let stream = frame_stream(&frames);
        let (parsed, _) = partition_ids().parse(stream).unwrap();
        assert_eq!(parsed, HashSet::from_iter([10]));

        let frames = vec![BytesFrame::SimpleString {
            data: b"10".to_vec().into(),
            attributes: None,
        }];

        let stream = frame_stream(&frames);
        let (parsed, _) = partition_ids().parse(stream).unwrap();
        assert_eq!(parsed, HashSet::from_iter([10]));

        let frames = vec![BytesFrame::SimpleString {
            data: b"10,59,24".to_vec().into(),
            attributes: None,
        }];

        let stream = frame_stream(&frames);
        let (parsed, _) = partition_ids().parse(stream).unwrap();
        assert_eq!(parsed, HashSet::from_iter([10, 59, 24]));
    }
}