use std::fs;
use std::path::{Path, PathBuf};
use anyhow::{Context as _, Result, bail};
use super::answer::Answer;
use zeroize::Zeroizing;
use super::channel::{Credential, Secrets, Spec};
use super::refused::Refused;
use super::request::Request;
use crate::home::{Home, write_private, write_private_new};
pub const DIR: &str = "remote";
const KEY_FILE: &str = "approval.key";
const SETTINGS_FILE: &str = "settings.json";
const CREDENTIAL_FILE: &str = "credential";
const REQUESTS: &str = "requests";
const ANSWERS: &str = "answers";
const USED: &str = "used";
const REFUSED: &str = "refused";
const STAGED: &str = ".staged-";
const CLAIM: &str = ".claim-";
const USED_KEPT_MS: i64 = 24 * 60 * 60 * 1000;
#[derive(Debug)]
pub enum Placing {
Placed,
AlreadyAnswered,
Lost(anyhow::Error),
}
#[derive(Debug, Clone)]
pub struct Store {
dir: PathBuf,
}
#[derive(Debug, Clone)]
pub struct ChannelFiles {
dir: PathBuf,
}
impl ChannelFiles {
#[cfg(test)]
pub fn dir(&self) -> &Path {
&self.dir
}
pub fn credential_path(&self) -> PathBuf {
self.dir.join(CREDENTIAL_FILE)
}
pub fn settings_path(&self) -> PathBuf {
self.dir.join(SETTINGS_FILE)
}
pub fn read_secrets(&self, spec: &Spec) -> Result<Secrets> {
let path = self.credential_path();
let text = crate::key_file::read(&path)?;
let refused = || {
format!(
"{} does not hold {} credentials",
path.display(),
spec.title
)
};
let Ok(serde_json::Value::Object(map)) = serde_json::from_str(&text) else {
bail!(refused());
};
let mut secrets = Secrets::new();
for (key, value) in map {
let serde_json::Value::String(value) = value else {
bail!(refused());
};
secrets.insert(key, Credential::new(value));
}
super::connect::check_fields(spec, true, &secrets).with_context(refused)?;
Ok(secrets)
}
pub fn put_secrets(&self, secrets: &Secrets) -> Result<()> {
let object: serde_json::Map<String, serde_json::Value> = secrets
.iter()
.map(|(k, v)| (k.clone(), serde_json::Value::String(v.to_string())))
.collect();
let text = Zeroizing::new(
serde_json::to_string(&object).context("encoding the channel's credentials")?,
);
write_private(&self.credential_path(), text.as_bytes())
}
pub fn remove(&self) -> Result<bool> {
match fs::remove_dir_all(&self.dir) {
Ok(()) => Ok(true),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
Err(e) => Err(e).with_context(|| format!("removing {}", self.dir.display())),
}
}
}
pub fn plain_id(id: &str) -> bool {
id.len() == 32 && id.bytes().all(|b| b.is_ascii_hexdigit())
}
impl Store {
pub fn of(home: &Home) -> Self {
Self::at(home.root().join(DIR))
}
pub fn at(dir: PathBuf) -> Self {
Self { dir }
}
pub fn dir(&self) -> &Path {
&self.dir
}
pub fn key_path(&self) -> PathBuf {
self.dir.join(KEY_FILE)
}
pub fn settings_path(&self) -> PathBuf {
self.dir.join(SETTINGS_FILE)
}
pub fn channel(&self, spec: &Spec) -> ChannelFiles {
ChannelFiles {
dir: self.dir.join(spec.name),
}
}
pub fn connected(&self) -> bool {
self.settings_path().exists()
}
fn request_path(&self, id: &str) -> PathBuf {
self.dir.join(REQUESTS).join(format!("{id}.json"))
}
fn answer_path(&self, id: &str) -> PathBuf {
self.dir.join(ANSWERS).join(format!("{id}.json"))
}
pub fn requests(&self) -> Result<Vec<Result<Request, String>>> {
let dir = self.dir.join(REQUESTS);
let entries = match fs::read_dir(&dir) {
Ok(entries) => entries,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(e) => return Err(e).with_context(|| format!("reading {}", dir.display())),
};
let mut out = Vec::new();
for entry in entries {
let entry = entry.with_context(|| format!("reading {}", dir.display()))?;
let name = entry.file_name();
let Some(id) = name.to_str().and_then(|n| n.strip_suffix(".json")) else {
continue;
};
if !plain_id(id) {
continue;
}
let read = fs::read_to_string(entry.path())
.ok()
.and_then(|text| serde_json::from_str::<Request>(&text).ok())
.filter(|r| r.id == id);
out.push(read.ok_or_else(|| id.to_owned()));
}
Ok(out)
}
pub fn request(&self, id: &str) -> Option<Request> {
if !plain_id(id) {
return None;
}
let text = fs::read_to_string(self.request_path(id)).ok()?;
serde_json::from_str::<Request>(&text)
.ok()
.filter(|r| r.id == id)
}
pub fn put_request(&self, request: &Request) -> Result<()> {
let text = serde_json::to_vec(request).context("encoding a request")?;
write_private(&self.request_path(&request.id), &text)
}
pub fn answer(&self, id: &str) -> Option<Answer> {
if !plain_id(id) {
return None;
}
let text = fs::read_to_string(self.answer_path(id)).ok()?;
serde_json::from_str(&text).ok()
}
pub fn has_answer(&self, id: &str) -> bool {
plain_id(id) && self.answer_path(id).exists()
}
pub fn put_answer_once_recorded(
&self,
answer: &Answer,
record: impl FnOnce() -> Result<()>,
) -> Result<Placing> {
if !plain_id(&answer.id) {
bail!("not a request id");
}
let place = self.answer_path(&answer.id);
if place.exists() {
return Ok(Placing::AlreadyAnswered);
}
let text = serde_json::to_vec(answer).context("encoding an answer")?;
let dir = self.dir.join(ANSWERS);
let staged = dir.join(format!("{STAGED}{}", answer.id));
let claim = dir.join(format!("{CLAIM}{}", answer.id));
write_private(&staged, &text)?;
let claimed = fs::hard_link(&staged, &claim);
let _ = fs::remove_file(&staged);
match claimed {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
return Ok(Placing::AlreadyAnswered);
}
Err(e) => return Err(e).context("claiming the answer"),
}
if let Err(error) = record() {
let _ = fs::remove_file(&claim);
return Err(error);
}
let placed = fs::hard_link(&claim, &place);
let _ = fs::remove_file(&claim);
Ok(match placed {
Ok(()) => Placing::Placed,
Err(e) => Placing::Lost(anyhow::Error::new(e).context("placing the answer")),
})
}
pub fn sweep_unplaced(&self) {
let Ok(entries) = fs::read_dir(self.dir.join(ANSWERS)) else {
return;
};
for entry in entries.flatten() {
let name = entry.file_name();
let name = name.to_string_lossy();
if name.starts_with(STAGED) || name.starts_with(CLAIM) {
let _ = fs::remove_file(entry.path());
}
}
}
#[cfg(test)]
pub fn put_answer(&self, answer: &Answer) -> Result<bool> {
let text = serde_json::to_vec(answer).context("encoding an answer")?;
write_private_new(&self.answer_path(&answer.id), &text)
}
pub fn use_once(&self, id: &str) -> Result<bool> {
write_private_new(&self.dir.join(USED).join(id), b"")
}
pub fn used(&self, id: &str) -> bool {
self.dir.join(USED).join(id).exists()
}
#[cfg(test)]
pub fn forget_answer(&self, id: &str) {
let _ = fs::remove_file(self.answer_path(id));
}
pub fn forget(&self, id: &str) {
let _ = fs::remove_file(self.request_path(id));
let _ = fs::remove_file(self.answer_path(id));
}
fn refused_path(&self, id: &str) -> PathBuf {
self.dir.join(REFUSED).join(format!("{id}.json"))
}
pub fn put_refused(&self, note: &Refused) -> Result<()> {
let text = serde_json::to_vec(note).context("encoding a refusal")?;
write_private(&self.refused_path(¬e.request.id), &text)
}
pub fn refused(&self) -> Vec<(String, Option<Refused>)> {
let Ok(entries) = fs::read_dir(self.dir.join(REFUSED)) else {
return Vec::new();
};
let mut out = Vec::new();
for entry in entries.flatten() {
let name = entry.file_name();
let Some(id) = name.to_str().and_then(|n| n.strip_suffix(".json")) else {
continue;
};
if !plain_id(id) {
continue;
}
let note = fs::read_to_string(entry.path())
.ok()
.and_then(|text| serde_json::from_str::<Refused>(&text).ok())
.filter(|n| n.request.id == id);
out.push((id.to_owned(), note));
}
out
}
pub fn forget_refused(&self, id: &str) {
let _ = fs::remove_file(self.refused_path(id));
}
pub fn sweep_used(&self, now_ms: i64) {
let Ok(entries) = fs::read_dir(self.dir.join(USED)) else {
return;
};
for entry in entries.flatten() {
let old = entry
.metadata()
.and_then(|m| m.modified())
.ok()
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.and_then(|d| i64::try_from(d.as_millis()).ok())
.is_some_and(|ms| now_ms - ms > USED_KEPT_MS);
if old {
let _ = fs::remove_file(entry.path());
}
}
}
}