use crate::error::{Failure, Result};
use std::future::Future;
use std::pin::Pin;
use std::time::Duration;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Phase {
Connect,
Authenticate,
Query,
}
impl Phase {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Connect => "connect",
Self::Authenticate => "authenticate",
Self::Query => "query",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AbortOutcome {
Confirmed,
NotReached,
}
pub type AbortFuture<'a> = Pin<Box<dyn Future<Output = Result<AbortOutcome>> + Send + 'a>>;
pub trait ServerAbort {
fn abort(&self, session: u64) -> AbortFuture<'_>;
}
#[must_use]
pub fn exceeded(phase: Phase, limit: Duration) -> Failure {
Failure::timeout(
"timeout.phase_exceeded",
format!(
"the {} phase went past its limit of {} s",
phase.as_str(),
limit.as_secs_f64()
),
)
.with_detail(
"detail",
format!("{}, {} s", phase.as_str(), limit.as_secs_f64()),
)
.with_hint("raise the limit, or narrow the work so it fits inside it")
}
pub async fn within<T, Fut>(phase: Phase, limit: Duration, work: Fut) -> Result<T>
where
Fut: Future<Output = Result<T>>,
{
let Ok(outcome) = tokio::time::timeout(limit, work).await else {
crate::i18n::report::budget_exceeded(phase.as_str(), limit.as_secs());
return Err(exceeded(phase, limit));
};
outcome
}
pub async fn within_aborting<T, Fut, A>(
phase: Phase,
limit: Duration,
session: u64,
aborter: &A,
work: Fut,
) -> Result<T>
where
Fut: Future<Output = Result<T>>,
A: ServerAbort + ?Sized,
{
let Ok(outcome) = tokio::time::timeout(limit, work).await else {
crate::i18n::report::budget_exceeded(phase.as_str(), limit.as_secs());
return Err(with_abort_outcome(
exceeded(phase, limit),
aborter.abort(session).await,
));
};
outcome
}
pub async fn within_aborting_or_stopped<T, Fut, A>(
phase: Phase,
limit: Duration,
session: u64,
aborter: &A,
stopping: &tokio_util::sync::CancellationToken,
work: Fut,
) -> Result<T>
where
Fut: Future<Output = Result<T>>,
A: ServerAbort + ?Sized,
{
tokio::select! {
outcome = tokio::time::timeout(limit, work) => {
let Ok(outcome) = outcome else {
crate::i18n::report::budget_exceeded(phase.as_str(), limit.as_secs());
return Err(with_abort_outcome(
exceeded(phase, limit),
aborter.abort(session).await,
));
};
outcome
}
() = stopping.cancelled() => {
Err(with_abort_outcome(cancelled(), aborter.abort(session).await))
}
}
}
fn cancelled() -> Failure {
Failure::interrupted(
"interrupted.by_caller",
"the invocation was stopped by the caller",
)
}
#[must_use]
pub fn with_abort_outcome(failure: Failure, outcome: Result<AbortOutcome>) -> Failure {
match outcome {
Ok(AbortOutcome::Confirmed) => failure
.with_cause("the server confirmed the work has stopped")
.with_hint("the work is no longer running on the server"),
Ok(AbortOutcome::NotReached) => failure
.with_cause("the ask to stop did not reach the server")
.with_hint("the work may still be running on the server"),
Err(reason) => failure
.with_cause(format!("the ask to stop failed: {reason}"))
.with_hint("the work may still be running on the server"),
}
}
#[cfg(test)]
mod tests {
use super::*;
struct Answering(AbortOutcome);
impl ServerAbort for Answering {
fn abort(&self, _session: u64) -> AbortFuture<'_> {
let outcome = self.0;
Box::pin(async move { Ok(outcome) })
}
}
struct Unreachable;
impl ServerAbort for Unreachable {
fn abort(&self, _session: u64) -> AbortFuture<'_> {
Box::pin(async {
Err(Failure::network(
"network.unreachable",
"the second connection could not be opened",
))
})
}
}
#[test]
fn every_phase_carries_its_own_identifier() {
assert_eq!(Phase::Connect.as_str(), "connect");
assert_eq!(Phase::Authenticate.as_str(), "authenticate");
assert_eq!(Phase::Query.as_str(), "query");
}
#[test]
fn a_budget_that_runs_out_names_the_phase_and_the_limit() {
let failure = exceeded(Phase::Query, Duration::from_secs(5));
assert_eq!(failure.exit_number().code(), 124);
assert!(failure.message().contains("query"));
assert!(failure.message().contains('5'));
}
#[test]
fn a_confirmed_abort_says_the_work_is_no_longer_running() {
let failure = with_abort_outcome(
exceeded(Phase::Query, Duration::from_secs(1)),
Ok(AbortOutcome::Confirmed),
);
assert!(failure
.hint()
.is_some_and(|hint| hint.contains("no longer running")));
}
#[test]
fn an_abort_that_never_arrived_says_the_work_may_continue_there() {
for outcome in [
Ok(AbortOutcome::NotReached),
Err(Failure::network("network.unreachable", "lost")),
] {
let failure =
with_abort_outcome(exceeded(Phase::Query, Duration::from_secs(1)), outcome);
assert!(
failure
.hint()
.is_some_and(|hint| hint.contains("may still be running")),
"the caller must never assume an abort that did not arrive"
);
assert_eq!(failure.exit_number().code(), 124);
}
}
#[tokio::test]
async fn work_that_fits_inside_the_budget_is_handed_straight_through() {
let value = within(Phase::Query, Duration::from_secs(30), async {
Ok::<u8, Failure>(7)
})
.await
.expect("fits");
assert_eq!(value, 7);
}
#[tokio::test]
async fn work_that_goes_past_the_budget_ends_in_the_published_number() {
let failure = within(Phase::Connect, Duration::from_millis(10), async {
tokio::time::sleep(Duration::from_secs(30)).await;
Ok::<u8, Failure>(7)
})
.await
.expect_err("must run out");
assert_eq!(failure.exit_number().code(), 124);
assert!(failure.message().contains("connect"));
}
#[tokio::test]
async fn running_out_of_time_asks_the_server_to_stop_as_well() {
let failure = within_aborting(
Phase::Query,
Duration::from_millis(10),
42,
&Answering(AbortOutcome::Confirmed),
async {
tokio::time::sleep(Duration::from_secs(30)).await;
Ok::<u8, Failure>(7)
},
)
.await
.expect_err("must run out");
assert!(failure
.causes()
.iter()
.any(|cause| cause.contains("confirmed")));
}
#[tokio::test]
async fn an_ask_that_fails_is_declared_rather_than_hidden() {
let failure = within_aborting(
Phase::Query,
Duration::from_millis(10),
42,
&Unreachable,
async {
tokio::time::sleep(Duration::from_secs(30)).await;
Ok::<u8, Failure>(7)
},
)
.await
.expect_err("must run out");
assert!(failure
.hint()
.is_some_and(|hint| hint.contains("may still be running")));
}
#[tokio::test]
async fn work_that_fits_never_opens_the_second_connection() {
struct NeverCalled;
impl ServerAbort for NeverCalled {
fn abort(&self, _session: u64) -> AbortFuture<'_> {
Box::pin(async {
Err(Failure::server(
"server.unclassified",
"the second connection must never be opened here",
))
})
}
}
within_aborting(
Phase::Query,
Duration::from_secs(30),
42,
&NeverCalled,
async { Ok::<u8, Failure>(7) },
)
.await
.expect("fits inside the budget");
}
}