use std::time::{Duration, Instant};
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Invocation {
pub request_id: String,
pub trace_id: Option<String>,
pub invoked_arn: Option<String>,
pub tenant_id: Option<String>,
pub deadline: Deadline,
pub started: Instant,
}
impl Invocation {
#[must_use]
pub fn trace_root(&self) -> Option<&str> {
self.trace_id.as_deref().and_then(|header| {
header
.split(';')
.find_map(|part| part.trim().strip_prefix("Root="))
})
}
#[must_use]
pub fn new(request_id: impl Into<String>, deadline: Deadline) -> Self {
Self {
request_id: request_id.into(),
trace_id: None,
invoked_arn: None,
tenant_id: None,
deadline,
started: Instant::now(),
}
}
#[must_use]
pub fn elapsed(&self) -> Duration {
self.started.elapsed()
}
#[must_use]
pub fn with_trace_id(mut self, trace_id: Option<String>) -> Self {
self.trace_id = trace_id;
self
}
#[must_use]
pub fn with_invoked_arn(mut self, arn: Option<String>) -> Self {
self.invoked_arn = arn;
self
}
#[must_use]
pub fn with_tenant_id(mut self, tenant_id: Option<String>) -> Self {
self.tenant_id = tenant_id;
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Deadline {
at: Instant,
}
impl Deadline {
#[must_use]
pub fn after(budget: Duration) -> Self {
Self {
at: Instant::now() + budget,
}
}
#[must_use]
pub const fn at(at: Instant) -> Self {
Self { at }
}
#[must_use]
pub const fn instant(self) -> Instant {
self.at
}
#[must_use]
pub fn remaining(self) -> Duration {
self.at.saturating_duration_since(Instant::now())
}
#[must_use]
pub fn is_expired(self) -> bool {
self.remaining().is_zero()
}
#[must_use]
pub fn with_margin(self, margin: Duration) -> Self {
Self {
at: self
.at
.checked_sub(margin)
.unwrap_or_else(|| Instant::now().min(self.at)),
}
}
#[must_use]
pub fn child(self, budget: Duration) -> Self {
Self {
at: Instant::now()
.checked_add(budget)
.map_or(self.at, |at| at.min(self.at)),
}
}
#[must_use]
pub fn earliest(self, other: Self) -> Self {
self.min(other)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Context<Scope> {
invocation: Invocation,
scope: Scope,
}
impl<Scope> Context<Scope> {
#[must_use]
pub fn new(invocation: Invocation, scope: Scope) -> Self {
Self { invocation, scope }
}
pub fn scope(&self) -> &Scope {
&self.scope
}
pub fn invocation(&self) -> &Invocation {
&self.invocation
}
pub fn deadline(&self) -> Deadline {
self.invocation.deadline
}
pub fn into_scope(self) -> Scope {
self.scope
}
}
#[cfg(feature = "_time")]
impl Deadline {
pub async fn run<F, T>(self, work: F) -> Result<T, crate::RuntimeError>
where
F: std::future::Future<Output = T>,
{
let started = Instant::now();
if self.is_expired() {
return Err(crate::RuntimeError::DeadlineExceeded {
elapsed: Duration::ZERO,
});
}
match tokio::time::timeout(self.remaining(), work).await {
Ok(value) => Ok(value),
Err(_) => Err(crate::RuntimeError::DeadlineExceeded {
elapsed: started.elapsed(),
}),
}
}
}