use std::fs::{self, File};
use std::io;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
use serde::{Deserialize, Serialize};
use super::super::fingerprint::digest;
use super::draft::micros_z;
use super::rules::Stop;
use super::state::Destination;
use crate::store::fileio::{atomic_write, private, private_mkdir, remove_file};
use crate::store::time::Stamp;
pub const SIX_HOURS: i64 = 6 * 3600;
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Record {
pub host: String,
pub wait_until: Option<String>,
pub block: Option<Blocked>,
pub failing_since: Option<String>,
pub cause: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Blocked {
pub reason: String,
pub status: Option<u16>,
pub code: Option<String>,
pub message: String,
pub since: String,
pub next_attempt: String,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Gate {
Open,
Closed,
Due,
}
pub fn stamp(time: SystemTime) -> Stamp {
let since = time.duration_since(UNIX_EPOCH).unwrap_or_default();
Stamp::from_micros(i64::try_from(since.as_micros()).unwrap_or(i64::MAX))
}
fn reached(at: Option<&str>, now: Stamp) -> bool {
at.is_none_or(|at| Stamp::parse(at).map_or(true, |at| at.instant() <= now.instant()))
}
impl Record {
pub fn gate(&self, now: Stamp) -> Gate {
if !reached(self.wait_until.as_deref(), now) {
return Gate::Closed;
}
match &self.block {
None => Gate::Open,
Some(block) if reached(Some(&block.next_attempt), now) => Gate::Due,
Some(_) => Gate::Closed,
}
}
fn empty(&self) -> bool {
self.wait_until.is_none() && self.block.is_none() && self.failing_since.is_none()
}
fn wait(&mut self, seconds: u64, failing: bool, now: Stamp) {
let seconds = i64::try_from(seconds).unwrap_or(SIX_HOURS).min(SIX_HOURS);
self.wait_until = Some(micros_z(now.after(seconds)));
if failing && self.failing_since.is_none() {
self.failing_since = Some(micros_z(now));
}
}
pub fn noted(mut self, host: &str, stop: &Stop, now: Stamp) -> Self {
host.clone_into(&mut self.host);
self.cause = Some(stop.message().to_string());
match stop {
Stop::Wait {
seconds, failing, ..
} => self.wait(*seconds, *failing, now),
Stop::Retry { seconds, .. } => self.wait(*seconds, false, now),
Stop::Block {
block,
message,
status,
code,
} => {
let since = match &self.block {
Some(old) if old.reason == block.name() => old.since.clone(),
_ => micros_z(now),
};
self.wait_until = None;
self.block = Some(Blocked {
reason: block.name().to_string(),
status: *status,
code: code.clone(),
message: message.clone(),
since,
next_attempt: micros_z(now.after(SIX_HOURS)),
});
}
Stop::Conversation(_) => {}
}
self
}
}
pub fn key(destination: &Destination) -> String {
let json = serde_json::to_vec(destination).expect("a descriptor serializes");
digest(&json)[..32].to_string()
}
fn path(landing: &Path, key: &str) -> PathBuf {
landing.join(format!("{key}.json"))
}
pub fn read(landing: &Path, key: &str) -> Option<Record> {
let text = fs::read(path(landing, key)).ok()?;
serde_json::from_slice(&text).ok()
}
pub fn gate(landing: &Path, destination: &Destination, now: Stamp) -> Gate {
read(landing, &key(destination)).map_or(Gate::Open, |record| record.gate(now))
}
pub(super) struct Locked {
_file: File,
}
pub(super) fn lock(landing: &Path) -> io::Result<Locked> {
private_mkdir(landing)?;
let file = private()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(landing.join(".lock"))?;
file.lock()?;
Ok(Locked { _file: file })
}
pub fn update<T>(
landing: &Path,
key: &str,
change: impl FnOnce(Option<Record>) -> (Option<Record>, T),
) -> io::Result<T> {
let _held = lock(landing)?;
let (record, answer) = change(read(landing, key));
let file = path(landing, key);
match record.filter(|record| !record.empty()) {
Some(record) => {
let mut text = serde_json::to_string(&record).expect("a record serializes");
text.push('\n');
atomic_write(&file, &text, false)?;
}
None => remove_file(&file)?,
}
Ok(answer)
}
pub fn note(landing: &Path, key: &str, host: &str, stop: &Stop, now: Stamp) -> io::Result<()> {
update(landing, key, |record| {
(Some(record.unwrap_or_default().noted(host, stop, now)), ())
})
}
fn edit(landing: &Path, key: &str, change: impl FnOnce(&mut Record)) -> io::Result<()> {
update(landing, key, |record| {
let record = record.map(|mut record| {
change(&mut record);
record
});
(record, ())
})
}
pub fn landed(landing: &Path, key: &str) -> io::Result<()> {
edit(landing, key, |record| {
(record.wait_until, record.failing_since, record.cause) = (None, None, None);
})
}
pub fn lift(landing: &Path, key: &str) -> io::Result<()> {
edit(landing, key, |record| record.block = None)
}
pub fn claim(landing: &Path, key: &str, now: Stamp) -> io::Result<Option<Blocked>> {
update(landing, key, |record| match record {
Some(mut record) if record.gate(now) == Gate::Due => {
let was = record.block.clone();
if let Some(block) = &mut record.block {
block.next_attempt = micros_z(now.after(SIX_HOURS));
}
(Some(record), was)
}
other => (other, None),
})
}
pub fn unclaim(landing: &Path, key: &str, was: &Blocked) -> io::Result<()> {
edit(landing, key, |record| {
if let Some(block) = &mut record.block
&& block.reason == was.reason
{
block.next_attempt.clone_from(&was.next_attempt);
}
})
}
pub fn unblock(
landing: &Path,
which: impl Fn(&Blocked) -> bool,
waits: bool,
) -> io::Result<Vec<Record>> {
let mut ended = Vec::new();
for key in super::keys::keys(landing)? {
let was = update(landing, &key, |record| {
let Some(mut after) = record.clone() else {
return (None, None);
};
let blocked = after.block.take_if(|block| which(block)).is_some();
let waiting = waits && after.wait_until.take().is_some();
match blocked || waiting {
true => (Some(after), record),
false => (record, None),
}
})?;
ended.extend(was);
}
Ok(ended)
}