use std::cell::Cell;
use std::io;
use std::path::Path;
use super::answer::{Answer, said};
use super::destination::{Gate, claim, key, landed, lift, note, read, stamp, unclaim};
use super::kept::{self, credentials};
use super::queue::Queue;
use super::rules::{Action, Block, Stop};
use super::slots::directory;
use super::state::public_url;
use super::turn::{Here, Run, land_queue};
use crate::conversation::Error;
use crate::profile::files::Endpoint;
use crate::remote::selection::Selection;
pub struct Trial<'a> {
landing: &'a Path,
key: &'a str,
block: Block,
answered: Cell<bool>,
}
impl Trial<'_> {
pub fn pending(&self) -> bool {
!self.answered.get()
}
pub fn taken(&self) -> io::Result<()> {
self.answered.set(true);
lift(self.landing, self.key)
}
pub fn refused(&self, action: Action, answer: &Answer) -> Stop {
self.answered.set(true);
match action {
Action::Keep(stop @ (Stop::Block { .. } | Stop::Wait { .. })) => stop,
Action::Keep(Stop::Retry { seconds, message }) => Stop::Wait {
seconds,
failing: false,
message,
},
_ => {
let (status, code) = match answer {
Answer::Refused(refusal) => (Some(refusal.status), refusal.code.clone()),
_ => (None, None),
};
Stop::Block {
block: self.block,
message: said(answer),
status,
code,
}
}
}
}
}
pub enum Gated {
Closed,
Busy,
Ran(Box<Run>),
}
fn named(reason: &str) -> Block {
match reason {
"storage" => Block::Storage,
"credential" => Block::Credential,
_ => Block::Forbidden,
}
}
pub fn land(queue: &Queue, id: &str, here: &Here, home: &Path) -> Result<Gated, Error> {
let landing = directory(home);
let key = key(&here.destination);
let now = stamp(here.cap.now());
let record = read(&landing, &key);
let claimed = match record.as_ref().map(|record| record.gate(now)) {
Some(Gate::Closed) => return Ok(Gated::Closed),
Some(Gate::Due) => match claim(&landing, &key, now)? {
Some(block) => Some(block),
None => return Ok(Gated::Closed),
},
_ => None,
};
let trial = claimed.as_ref().map(|block| Trial {
landing: &landing,
key: &key,
block: named(&block.reason),
answered: Cell::new(false),
});
let mut tried = here.clone();
tried.trial = trial.as_ref();
let untried = || match (&claimed, &trial) {
(Some(was), Some(trial)) if trial.pending() => unclaim(&landing, &key, was),
_ => Ok(()),
};
let Some(mut run) = land_queue(queue, id, &tried)? else {
untried()?;
return Ok(Gated::Busy);
};
let said = credentials(here.selection);
run.stopped = run.stopped.map(|stop| kept::stop(stop, &said));
match &run.stopped {
Some(stop) if stop.destination() => {
let arrived = stamp(here.cap.now());
note(&landing, &key, &host(here.selection), stop, arrived)?;
}
_ => {
untried()?;
let stored = !run.landed.is_empty() || run.undocumented.is_some();
if record.is_some() && stored {
landed(&landing, &key)?;
}
}
}
Ok(Gated::Ran(Box::new(run)))
}
pub fn host(selection: &Selection) -> String {
let authority = |url: &str| {
let shown = public_url(url);
let rest = shown
.split_once("://")
.map_or(shown.as_str(), |(_, rest)| rest);
rest.split('/').next().unwrap_or_default().to_string()
};
let postgres = |schema: &str| format!("PostgreSQL (schema {schema})");
match selection {
Selection::File(root) => root.display().to_string(),
Selection::Postgres { dsn, schema } if dsn.contains("://") => {
format!("{} (schema {schema})", authority(dsn))
}
Selection::Postgres { schema, .. } => postgres(schema),
Selection::Remote { url, .. } => authority(url),
Selection::Profile(resolved) => {
let source = resolved.profile.history.as_ref().map(|h| &h.source);
match source.and_then(|s| resolved.bindings.get(s)) {
Some(binding) => match &binding.endpoint {
Endpoint::Http { url, .. } => authority(url),
Endpoint::File { root } => root.display().to_string(),
Endpoint::Postgres { schema, .. } => postgres(schema),
},
None => resolved.name.clone(),
}
}
}
}