-
Notifications
You must be signed in to change notification settings - Fork 220
Expand file tree
/
Copy pathappend.rs
More file actions
2217 lines (1951 loc) · 90.1 KB
/
append.rs
File metadata and controls
2217 lines (1951 loc) · 90.1 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
//! The [Append] wrapper consists of a [Blob] and a write buffer, and provides a logical view over
//! the underlying blob which has a page-oriented structure that provides integrity guarantees. The
//! wrapper also provides read caching managed by a page cache.
//!
//! # Recovery
//!
//! On `sync`, this wrapper will durably write buffered data to the underlying blob in pages. All
//! pages have a [Checksum] at the end. If no CRC record existed before for the page being written,
//! then one of the checksums will be all zero. If a checksum already existed for the page being
//! written, then the write will overwrite only the checksum with the lesser length value. Should
//! this write fail, the previously committed page state can still be recovered.
//!
//! During initialization, the wrapper will back up over any page that is not accompanied by a
//! valid CRC, treating it as the result of an incomplete write that may be invalid.
use super::read::{PageReader, Replay};
use crate::{
buffer::{
paged::{CacheRef, Checksum, CHECKSUM_SIZE},
tip::Buffer,
},
Blob, Error, IoBuf, IoBufMut, IoBufs,
};
use bytes::BufMut;
use commonware_cryptography::Crc32;
use commonware_utils::sync::{AsyncRwLock, AsyncRwLockWriteGuard};
use std::{
num::{NonZeroU16, NonZeroUsize},
sync::Arc,
};
use tracing::warn;
/// Indicates which CRC slot in a page record must not be overwritten.
#[derive(Clone, Copy)]
enum ProtectedCrc {
First,
Second,
}
/// Describes the state of the underlying blob with respect to the buffer.
#[derive(Clone)]
struct BlobState<B: Blob> {
blob: B,
/// The page where the next appended byte will be written to.
current_page: u64,
/// The state of the partial page in the blob. If it was written due to a sync call, then this
/// will contain its CRC record.
partial_page_state: Option<Checksum>,
}
/// A [Blob] wrapper that supports write-cached appending of data, with checksums for data integrity
/// and page cache managed caching.
#[derive(Clone)]
pub struct Append<B: Blob> {
/// The underlying blob being wrapped.
blob_state: Arc<AsyncRwLock<BlobState<B>>>,
/// Unique id assigned to this blob by the page cache.
id: u64,
/// A reference to the page cache that manages read caching for this blob.
cache_ref: CacheRef,
/// The write buffer containing any logical bytes following the last full page boundary in the
/// underlying blob.
buffer: Arc<AsyncRwLock<Buffer>>,
}
/// Returns the capacity with a floor applied to ensure it can hold at least one full page of new
/// data even when caching a nearly-full page of already written data.
fn capacity_with_floor(capacity: usize, page_size: u64) -> usize {
let floor = page_size as usize * 2;
if capacity < floor {
warn!(
floor,
"requested buffer capacity is too low, increasing it to floor"
);
floor
} else {
capacity
}
}
impl<B: Blob> Append<B> {
/// Create a new [Append] wrapper of the provided `blob` that is known to have `blob_size`
/// underlying physical bytes, using the provided `cache_ref` for read caching, and a write
/// buffer with capacity `capacity`. Rewinds the blob if necessary to ensure it only contains
/// checksum-validated data.
pub async fn new(
blob: B,
original_blob_size: u64,
capacity: usize,
cache_ref: CacheRef,
) -> Result<Self, Error> {
let (partial_page_state, pages, invalid_data_found) =
Self::read_last_valid_page(&blob, original_blob_size, cache_ref.page_size()).await?;
if invalid_data_found {
// Invalid data was detected, trim it from the blob.
let new_blob_size = pages * (cache_ref.page_size() + CHECKSUM_SIZE);
warn!(
original_blob_size,
new_blob_size, "truncating blob to remove invalid data"
);
blob.resize(new_blob_size).await?;
blob.sync().await?;
}
let capacity = capacity_with_floor(capacity, cache_ref.page_size());
let (blob_state, partial_data) = match partial_page_state {
Some((partial_page, crc_record)) => (
BlobState {
blob,
current_page: pages - 1,
partial_page_state: Some(crc_record),
},
Some(partial_page),
),
None => (
BlobState {
blob,
current_page: pages,
partial_page_state: None,
},
None,
),
};
let buffer = Buffer::from(
blob_state.current_page * cache_ref.page_size(),
partial_data.unwrap_or_default(),
capacity,
cache_ref.pool().clone(),
);
Ok(Self {
blob_state: Arc::new(AsyncRwLock::new(blob_state)),
id: cache_ref.next_id(),
cache_ref,
buffer: Arc::new(AsyncRwLock::new(buffer)),
})
}
/// Scans backwards from the end of the blob, stopping when it finds a valid page.
///
/// # Returns
///
/// A tuple of `(partial_page, page_count, invalid_data_found)`:
///
/// - `partial_page`: If the last valid page is partial (contains fewer than `page_size` logical
/// bytes), returns `Some((data, crc_record))` containing the logical data and its CRC record.
/// Returns `None` if the last valid page is full or if no valid pages exist.
///
/// - `page_count`: The number of pages in the blob up to and including the last valid page
/// found (whether or not it's partial). Note that it's possible earlier pages may be invalid
/// since this function stops scanning when it finds one valid page.
///
/// - `invalid_data_found`: `true` if there are any bytes in the blob that follow the last valid
/// page. Typically the blob should be resized to eliminate them since their integrity cannot
/// be guaranteed.
async fn read_last_valid_page(
blob: &B,
blob_size: u64,
page_size: u64,
) -> Result<(Option<(IoBuf, Checksum)>, u64, bool), Error> {
let physical_page_size = page_size + CHECKSUM_SIZE;
let partial_bytes = blob_size % physical_page_size;
let mut last_page_end = blob_size - partial_bytes;
// If the last physical page in the blob is truncated, it can't have a valid CRC record and
// must be invalid.
let mut invalid_data_found = partial_bytes != 0;
while last_page_end != 0 {
// Read the last page and parse its CRC record.
let page_start = last_page_end - physical_page_size;
let buf = blob
.read_at(page_start, physical_page_size as usize)
.await?
.coalesce()
.freeze();
match Checksum::validate_page(buf.as_ref()) {
Some(crc_record) => {
// Found a valid page.
let (len, _) = crc_record.get_crc();
let len = len as u64;
if len != page_size {
// The page is partial (logical data doesn't fill the page).
let logical_bytes = buf.slice(..len as usize);
return Ok((
Some((logical_bytes, crc_record)),
last_page_end / physical_page_size,
invalid_data_found,
));
}
// The page is full.
return Ok((None, last_page_end / physical_page_size, invalid_data_found));
}
None => {
// The page is invalid.
last_page_end = page_start;
invalid_data_found = true;
}
}
}
// No valid page exists in the blob.
Ok((None, 0, invalid_data_found))
}
/// Append all bytes in `buf` to the tip of the blob.
pub async fn append(&self, buf: &[u8]) -> Result<(), Error> {
let mut buffer = self.buffer.write().await;
if !buffer.append(buf) {
return Ok(());
}
// Buffer is over capacity, so we need to write data to the blob.
self.flush_internal(buffer, false).await
}
/// Flush all full pages from the buffer to disk, resetting the buffer to contain only the bytes
/// in any final partial page. If `write_partial_page` is true, the partial page will be written
/// to the blob as well along with a CRC record.
///
/// # Serialization
///
/// This method reads `partial_page_state` from `blob_state` under a read lock, then later
/// acquires `blob_state` as a write lock to commit the new state. This is safe because the
/// caller always holds the buffer write lock (`buf_guard`), and all paths into `flush_internal`
/// require that lock, so concurrent flushes are impossible.
async fn flush_internal(
&self,
mut buf_guard: AsyncRwLockWriteGuard<'_, Buffer>,
write_partial_page: bool,
) -> Result<(), Error> {
let buffer = &mut *buf_guard;
// Read the old partial page state before doing the heavy work of preparing physical pages.
// This is safe because partial_page_state is only modified by flush_internal, and we hold
// the buffer write lock which prevents concurrent flushes.
let old_partial_page_state = {
let blob_state = self.blob_state.read().await;
blob_state.partial_page_state.clone()
};
// Prepare the *physical* pages corresponding to the data in the buffer.
// Pass the old partial page state so the CRC record is constructed correctly.
let (mut physical_pages, partial_page_state) = self.to_physical_pages(
&*buffer,
write_partial_page,
old_partial_page_state.as_ref(),
);
// If there's nothing to write, return early.
if physical_pages.is_empty() {
return Ok(());
}
// Split buffered bytes into full logical pages to hand off now, leaving any trailing
// partial page in tip for continued buffering.
let logical_page_size = self.cache_ref.page_size() as usize;
let pages_to_cache = buffer.len() / logical_page_size;
let bytes_to_drain = pages_to_cache * logical_page_size;
// Remember the logical start offset and page bytes for caching of flushed full pages.
let cache_pages = if pages_to_cache > 0 {
Some((buffer.offset, buffer.slice(..bytes_to_drain)))
} else {
None
};
// Drain full pages from the buffered logical data. If the tip is fully drained, detach its
// backing so empty append buffers don't retain pooled storage.
if bytes_to_drain == buffer.len() && bytes_to_drain != 0 {
let _ = buffer
.take()
.expect("take must succeed when flush drains all buffered bytes");
} else if bytes_to_drain != 0 {
buffer.drop_prefix(bytes_to_drain);
buffer.offset += bytes_to_drain as u64;
}
let new_offset = buffer.offset;
// Cache full pages before releasing the tip lock so reads don't observe stale persisted
// bytes during the handoff from tip to cache.
if let Some((cache_offset, pages)) = cache_pages {
let remaining = self.cache_ref.cache(self.id, pages.as_ref(), cache_offset);
assert_eq!(remaining, 0, "cached full-page prefix must be page-aligned");
}
// Acquire a write lock on the blob state so nobody tries to read or modify the blob while
// we're writing to it.
let mut blob_state = self.blob_state.write().await;
// Release the buffer lock to allow for concurrent reads & buffered writes while we write
// the physical pages.
drop(buf_guard);
let physical_page_size = logical_page_size + CHECKSUM_SIZE as usize;
let write_at_offset = blob_state.current_page * physical_page_size as u64;
// Identify protected regions based on the OLD partial page state
let protected_regions = Self::identify_protected_regions(old_partial_page_state.as_ref());
// Update state before writing. This may appear to risk data loss if writes fail,
// but write failures are fatal per this codebase's design - callers must not use
// the blob after any mutable method returns an error.
blob_state.current_page += pages_to_cache as u64;
blob_state.partial_page_state = partial_page_state;
// Make sure the buffer offset and underlying blob agree on the state of the tip.
assert_eq!(
blob_state.current_page * self.cache_ref.page_size(),
new_offset
);
// Write the physical pages to the blob.
// If there are protected regions in the first page, we need to write around them.
if let Some((prefix_len, protected_crc)) = protected_regions {
match protected_crc {
ProtectedCrc::First => {
// Protected CRC is first: [page_size..page_size+6]
// Write 1: New data in first page [prefix_len..page_size]
if prefix_len < logical_page_size {
let _ = physical_pages.split_to(prefix_len);
let first_payload = physical_pages.split_to(logical_page_size - prefix_len);
blob_state
.blob
.write_at(write_at_offset + prefix_len as u64, first_payload)
.await?;
} else {
// Skip the protected first page bytes when they are fully covered.
let _ = physical_pages.split_to(logical_page_size);
}
// Write 2: Second CRC of first page + all remaining pages [page_size+6..end]
if physical_pages.len() > 6 {
let _ = physical_pages.split_to(6);
blob_state
.blob
.write_at(
write_at_offset + (logical_page_size + 6) as u64,
physical_pages,
)
.await?;
}
}
ProtectedCrc::Second => {
// Protected CRC is second: [page_size+6..page_size+12]
// Write 1: New data + first CRC of first page [prefix_len..page_size+6]
let first_crc_end = logical_page_size + 6;
if prefix_len < first_crc_end {
let _ = physical_pages.split_to(prefix_len);
let first_payload = physical_pages.split_to(first_crc_end - prefix_len);
blob_state
.blob
.write_at(write_at_offset + prefix_len as u64, first_payload)
.await?;
} else {
// Skip the fully protected first segment when no bytes from it need update.
let _ = physical_pages.split_to(first_crc_end);
}
// Write 2: All remaining pages (if any) [physical_page_size..end]
let skip = physical_page_size - first_crc_end;
if physical_pages.len() > skip {
let _ = physical_pages.split_to(skip);
blob_state
.blob
.write_at(write_at_offset + physical_page_size as u64, physical_pages)
.await?;
}
}
}
} else {
// No protected regions, write everything in one operation
blob_state
.blob
.write_at(write_at_offset, physical_pages)
.await?;
}
Ok(())
}
/// Returns the logical size of the blob. This accounts for both written and buffered data.
pub async fn size(&self) -> u64 {
let buffer = self.buffer.read().await;
buffer.size()
}
/// Read exactly `len` immutable bytes starting at `offset`.
pub async fn read_at(&self, offset: u64, len: usize) -> Result<IoBufs, Error> {
// Read into a temporary contiguous buffer and copy back to preserve structure.
// SAFETY: read_into below initializes all `len` bytes.
let mut buf = unsafe { self.cache_ref.pool().alloc_len(len) };
self.read_into(buf.as_mut(), offset).await?;
Ok(buf.into())
}
/// Reads up to `buf.len()` bytes starting at `logical_offset`, but only as many as are
/// available.
///
/// This is useful for reading variable-length prefixes (like varints) where you want to read
/// up to a maximum number of bytes but the actual data might be shorter.
///
/// Returns the buffer (truncated to actual bytes read) and the number of bytes read.
/// Returns an error if no bytes are available at the given offset.
pub async fn read_up_to(
&self,
logical_offset: u64,
len: usize,
bufs: impl Into<IoBufMut> + Send,
) -> Result<(IoBufMut, usize), Error> {
let mut bufs = bufs.into();
if len == 0 {
bufs.truncate(0);
return Ok((bufs, 0));
}
let blob_size = self.size().await;
let available = (blob_size.saturating_sub(logical_offset) as usize).min(len);
if available == 0 {
return Err(Error::BlobInsufficientLength);
}
// SAFETY: read_into below fills all `available` bytes.
unsafe { bufs.set_len(available) };
self.read_into(bufs.as_mut(), logical_offset).await?;
Ok((bufs, available))
}
/// Reads bytes starting at `logical_offset` into `buf`.
///
/// This method allows reading directly into a mutable slice without taking ownership of the
/// buffer or requiring a specific buffer type.
pub async fn read_into(&self, buf: &mut [u8], logical_offset: u64) -> Result<(), Error> {
// Ensure the read doesn't overflow.
let end_offset = logical_offset
.checked_add(buf.len() as u64)
.ok_or(Error::OffsetOverflow)?;
// Acquire a read lock on the buffer.
let buffer = self.buffer.read().await;
// If the data required is beyond the size of the blob, return an error.
if end_offset > buffer.size() {
return Err(Error::BlobInsufficientLength);
}
// Extract any bytes from the buffer that overlap with the requested range.
let remaining = if end_offset <= buffer.offset {
// No overlap with tip.
buf.len()
} else {
// Overlap is always a suffix of requested range.
let overlap_start = buffer.offset.max(logical_offset);
let dst_start = (overlap_start - logical_offset) as usize;
let src_start = (overlap_start - buffer.offset) as usize;
let copied = buf.len() - dst_start;
buf[dst_start..].copy_from_slice(&buffer.as_ref()[src_start..src_start + copied]);
dst_start
};
// Release buffer lock before potential I/O.
drop(buffer);
if remaining == 0 {
return Ok(());
}
// Fast path: try to read *only* from page cache without acquiring blob lock. This allows
// concurrent reads even while a flush is in progress.
let cached = self
.cache_ref
.read_cached(self.id, &mut buf[..remaining], logical_offset);
if cached == remaining {
// All bytes found in cache.
return Ok(());
}
// Slow path: cache miss (partial or full), acquire blob read lock to ensure any in-flight
// write completes before we read from the blob.
let blob_guard = self.blob_state.read().await;
// Read remaining bytes that were not already obtained from the earlier cache read.
let uncached_offset = logical_offset + cached as u64;
let uncached_len = remaining - cached;
self.cache_ref
.read(
&blob_guard.blob,
self.id,
&mut buf[cached..cached + uncached_len],
uncached_offset,
)
.await
}
/// Returns the protected region info for a partial page, if any.
///
/// # Returns
///
/// `None` if there's no existing partial page.
///
/// `Some((prefix_len, protected_crc))` where:
/// - `prefix_len`: bytes `[0..prefix_len]` were already written and can be substituted with
/// zeros (skip writing)
/// - `protected_crc`: which CRC slot must not be overwritten
fn identify_protected_regions(
partial_page_state: Option<&Checksum>,
) -> Option<(usize, ProtectedCrc)> {
let crc_record = partial_page_state?;
let (old_len, _) = crc_record.get_crc();
// The protected CRC is the one with the larger (authoritative) length.
let protected_crc = if crc_record.len1 >= crc_record.len2 {
ProtectedCrc::First
} else {
ProtectedCrc::Second
};
Some((old_len as usize, protected_crc))
}
/// Prepare physical-page writes from buffered logical bytes.
///
/// Each physical page contains one logical page plus CRC record. If the last page is not yet
/// full, it will be included only if `include_partial_page` is true.
///
/// # Arguments
///
/// * `buffer` - The buffer containing logical page data
/// * `include_partial_page` - Whether to include a partial page if one exists
/// * `old_crc_record` - The CRC record from a previously committed partial page, if any.
/// When present, the first page's CRC record will preserve the old CRC in its original slot
/// and place the new CRC in the other slot.
fn to_physical_pages(
&self,
buffer: &Buffer,
include_partial_page: bool,
old_crc_record: Option<&Checksum>,
) -> (IoBufs, Option<Checksum>) {
let logical_page_size = self.cache_ref.page_size() as usize;
let physical_page_size = logical_page_size + CHECKSUM_SIZE as usize;
let pages_to_write = buffer.len() / logical_page_size;
let mut write_buffer = IoBufs::default();
let buffer_data = buffer.as_ref();
if pages_to_write > 0 {
let logical_page_size_u16 =
u16::try_from(logical_page_size).expect("page size must fit in u16 for CRC record");
// Build CRC bytes for full pages once. Full-page payload bytes are appended below as
// slices from tip, so we avoid copying logical payload here.
let mut crcs = self
.cache_ref
.pool()
.alloc(CHECKSUM_SIZE as usize * pages_to_write);
for page in 0..pages_to_write {
let start_read_idx = page * logical_page_size;
let end_read_idx = start_read_idx + logical_page_size;
let logical_page = &buffer_data[start_read_idx..end_read_idx];
let crc = Crc32::checksum(logical_page);
// For the first page, if there's an old partial page CRC, construct the record
// to preserve the old CRC in its original slot.
let crc_record = if let (0, Some(old_crc)) = (page, old_crc_record) {
Self::build_crc_record_preserving_old(logical_page_size_u16, crc, old_crc)
} else {
Checksum::new(logical_page_size_u16, crc)
};
crcs.put_slice(&crc_record.to_bytes());
}
let crc_blob = crcs.freeze();
// Physical full-page layout is [logical_page_bytes, crc_record_bytes].
for page in 0..pages_to_write {
let start_read_idx = page * logical_page_size;
let end_read_idx = start_read_idx + logical_page_size;
write_buffer.append(buffer.slice(start_read_idx..end_read_idx));
let crc_start = page * CHECKSUM_SIZE as usize;
write_buffer.append(crc_blob.slice(crc_start..crc_start + CHECKSUM_SIZE as usize));
}
}
if !include_partial_page {
return (write_buffer, None);
}
let partial_page = &buffer_data[pages_to_write * logical_page_size..];
if partial_page.is_empty() {
// No partial page data to write.
return (write_buffer, None);
}
// If there are no full pages and the partial page length matches what was already
// written, there's nothing new to write.
if pages_to_write == 0 {
if let Some(old_crc) = old_crc_record {
let (old_len, _) = old_crc.get_crc();
if partial_page.len() == old_len as usize {
return (write_buffer, None);
}
}
}
let partial_len = partial_page.len();
let crc = Crc32::checksum(partial_page);
// For partial pages: if this is the first page and there's an old CRC, preserve it.
// Otherwise just use the new CRC in slot 0.
let crc_record = if let (0, Some(old_crc)) = (pages_to_write, old_crc_record) {
Self::build_crc_record_preserving_old(partial_len as u16, crc, old_crc)
} else {
Checksum::new(partial_len as u16, crc)
};
// A persisted partial page still occupies one full physical page:
// [partial logical bytes, zero padding, crc record].
let mut padded = self.cache_ref.pool().alloc(physical_page_size);
padded.put_slice(partial_page);
let zero_count = logical_page_size - partial_len;
if zero_count > 0 {
padded.put_bytes(0, zero_count);
}
padded.put_slice(&crc_record.to_bytes());
write_buffer.append(padded.freeze());
// Return the CRC record that matches what we wrote to disk, so that future flushes
// correctly identify which slot is protected.
(write_buffer, Some(crc_record))
}
/// Build a CRC record that preserves the old CRC in its original slot and places
/// the new CRC in the other slot.
const fn build_crc_record_preserving_old(
new_len: u16,
new_crc: u32,
old_crc: &Checksum,
) -> Checksum {
let (old_len, old_crc_val) = old_crc.get_crc();
// The old CRC is in the slot with the larger length value (first slot wins ties).
if old_crc.len1 >= old_crc.len2 {
// Old CRC is in slot 0, put new CRC in slot 1
Checksum {
len1: old_len,
crc1: old_crc_val,
len2: new_len,
crc2: new_crc,
}
} else {
// Old CRC is in slot 1, put new CRC in slot 0
Checksum {
len1: new_len,
crc1: new_crc,
len2: old_len,
crc2: old_crc_val,
}
}
}
/// Flushes any buffered data, then returns a [Replay] for the underlying blob.
///
/// The returned replay can be used to sequentially read all pages from the blob while ensuring
/// all data passes integrity verification. CRCs are validated but not included in the output.
pub async fn replay(&self, buffer_size: NonZeroUsize) -> Result<Replay<B>, Error> {
let logical_page_size = self.cache_ref.page_size();
let logical_page_size_nz =
NonZeroU16::new(logical_page_size as u16).expect("page_size is non-zero");
// Flush any buffered data (without fsync) so the reader sees all written data.
{
let buf_guard = self.buffer.write().await;
self.flush_internal(buf_guard, true).await?;
}
// Convert buffer size (bytes) to page count
let physical_page_size = logical_page_size + CHECKSUM_SIZE;
let prefetch_pages = buffer_size.get() / physical_page_size as usize;
let prefetch_pages = prefetch_pages.max(1); // At least 1 page
let blob_guard = self.blob_state.read().await;
// Compute both physical and logical blob sizes.
let (physical_blob_size, logical_blob_size) =
blob_guard.partial_page_state.as_ref().map_or_else(
|| {
// All pages are full.
let physical = physical_page_size * blob_guard.current_page;
let logical = logical_page_size * blob_guard.current_page;
(physical, logical)
},
|crc_record| {
// There's a partial page with a checksum.
let (partial_len, _) = crc_record.get_crc();
let partial_len = partial_len as u64;
// Physical: all pages including the partial one (which is padded to full size).
let physical = physical_page_size * (blob_guard.current_page + 1);
// Logical: full pages before this + partial page's actual data length.
let logical = logical_page_size * blob_guard.current_page + partial_len;
(physical, logical)
},
);
let reader = PageReader::new(
blob_guard.blob.clone(),
physical_blob_size,
logical_blob_size,
prefetch_pages,
logical_page_size_nz,
);
Ok(Replay::new(reader))
}
}
impl<B: Blob> Append<B> {
pub async fn sync(&self) -> Result<(), Error> {
// Flush any buffered data, including any partial page. When flush_internal returns,
// write_at has completed and data has been written to the underlying blob.
let buf_guard = self.buffer.write().await;
self.flush_internal(buf_guard, true).await?;
// Sync the underlying blob. We need the blob read lock here since sync() requires access
// to the blob, but only a read lock since we're not modifying blob state.
let blob_state = self.blob_state.read().await;
blob_state.blob.sync().await
}
/// Resize the blob to the provided logical `size`.
///
/// This truncates the blob to contain only `size` logical bytes. The physical blob size will
/// be adjusted to include the necessary CRC records for the remaining pages.
///
/// # Warning
///
/// - Concurrent mutable operations (append, resize) are not supported and will cause data loss.
/// - Concurrent readers which try to read past the new size during the resize may error.
/// - The resize is not guaranteed durable until the next sync.
pub async fn resize(&self, size: u64) -> Result<(), Error> {
let current_size = self.size().await;
// Handle growing by appending zero bytes.
if size > current_size {
let zeros_needed = (size - current_size) as usize;
let mut zeros = self.cache_ref.pool().alloc(zeros_needed);
zeros.put_bytes(0, zeros_needed);
self.append(zeros.as_ref()).await?;
return Ok(());
}
// Implementation note: rewinding the blob across a page boundary potentially results in
// stale data remaining in the page cache. We don't proactively purge the data
// within this function since it would be inaccessible anyway. Instead we ensure it is
// always updated should the blob grow back to the point where we have new data for the same
// page, if any old data hasn't expired naturally by then.
let logical_page_size = self.cache_ref.page_size();
let physical_page_size = logical_page_size + CHECKSUM_SIZE;
// Flush any buffered data first to ensure we have a consistent state on disk.
self.sync().await?;
// Acquire both locks to prevent concurrent operations.
let mut buf_guard = self.buffer.write().await;
let mut blob_guard = self.blob_state.write().await;
// Calculate the physical size needed for the new logical size.
let full_pages = size / logical_page_size;
let partial_bytes = size % logical_page_size;
let new_physical_size = if partial_bytes > 0 {
// We need full_pages + 1 physical pages to hold the partial data.
// The partial page will be padded to full physical page size.
(full_pages + 1) * physical_page_size
} else {
// No partial page needed.
full_pages * physical_page_size
};
// Resize the underlying blob.
blob_guard.blob.resize(new_physical_size).await?;
blob_guard.partial_page_state = None;
// Update blob state and buffer based on the desired logical size. The partial page data is
// read with CRC validation; the validated length may exceed partial_bytes (reflecting the
// old data length), but we only load the prefix we need. The next sync will write the
// correct CRC for the new length.
//
// Note: This updates state before validation completes, which could leave state
// inconsistent if validation fails. This is acceptable because failures from mutable
// methods are fatal - callers must not use the blob after any error.
blob_guard.current_page = full_pages;
buf_guard.offset = full_pages * logical_page_size;
if partial_bytes > 0 {
// There's a partial page. Read its data from disk with CRC validation.
let page_data =
super::get_page_from_blob(&blob_guard.blob, full_pages, logical_page_size).await?;
// Ensure the validated data covers what we need.
if (page_data.len() as u64) < partial_bytes {
return Err(Error::InvalidChecksum);
}
buf_guard.clear();
let over_capacity = buf_guard.append(&page_data.as_ref()[..partial_bytes as usize]);
assert!(!over_capacity);
} else {
// No partial page - all pages are full or blob is empty.
buf_guard.clear();
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{deterministic, BufferPool, BufferPoolConfig, Runner as _, Storage as _};
use commonware_codec::ReadExt;
use commonware_macros::test_traced;
use commonware_utils::{NZUsize, NZU16};
use prometheus_client::registry::Registry;
use std::num::NonZeroU16;
const PAGE_SIZE: NonZeroU16 = NZU16!(103); // janky size to ensure we test page alignment
const BUFFER_SIZE: usize = PAGE_SIZE.get() as usize * 2;
#[test_traced("DEBUG")]
fn test_append_crc_empty() {
let executor = deterministic::Runner::default();
executor.start(|context: deterministic::Context| async move {
// Open a new blob.
let (blob, blob_size) = context.open("test_partition", b"test_blob").await.unwrap();
assert_eq!(blob_size, 0);
// Create a page cache reference.
let cache_ref = CacheRef::from_pooler(&context, PAGE_SIZE, NZUsize!(BUFFER_SIZE));
// Create an Append wrapper.
let append = Append::new(blob, blob_size, BUFFER_SIZE, cache_ref.clone())
.await
.unwrap();
// Verify initial size is 0.
assert_eq!(append.size().await, 0);
// Close & re-open.
append.sync().await.unwrap();
drop(append);
let (blob, blob_size) = context.open("test_partition", b"test_blob").await.unwrap();
assert_eq!(blob_size, 0); // There was no need to write a crc since there was no data.
let append = Append::new(blob, blob_size, BUFFER_SIZE, cache_ref.clone())
.await
.unwrap();
assert_eq!(append.size().await, 0);
});
}
#[test_traced("DEBUG")]
fn test_append_crc_basic() {
let executor = deterministic::Runner::default();
executor.start(|context: deterministic::Context| async move {
// Open a new blob.
let (blob, blob_size) = context.open("test_partition", b"test_blob").await.unwrap();
assert_eq!(blob_size, 0);
// Create a page cache reference.
let cache_ref = CacheRef::from_pooler(&context, PAGE_SIZE, NZUsize!(BUFFER_SIZE));
// Create an Append wrapper.
let append = Append::new(blob, blob_size, BUFFER_SIZE, cache_ref.clone())
.await
.unwrap();
// Verify initial size is 0.
assert_eq!(append.size().await, 0);
// Append some bytes.
let data = vec![1, 2, 3, 4, 5];
append.append(&data).await.unwrap();
// Verify size reflects appended data.
assert_eq!(append.size().await, 5);
// Append more bytes.
let more_data = vec![6, 7, 8, 9, 10];
append.append(&more_data).await.unwrap();
// Verify size is cumulative.
assert_eq!(append.size().await, 10);
// Read back the first chunk and verify.
let read_buf = append.read_at(0, 5).await.unwrap().coalesce();
assert_eq!(read_buf, &data[..]);
// Read back the second chunk and verify.
let read_buf = append.read_at(5, 5).await.unwrap().coalesce();
assert_eq!(read_buf, &more_data[..]);
// Read all data at once and verify.
let read_buf = append.read_at(0, 10).await.unwrap().coalesce();
assert_eq!(read_buf, &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
// Close and reopen the blob and make sure the data is still there and the trailing
// checksum is written & stripped as expected.
append.sync().await.unwrap();
drop(append);
let (blob, blob_size) = context.open("test_partition", b"test_blob").await.unwrap();
// Physical page = 103 logical + 12 Checksum = 115 bytes (padded partial page)
assert_eq!(blob_size, 115);
let append = Append::new(blob, blob_size, BUFFER_SIZE, cache_ref.clone())
.await
.unwrap();
assert_eq!(append.size().await, 10); // CRC should be stripped after verification
// Append data that spans a page boundary.
// PAGE_SIZE=103 is the logical page size. We have 10 bytes, so writing
// 100 more bytes (total 110) will cross the page boundary at byte 103.
let spanning_data: Vec<u8> = (11..=110).collect();
append.append(&spanning_data).await.unwrap();
assert_eq!(append.size().await, 110);
// Read back data that spans the page boundary.
let read_buf = append.read_at(10, 100).await.unwrap().coalesce();
assert_eq!(read_buf, &spanning_data[..]);
// Read all 110 bytes at once.
let read_buf = append.read_at(0, 110).await.unwrap().coalesce();
let expected: Vec<u8> = (1..=110).collect();
assert_eq!(read_buf, &expected[..]);
// Drop and re-open and make sure bytes are still there.
append.sync().await.unwrap();
drop(append);
let (blob, blob_size) = context.open("test_partition", b"test_blob").await.unwrap();
// 2 physical pages: 2 * 115 = 230 bytes
assert_eq!(blob_size, 230);
let append = Append::new(blob, blob_size, BUFFER_SIZE, cache_ref.clone())
.await
.unwrap();
assert_eq!(append.size().await, 110);
// Append data to reach exactly a page boundary.
// Logical page size is 103. We have 110 bytes, next boundary is 206 (103 * 2).
// So we need 96 more bytes.
let boundary_data: Vec<u8> = (111..=206).collect();
assert_eq!(boundary_data.len(), 96);
append.append(&boundary_data).await.unwrap();
assert_eq!(append.size().await, 206);
// Verify we can read it back.
let read_buf = append.read_at(0, 206).await.unwrap().coalesce();
let expected: Vec<u8> = (1..=206).collect();
assert_eq!(read_buf, &expected[..]);
// Drop and re-open at the page boundary.
append.sync().await.unwrap();
drop(append);
let (blob, blob_size) = context.open("test_partition", b"test_blob").await.unwrap();
// Physical size should be exactly 2 pages: 115 * 2 = 230 bytes
assert_eq!(blob_size, 230);
let append = Append::new(blob, blob_size, BUFFER_SIZE, cache_ref)
.await
.unwrap();
assert_eq!(append.size().await, 206);
// Verify data is still readable after reopen.
let read_buf = append.read_at(0, 206).await.unwrap().coalesce();
assert_eq!(read_buf, &expected[..]);
});
}
#[test_traced("DEBUG")]
fn test_sync_releases_tip_pool_slot_after_full_drain() {
let executor = deterministic::Runner::default();
executor.start(|context: deterministic::Context| async move {
let mut registry = Registry::default();
let pool = BufferPool::new(
BufferPoolConfig::for_storage()
.with_pool_min_size(PAGE_SIZE.get() as usize)
.with_max_per_class(NZUsize!(2)),
&mut registry,
);
let cache_ref = CacheRef::new(&context, pool.clone(), PAGE_SIZE, NZUsize!(1));
let (blob, blob_size) = context
.open("test_partition", b"release_tip_backing")
.await
.unwrap();
assert_eq!(blob_size, 0);