use super::*;
impl Display for TimeoutError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.write_str(ERR_DEADLINE_EXCEEDED)
}
}
impl Error for TimeoutError {}
impl PrefixTimeout {
pub fn new<P>(prefix: P, timeout_ms: u64) -> Self
where
P: Into<String>,
{
Self {
prefix: prefix.into(),
timeout_ms,
}
}
}
impl RequestDeadline {
#[inline(always)]
pub fn from_instant(now: Instant, budget_ms: u64) -> Self {
let dur: Duration = Duration::from_millis(budget_ms);
let deadline: Instant = now.checked_add(dur).unwrap_or(now);
Self {
started_at: now,
deadline,
budget_ms,
}
}
#[inline]
pub fn from_context(ctx: &Context) -> Option<Self> {
ctx.try_get_attribute::<Self, _>(ATTR_REQUEST_DEADLINE)
}
#[inline(always)]
pub fn remaining(&self) -> Duration {
self.get_deadline()
.saturating_duration_since(Instant::now())
}
#[inline(always)]
pub fn elapsed(&self) -> Duration {
self.get_started_at().elapsed()
}
#[inline(always)]
pub fn is_expired(&self) -> bool {
Instant::now() >= self.get_deadline()
}
}
impl Default for TimeoutConfig {
fn default() -> Self {
Self {
default_timeout_ms: DEFAULT_TIMEOUT_MS,
prefix_timeouts: Vec::new(),
honor_client_header: true,
client_header_name: DEFAULT_TIMEOUT_HEADER.to_owned(),
expose_remaining_header: false,
timeout_status: HttpStatus::GatewayTimeout,
timeout_content_type: DEFAULT_TIMEOUT_CONTENT_TYPE.to_owned(),
timeout_body: DEFAULT_TIMEOUT_BODY.to_vec(),
}
}
}
impl TimeoutConfig {
pub fn with_default_timeout_ms(mut self, timeout_ms: u64) -> Self {
self.set_default_timeout_ms(timeout_ms);
self
}
pub fn with_prefix_timeout<P>(mut self, prefix: P, timeout_ms: u64) -> Self
where
P: Into<String>,
{
self.get_mut_prefix_timeouts()
.push(PrefixTimeout::new(prefix, timeout_ms));
self
}
pub fn with_honor_client_header(mut self, enabled: bool) -> Self {
self.set_honor_client_header(enabled);
self
}
pub fn with_expose_remaining_header(mut self, enabled: bool) -> Self {
self.set_expose_remaining_header(enabled);
self
}
}
impl TimeoutPlugin {
pub fn new(config: TimeoutConfig) -> Self {
let mut prefix_rules: Vec<(String, u64)> = config
.get_prefix_timeouts()
.iter()
.map(|r: &PrefixTimeout| (normalize_prefix(r.get_prefix()), r.get_timeout_ms()))
.collect();
prefix_rules.sort_by_key(|a: &(String, u64)| Reverse(a.0.len()));
let client_header_lower: String =
config.get_client_header_name().trim().to_ascii_lowercase();
Self {
config,
prefix_rules: prefix_rules.into_boxed_slice(),
client_header_lower,
}
}
pub fn init(config: TimeoutConfig) -> &'static Self {
TIMEOUT_PLUGIN.get_or_init(|| Self::new(config))
}
#[inline(always)]
pub fn get() -> Option<&'static Self> {
TIMEOUT_PLUGIN.get()
}
pub fn get_config(&self) -> &TimeoutConfig {
let Self { config, .. } = self;
config
}
#[inline]
pub fn resolve_budget_ms(&self, request: &Request) -> u64 {
let Self {
config,
prefix_rules,
client_header_lower,
..
} = self;
let mut base_ms: u64 = config.get_default_timeout_ms();
if !prefix_rules.is_empty() {
let path: &str = request.get_path();
for (prefix, ms) in prefix_rules.iter() {
if path_matches_prefix(path, prefix) {
base_ms = *ms;
break;
}
}
}
if base_ms == 0 {
return 0;
}
if config.get_honor_client_header()
&& !client_header_lower.is_empty()
&& let Some(values) = request.get_headers().get(client_header_lower.as_str())
&& let Some(raw) = values.back()
&& let Some(client_ms) = parse_timeout_header_ms(raw)
{
return base_ms.min(client_ms);
}
base_ms
}
pub fn apply_timeout_response(&self, response: &mut Response) {
let Self { config, .. } = self;
response
.set_status_code(config.get_timeout_status().code())
.set_header(CONTENT_TYPE, config.get_timeout_content_type())
.set_body(config.get_timeout_body().clone());
}
}
impl ServerHook for TimeoutRequestHook {
#[inline(always)]
async fn new(_: &mut Stream, _: &mut Context) -> Self {
Self
}
#[inline(always)]
async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
let Some(plugin) = TimeoutPlugin::get() else {
return Status::Continue;
};
let budget_ms: u64 = plugin.resolve_budget_ms(ctx.get_request());
if budget_ms > 0 {
let deadline: RequestDeadline =
RequestDeadline::from_instant(Instant::now(), budget_ms);
ctx.set_attribute(ATTR_REQUEST_DEADLINE, deadline);
}
Status::Continue
}
}
impl ServerHook for TimeoutResponseHook {
#[inline(always)]
async fn new(_: &mut Stream, _: &mut Context) -> Self {
Self
}
#[inline(always)]
async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
let Some(plugin) = TimeoutPlugin::get() else {
return Status::Continue;
};
let Some(deadline) = ctx.try_get_attribute_ref::<RequestDeadline, _>(ATTR_REQUEST_DEADLINE)
else {
return Status::Continue;
};
if deadline.is_expired() {
plugin.apply_timeout_response(ctx.get_mut_response());
} else if plugin.get_config().get_expose_remaining_header() {
let mut rem_ms: u64 = deadline.remaining().as_millis().min(u64::MAX as u128) as u64;
let mut buf: [u8; 20] = [0u8; 20];
let mut pos: usize = buf.len();
if rem_ms == 0 {
pos -= 1;
buf[pos] = b'0';
} else {
while rem_ms > 0 {
pos -= 1;
buf[pos] = b'0' + ((rem_ms % 10) as u8);
rem_ms /= 10;
}
}
if let Ok(rem_str) = from_utf8(&buf[pos..]) {
ctx.get_mut_response()
.set_header(HEADER_TIMEOUT_REMAINING_MS, rem_str);
}
}
Status::Continue
}
}