| 623 | } |
| 624 | |
| 625 | fn with_header<R: io::Read + io::Seek>( |
| 626 | min_tx_offset: u64, |
| 627 | header: Header, |
| 628 | mut reader: R, |
| 629 | offset_index: Option<&TxOffsetIndex>, |
| 630 | ) -> Result<Self, error::SegmentMetadata> { |
| 631 | let mut sofar = offset_index |
| 632 | .and_then(|index| Self::find_valid_indexed_commit(min_tx_offset, header, &mut reader, index).ok()) |
| 633 | .unwrap_or_else(|| Self { |
| 634 | header, |
| 635 | tx_range: Range { |
| 636 | start: min_tx_offset, |
| 637 | end: min_tx_offset, |
| 638 | }, |
| 639 | size_in_bytes: Header::LEN as u64, |
| 640 | max_epoch: u64::default(), |
| 641 | max_commit_offset: min_tx_offset, |
| 642 | max_commit: None, |
| 643 | }); |
| 644 | |
| 645 | reader.seek(SeekFrom::Start(sofar.size_in_bytes))?; |
| 646 | |
| 647 | fn commit_meta<R: io::Read>( |
| 648 | reader: &mut R, |
| 649 | sofar: &Metadata, |
| 650 | ) -> Result<Option<commit::Metadata>, error::SegmentMetadata> { |
| 651 | commit::Metadata::extract(reader).map_err(|e| { |
| 652 | if matches!(e.kind(), io::ErrorKind::InvalidData | io::ErrorKind::UnexpectedEof) { |
| 653 | error::SegmentMetadata::InvalidCommit { |
| 654 | sofar: sofar.clone(), |
| 655 | source: e, |
| 656 | } |
| 657 | } else { |
| 658 | e.into() |
| 659 | } |
| 660 | }) |
| 661 | } |
| 662 | while let Some(commit) = commit_meta(&mut reader, &sofar)? { |
| 663 | debug!("commit::{commit:?}"); |
| 664 | if commit.tx_range.start != sofar.tx_range.end { |
| 665 | return Err(io::Error::new( |
| 666 | io::ErrorKind::InvalidData, |
| 667 | format!( |
| 668 | "out-of-order offset: expected={} actual={}", |
| 669 | sofar.tx_range.end, commit.tx_range.start, |
| 670 | ), |
| 671 | ) |
| 672 | .into()); |
| 673 | } |
| 674 | sofar.tx_range.end = commit.tx_range.end; |
| 675 | sofar.size_in_bytes += commit.size_in_bytes; |
| 676 | // TODO: Should it be an error to encounter an epoch going backwards? |
| 677 | sofar.max_epoch = commit.epoch.max(sofar.max_epoch); |
| 678 | sofar.max_commit_offset = commit.tx_range.start; |
| 679 | sofar.max_commit = Some(commit); |
| 680 | } |
| 681 | |
| 682 | Ok(sofar) |