use std::{
fs, io,
path::{Path, PathBuf},
};
use super::{JobId, JobRecord};
use crate::config_writer::{write_bytes_atomically_with_durability, WriteDurability};
#[derive(Clone, Debug)]
pub(in crate::app::daemon_host) struct JobStore {
dir: PathBuf,
}
const RECORD_SUFFIX: &str = ".json";
impl JobStore {
pub(in crate::app::daemon_host) fn open(state_dir: &Path) -> io::Result<Self> {
let dir = state_dir.join("jobs");
crate::daemon::create_private_dir(&dir)?;
Ok(Self { dir })
}
pub(in crate::app::daemon_host) fn write(&self, record: &JobRecord) -> io::Result<()> {
let mut contents = serde_json::to_vec_pretty(record)?;
contents.push(b'\n');
write_bytes_atomically_with_durability(
&self.path_of(&record.id),
&contents,
WriteDurability::Durable,
)?;
crate::daemon::sync_dir(&self.dir)
}
pub(in crate::app::daemon_host) fn remove(&self, id: &JobId) -> io::Result<()> {
match fs::remove_file(self.path_of(id)) {
Ok(()) => crate::daemon::sync_dir(&self.dir),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(error),
}
}
pub(in crate::app::daemon_host) fn load(&self) -> io::Result<Vec<JobRecord>> {
let mut records = Vec::new();
for entry in fs::read_dir(&self.dir)? {
let path = entry?.path();
let Some(stem) = path
.file_name()
.and_then(|name| name.to_str())
.and_then(|name| name.strip_suffix(RECORD_SUFFIX))
else {
continue;
};
match read_record(&path, stem) {
Ok(record) => records.push(record),
Err(error) => {
tracing::warn!(path = %path.display(), %error, "skipping unreadable job record");
}
}
}
Ok(records)
}
fn path_of(&self, id: &JobId) -> PathBuf {
self.dir.join(format!("{}{RECORD_SUFFIX}", id.as_str()))
}
}
#[derive(Debug, thiserror::Error)]
enum UnreadableRecord {
#[error(transparent)]
Io(#[from] io::Error),
#[error(transparent)]
Json(#[from] serde_json::Error),
#[error("the file is named for job {name}, but the record is job {id}")]
Misnamed { name: String, id: JobId },
}
fn read_record(path: &Path, stem: &str) -> Result<JobRecord, UnreadableRecord> {
let record: JobRecord = serde_json::from_slice(&fs::read(path)?)?;
if record.id.as_str() != stem {
return Err(UnreadableRecord::Misnamed {
name: stem.to_owned(),
id: record.id,
});
}
Ok(record)
}
#[cfg(test)]
#[path = "store_tests.rs"]
mod tests;