-
Notifications
You must be signed in to change notification settings - Fork 220
Expand file tree
/
Copy pathvariable.rs
More file actions
2830 lines (2486 loc) · 109 KB
/
variable.rs
File metadata and controls
2830 lines (2486 loc) · 109 KB
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
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! An append-only log for storing arbitrary variable length items.
//!
//! `segmented::Journal` is an append-only log for storing arbitrary variable length data on disk. In
//! addition to replay, stored items can be directly retrieved given their section number and offset
//! within the section.
//!
//! # Format
//!
//! Data stored in `Journal` is persisted in one of many Blobs within a caller-provided `partition`.
//! The particular [Blob] in which data is stored is identified by a `section` number (`u64`).
//! Within a `section`, data is appended as an `item` with the following format:
//!
//! ```text
//! +---+---+---+---+---+---+---+---+
//! | 0 ~ 4 | ... |
//! +---+---+---+---+---+---+---+---+
//! | Size (varint u32) | Data |
//! +---+---+---+---+---+---+---+---+
//! ```
//!
//! # Open Blobs
//!
//! `Journal` uses 1 `commonware-storage::Blob` per `section` to store data. All `Blobs` in a given
//! `partition` are kept open during the lifetime of `Journal`. If the caller wishes to bound the
//! number of open `Blobs`, they can group data into fewer `sections` and/or prune unused
//! `sections`.
//!
//! # Sync
//!
//! Data written to `Journal` may not be immediately persisted to `Storage`. It is up to the caller
//! to determine when to force pending data to be written to `Storage` using the `sync` method. When
//! calling `close`, all pending data is automatically synced and any open blobs are dropped.
//!
//! # Pruning
//!
//! All data appended to `Journal` must be assigned to some `section` (`u64`). This assignment
//! allows the caller to prune data from `Journal` by specifying a minimum `section` number. This
//! could be used, for example, by some blockchain application to prune old blocks.
//!
//! # Replay
//!
//! During application initialization, it is very common to replay data from `Journal` to recover
//! some in-memory state. `Journal` is heavily optimized for this pattern and provides a `replay`
//! method to produce a stream of all items in the `Journal` in order of their `section` and
//! `offset`.
//!
//! # Compression
//!
//! `Journal` supports optional compression using `zstd`. This can be enabled by setting the
//! `compression` field in the `Config` struct to a valid `zstd` compression level. This setting can
//! be changed between initializations of `Journal`, however, it must remain populated if any data
//! was written with compression enabled.
//!
//! # Example
//!
//! ```rust
//! use commonware_runtime::{Spawner, Runner, deterministic, buffer::paged::CacheRef};
//! use commonware_storage::journal::segmented::variable::{Journal, Config};
//! use commonware_utils::{NZUsize, NZU16};
//!
//! let executor = deterministic::Runner::default();
//! executor.start(|context| async move {
//! // Create a page cache
//! let page_cache = CacheRef::from_pooler(&context, NZU16!(1024), NZUsize!(10));
//!
//! // Create a journal
//! let mut journal = Journal::init(context, Config {
//! partition: "partition".into(),
//! compression: None,
//! codec_config: (),
//! page_cache,
//! write_buffer: NZUsize!(1024 * 1024),
//! }).await.unwrap();
//!
//! // Append data to the journal
//! journal.append(1, &128).await.unwrap();
//!
//! // Sync the journal
//! journal.sync_all().await.unwrap();
//! });
//! ```
use super::manager::{AppendFactory, Config as ManagerConfig, Manager};
use crate::journal::Error;
use commonware_codec::{
varint::{UInt, MAX_U32_VARINT_SIZE},
Codec, CodecShared, EncodeSize, ReadExt, Write as CodecWrite,
};
use commonware_runtime::{
buffer::paged::{Append, CacheRef, Replay},
Blob, Buf, IoBuf, IoBufMut, Metrics, Storage,
};
use futures::stream::{self, Stream, StreamExt};
use std::{io::Cursor, num::NonZeroUsize};
use tracing::{trace, warn};
use zstd::{bulk::compress, decode_all};
/// Configuration for `Journal` storage.
#[derive(Clone)]
pub struct Config<C> {
/// The `commonware-runtime::Storage` partition to use
/// for storing journal blobs.
pub partition: String,
/// Optional compression level (using `zstd`) to apply to data before storing.
pub compression: Option<u8>,
/// The codec configuration to use for encoding and decoding items.
pub codec_config: C,
/// The page cache to use for caching data.
pub page_cache: CacheRef,
/// The size of the write buffer to use for each blob.
pub write_buffer: NonZeroUsize,
}
/// Decodes a varint length prefix from a buffer.
/// Returns (item_size, varint_len).
#[inline]
fn decode_length_prefix(buf: &mut impl Buf) -> Result<(usize, usize), Error> {
let initial = buf.remaining();
let size = UInt::<u32>::read(buf)?.0 as usize;
let varint_len = initial - buf.remaining();
Ok((size, varint_len))
}
/// Result of finding an item in a buffer (offsets/lengths, not slices).
enum ItemInfo {
/// All item data is available in the buffer.
Complete {
/// Length of the varint prefix.
varint_len: usize,
/// Length of the item data.
data_len: usize,
},
/// Only some item data is available.
Incomplete {
/// Length of the varint prefix.
varint_len: usize,
/// Bytes of item data available in buffer.
prefix_len: usize,
/// Full size of the item.
total_len: usize,
},
}
/// Find an item in a buffer by decoding its length prefix.
///
/// Returns (next_offset, item_info). The buffer is advanced past the varint.
fn find_item(buf: &mut impl Buf, offset: u64) -> Result<(u64, ItemInfo), Error> {
let available = buf.remaining();
let (size, varint_len) = decode_length_prefix(buf)?;
let next_offset = offset
.checked_add(varint_len as u64)
.ok_or(Error::OffsetOverflow)?
.checked_add(size as u64)
.ok_or(Error::OffsetOverflow)?;
let buffered = available.saturating_sub(varint_len);
let item = if buffered >= size {
ItemInfo::Complete {
varint_len,
data_len: size,
}
} else {
ItemInfo::Incomplete {
varint_len,
prefix_len: buffered,
total_len: size,
}
};
Ok((next_offset, item))
}
/// State for replaying a single section's blob.
struct ReplayState<B: Blob, C> {
section: u64,
blob: Append<B>,
replay: Replay<B>,
skip_bytes: u64,
offset: u64,
valid_offset: u64,
codec_config: C,
compressed: bool,
done: bool,
}
/// Decode item data with optional decompression.
fn decode_item<V: Codec>(item_data: impl Buf, cfg: &V::Cfg, compressed: bool) -> Result<V, Error> {
if compressed {
let decompressed =
decode_all(item_data.reader()).map_err(|_| Error::DecompressionFailed)?;
V::decode_cfg(decompressed.as_ref(), cfg).map_err(Error::Codec)
} else {
V::decode_cfg(item_data, cfg).map_err(Error::Codec)
}
}
/// A segmented journal with variable-size entries.
///
/// Each section is stored in a separate blob. Items are length-prefixed with a varint.
///
/// # Repair
///
/// Like
/// [sqlite](https://github.com/sqlite/sqlite/blob/8658a8df59f00ec8fcfea336a2a6a4b5ef79d2ee/src/wal.c#L1504-L1505)
/// and
/// [rocksdb](https://github.com/facebook/rocksdb/blob/0c533e61bc6d89fdf1295e8e0bcee4edb3aef401/include/rocksdb/options.h#L441-L445),
/// the first invalid data read will be considered the new end of the journal (and the
/// underlying [Blob] will be truncated to the last valid item). Repair occurs during
/// replay (not init) because any blob could have trailing bytes.
pub struct Journal<E: Storage + Metrics, V: Codec> {
manager: Manager<E, AppendFactory>,
/// Compression level (if enabled).
compression: Option<u8>,
/// Codec configuration.
codec_config: V::Cfg,
}
impl<E: Storage + Metrics, V: CodecShared> Journal<E, V> {
/// Initialize a new `Journal` instance.
///
/// All backing blobs are opened but not read during
/// initialization. The `replay` method can be used
/// to iterate over all items in the `Journal`.
pub async fn init(context: E, cfg: Config<V::Cfg>) -> Result<Self, Error> {
let manager_cfg = ManagerConfig {
partition: cfg.partition,
factory: AppendFactory {
write_buffer: cfg.write_buffer,
page_cache_ref: cfg.page_cache,
},
};
let manager = Manager::init(context, manager_cfg).await?;
Ok(Self {
manager,
compression: cfg.compression,
codec_config: cfg.codec_config,
})
}
/// Reads an item from the blob at the given offset.
async fn read(
compressed: bool,
cfg: &V::Cfg,
blob: &Append<E::Blob>,
offset: u64,
) -> Result<(u64, u32, V), Error> {
// Read varint header (max 5 bytes for u32)
let (buf, available) = blob
.read_up_to(
offset,
MAX_U32_VARINT_SIZE,
IoBufMut::with_capacity(MAX_U32_VARINT_SIZE),
)
.await?;
let buf = buf.freeze();
let mut cursor = Cursor::new(buf.slice(..available));
let (next_offset, item_info) = find_item(&mut cursor, offset)?;
// Decode item - either directly from buffer or by chaining prefix with remainder
let (item_size, decoded) = match item_info {
ItemInfo::Complete {
varint_len,
data_len,
} => {
// Data follows varint in buffer
let data = buf.slice(varint_len..varint_len + data_len);
let decoded = decode_item::<V>(data, cfg, compressed)?;
(data_len as u32, decoded)
}
ItemInfo::Incomplete {
varint_len,
prefix_len,
total_len,
} => {
// Read remainder and chain with prefix to avoid copying
let prefix = buf.slice(varint_len..varint_len + prefix_len);
let read_offset = offset + varint_len as u64 + prefix_len as u64;
let remainder_len = total_len - prefix_len;
let mut remainder = vec![0u8; remainder_len];
blob.read_into(&mut remainder, read_offset).await?;
let chained = prefix.chain(IoBuf::from(remainder));
let decoded = decode_item::<V>(chained, cfg, compressed)?;
(total_len as u32, decoded)
}
};
Ok((next_offset, item_size, decoded))
}
/// Returns an ordered stream of all items in the journal starting with the item at the given
/// `start_section` and `offset` into that section. Each item is returned as a tuple of
/// (section, offset, size, item).
pub async fn replay(
&self,
start_section: u64,
mut start_offset: u64,
buffer: NonZeroUsize,
) -> Result<impl Stream<Item = Result<(u64, u64, u32, V), Error>> + Send + '_, Error> {
// Collect all blobs to replay (keeping blob reference for potential resize)
let codec_config = self.codec_config.clone();
let compressed = self.compression.is_some();
let mut blobs = Vec::new();
for (§ion, blob) in self.manager.sections_from(start_section) {
blobs.push((
section,
blob.clone(),
blob.replay(buffer).await?,
codec_config.clone(),
compressed,
));
}
// Stream items as they are read to avoid occupying too much memory
Ok(stream::iter(blobs).flat_map(
move |(section, blob, replay, codec_config, compressed)| {
// Calculate initial skip bytes for first blob
let skip_bytes = if section == start_section {
start_offset
} else {
start_offset = 0;
0
};
stream::unfold(
ReplayState {
section,
blob,
replay,
skip_bytes,
offset: 0,
valid_offset: skip_bytes,
codec_config,
compressed,
done: false,
},
move |mut state| async move {
if state.done {
return None;
}
let blob_size = state.replay.blob_size();
let mut batch: Vec<Result<(u64, u64, u32, V), Error>> = Vec::new();
loop {
// Ensure we have enough data for varint header.
// ensure() returns Ok(false) if exhausted with fewer bytes,
// but we still try to decode from remaining bytes.
match state.replay.ensure(MAX_U32_VARINT_SIZE).await {
Ok(true) => {}
Ok(false) => {
// Reader exhausted - check if buffer is empty
if state.replay.remaining() == 0 {
state.done = true;
return if batch.is_empty() {
None
} else {
Some((batch, state))
};
}
// Buffer still has data - continue to try decoding
}
Err(err) => {
batch.push(Err(err.into()));
state.done = true;
return Some((batch, state));
}
}
// Skip bytes if needed (for start_offset)
if state.skip_bytes > 0 {
let to_skip =
state.skip_bytes.min(state.replay.remaining() as u64) as usize;
state.replay.advance(to_skip);
state.skip_bytes -= to_skip as u64;
state.offset += to_skip as u64;
continue;
}
// Try to decode length prefix
let before_remaining = state.replay.remaining();
let (item_size, varint_len) =
match decode_length_prefix(&mut state.replay) {
Ok(result) => result,
Err(err) => {
// Could be incomplete varint - check if reader exhausted
if state.replay.is_exhausted()
|| before_remaining < MAX_U32_VARINT_SIZE
{
// Treat as trailing bytes
if state.valid_offset < blob_size
&& state.offset < blob_size
{
warn!(
blob = state.section,
bad_offset = state.offset,
new_size = state.valid_offset,
"trailing bytes detected: truncating"
);
if let Err(err) =
state.blob.resize(state.valid_offset).await
{
batch.push(Err(err.into()));
state.done = true;
return Some((batch, state));
}
}
state.done = true;
return if batch.is_empty() {
None
} else {
Some((batch, state))
};
}
batch.push(Err(err));
state.done = true;
return Some((batch, state));
}
};
// Ensure we have enough data for item body
match state.replay.ensure(item_size).await {
Ok(true) => {}
Ok(false) => {
// Incomplete item at end - truncate
warn!(
blob = state.section,
bad_offset = state.offset,
new_size = state.valid_offset,
"incomplete item at end: truncating"
);
if let Err(err) = state.blob.resize(state.valid_offset).await {
batch.push(Err(err.into()));
state.done = true;
return Some((batch, state));
}
state.done = true;
return if batch.is_empty() {
None
} else {
Some((batch, state))
};
}
Err(err) => {
batch.push(Err(err.into()));
state.done = true;
return Some((batch, state));
}
}
// Decode item - use take() to limit bytes read
let item_offset = state.offset;
let next_offset = match state
.offset
.checked_add(varint_len as u64)
.and_then(|o| o.checked_add(item_size as u64))
{
Some(o) => o,
None => {
batch.push(Err(Error::OffsetOverflow));
state.done = true;
return Some((batch, state));
}
};
match decode_item::<V>(
(&mut state.replay).take(item_size),
&state.codec_config,
state.compressed,
) {
Ok(decoded) => {
batch.push(Ok((
state.section,
item_offset,
item_size as u32,
decoded,
)));
state.valid_offset = next_offset;
state.offset = next_offset;
}
Err(err) => {
batch.push(Err(err));
state.done = true;
return Some((batch, state));
}
}
// Return batch if we have items and buffer is low
if !batch.is_empty() && state.replay.remaining() < MAX_U32_VARINT_SIZE {
return Some((batch, state));
}
}
},
)
.flat_map(stream::iter)
},
))
}
/// Encode an item.
///
/// Returns `(buf, item_len)` where `item_len` is the length of the encoded (and
/// possibly compressed) payload, excluding the size prefix.
pub(crate) fn encode_item(compression: Option<u8>, item: &V) -> Result<(Vec<u8>, u32), Error> {
let mut buf = Vec::new();
let item_len = Self::encode_item_into(compression, item, &mut buf)?;
Ok((buf, item_len))
}
/// Encode an item with its length prefix, appending the encoded bytes to `buf`.
///
/// Existing contents of `buf` are preserved; this allows callers to accumulate
/// multiple encoded items into a single buffer.
///
/// Returns the payload length, excluding the size prefix.
pub(crate) fn encode_item_into(
compression: Option<u8>,
item: &V,
buf: &mut Vec<u8>,
) -> Result<u32, Error> {
if let Some(compression) = compression {
// Compressed: encode first, then compress
let encoded = item.encode();
let compressed =
compress(&encoded, compression as i32).map_err(|_| Error::CompressionFailed)?;
let item_len = compressed.len();
let item_len_u32: u32 = match item_len.try_into() {
Ok(len) => len,
Err(_) => return Err(Error::ItemTooLarge(item_len)),
};
let size_len = UInt(item_len_u32).encode_size();
let entry_len = size_len
.checked_add(item_len)
.ok_or(Error::OffsetOverflow)?;
buf.reserve(entry_len);
UInt(item_len_u32).write(buf);
buf.extend_from_slice(&compressed);
Ok(item_len_u32)
} else {
// Uncompressed: pre-allocate exact size to avoid copying
let item_len = item.encode_size();
let item_len_u32: u32 = match item_len.try_into() {
Ok(len) => len,
Err(_) => return Err(Error::ItemTooLarge(item_len)),
};
let size_len = UInt(item_len_u32).encode_size();
let entry_len = size_len
.checked_add(item_len)
.ok_or(Error::OffsetOverflow)?;
buf.reserve(entry_len);
UInt(item_len_u32).write(buf);
item.write(buf);
Ok(item_len_u32)
}
}
/// Appends an item to `Journal` in a given `section`, returning the offset
/// where the item was written and the size of the item (which may differ
/// from the raw encoded size if compression is enabled).
pub async fn append(&mut self, section: u64, item: &V) -> Result<(u64, u32), Error> {
let (buf, item_len) = Self::encode_item(self.compression, item)?;
self.append_raw(section, &buf)
.await
.map(|offset| (offset, item_len))
}
/// Append pre-encoded bytes to the given section, returning the byte offset
/// where the data was written.
///
/// The buffer must be in the on-disk format produced by [Self::encode_item].
pub(crate) async fn append_raw(&mut self, section: u64, buf: &[u8]) -> Result<u64, Error> {
let blob = self.manager.get_or_create(section).await?;
let offset = blob.size().await;
blob.append(buf).await?;
trace!(blob = section, offset, "appended item");
Ok(offset)
}
/// Retrieves an item from `Journal` at a given `section` and `offset`.
///
/// # Errors
/// - [Error::AlreadyPrunedToSection] if the requested `section` has been pruned during the
/// current execution.
/// - [Error::SectionOutOfRange] if the requested `section` is empty (i.e. has never had any
/// data appended to it, or has been pruned in a previous execution).
/// - An invalid `offset` for a given section (that is, an offset that doesn't correspond to a
/// previously appended item) will result in an error, with the specific type being
/// undefined.
pub async fn get(&self, section: u64, offset: u64) -> Result<V, Error> {
let blob = self
.manager
.get(section)?
.ok_or(Error::SectionOutOfRange(section))?;
// Perform a multi-op read.
let (_, _, item) =
Self::read(self.compression.is_some(), &self.codec_config, blob, offset).await?;
Ok(item)
}
/// Read multiple items from the same section.
///
/// Offsets should be sorted in ascending order.
pub async fn get_many(&self, section: u64, offsets: &[u64]) -> Result<Vec<V>, Error> {
if offsets.is_empty() {
return Ok(Vec::new());
}
let blob = self
.manager
.get(section)?
.ok_or(Error::SectionOutOfRange(section))?;
let compressed = self.compression.is_some();
let cfg = &self.codec_config;
let mut items = Vec::with_capacity(offsets.len());
for &offset in offsets {
let (_, _, item) = Self::read(compressed, cfg, blob, offset).await?;
items.push(item);
}
Ok(items)
}
/// Read consecutive items from the same section. `offsets` must be sorted in strictly
/// ascending order and identify items that are adjacent in the section.
///
/// # Errors
///
/// Returns [`Error::OffsetDataMismatch`] if the on-disk varint at any offset reports a size
/// inconsistent with the gap to the next offset. This indicates either on-disk corruption or a
/// caller violation of the byte-adjacency precondition.
///
/// # Panics
///
/// Panics if `offsets` is not strictly increasing.
pub(crate) async fn get_many_consecutive(
&self,
section: u64,
offsets: &[u64],
) -> Result<Vec<V>, Error> {
if offsets.len() <= 1 {
return self.get_many(section, offsets).await;
}
let blob = self
.manager
.get(section)?
.ok_or(Error::SectionOutOfRange(section))?;
let start = offsets[0];
let end = offsets[offsets.len() - 1];
if end <= start {
return self.get_many(section, offsets).await;
}
let range_len = usize::try_from(end - start).map_err(|_| Error::OffsetOverflow)?;
let bytes = blob.read_at(start, range_len).await?.coalesce();
let bytes = bytes.as_ref();
let compressed = self.compression.is_some();
let cfg = &self.codec_config;
let mut items = Vec::with_capacity(offsets.len());
let mut local_offset = 0usize;
for window in offsets.windows(2) {
let offset = window[0];
let next_offset = window[1];
assert!(offset < next_offset, "offsets must be strictly increasing");
let item_len =
usize::try_from(next_offset - offset).map_err(|_| Error::OffsetOverflow)?;
let mut cursor = Cursor::new(&bytes[local_offset..]);
let (size, varint_len) = decode_length_prefix(&mut cursor)?;
let actual_len = size + varint_len;
if actual_len != item_len {
return Err(Error::OffsetDataMismatch {
section,
offset,
expected_len: item_len,
actual_len,
});
}
let data_start = local_offset
.checked_add(varint_len)
.ok_or(Error::OffsetOverflow)?;
let data_end = local_offset
.checked_add(item_len)
.ok_or(Error::OffsetOverflow)?;
items.push(decode_item::<V>(
&bytes[data_start..data_end],
cfg,
compressed,
)?);
local_offset = data_end;
}
let (_, _, item) = Self::read(compressed, cfg, blob, end).await?;
items.push(item);
Ok(items)
}
/// Get an item if it can be done synchronously (e.g. without I/O), returning `None` otherwise.
pub fn try_get_sync(&self, section: u64, offset: u64) -> Option<V> {
let mut buf = Vec::new();
self.try_get_sync_into(section, offset, &mut buf)
}
/// Get an item synchronously using caller-provided buffer.
pub fn try_get_sync_into(&self, section: u64, offset: u64, buf: &mut Vec<u8>) -> Option<V> {
let blob = self.manager.get(section).ok()??;
let remaining = blob.try_size()?.checked_sub(offset)?;
let header_len = usize::try_from(remaining.min(MAX_U32_VARINT_SIZE as u64)).ok()?;
if header_len == 0 {
return None;
}
// Read the varint header to determine item size.
let mut header = [0u8; MAX_U32_VARINT_SIZE];
if !blob.try_read_sync(offset, &mut header[..header_len]) {
return None;
}
let mut cursor = Cursor::new(&header[..header_len]);
let (_, item_info) = find_item(&mut cursor, offset).ok()?;
let (varint_len, data_len) = match item_info {
ItemInfo::Complete {
varint_len,
data_len,
} => (varint_len, data_len),
ItemInfo::Incomplete {
varint_len,
total_len,
..
} => (varint_len, total_len),
};
let item_len = varint_len.checked_add(data_len)?;
if item_len > usize::try_from(remaining).ok()? {
return None;
}
// If the full item fits in the header read, decode directly.
if item_len <= header_len {
return decode_item::<V>(
&header[varint_len..varint_len + data_len],
&self.codec_config,
self.compression.is_some(),
)
.ok();
}
// Otherwise try reading the full item from cache.
buf.resize(item_len, 0);
if !blob.try_read_sync(offset, buf) {
return None;
}
decode_item::<V>(
&buf[varint_len..varint_len + data_len],
&self.codec_config,
self.compression.is_some(),
)
.ok()
}
/// Gets the size of the journal for a specific section.
///
/// Returns 0 if the section does not exist.
pub async fn size(&self, section: u64) -> Result<u64, Error> {
self.manager.size(section).await
}
/// Rewinds the journal to the given `section` and `offset`, removing any data beyond it.
///
/// # Warnings
///
/// * This operation is not guaranteed to survive restarts until sync is called.
/// * This operation is not atomic, but it will always leave the journal in a consistent state
/// in the event of failure since blobs are always removed in reverse order of section.
pub async fn rewind_to_offset(&mut self, section: u64, offset: u64) -> Result<(), Error> {
self.manager.rewind(section, offset).await
}
/// Rewinds the journal to the given `section` and `size`.
///
/// This removes any data beyond the specified `section` and `size`.
///
/// # Warnings
///
/// * This operation is not guaranteed to survive restarts until sync is called.
/// * This operation is not atomic, but it will always leave the journal in a consistent state
/// in the event of failure since blobs are always removed in reverse order of section.
pub async fn rewind(&mut self, section: u64, size: u64) -> Result<(), Error> {
self.manager.rewind(section, size).await
}
/// Rewinds the `section` to the given `size`.
///
/// Unlike [Self::rewind], this method does not modify anything other than the given `section`.
///
/// # Warning
///
/// This operation is not guaranteed to survive restarts until sync is called.
pub async fn rewind_section(&mut self, section: u64, size: u64) -> Result<(), Error> {
self.manager.rewind_section(section, size).await
}
/// Ensures that all data in a given `section` is synced to the underlying store.
///
/// If the `section` does not exist, no error will be returned.
pub async fn sync(&self, section: u64) -> Result<(), Error> {
self.manager.sync(section).await
}
/// Syncs all open sections.
pub async fn sync_all(&self) -> Result<(), Error> {
self.manager.sync_all().await
}
/// Prunes all `sections` less than `min`. Returns true if any sections were pruned.
pub async fn prune(&mut self, min: u64) -> Result<bool, Error> {
self.manager.prune(min).await
}
/// Returns the number of the oldest section in the journal.
pub fn oldest_section(&self) -> Option<u64> {
self.manager.oldest_section()
}
/// Returns the number of the newest section in the journal.
pub fn newest_section(&self) -> Option<u64> {
self.manager.newest_section()
}
/// Returns true if no sections exist.
pub fn is_empty(&self) -> bool {
self.manager.is_empty()
}
/// Returns the number of sections.
pub fn num_sections(&self) -> usize {
self.manager.num_sections()
}
/// Removes any underlying blobs created by the journal.
pub async fn destroy(self) -> Result<(), Error> {
self.manager.destroy().await
}
/// Clear all data, resetting the journal to an empty state.
///
/// Unlike `destroy`, this keeps the journal alive so it can be reused.
pub async fn clear(&mut self) -> Result<(), Error> {
self.manager.clear().await
}
}
#[cfg(test)]
mod tests {
use super::*;
use commonware_macros::test_traced;
use commonware_runtime::{deterministic, Blob, BufMut, Runner, Storage, Supervisor as _};
use commonware_utils::{NZUsize, NZU16};
use futures::{pin_mut, StreamExt};
use std::num::NonZeroU16;
const PAGE_SIZE: NonZeroU16 = NZU16!(1024);
const PAGE_CACHE_SIZE: NonZeroUsize = NZUsize!(10);
#[test_traced]
fn test_journal_append_and_read() {
// Initialize the deterministic context
let executor = deterministic::Runner::default();
// Start the test within the executor
executor.start(|context| async move {
// Initialize the journal
let cfg = Config {
partition: "test-partition".into(),
compression: None,
codec_config: (),
page_cache: CacheRef::from_pooler(&context, PAGE_SIZE, PAGE_CACHE_SIZE),
write_buffer: NZUsize!(1024),
};
let index = 1u64;
let data = 10;
let mut journal = Journal::init(context.child("first"), cfg.clone())
.await
.expect("Failed to initialize journal");
// Append an item to the journal
journal
.append(index, &data)
.await
.expect("Failed to append data");
// Check metrics
let buffer = context.encode();
assert!(buffer.contains("first_tracked 1"));
// Drop and re-open the journal to simulate a restart
journal.sync(index).await.expect("Failed to sync journal");
drop(journal);
let journal = Journal::<_, i32>::init(context.child("second"), cfg)
.await
.expect("Failed to re-initialize journal");
// Replay the journal and collect items
let mut items = Vec::new();
let stream = journal
.replay(0, 0, NZUsize!(1024))
.await
.expect("unable to setup replay");
pin_mut!(stream);
while let Some(result) = stream.next().await {
match result {
Ok((blob_index, _, _, item)) => items.push((blob_index, item)),
Err(err) => panic!("Failed to read item: {err}"),
}
}
// Verify that the item was replayed correctly
assert_eq!(items.len(), 1);
assert_eq!(items[0].0, index);
assert_eq!(items[0].1, data);
// Check metrics
let buffer = context.encode();
assert!(buffer.contains("second_tracked 1"));
});
}
#[test_traced]
fn test_journal_multiple_appends_and_reads() {
// Initialize the deterministic context
let executor = deterministic::Runner::default();
// Start the test within the executor
executor.start(|context| async move {
// Create a journal configuration
let cfg = Config {
partition: "test-partition".into(),
compression: None,
codec_config: (),
page_cache: CacheRef::from_pooler(&context, PAGE_SIZE, PAGE_CACHE_SIZE),
write_buffer: NZUsize!(1024),
};
// Initialize the journal
let mut journal = Journal::init(context.child("first"), cfg.clone())
.await
.expect("Failed to initialize journal");
// Append multiple items to different blobs
let data_items = vec![(1u64, 1), (1u64, 2), (2u64, 3), (3u64, 4)];
for (index, data) in &data_items {
journal
.append(*index, data)
.await
.expect("Failed to append data");
journal.sync(*index).await.expect("Failed to sync blob");
}
// Check metrics
let buffer = context.encode();
assert!(buffer.contains("first_tracked 3"));
assert!(buffer.contains("first_synced_total 4"));
// Drop and re-open the journal to simulate a restart
drop(journal);
let journal = Journal::init(context.child("second"), cfg)
.await
.expect("Failed to re-initialize journal");
// Replay the journal and collect items
let mut items = Vec::<(u64, u32)>::new();
{
let stream = journal
.replay(0, 0, NZUsize!(1024))
.await
.expect("unable to setup replay");
pin_mut!(stream);
while let Some(result) = stream.next().await {
match result {
Ok((blob_index, _, _, item)) => items.push((blob_index, item)),
Err(err) => panic!("Failed to read item: {err}"),
}
}
}
// Verify that all items were replayed correctly
assert_eq!(items.len(), data_items.len());
for ((expected_index, expected_data), (actual_index, actual_data)) in