reductstore 1.19.8

ReductStore is a time series database designed specifically for storing and managing large amounts of blob data.
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
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
// Copyright 2021-2026 ReductSoftware UG
// Licensed under the Apache License, Version 2.0

use crate::storage::block_manager::BlockRef;
use crate::storage::entry::{Entry, RecordType, RecordWriter};
use crate::storage::proto::{record, us_to_ts, Record};
use async_trait::async_trait;
use log::debug;
use reduct_base::error::ReductError;
use reduct_base::io::{WriteChunk, WriteRecord};
use reduct_base::Labels;
use std::sync::Arc;
use tokio::sync::OwnedSemaphorePermit;

struct InFlightWriteRecord {
    inner: Box<dyn WriteRecord + Sync + Send>,
    _permit: Option<OwnedSemaphorePermit>,
}

impl InFlightWriteRecord {
    fn new(
        inner: Box<dyn WriteRecord + Sync + Send>,
        permit: Option<OwnedSemaphorePermit>,
    ) -> Self {
        Self {
            inner,
            _permit: permit,
        }
    }
}

#[async_trait]
impl WriteRecord for InFlightWriteRecord {
    async fn send(&mut self, chunk: WriteChunk) -> Result<(), ReductError> {
        self.inner.send(chunk).await
    }

    async fn send_timeout(
        &mut self,
        chunk: WriteChunk,
        timeout: std::time::Duration,
    ) -> Result<(), ReductError> {
        self.inner.send_timeout(chunk, timeout).await
    }
}

