use std::time::{Duration, Instant};
use anyhow::Result;
use openmoat_core::Decision;
use openmoat_hosts::{FailureOutcome, GUARD_BUDGET_S, HookFailure};
use super::request::Request;
use super::settings::Settings;
use super::store::Store;
use crate::hangs::{self, Phase};
use crate::proxy_session::Key;
pub const DEFAULT_WAIT_S: u64 = 20;
pub const ANSWER_MARGIN: Duration = Duration::from_secs(5);
pub const RELAY_MARGIN: Duration = Duration::from_secs(5);
pub const MAX_WAIT_S: u64 = GUARD_BUDGET_S - ANSWER_MARGIN.as_secs();
const _: () = assert!(DEFAULT_WAIT_S <= MAX_WAIT_S);
pub const FAIL_OPEN_SHARE: u32 = 4;
const STEP: Duration = Duration::from_millis(100);
const LIVE_EVERY: Duration = Duration::from_secs(1);
pub fn host_limit(failure: &HookFailure) -> Duration {
let Some(timeout) = failure.timeout_s else {
return Duration::ZERO;
};
let timeout = Duration::from_secs(u64::from(timeout));
match failure.times_out {
FailureOutcome::Blocks => timeout,
FailureOutcome::BlocksFrom(_)
| FailureOutcome::BlocksWhenMissing
| FailureOutcome::Runs
| FailureOutcome::NotDocumented => timeout / FAIL_OPEN_SHARE,
}
}
pub fn room(failure: &HookFailure, elapsed: Duration, relayed: bool) -> Duration {
let end = host_limit(failure).min(Duration::from_secs(GUARD_BUDGET_S));
let margin = if relayed {
ANSWER_MARGIN + RELAY_MARGIN
} else {
ANSWER_MARGIN
};
end.saturating_sub(margin).saturating_sub(elapsed)
}
pub struct Hold<'a> {
pub until: Instant,
pub clock: &'a dyn Fn() -> i64,
}
#[cfg(test)]
impl Hold<'static> {
pub fn none() -> Self {
Self {
until: Instant::now(),
clock: &crate::time::now_ms,
}
}
}
#[derive(Debug)]
pub enum Waited {
Not,
NoAnswer(Duration),
Answered(Box<(Decision, Option<Request>)>, Duration),
Taken(Box<Decision>),
}
pub fn hold(
store: &Store,
key: &Key,
settings: &Settings,
(open, held): (&Request, &Decision),
limits: &Hold<'_>,
) -> Result<Waited> {
let started = Instant::now();
let until = limits.until.min(started + settings.wait());
if until <= started || !super::live::live(store, key, &settings.channel, (limits.clock)()) {
return Ok(Waited::Not);
}
hangs::enter(Phase::Approval);
let mut seen_live = started;
loop {
if store.used(&open.id) {
let mut kept = held.clone();
kept.reasons.push(format!(
"request {} was approved once and is used",
open.code()
));
return Ok(Waited::Taken(Box::new(kept)));
}
if store.has_answer(&open.id) {
let now = Settings::load(&store.settings_path(), key)?;
if let Some((decided, used)) = super::gate::answered(store, key, &now, open, held)? {
return Ok(Waited::Answered(
Box::new((decided, used)),
started.elapsed(),
));
}
}
let now = Instant::now();
if now >= until || open.expired((limits.clock)()) {
break;
}
if seen_live.elapsed() >= LIVE_EVERY {
if !super::live::live(store, key, &settings.channel, (limits.clock)()) {
break;
}
seen_live = Instant::now();
}
std::thread::sleep(STEP.min(until.saturating_duration_since(now)));
}
Ok(Waited::NoAnswer(started.elapsed()))
}