use std::collections::VecDeque;
use std::io::{self, Read, Seek, SeekFrom};
use std::path::Path;
use std::time::Instant;
use crate::storage::wal::WalRecord;
pub(crate) struct SealedWalSegment {
pub epoch: u64,
pub first_lsn: u64,
pub last_lsn: u64,
pub sha256: [u8; 32],
pub bytes: u64,
pub oldest_captured_at: Instant,
pub file: reddb_file::ServerlessWriterLeaseTempFile,
}
#[derive(Default)]
struct PendingBatch {
payload: Vec<u8>,
first_lsn: u64,
frames: u64,
oldest_captured_at: Option<Instant>,
}
struct TapState {
max_segment_bytes: u64,
wal_generation: u64,
wal_offset: u64,
wal_format_version: u8,
epoch: u64,
next_lsn: u64,
pending: PendingBatch,
sealed: VecDeque<SealedWalSegment>,
last_sealed_sha: Option<[u8; 32]>,
discontinuity: Option<String>,
in_flight: Option<(Instant, u64)>,
captured_frames_total: u64,
captured_bytes_total: u64,
}
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct WalArchiveTapStatus {
pub epoch: u64,
pub next_lsn: u64,
pub pending_frames: u64,
pub pending_bytes: u64,
pub sealed_segments: u64,
pub sealed_bytes: u64,
pub oldest_unarchived_at: Option<Instant>,
pub captured_frames_total: u64,
pub captured_bytes_total: u64,
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct WalArchiveCut {
pub wal_lsn: u64,
pub prev_sha256: Option<[u8; 32]>,
}
pub(crate) struct WalArchiveTap {
state: parking_lot::Mutex<TapState>,
}
impl WalArchiveTap {
pub(crate) fn new(
epoch: u64,
next_lsn: u64,
prev_sha: Option<[u8; 32]>,
max_segment_bytes: u64,
) -> Self {
Self {
state: parking_lot::Mutex::new(TapState {
max_segment_bytes: max_segment_bytes.max(1),
wal_generation: 0,
wal_offset: 0,
wal_format_version: 0,
epoch,
next_lsn: next_lsn.max(1),
pending: PendingBatch::default(),
sealed: VecDeque::new(),
last_sealed_sha: prev_sha,
discontinuity: None,
in_flight: None,
captured_frames_total: 0,
captured_bytes_total: 0,
}),
}
}
pub(crate) fn reset_cursor(&self, wal_generation: u64, wal_offset: u64, format_version: u8) {
let mut state = self.state.lock();
state.wal_generation = wal_generation;
state.wal_offset = wal_offset;
state.wal_format_version = format_version;
}
pub(crate) fn capture(&self, wal_path: &Path, wal_generation: u64, end: u64) -> io::Result<()> {
let mut state = self.state.lock();
Self::capture_locked(&mut state, wal_path, wal_generation, end)
}
fn capture_locked(
state: &mut TapState,
wal_path: &Path,
wal_generation: u64,
end: u64,
) -> io::Result<()> {
if let Some(reason) = &state.discontinuity {
return Err(io::Error::other(format!(
"WAL archive stream is discontinuous: {reason}"
)));
}
if state.wal_generation != wal_generation {
let reason = format!(
"local WAL generation moved from {} to {wal_generation} without archive capture",
state.wal_generation
);
state.discontinuity = Some(reason.clone());
return Err(io::Error::other(reason));
}
if end <= state.wal_offset {
return Ok(());
}
let start = state.wal_offset;
let length = usize::try_from(end - start)
.map_err(|_| io::Error::other("WAL archive capture range overflows memory"))?;
let mut buffer = vec![0u8; length];
let mut file = std::fs::File::open(wal_path)?;
file.seek(SeekFrom::Start(start))?;
file.read_exact(&mut buffer)?;
let format_version = state.wal_format_version;
let now = Instant::now();
let mut cursor = io::Cursor::new(buffer.as_slice());
let mut complete = 0usize;
while complete < buffer.len() {
let frame_start = complete;
cursor.set_position(frame_start as u64);
let record = match WalRecord::read_with_format_version(&mut cursor, format_version) {
Ok(Some((_, record))) => record,
Ok(None) => break,
Err(err) if err.kind() == io::ErrorKind::UnexpectedEof => break,
Err(err) => {
let reason = format!(
"local WAL frame at offset {} is unreadable: {err}",
start + frame_start as u64
);
state.discontinuity = Some(reason.clone());
return Err(io::Error::other(reason));
}
};
let frame_end = cursor.position() as usize;
complete = frame_end;
if !archived_record(&record) {
continue;
}
let frame = &buffer[frame_start..frame_end];
let lsn = state.next_lsn;
state.next_lsn += 1;
let pending = &mut state.pending;
if pending.frames == 0 {
pending.first_lsn = lsn;
pending.oldest_captured_at = Some(now);
}
reddb_file::push_serverless_wal_segment_frame(&mut pending.payload, frame);
pending.frames += 1;
state.captured_frames_total += 1;
state.captured_bytes_total += frame.len() as u64;
if state.pending.payload.len() as u64 >= state.max_segment_bytes {
Self::seal_locked(state)?;
}
}
state.wal_offset = start + complete as u64;
Ok(())
}
pub(crate) fn seal_if_due(
&self,
now: Instant,
max_age: std::time::Duration,
max_bytes: u64,
force: bool,
) -> io::Result<bool> {
let mut state = self.state.lock();
let due = match state.pending.oldest_captured_at {
None => false,
Some(oldest) => {
force
|| now.saturating_duration_since(oldest) >= max_age
|| state.pending.payload.len() as u64 >= max_bytes
}
};
if !due {
return Ok(false);
}
Self::seal_locked(&mut state)?;
Ok(true)
}
fn seal_locked(state: &mut TapState) -> io::Result<()> {
if state.pending.frames == 0 {
return Ok(());
}
let pending = std::mem::take(&mut state.pending);
let header = reddb_file::ServerlessWalSegmentHeader {
wal_format_version: state.wal_format_version,
epoch: state.epoch,
first_lsn: pending.first_lsn,
last_lsn: pending.first_lsn + pending.frames - 1,
prev_sha256: state.last_sealed_sha,
};
let (bytes, sha256) =
reddb_file::encode_serverless_wal_segment(&header, pending.frames, &pending.payload)
.map_err(|err| io::Error::other(err.to_string()))?;
let file = reddb_file::ServerlessWriterLeaseTempFile::new("wal-segment");
file.write_bytes(&bytes)
.map_err(|err| io::Error::other(err.to_string()))?;
state.last_sealed_sha = Some(sha256);
state.sealed.push_back(SealedWalSegment {
epoch: header.epoch,
first_lsn: header.first_lsn,
last_lsn: header.last_lsn,
sha256,
bytes: bytes.len() as u64,
oldest_captured_at: pending.oldest_captured_at.unwrap_or_else(Instant::now),
file,
});
Ok(())
}
pub(crate) fn cut(
&self,
wal_path: &Path,
wal_generation: u64,
end: u64,
copy: impl FnOnce(u64) -> io::Result<()>,
) -> io::Result<WalArchiveCut> {
let mut state = self.state.lock();
Self::capture_locked(&mut state, wal_path, wal_generation, end)?;
copy(state.wal_offset)?;
Self::seal_locked(&mut state)?;
Ok(WalArchiveCut {
wal_lsn: state.next_lsn - 1,
prev_sha256: state.last_sealed_sha,
})
}
pub(crate) fn upload_front_below<E>(
&self,
limit_lsn: u64,
upload: impl FnOnce(&SealedWalSegment) -> Result<(), E>,
) -> Result<Option<(u64, u64, u64)>, E> {
let front = {
let mut state = self.state.lock();
if state
.sealed
.front()
.is_some_and(|segment| segment.last_lsn >= limit_lsn)
{
return Ok(None);
}
match state.sealed.pop_front() {
Some(segment) => {
state.in_flight = Some((segment.oldest_captured_at, segment.bytes));
segment
}
None => return Ok(None),
}
};
let result = upload(&front);
let mut state = self.state.lock();
state.in_flight = None;
match result {
Ok(()) => Ok(Some((front.first_lsn, front.last_lsn, front.bytes))),
Err(err) => {
state.sealed.push_front(front);
Err(err)
}
}
}
pub(crate) fn status(&self) -> WalArchiveTapStatus {
let state = self.state.lock();
let oldest_sealed = state
.in_flight
.map(|(oldest, _)| oldest)
.or_else(|| state.sealed.front().map(|s| s.oldest_captured_at));
WalArchiveTapStatus {
epoch: state.epoch,
next_lsn: state.next_lsn,
pending_frames: state.pending.frames,
pending_bytes: state.pending.payload.len() as u64,
sealed_segments: state.sealed.len() as u64 + u64::from(state.in_flight.is_some()),
sealed_bytes: state.sealed.iter().map(|s| s.bytes).sum::<u64>()
+ state.in_flight.map(|(_, bytes)| bytes).unwrap_or(0),
oldest_unarchived_at: oldest_sealed.or(state.pending.oldest_captured_at),
captured_frames_total: state.captured_frames_total,
captured_bytes_total: state.captured_bytes_total,
}
}
pub(crate) fn discontinuity(&self) -> Option<String> {
self.state.lock().discontinuity.clone()
}
pub(crate) fn restart_after_discontinuity(
&self,
wal_generation: u64,
wal_offset: u64,
format_version: u8,
) -> io::Result<()> {
let mut state = self.state.lock();
if state.discontinuity.is_none() {
return Ok(());
}
Self::seal_locked(&mut state)?;
state.next_lsn += 1;
state.wal_generation = wal_generation;
state.wal_offset = wal_offset;
state.wal_format_version = format_version;
state.discontinuity = None;
Ok(())
}
}
impl super::UnifiedStore {
fn archive_commit(&self) -> io::Result<&std::sync::Arc<super::commit::StoreCommitCoordinator>> {
self.commit
.as_ref()
.ok_or_else(|| io::Error::other("store has no commit WAL to archive"))
}
pub(crate) fn attach_wal_archive_tap(
&self,
tap: std::sync::Arc<WalArchiveTap>,
) -> io::Result<()> {
self.archive_commit()?.attach_archive_tap(tap)
}
pub(crate) fn wal_archive_tap(&self) -> Option<std::sync::Arc<WalArchiveTap>> {
self.commit.as_ref().and_then(|commit| commit.archive_tap())
}
pub(crate) fn capture_wal_archive_frames(&self) -> io::Result<()> {
self.archive_commit()?.capture_archive_frames()
}
pub(crate) fn cut_wal_archive_generation(
&self,
destination: &Path,
) -> io::Result<WalArchiveCut> {
self.archive_commit()?.cut_archive_generation(destination)
}
pub(crate) fn restart_wal_archive_after_discontinuity(&self) -> io::Result<()> {
self.archive_commit()?.restart_archive_after_discontinuity()
}
pub(crate) fn commit_wal_path(&self) -> Option<std::path::PathBuf> {
self.commit
.as_ref()
.map(|commit| commit.wal_path().to_path_buf())
}
}
pub(crate) fn archived_record(record: &WalRecord) -> bool {
!matches!(
record,
WalRecord::PageOwnership { .. }
| WalRecord::FullPageImage { .. }
| WalRecord::Checkpoint { .. }
)
}