impl Entry {
    /// Starts a new record write.
    ///
    /// # Arguments
    ///
    /// * `time` - The timestamp of the record.
    /// * `content_size` - The size of the record content.
    /// * `content_type` - The content type of the record.
    /// * `labels` - The labels of the record.
    ///
    /// # Returns
    ///
    /// * `Sender<Result<Bytes, ReductError>>` - The sender to send the record content in chunks.
    /// * `HTTPError` - The error if any.
    pub async fn begin_write(
        &self,
        time: u64,
        content_size: u64,
        content_type: String,
        labels: Labels,
    ) -> Result<Box<dyn WriteRecord + Sync + Send>, ReductError> {
        let permit = self.acquire_writer_slot().await?;
        // Strategy validates labels and can perform pre-write maintenance.
        self.system_behavior.prepare_write(self, &labels).await?;

        let settings = self.settings.read().await?;
        let mut block_ref = {
            let mut bm = self.block_manager.write().await?;
            // When we write, the likely case is that we are writing the latest record
            // in the entry. In this case, we can just append to the latest block.
            let block_ref = if bm.index().tree().is_empty() {
                bm.start_new_block(time, settings.max_block_size).await?
            } else {
                let block_id = *bm.index().tree().last().unwrap();
                bm.load_block(block_id).await?
            };
            block_ref
        };

        let _record_type = {
            let is_belated = {
                let block = block_ref.write().await?;
                block.record_count() > 0 && block.latest_record_time() >= time
            };
            if is_belated {
                debug!(
                    "Timestamp {} is belated for {}/{}. Looking for a block",
                    time, self.bucket_name, self.name
                );
                // The timestamp is belated. We need to find the proper block to write to.
                let mut bm = self.block_manager.write().await?;
                let index_tree = bm.index().tree();
                let record_type = if *index_tree.first().unwrap() > time {
                    // The timestamp is the earliest. We need to create a new block.
                    debug!(
                        "Timestamp {} is the earliest for {}/{}. Creating a new block",
                        time, self.bucket_name, self.name
                    );
                    block_ref = bm.start_new_block(time, settings.max_block_size).await?;
                    RecordType::BelatedFirst
                } else {
                    block_ref = bm.find_block(time).await?;
                    drop(bm); // drop the lock early to avoid blocking other operations

                    let block_id = block_ref.read().await?.block_id();
                    debug!(
                        "Timestamp {} is belated for {}/{}. Writing to block {}",
                        time, self.bucket_name, self.name, block_id
                    );
                    let record = block_ref.read().await?.get_record(time).map(|r| r.clone());
                    // check if the record already exists
                    if let Some(mut record) = record {
                        // We overwrite the record if it is errored and the size is the same.
                        return if record.state != record::State::Errored as i32
                            || record.end - record.begin != content_size as u64
                        {
                            Err(ReductError::conflict(&format!(
                                "A record with timestamp {} already exists",
                                time
                            )))
                        } else {
                            {
                                let mut block = block_ref.write().await?;
                                record.labels = labels
                                    .into_iter()
                                    .map(|(name, value)| record::Label { name, value })
                                    .collect();
                                record.state = record::State::Started as i32;
                                record.content_type = content_type;
                                block.insert_or_update_record(record);
                            }

                            let writer = RecordWriter::try_new(
                                Arc::clone(&self.block_manager),
                                block_ref,
                                time,
                            )
                            .await?;

                            return Ok(Box::new(InFlightWriteRecord::new(
                                Box::new(writer),
                                permit,
                            )));
                        };
                    }
                    RecordType::Belated
                };
                record_type
            } else {
                // The timestamp is the latest. We can just append to the latest block.
                RecordType::Latest
            }
        };

        let mut block_ref = {
            let block = block_ref.read().await?;
            // Check if the block has enough space for the record.
            let has_no_space = block.size() + content_size as u64 > settings.max_block_size;
            let has_too_many_records = block.record_count() + 1 > settings.max_block_records;

            drop(block);
            if has_no_space || has_too_many_records {
                // We need to create a new block.
                debug!(
                    "Creating a new block for {}/{} (has_no_space={}, has_too_many_records={})",
                    self.bucket_name, self.name, has_no_space, has_too_many_records
                );
                let mut bm = self.block_manager.write().await?;
                bm.finish_block(block_ref.clone()).await?;
                bm.start_new_block(time, settings.max_block_size).await?
            } else {
                // We can just append to the latest block.
                block_ref.clone()
            }
        };

        Self::prepare_block_for_writing(&mut block_ref, time, content_size, content_type, labels)
            .await?;

        let writer =
            RecordWriter::try_new(Arc::clone(&self.block_manager), block_ref, time).await?;
        Ok(Box::new(InFlightWriteRecord::new(Box::new(writer), permit)))
    }

