oplog state persists timestamp of last snapshot

This commit is contained in:
Kiril Videlov 2024-05-23 21:40:07 +02:00
parent 3e066d4944
commit c2a5014ed0

View File

@ -1,8 +1,9 @@
use anyhow::Result;
use anyhow::{Context, Result};
use std::{
fs::File,
io::Read,
path::{Path, PathBuf},
time::Duration,
};
use serde::{Deserialize, Serialize};
@ -14,6 +15,9 @@ use super::OPLOG_FILE_NAME;
pub struct Oplog {
/// This is the sha of the last oplog commit
pub head_sha: Option<String>,
/// The time when the last snapshot was created. Seconds since Epoch
#[serde(default)]
pub modified_at: u64,
}
pub struct OplogHandle {
@ -34,7 +38,7 @@ impl OplogHandle {
pub fn set_oplog_head(&self, sha: String) -> Result<()> {
let mut oplog = self.read_file()?;
oplog.head_sha = Some(sha);
self.write_file(&oplog)?;
self.write_file(oplog)?;
Ok(())
}
@ -46,6 +50,14 @@ impl OplogHandle {
Ok(oplog.head_sha)
}
/// Gets the time when the last snapshot was created.
///
/// Errors if the file cannot be read or written.
pub fn get_modified_at(&self) -> anyhow::Result<Duration> {
let oplog = self.read_file()?;
Ok(Duration::from_secs(oplog.modified_at))
}
/// Reads and parses the state file.
///
/// If the file does not exist, it will be created.
@ -64,8 +76,13 @@ impl OplogHandle {
Ok(oplog)
}
fn write_file(&self, oplog: &Oplog) -> anyhow::Result<()> {
write(self.file_path.as_path(), oplog)
fn write_file(&self, oplog: Oplog) -> anyhow::Result<()> {
let mut oplog = oplog;
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.context("failed to get time since epoch")?;
oplog.modified_at = now.as_secs();
write(self.file_path.as_path(), &oplog)
}
}