use std::{
fs, io,
path::{Path, PathBuf},
};
use rho_sdk::SessionId;
use serde::{Deserialize, Serialize};
use super::record::SessionRecord;
use crate::config_writer::{write_bytes_atomically_with_durability, WriteDurability};
const RECORD_SUFFIX: &str = ".json";
const RECORD_VERSION: u32 = 1;
#[derive(Clone, Debug)]
pub(crate) struct PullRequestStore {
dir: PathBuf,
}
#[derive(Serialize)]
struct RecordFileOut<'a> {
version: u32,
session: &'a SessionId,
record: &'a SessionRecord,
}
#[derive(Deserialize)]
struct RecordFileIn {
session: SessionId,
record: SessionRecord,
}
#[derive(Deserialize)]
struct RecordVersion {
version: u32,
}
impl PullRequestStore {
pub(crate) fn open(state_dir: &Path) -> io::Result<Self> {
let dir = state_dir.join("pull-requests");
crate::daemon::create_private_dir(&dir)?;
Ok(Self { dir })
}
pub(crate) fn load_all(&self) -> Vec<(SessionId, SessionRecord)> {
let entries = match fs::read_dir(&self.dir) {
Ok(entries) => entries,
Err(error) => {
tracing::warn!(dir = %self.dir.display(), %error, "could not list pull request records");
return Vec::new();
}
};
let mut records = Vec::new();
for entry in entries {
let path = match entry {
Ok(entry) => entry.path(),
Err(error) => {
tracing::warn!(dir = %self.dir.display(), %error, "could not list pull request records");
continue;
}
};
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 pull request record");
}
}
}
records
}
pub(crate) fn save(&self, session: &SessionId, record: &SessionRecord) -> io::Result<()> {
if record.is_empty() {
return self.forget(session);
}
let file = RecordFileOut {
version: RECORD_VERSION,
session,
record,
};
let mut contents = serde_json::to_vec_pretty(&file)?;
contents.push(b'\n');
write_bytes_atomically_with_durability(
&self.path_of(session)?,
&contents,
WriteDurability::Durable,
)?;
crate::daemon::sync_dir(&self.dir)
}
pub(crate) fn forget(&self, session: &SessionId) -> io::Result<()> {
match fs::remove_file(self.path_of(session)?) {
Ok(()) => crate::daemon::sync_dir(&self.dir),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(error),
}
}
fn path_of(&self, session: &SessionId) -> io::Result<PathBuf> {
let name = file_name(session.as_str()).ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("session id {session:?} cannot name a pull request record file"),
)
})?;
Ok(self.dir.join(name))
}
}
fn file_name(session: &str) -> Option<String> {
let plain = !session.is_empty()
&& session
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_');
plain.then(|| format!("{session}{RECORD_SUFFIX}"))
}
#[derive(Debug, thiserror::Error)]
enum UnreadableRecord {
#[error(transparent)]
Io(#[from] io::Error),
#[error(transparent)]
Json(#[from] serde_json::Error),
#[error("the file is in format version {found}, which this rho does not read")]
Version { found: u32 },
#[error("the file name is not a session id rho writes")]
Foreign,
#[error("the file is named for session {name}, but the record is session {session}")]
Misnamed { name: String, session: SessionId },
}
fn read_record(path: &Path, stem: &str) -> Result<(SessionId, SessionRecord), UnreadableRecord> {
if file_name(stem).is_none() {
return Err(UnreadableRecord::Foreign);
}
let contents = fs::read(path)?;
let RecordVersion { version } = serde_json::from_slice(&contents)?;
if version != RECORD_VERSION {
return Err(UnreadableRecord::Version { found: version });
}
let RecordFileIn { session, record } = serde_json::from_slice(&contents)?;
if session.as_str() != stem {
return Err(UnreadableRecord::Misnamed {
name: stem.to_owned(),
session,
});
}
Ok((session, record))
}
#[cfg(test)]
#[path = "store_tests.rs"]
mod tests;