1pub mod transport;
22
23use std::collections::HashMap;
24use std::sync::atomic::{AtomicUsize, Ordering};
25use std::sync::{Arc, Mutex, PoisonError};
26use std::time::Duration;
27
28use tokio::sync::{OwnedSemaphorePermit, Semaphore};
29use tokio::time::Instant;
30
31use crate::balance::Ejection;
32use crate::error::ClientError;
33use crate::retry::RetryBudget;
34use crate::retry::budget::Ledger;
35
36pub use transport::OriginTransport;
37
38const PRUNE_ABOVE: usize = 1024;
40
41#[derive(Clone, Copy, Debug, PartialEq, Eq)]
43pub enum Ticket {
44 Normal,
46 Probe,
48 Forced,
50}
51
52#[derive(Clone, Copy, Debug, PartialEq, Eq)]
54pub enum Outcome {
55 Success,
57 Failure,
59 Neutral,
62}
63
64pub const fn outcome_of<T>(result: &Result<T, ClientError>) -> Outcome {
66 match result {
67 Ok(_) => Outcome::Success,
68 Err(e) => match e {
69 ClientError::Http(_) | ClientError::HttpClient(_) | ClientError::Timeout(_) => {
70 Outcome::Failure
71 }
72 ClientError::UnexpectedStatus {
73 status: 502..=504, ..
74 } => Outcome::Failure,
75 ClientError::TooManyPendingRequests { .. }
76 | ClientError::CircuitOpen { .. }
77 | ClientError::Config(_)
78 | ClientError::InvalidEndpoint(_)
79 | ClientError::InsecureTransport(_)
80 | ClientError::InsecureWebhook(_)
81 | ClientError::CapabilityNotDeclared { .. }
82 | ClientError::InvalidAuthScheme(_) => Outcome::Neutral,
83 _ => Outcome::Success,
84 },
85 }
86}
87
88#[derive(Debug, Default)]
90struct Health {
91 failures: u32,
92 ejected_until: Option<Instant>,
93 ejections: u32,
94 probing: bool,
95}
96
97enum Change {
99 None,
100 Closed,
101 Ejected(Duration),
102}
103
104#[derive(Clone, Copy, Debug, PartialEq, Eq)]
106pub enum Standing {
107 Available(Ticket),
109 Ejected(Option<Instant>),
111}
112
113pub struct OriginState {
115 key: String,
116 ejection: Option<Ejection>,
117 health: Mutex<Health>,
118 in_flight: AtomicUsize,
119 cap: Option<(Arc<Semaphore>, usize)>,
120 budget: Option<Ledger>,
121}
122
123impl OriginState {
124 fn new(
125 key: String,
126 ejection: Option<Ejection>,
127 cap: Option<usize>,
128 budget: Option<RetryBudget>,
129 ) -> Self {
130 Self {
131 key,
132 ejection,
133 health: Mutex::new(Health::default()),
134 in_flight: AtomicUsize::new(0),
135 cap: cap.map(|n| (Arc::new(Semaphore::new(n)), n)),
136 budget: budget.map(Ledger::new),
137 }
138 }
139
140 fn health(&self) -> std::sync::MutexGuard<'_, Health> {
141 self.health.lock().unwrap_or_else(PoisonError::into_inner)
142 }
143
144 pub fn in_flight(&self) -> usize {
146 self.in_flight.load(Ordering::SeqCst)
147 }
148
149 pub fn standing(&self, now: Instant) -> Standing {
152 let mut health = self.health();
154 match health.ejected_until {
155 None => Standing::Available(Ticket::Normal),
156 Some(until) if now < until => Standing::Ejected(Some(until)),
157 Some(_) if health.probing => Standing::Ejected(None),
158 Some(_) => {
159 health.probing = true;
160 drop(health);
161 Standing::Available(Ticket::Probe)
162 }
163 }
164 }
165
166 pub fn is_ejected(&self, now: Instant) -> bool {
169 let health = self.health();
170 health
171 .ejected_until
172 .is_some_and(|until| now < until || health.probing)
173 }
174
175 pub fn ejected_until(&self) -> Option<Instant> {
177 self.health().ejected_until
178 }
179
180 pub fn release_probe(&self) {
183 self.health().probing = false;
184 }
185
186 pub fn admit(&self, now: Instant) -> Result<Ticket, ClientError> {
189 match self.standing(now) {
190 Standing::Available(ticket) => Ok(ticket),
191 Standing::Ejected(until) => Err(ClientError::CircuitOpen {
192 origin: self.key.clone(),
193 retry_after: until.map(|until| until.saturating_duration_since(now)),
194 }),
195 }
196 }
197
198 pub fn enter(self: &Arc<Self>, ticket: Ticket) -> Result<CallGuard, ClientError> {
206 let permit = match &self.cap {
207 Some((sem, limit)) => {
208 let Ok(permit) = Arc::clone(sem).try_acquire_owned() else {
209 if ticket == Ticket::Probe {
210 self.release_probe();
211 }
212 return Err(ClientError::TooManyPendingRequests { limit: *limit });
213 };
214 Some(permit)
215 }
216 None => None,
217 };
218 self.in_flight.fetch_add(1, Ordering::SeqCst);
219 Ok(CallGuard {
220 state: Arc::clone(self),
221 ticket,
222 recorded: false,
223 permit,
224 })
225 }
226
227 fn record(&self, ticket: Ticket, outcome: Outcome, now: Instant) {
229 let Some(policy) = self.ejection else {
230 return;
231 };
232 let mut health = self.health();
233 let change = Self::apply(&mut health, ticket, outcome, policy, now);
234 drop(health);
235 match change {
236 Change::None => {}
237 Change::Closed => {
238 trace_info!(origin = %self.key, "origin back in rotation");
239 }
240 Change::Ejected(_lasts) => {
241 trace_warn!(origin = %self.key, ?_lasts, "origin ejected after failing in a row");
242 }
243 }
244 }
245
246 fn apply(
249 health: &mut Health,
250 ticket: Ticket,
251 outcome: Outcome,
252 policy: Ejection,
253 now: Instant,
254 ) -> Change {
255 if ticket == Ticket::Probe {
256 health.probing = false;
257 }
258 match (ticket, outcome) {
259 (_, Outcome::Neutral) | (Ticket::Forced, Outcome::Failure) => Change::None,
260 (Ticket::Normal, Outcome::Success) => {
261 health.failures = 0;
262 Change::None
263 }
264 (Ticket::Probe | Ticket::Forced, Outcome::Success) => {
265 let was_ejected = health.ejected_until.is_some();
266 *health = Health::default();
267 if was_ejected {
268 Change::Closed
269 } else {
270 Change::None
271 }
272 }
273 (Ticket::Normal, Outcome::Failure) => {
274 if health.ejected_until.is_some() {
275 return Change::None;
276 }
277 health.failures += 1;
278 if health.failures < policy.consecutive_failures {
279 return Change::None;
280 }
281 Change::Ejected(Self::eject(health, policy, now))
282 }
283 (Ticket::Probe, Outcome::Failure) => Change::Ejected(Self::eject(health, policy, now)),
284 }
285 }
286
287 fn eject(health: &mut Health, policy: Ejection, now: Instant) -> Duration {
289 health.ejections = health.ejections.saturating_add(1);
290 let lasts = ejection_length(policy, health.ejections);
291 health.ejected_until = Some(now + lasts);
292 health.failures = 0;
293 lasts
294 }
295
296 pub const fn budget(&self) -> Option<&Ledger> {
298 self.budget.as_ref()
299 }
300
301 pub fn snapshot(&self, now: Instant) -> OriginSnapshot {
303 let health = self.health();
304 OriginSnapshot {
305 origin: self.key.clone(),
306 in_flight: self.in_flight(),
307 ejected_for: health
308 .ejected_until
309 .map(|until| until.saturating_duration_since(now)),
310 consecutive_failures: health.failures,
311 consecutive_ejections: health.ejections,
312 }
313 }
314}
315
316impl std::fmt::Debug for OriginState {
317 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
318 f.debug_struct("OriginState")
319 .field("origin", &self.key)
320 .field("in_flight", &self.in_flight())
321 .field("health", &*self.health())
322 .finish_non_exhaustive()
323 }
324}
325
326pub fn ejection_length(policy: Ejection, n: u32) -> Duration {
329 let doublings = n.saturating_sub(1).min(31);
330 policy
331 .base
332 .checked_mul(1_u32 << doublings)
333 .map_or(policy.max, |d| d.min(policy.max))
334}
335
336pub struct CallGuard {
339 state: Arc<OriginState>,
340 ticket: Ticket,
341 recorded: bool,
342 permit: Option<OwnedSemaphorePermit>,
343}
344
345impl CallGuard {
346 pub fn record(&mut self, outcome: Outcome) {
349 if !self.recorded {
350 self.recorded = true;
351 self.state.record(self.ticket, outcome, Instant::now());
352 }
353 }
354
355 pub fn release_permit(&mut self) {
358 self.permit = None;
359 }
360}
361
362impl Drop for CallGuard {
363 fn drop(&mut self) {
364 self.record(Outcome::Neutral);
365 self.state.in_flight.fetch_sub(1, Ordering::SeqCst);
366 }
367}
368
369impl std::fmt::Debug for CallGuard {
370 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
371 f.debug_struct("CallGuard")
372 .field("origin", &self.state.key)
373 .field("ticket", &self.ticket)
374 .field("recorded", &self.recorded)
375 .finish_non_exhaustive()
376 }
377}
378
379#[derive(Clone, Debug, PartialEq, Eq)]
382#[non_exhaustive]
383pub struct OriginSnapshot {
384 pub origin: String,
387 pub in_flight: usize,
389 pub ejected_for: Option<Duration>,
393 pub consecutive_failures: u32,
395 pub consecutive_ejections: u32,
397}
398
399pub struct Origins {
401 ejection: Option<Ejection>,
402 cap: Option<usize>,
403 budget: Option<RetryBudget>,
404 map: Mutex<HashMap<String, Arc<OriginState>>>,
405}
406
407impl Origins {
408 pub fn new(
409 ejection: Option<Ejection>,
410 cap: Option<usize>,
411 budget: Option<RetryBudget>,
412 ) -> Self {
413 Self {
414 ejection,
415 cap,
416 budget,
417 map: Mutex::new(HashMap::new()),
418 }
419 }
420
421 pub const fn enforces(&self) -> bool {
424 self.ejection.is_some() || self.cap.is_some()
425 }
426
427 pub const fn has_budget(&self) -> bool {
429 self.budget.is_some()
430 }
431
432 pub fn get(&self, key: &str) -> Arc<OriginState> {
434 let mut map = self.map.lock().unwrap_or_else(PoisonError::into_inner);
435 if let Some(state) = map.get(key) {
436 return Arc::clone(state);
437 }
438 if map.len() >= PRUNE_ABOVE {
439 map.retain(|_, s| Arc::strong_count(s) > 1 || s.ejected_until().is_some());
441 }
442 let state = Arc::new(OriginState::new(
443 key.to_owned(),
444 self.ejection,
445 self.cap,
446 self.budget,
447 ));
448 map.insert(key.to_owned(), Arc::clone(&state));
449 drop(map);
450 state
451 }
452
453 pub fn snapshot(&self) -> Vec<OriginSnapshot> {
455 let now = Instant::now();
456 let map = self.map.lock().unwrap_or_else(PoisonError::into_inner);
457 let mut all: Vec<OriginSnapshot> = map.values().map(|s| s.snapshot(now)).collect();
458 drop(map);
459 all.sort_by(|a, b| a.origin.cmp(&b.origin));
460 all
461 }
462}
463
464impl std::fmt::Debug for Origins {
465 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
466 f.debug_struct("Origins")
467 .field("ejection", &self.ejection)
468 .field("cap", &self.cap)
469 .field("budget", &self.budget)
470 .field("origins", &self.snapshot())
471 .finish_non_exhaustive()
472 }
473}
474
475pub fn origin_key(url: &str, pinned: Option<std::net::SocketAddr>) -> Option<String> {
478 let uri: hyper::Uri = url.parse().ok()?;
479 let scheme = uri.scheme_str()?.to_ascii_lowercase();
480 let host = uri.host()?.to_ascii_lowercase();
481 let port = uri
482 .port_u16()
483 .unwrap_or(if scheme == "https" { 443 } else { 80 });
484 let origin = format!("{scheme}://{host}:{port}");
485 Some(pinned.map_or_else(|| origin.clone(), |addr| format!("{origin} via {addr}")))
486}
487
488#[cfg(test)]
489mod tests;