use std::fs::{self, File};
use std::io;
use std::path::Path;
use super::aside::{opening, said};
use super::draft::belongs;
use super::files::sync_directory;
use super::lock::tidy;
use super::queue::Queue;
use super::run::UNREADABLE_ANSWER;
use super::seal::SEAL_GONE;
use super::state::{Destination, State, UNREADABLE};
use crate::record::spool::Spool;
use crate::store::fileio::{atomic_write, remove_file};
pub const GONE: &str = "gone";
pub const BUSY: &str = "busy";
pub const PAUSED: &str = "paused";
pub const DAMAGED: &str = "damaged";
pub const MAY_BE_STORED: &str = "may_be_stored";
pub const POLICY: &str = "policy_differs";
#[derive(Debug, PartialEq, Eq)]
pub enum Outcome {
Retried { n: u64, bytes: u64 },
Discarded { bytes: u64 },
Stays { code: &'static str, why: String },
}
fn stays(code: &'static str, why: &str) -> Outcome {
Outcome::Stays {
code,
why: why.to_string(),
}
}
pub struct Found {
pub fingerprint: String,
pub conversation_id: String,
pub destination: Destination,
pub scope: String,
pub mount: String,
pub provenance: String,
pub project: String,
}
pub struct Ask<'a> {
pub duplicate: bool,
pub find: &'a dyn Fn(&State) -> Result<Found, String>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Recorder {
Direct,
Profile,
Unknown,
}
pub struct Chosen<'a> {
pub tree: &'a Path,
pub recorder: Recorder,
pub id: &'a str,
pub n: u64,
pub line: Option<&'a str>,
}
fn session(chosen: &Chosen) -> io::Result<Vec<File>> {
let spool = Spool::new(chosen.tree);
let key = crate::record::pause::session_key(chosen.id);
let names = match (chosen.recorder, key) {
(Recorder::Profile, Some(key)) => vec![key],
(Recorder::Unknown, Some(key)) => vec![chosen.id, key],
_ => vec![chosen.id],
};
names.into_iter().map(|name| spool.lock(name)).collect()
}
fn locked(
chosen: &Chosen,
then: impl FnOnce(&Queue, u64) -> io::Result<Outcome>,
) -> io::Result<Outcome> {
let _session = session(chosen)?;
let queue = Queue::new(chosen.tree);
let Some(lock) = queue.try_lock(chosen.id)? else {
return Ok(stays(BUSY, "another process holds its conversation"));
};
let file = Queue::part(&queue.held_dir(chosen.id), chosen.n, "jsonl");
let outcome = match fs::symlink_metadata(&file) {
Ok(_) if opening(&file)?.as_deref() != chosen.line => {
Ok(stays(GONE, "another turn has its number now"))
}
Ok(metadata) => then(&queue, metadata.len()),
Err(error) if error.kind() == io::ErrorKind::NotFound => {
Ok(stays(GONE, "it is no longer held"))
}
Err(error) => Err(error),
};
tidy(lock)?;
outcome
}
pub fn discard(chosen: &Chosen) -> io::Result<Outcome> {
locked(chosen, |queue, bytes| {
let directory = queue.held_dir(chosen.id);
for part in ["jsonl", "state", "reason"] {
remove_file(&Queue::part(&directory, chosen.n, part))?;
}
sync_directory(&directory)?;
let _ = fs::remove_dir(&directory);
Ok(Outcome::Discarded { bytes })
})
}
pub fn retry(
chosen: &Chosen,
ask: &Ask,
mut cut: impl FnMut(&str) -> io::Result<()>,
) -> io::Result<Outcome> {
locked(chosen, |queue, bytes| {
let (id, n) = (chosen.id, chosen.n);
if queue.paused(id)? {
return Ok(stays(PAUSED, "its conversation is paused"));
}
let directory = queue.held_dir(id);
let mut state = match State::read(&Queue::part(&directory, n, "state")) {
Ok(state) if state.conversation_id == id => state,
_ => return Ok(stays(DAMAGED, "its state cannot be read")),
};
let Some(line) = chosen.line.filter(|_| state.bytes == bytes) else {
return Ok(stays(DAMAGED, "its file is not the turn its state names"));
};
if !belongs(&state.draft, id, line, state.attempt) {
return Ok(stays(DAMAGED, "its draft id is not this turn's"));
}
let Some(said) = said(&directory, n) else {
return Ok(stays(DAMAGED, "its reason cannot be read"));
};
let answered = said.may_be_stored
|| (said.reason == UNREADABLE && said.message.as_deref() == Some(UNREADABLE_ANSWER));
if answered && !ask.duplicate {
let why = match said.message.as_deref() {
Some(SEAL_GONE) => {
"its seal was sent and the store holds no draft of it, so the store may \
hold it already; --allow-duplicate retries it anyway"
}
_ => {
"a 2xx was answered for it but could not be read, so the store may \
hold it already; --allow-duplicate retries it anyway"
}
};
return Ok(stays(MAY_BE_STORED, why));
}
state.sealing &= !ask.duplicate;
if let Some(theirs) = state.fingerprint.clone() {
let found = match (ask.find)(&state) {
Ok(found) => found,
Err(why) => return Ok(stays(POLICY, &why)),
};
if found.fingerprint != theirs {
let why = "the policy it was recorded under does not apply here now";
return Ok(stays(POLICY, why));
}
if found.conversation_id != id {
return Ok(stays(POLICY, "the profile found here did not record it"));
}
match &state.destination {
None => fill(&mut state, found),
Some(destination) if *destination == found.destination => {}
Some(_) => return Ok(stays(POLICY, "its profile names another destination now")),
}
} else if state.destination.is_none() {
return Ok(stays(DAMAGED, "its state names no destination"));
}
let n = move_back(queue, id, n, &state, &mut cut)?;
Ok(Outcome::Retried { n, bytes })
})
}
fn fill(state: &mut State, found: Found) {
state.destination = Some(found.destination);
state.scope = state.scope.take().or(Some(found.scope));
state.mount = state.mount.take().or(Some(found.mount));
state.provenance = state.provenance.take().or(Some(found.provenance));
state.project = state.project.take().or(Some(found.project));
}
fn move_back(
queue: &Queue,
id: &str,
n: u64,
state: &State,
cut: &mut impl FnMut(&str) -> io::Result<()>,
) -> io::Result<u64> {
let (from, to) = (queue.held_dir(id), queue.pending_dir(id));
let next = queue.next_n(id)?;
let reason = fs::read_to_string(Queue::part(&from, n, "reason"))?;
atomic_write(&Queue::part(&to, next, "state"), &state.text(), true)?;
atomic_write(&Queue::part(&to, next, "reason"), &reason, true)?;
sync_directory(&to)?;
cut("staged")?;
fs::rename(
Queue::part(&from, n, "jsonl"),
Queue::part(&to, next, "jsonl"),
)?;
queue.persist(&to, next)?;
sync_directory(&from)?;
cut("moved")?;
remove_file(&Queue::part(&from, n, "state"))?;
remove_file(&Queue::part(&from, n, "reason"))?;
sync_directory(&from)?;
let _ = fs::remove_dir(&from);
Ok(next)
}