    async fn prepare_block_for_writing(
        block: &mut BlockRef,
        time: u64,
        content_size: u64,
        content_type: String,
        labels: Labels,
    ) -> Result<(), ReductError> {
        let mut block = block.write().await?;
        let record = Record {
            timestamp: Some(us_to_ts(&time)),
            begin: block.size(),
            end: block.size() + content_size,
            content_type,
            state: record::State::Started as i32,
            labels: labels
                .into_iter()
                .map(|(name, value)| record::Label { name, value })
                .collect(),
        };

        block.insert_or_update_record(record);
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use crate::cfg::Cfg;
    use crate::storage::entry::tests::{entry, path, write_stub_record};
    use crate::storage::entry::{Entry, EntrySettings};
    use crate::storage::proto::{record, us_to_ts, Record};
    use bytes::Bytes;
    use reduct_base::error::ReductError;
    use reduct_base::Labels;
    use rstest::rstest;
    use serial_test::serial;
    use std::path::PathBuf;
    use std::sync::Arc;

    #[rstest]
    #[serial]
    #[tokio::test]
    async fn test_begin_write_new_block_size(path: PathBuf) {
        let entry = entry(
            EntrySettings {
                max_block_size: 10,
                max_block_records: 10000,
            },
            path,
        )
        .await;

        write_stub_record(&entry, 1).await;
        write_stub_record(&entry, 2000010).await;
        let mut bm = entry.block_manager.write().await.unwrap();

        assert_eq!(
            bm.load_block(1)
                .await
                .unwrap()
                .write()
                .await
                .unwrap()
                .get_record(1)
                .unwrap()
                .clone(),
            Record {
                timestamp: Some(us_to_ts(&1)),
                begin: 0,
                end: 10,
                content_type: "text/plain".to_string(),
                state: record::State::Finished as i32,
                labels: vec![],
            }
        );

        assert_eq!(
            bm.load_block(2000010)
                .await
                .unwrap()
                .write()
                .await
                .unwrap()
                .get_record(2000010)
                .unwrap()
                .clone(),
            Record {
                timestamp: Some(us_to_ts(&2000010)),
                begin: 0,
                end: 10,
                content_type: "text/plain".to_string(),
                state: record::State::Finished as i32,
                labels: vec![],
            }
        );
    }

    #[rstest]
    #[serial]
    #[tokio::test]
    async fn test_begin_write_new_block_records(path: PathBuf) {
        let entry = entry(
            EntrySettings {
                max_block_size: 10000,
                max_block_records: 1,
            },
            path,
        )
        .await;

        write_stub_record(&entry, 1).await;
        write_stub_record(&entry, 2).await;
        write_stub_record(&entry, 2000010).await;

        let mut bm = entry.block_manager.write().await.unwrap();
        let records = bm
            .load_block(1)
            .await
            .unwrap()
            .write()
            .await
            .unwrap()
            .record_index()
            .clone();
        assert_eq!(
            records.get(&1).unwrap().clone(),
            Record {
                timestamp: Some(us_to_ts(&1)),
                begin: 0,
                end: 10,
                content_type: "text/plain".to_string(),
                state: record::State::Finished as i32,
                labels: vec![],
            }
        );

        let records = bm
            .load_block(2000010)
            .await
            .unwrap()
            .write()
            .await
            .unwrap()
            .record_index()
            .clone();
        assert_eq!(
            records.get(&2000010).unwrap().clone(),
            Record {
                timestamp: Some(us_to_ts(&2000010)),
                begin: 0,
                end: 10,
                content_type: "text/plain".to_string(),
                state: record::State::Finished as i32,
                labels: vec![],
            }
        );
    }

    #[rstest]
    #[serial]
    #[tokio::test]
    async fn test_begin_write_belated_record(#[future] entry: Arc<Entry>) {
        let entry = entry.await;
        write_stub_record(&entry, 1000000).await;
        write_stub_record(&entry, 3000000).await;
        write_stub_record(&entry, 2000000).await;

        let mut bm = entry.block_manager.write().await.unwrap();
        let records = bm
            .load_block(1000000)
            .await
            .unwrap()
            .read()
            .await
            .unwrap()
            .record_index()
            .clone();
        assert_eq!(records.len(), 3);
        assert_eq!(
            records.get(&1000000).unwrap().timestamp,
            Some(us_to_ts(&1000000))
        );
        assert_eq!(
            records.get(&2000000).unwrap().timestamp,
            Some(us_to_ts(&2000000))
        );
        assert_eq!(
            records.get(&3000000).unwrap().timestamp,
            Some(us_to_ts(&3000000))
        );
    }

    #[rstest]
    #[serial]
    #[tokio::test]
    async fn test_begin_write_belated_first(#[future] entry: Arc<Entry>) {
        let entry = entry.await;
        write_stub_record(&entry, 3000000).await;
        write_stub_record(&entry, 1000000).await;

        let mut bm = entry.block_manager.write().await.unwrap();
        let records = bm
            .load_block(1000000)
            .await
            .unwrap()
            .read()
            .await
            .unwrap()
            .record_index()
            .clone();
        assert_eq!(records.len(), 1);
        assert_eq!(
            records.get(&1000000).unwrap().timestamp,
            Some(us_to_ts(&1000000))
        );
    }

    #[rstest]
    #[serial]
    #[tokio::test]
    async fn test_begin_write_existing_record(#[future] entry: Arc<Entry>) {
        let entry = entry.await;
        write_stub_record(&entry, 1000000).await;
        write_stub_record(&entry, 2000000).await;
        let err = entry
            .begin_write(1000000, 10, "text/plain".to_string(), Labels::new())
            .await;
        assert_eq!(
            err.err(),
            Some(ReductError::conflict(
                "A record with timestamp 1000000 already exists"
            ))
        );
    }

    #[rstest]
    #[serial]
    #[tokio::test]
    async fn test_begin_write_existing_record_belated(#[future] entry: Arc<Entry>) {
        let entry = entry.await;
        write_stub_record(&entry, 2000000).await;
        write_stub_record(&entry, 1000000).await;
        let err = entry
            .begin_write(1000000, 10, "text/plain".to_string(), Labels::new())
            .await;
        assert_eq!(
            err.err(),
            Some(ReductError::conflict(
                "A record with timestamp 1000000 already exists"
            ))
        );
    }

    #[rstest]
    #[serial]
    #[tokio::test]
    async fn test_begin_write_belated_new_block_when_full(path: PathBuf) {
        let entry = entry(
            EntrySettings {
                max_block_size: 10000,
                max_block_records: 2,
            },
            path,
        )
        .await;

        write_stub_record(&entry, 1000000).await;
        write_stub_record(&entry, 3000000).await;
        write_stub_record(&entry, 2000000).await;

        let mut bm = entry.block_manager.write().await.unwrap();
        let records = bm
            .load_block(1000000)
            .await
            .unwrap()
            .read()
            .await
            .unwrap()
            .record_index()
            .clone();
        assert_eq!(records.len(), 2);
        assert!(records.contains_key(&1000000));
        assert!(records.contains_key(&3000000));

        let records = bm
            .load_block(2000000)
            .await
            .unwrap()
            .read()
            .await
            .unwrap()
            .record_index()
            .clone();
        assert_eq!(records.len(), 1);
        assert!(records.contains_key(&2000000));
    }

    #[rstest]
    #[serial]
    #[tokio::test]
    async fn test_begin_override_errored(#[future] entry: Arc<Entry>) {
        let entry = entry.await;
        let mut sender = entry
            .clone()
            .begin_write(1000000, 10, "text/plain".to_string(), Labels::new())
            .await
            .unwrap();

        sender.send(Ok(None)).await.unwrap();

        let mut sender = entry
            .clone()
            .begin_write(
                1000000,
                10,
                "text/html".to_string(),
                Labels::from_iter(vec![("a".to_string(), "b".to_string())]),
            )
            .await
            .unwrap();
        sender
            .send(Ok(Some(Bytes::from(vec![0; 10]))))
            .await
            .unwrap();

        let record = entry
            .block_manager
            .write()
            .await
            .unwrap()
            .load_block(1000000)
            .await
            .unwrap()
            .read()
            .await
            .unwrap()
            .get_record(1000000)
            .unwrap()
            .clone();
        assert_eq!(record.content_type, "text/html");
        assert_eq!(record.labels.len(), 1);
        assert_eq!(record.labels[0].name, "a");
        assert_eq!(record.labels[0].value, "b");
    }

    #[rstest]
    #[serial]
    #[tokio::test]
    async fn test_begin_not_override_if_different_size(#[future] entry: Arc<Entry>) {
        let entry = entry.await;
        let mut sender = entry
            .clone()
            .begin_write(1000000, 10, "text/plain".to_string(), Labels::new())
            .await
            .unwrap();
        sender.send(Ok(None)).await.unwrap();

        let err = entry
            .clone()
            .begin_write(
                1000000,
                5,
                "text/html".to_string(),
                Labels::from_iter(vec![("a".to_string(), "b".to_string())]),
            )
            .await
            .err();
        assert_eq!(
            err,
            Some(ReductError::conflict(
                "A record with timestamp 1000000 already exists"
            ))
        );
    }

    #[rstest]
    #[serial]
    #[tokio::test]
    async fn test_belated_record_readable_after_rotation(#[future] entry: Arc<Entry>) {
        let entry = entry.await;
        // Fill the first block
        write_stub_record(&entry, 1000000).await;
        // Rotate to a new block
        write_stub_record(&entry, 3000000).await;
        // Belated write into the first block
        write_stub_record(&entry, 2000000).await;

        // We must be able to read the belated record back
        let reader = entry.begin_read(2000000).await;
        assert!(reader.is_ok(), "Belated record should be readable");
    }

    #[rstest]
    #[serial]
    #[tokio::test]
    async fn test_meta_entry_requires_key_label(path: PathBuf) {
        let entry = Arc::new(
            Entry::try_build(
                "entry/$meta",
                path,
                EntrySettings {
                    max_block_size: 10000,
                    max_block_records: 10000,
                },
                Cfg::default().into(),
            )
            .await
            .unwrap(),
        );

        let err = entry
            .begin_write(1, 4, "application/json".to_string(), Labels::new())
            .await
            .err()
            .unwrap();
        assert_eq!(
            err,
            ReductError::unprocessable_entity(
                "System entry 'entry/$meta' records must contain label 'key'"
            )
        );
    }

    #[rstest]
    #[serial]
    #[tokio::test]
    async fn test_meta_entry_replaces_previous_record_with_same_key(path: PathBuf) {
        let entry = Arc::new(
            Entry::try_build(
                "entry/$meta",
                path,
                EntrySettings {
                    max_block_size: 10000,
                    max_block_records: 10000,
                },
                Cfg::default().into(),
            )
            .await
            .unwrap(),
        );

        let mut sender = entry
            .begin_write(
                1,
                7,
                "application/json".to_string(),
                Labels::from_iter([("key".to_string(), "schema".to_string())]),
            )
            .await
            .unwrap();
        sender
            .send(Ok(Some(Bytes::from_static(br#"{"v":1}"#))))
            .await
            .unwrap();
        sender.send(Ok(None)).await.unwrap();

        let mut sender = entry
            .begin_write(
                2,
                7,
                "application/json".to_string(),
                Labels::from_iter([("key".to_string(), "schema".to_string())]),
            )
            .await
            .unwrap();
        sender
            .send(Ok(Some(Bytes::from_static(br#"{"v":2}"#))))
            .await
            .unwrap();
        sender.send(Ok(None)).await.unwrap();

        assert!(entry.begin_read(1).await.is_err());
        assert!(entry.begin_read(2).await.is_ok());
    }

    #[rstest]
    #[serial]
    #[tokio::test]
    async fn test_meta_entry_remove_true_is_rejected(path: PathBuf) {
        let entry = Arc::new(
            Entry::try_build(
                "entry/$meta",
                path,
                EntrySettings {
                    max_block_size: 10000,
                    max_block_records: 10000,
                },
                Cfg::default().into(),
            )
            .await
            .unwrap(),
        );

        let mut sender = entry
            .begin_write(
                1,
                7,
                "application/json".to_string(),
                Labels::from_iter([("key".to_string(), "$plugin".to_string())]),
            )
            .await
            .unwrap();
        sender
            .send(Ok(Some(Bytes::from_static(br#"{"v":1}"#))))
            .await
            .unwrap();
        sender.send(Ok(None)).await.unwrap();

        let err = entry
            .begin_write(
                2,
                2,
                "application/json".to_string(),
                Labels::from_iter([
                    ("key".to_string(), "$plugin".to_string()),
                    ("remove".to_string(), "true".to_string()),
                ]),
            )
            .await
            .err()
            .unwrap();

        assert_eq!(
            err,
            ReductError::unprocessable_entity(
                "System entry 'entry/$meta' does not support writing records with label 'remove=true'; use record update"
            )
        );
        assert!(entry.begin_read(1).await.is_ok());
    }
}