use std::{fmt, time::Duration};
use serde_json::Value;
use crate::{app::mcp_server::webhooks::WebhookTarget, error_causes::with_causes};
const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
const FIRST_RETRY_GAP: Duration = Duration::from_secs(2);
const MAX_RETRY_GAP: Duration = Duration::from_secs(10 * 60);
const RETRY_HORIZON: Duration = Duration::from_secs(70 * 60);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct RetrySchedule {
pub(super) first_gap: Duration,
pub(super) max_gap: Duration,
pub(super) horizon: Duration,
}
impl RetrySchedule {
pub(super) const DEFAULT: Self = Self {
first_gap: FIRST_RETRY_GAP,
max_gap: MAX_RETRY_GAP,
horizon: RETRY_HORIZON,
};
pub(super) fn gaps(self) -> impl Iterator<Item = Duration> {
let mut gap = self.first_gap;
let mut elapsed = Duration::ZERO;
std::iter::from_fn(move || {
elapsed = elapsed.saturating_add(gap);
if elapsed > self.horizon {
return None;
}
let this = gap;
gap = gap.saturating_mul(2).min(self.max_gap);
Some(this)
})
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum Answer {
Status(u16),
Error(String),
}
impl fmt::Display for Answer {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Status(status) => write!(formatter, "answer {status}"),
Self::Error(error) => write!(formatter, "error: {error}"),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Verdict {
Delivered(u16),
Retry,
Stall,
}
pub(super) fn verdict(answer: &Answer) -> Verdict {
match *answer {
Answer::Status(status @ 200..=299) => Verdict::Delivered(status),
Answer::Status(408 | 429 | 500..=599) | Answer::Error(_) => Verdict::Retry,
Answer::Status(_) => Verdict::Stall,
}
}
pub(super) struct HttpPoster {
client: reqwest::Client,
}
impl HttpPoster {
pub(super) fn new() -> anyhow::Result<Self> {
let client = crate::reqwest_client_builder()
.timeout(REQUEST_TIMEOUT)
.redirect(reqwest::redirect::Policy::none())
.user_agent(concat!("rho/", env!("CARGO_PKG_VERSION")))
.build()?;
Ok(Self { client })
}
pub(super) async fn post(&self, target: &WebhookTarget, body: &Value) -> Answer {
let sent = self
.client
.post(&target.url)
.bearer_auth(&target.secret)
.header(reqwest::header::CONTENT_TYPE, "application/json")
.body(body.to_string())
.send()
.await;
match sent {
Ok(response) => Answer::Status(response.status().as_u16()),
Err(error) => Answer::Error(with_causes(&error.without_url())),
}
}
}
#[cfg(test)]
#[path = "delivery_tests.rs"]
mod tests;