hookburn_core/client.rs
1use crate::error::CoreError;
2use crate::retry::RetryPolicy;
3use reqwest::Client;
4use serde::Serialize;
5use std::time::Duration;
6
7/// A thin wrapper around [`reqwest::Client`] shared by all hookburn service crates.
8///
9/// Service crates (e.g. `discord_hook`, `slack_hook`) hold one of these,
10/// configure it at construction time, and call [`HttpClient::post_json`] to
11/// fire requests.
12///
13/// **TLS configuration** is the responsibility of the service crate — build a
14/// [`reqwest::Client`] with your chosen TLS backend and pass it in via
15/// [`HttpClient::with_reqwest`].
16#[derive(Clone, Debug)]
17pub struct HttpClient {
18 inner: Client,
19}
20
21impl HttpClient {
22 /// Create a client backed by a freshly-constructed [`reqwest::Client`].
23 ///
24 /// A 30-second request timeout is applied by default so that a slow or
25 /// unresponsive endpoint can never hang your application indefinitely.
26 /// Override this by building your own [`reqwest::Client`] and passing it
27 /// to [`HttpClient::with_reqwest`].
28 ///
29 /// # Panics
30 ///
31 /// Panics if the TLS backend is unavailable (e.g., no TLS feature enabled).
32 #[must_use]
33 pub fn new() -> Self {
34 let inner = Client::builder()
35 .timeout(Duration::from_secs(30))
36 .build()
37 .expect("failed to initialise reqwest client — TLS backend unavailable");
38 Self { inner }
39 }
40
41 /// Wrap an existing [`reqwest::Client`].
42 ///
43 /// Use this to share a connection pool or inject custom configuration
44 /// (timeouts, proxies, etc.) across your application.
45 #[must_use]
46 pub const fn with_reqwest(client: Client) -> Self {
47 Self { inner: client }
48 }
49
50 /// POST `body` serialized as JSON to `url` and return the raw response.
51 ///
52 /// When the **`tracing`** feature is enabled this method emits an
53 /// `info_span` named `hookburn.post_json` capturing the request URL,
54 /// HTTP status, and wall-clock latency.
55 ///
56 /// # Errors
57 ///
58 /// Returns `reqwest::Error` if the request fails, times out, or the
59 /// response cannot be parsed.
60 pub async fn post_json(
61 &self,
62 url: &str,
63 body: &(impl Serialize + Sync),
64 ) -> Result<reqwest::Response, reqwest::Error> {
65 #[cfg(not(feature = "tracing"))]
66 {
67 self.inner.post(url).json(body).send().await
68 }
69
70 #[cfg(feature = "tracing")]
71 {
72 use tracing::Instrument;
73 let span = tracing::info_span!("hookburn.post_json", url = %url);
74 let start = std::time::Instant::now();
75 let result = self
76 .inner
77 .post(url)
78 .json(body)
79 .send()
80 .instrument(span.clone())
81 .await;
82 let latency_ms = start.elapsed().as_millis();
83 let _enter = span.enter();
84 match &result {
85 Ok(resp) => tracing::info!(status = resp.status().as_u16(), latency_ms),
86 Err(err) => tracing::error!(error = %err, latency_ms),
87 }
88 result
89 }
90 }
91
92 /// POST `body` serialized as JSON to `url`, retrying on failure according
93 /// to the supplied [`RetryPolicy`].
94 ///
95 /// Each retry is separated by an exponentially increasing delay
96 /// (`base_delay × 2ⁿ`). When `policy.jitter` is `true` a random
97 /// fraction of the current step is added to the delay.
98 ///
99 /// Returns the first successful [`reqwest::Response`], or the error from
100 /// the final attempt if all attempts are exhausted.
101 ///
102 /// # Errors
103 ///
104 /// Returns `reqwest::Error` if all retry attempts fail.
105 ///
106 /// # Example
107 ///
108 /// ```rust,ignore
109 /// use hookburn_core::RetryPolicy;
110 ///
111 /// let policy = RetryPolicy { max_attempts: 4, ..Default::default() };
112 /// let resp = client.post_json_with_retry(url, &payload, &policy).await?;
113 /// ```
114 pub async fn post_json_with_retry(
115 &self,
116 url: &str,
117 body: &(impl Serialize + Sync),
118 policy: &RetryPolicy,
119 ) -> Result<reqwest::Response, CoreError> {
120 let max = policy.max_attempts.max(1);
121 let mut last_err: Option<reqwest::Error> = None;
122
123 for attempt in 0..max {
124 match self.post_json(url, body).await {
125 Ok(resp) => return Ok(resp),
126 Err(err) => {
127 let is_last = attempt + 1 >= max;
128 if !is_last {
129 let factor = 1u32 << attempt;
130 let base = policy.base_delay * factor;
131 let delay = if policy.jitter {
132 let nanos = std::time::SystemTime::now()
133 .duration_since(std::time::UNIX_EPOCH)
134 .unwrap_or_default()
135 .subsec_nanos();
136 let jitter = f64::from(nanos % 1_000) / 1_000.0;
137 base + Duration::from_secs_f64(base.as_secs_f64() * jitter)
138 } else {
139 base
140 };
141 tokio::time::sleep(delay).await;
142 }
143 last_err = Some(err);
144 }
145 }
146 }
147
148 Err(CoreError::RetryExhausted(
149 last_err
150 .map(|e| e.to_string())
151 .unwrap_or_else(|| "All retry attempts failed".to_string()),
152 ))
153 }
154
155 /// Access the underlying [`reqwest::Client`] for advanced use-cases.
156 #[must_use]
157 pub const fn inner(&self) -> &Client {
158 &self.inner
159 }
160}
161
162impl Default for HttpClient {
163
164 fn default() -> Self {
165 Self::new()
166 }
167}
168
169// ---------------------------------------------------------------------------
170// Domain validation utility
171// ---------------------------------------------------------------------------
172
173/// Return `true` if `url` uses HTTPS and its host exactly matches one of the
174/// `allowed` domains.
175///
176/// This is a convenience helper for service-crate constructors that want to
177/// enforce a fixed set of known-good endpoints. Matching is against the bare
178/// hostname only — port and path are excluded from the comparison.
179///
180/// # Example
181///
182/// ```rust
183/// use hookburn_core::is_allowed_domain;
184///
185/// assert!(is_allowed_domain("https://hooks.slack.com/services/T/B/X", &["hooks.slack.com"]));
186/// assert!(!is_allowed_domain("https://evil.com/hooks.slack.com", &["hooks.slack.com"]));
187/// assert!(!is_allowed_domain("http://hooks.slack.com/services/T/B/X", &["hooks.slack.com"]));
188/// ```
189#[must_use]
190pub fn is_allowed_domain(url: &str, allowed: &[&str]) -> bool {
191 let Some(rest) = url.strip_prefix("https://") else {
192 return false;
193 };
194 // host[:port]/path — take only the host[:port] segment, then strip port.
195 let host_port = rest.split('/').next().unwrap_or("");
196 let host = host_port.split(':').next().unwrap_or("");
197 allowed.contains(&host)
198}
199
200// ---------------------------------------------------------------------------
201// HttpClientBuilder
202// ---------------------------------------------------------------------------
203
204/// Builder for [`HttpClient`] with configurable timeout settings.
205///
206/// # Example
207///
208/// ```rust
209/// use hookburn_core::HttpClientBuilder;
210/// use std::time::Duration;
211///
212/// let client = HttpClientBuilder::new()
213/// .connect_timeout(Duration::from_secs(5))
214/// .request_timeout(Duration::from_secs(15))
215/// .build()
216/// .expect("failed to build client");
217/// ```
218#[derive(Default)]
219pub struct HttpClientBuilder {
220 connect_timeout: Option<Duration>,
221 request_timeout: Option<Duration>,
222}
223
224impl HttpClientBuilder {
225 /// New Client builder
226 #[must_use]
227 pub fn new() -> Self {
228 Self::default()
229 }
230
231 /// Set the maximum time allowed to establish a TCP connection.
232 #[must_use]
233 pub const fn connect_timeout(mut self, timeout: Duration) -> Self {
234 self.connect_timeout = Some(timeout);
235 self
236 }
237
238 /// Set the maximum time allowed for a complete request/response cycle.
239 ///
240 /// Defaults to 30 seconds when not set.
241 #[must_use]
242 pub const fn request_timeout(mut self, timeout: Duration) -> Self {
243 self.request_timeout = Some(timeout);
244 self
245 }
246
247 /// Build the [`HttpClient`].
248 ///
249 /// # Errors
250 ///
251 /// Returns an error if the underlying [`reqwest::Client`] cannot be
252 /// constructed (e.g. TLS backend unavailable).
253 pub fn build(self) -> Result<HttpClient, reqwest::Error> {
254 let mut builder =
255 Client::builder().timeout(self.request_timeout.unwrap_or(Duration::from_secs(30)));
256 if let Some(t) = self.connect_timeout {
257 builder = builder.connect_timeout(t);
258 }
259 Ok(HttpClient { inner: builder.build()? })
260 }
261}