use std::{
io,
path::{Path, PathBuf},
};
use rho_protocol::{
ConfigRevision, ErrorCode, HooksFileGetResponse, HooksFileSetParams, HooksFileSetResponse,
RpcError,
};
use sha2::{Digest, Sha256};
const ABSENT: &str = "absent";
pub(super) struct HooksFileStore {
path: PathBuf,
writes: tokio::sync::Mutex<()>,
}
impl HooksFileStore {
pub(super) fn new(rho_home: &Path) -> Self {
Self {
path: crate::hooks::user_hooks_path(rho_home),
writes: tokio::sync::Mutex::new(()),
}
}
pub(super) fn get(&self) -> Result<HooksFileGetResponse, RpcError> {
let bytes = self.read()?;
let revision = revision(bytes.as_deref());
let text = bytes
.map(|bytes| {
String::from_utf8(bytes).map_err(|_| {
RpcError::new(
ErrorCode::InternalError,
format!("{} is not UTF-8 text", self.path.display()),
)
})
})
.transpose()?;
let path = crate::paths::without_verbatim_prefix(self.path.clone());
Ok(HooksFileGetResponse::new(path, revision, text))
}
pub(super) async fn set(
&self,
params: HooksFileSetParams,
) -> Result<HooksFileSetResponse, RpcError> {
if let Some(text) = ¶ms.text {
crate::hooks::check_user_hooks(&self.path, text)
.map_err(|error| RpcError::new(ErrorCode::InvalidParams, error.to_string()))?;
}
let _writing = self.writes.lock().await;
let _locked = self.lock()?;
if revision(self.read()?.as_deref()) != params.revision {
return Err(RpcError::new(
ErrorCode::ConfigConflict,
format!(
"{} changed since it was read; read it again",
self.path.display()
),
));
}
let written = match ¶ms.text {
Some(text) => crate::config_writer::write_bytes_atomically(&self.path, text.as_bytes()),
None => match std::fs::remove_file(&self.path) {
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
removed => removed,
},
};
written.map_err(|error| {
RpcError::new(
ErrorCode::InternalError,
format!("could not write {}: {error}", self.path.display()),
)
})?;
Ok(HooksFileSetResponse::new(revision(
params.text.as_deref().map(str::as_bytes),
)))
}
fn lock(&self) -> Result<crate::config_writer::edit_lock::EditFileLock, RpcError> {
crate::config_writer::edit_lock::acquire_edit_lock(&self.path).map_err(|error| {
if error.kind() == io::ErrorKind::WouldBlock {
RpcError::new(
ErrorCode::ConfigConflict,
format!("{} is being edited; read it again", self.path.display()),
)
} else {
RpcError::new(
ErrorCode::InternalError,
format!("could not lock {}: {error}", self.path.display()),
)
}
})
}
fn read(&self) -> Result<Option<Vec<u8>>, RpcError> {
match std::fs::read(&self.path) {
Ok(bytes) => Ok(Some(bytes)),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
Err(error) => Err(RpcError::new(
ErrorCode::InternalError,
format!("could not read {}: {error}", self.path.display()),
)),
}
}
}
fn revision(bytes: Option<&[u8]>) -> ConfigRevision {
ConfigRevision::new(bytes.map_or_else(
|| ABSENT.to_owned(),
|bytes| hex::encode(Sha256::digest(bytes)),
))
}