|
| 1 | +//! Reject certain requests as instance load reaches capacity. |
| 2 | +//! |
| 3 | +//! The primary goal of this middleware is to avoid starving the download endpoint of resources. |
| 4 | +//! When bots send many parallel requests that run slow database queries, download requests may |
| 5 | +//! block and eventually timeout waiting for a database connection. |
| 6 | +//! |
| 7 | +//! Bots must continue to respect our crawler policy, but until we can manually block bad clients |
| 8 | +//! we should avoid dropping download requests even if that means rejecting some legitimate |
| 9 | +//! requests to other endpoints. |
| 10 | +
|
| 11 | +use std::sync::atomic::{AtomicUsize, Ordering}; |
| 12 | + |
| 13 | +use super::prelude::*; |
| 14 | +use conduit::{RequestExt, StatusCode}; |
| 15 | + |
| 16 | +#[derive(Default)] |
| 17 | +pub(super) struct BalanceCapacity { |
| 18 | + handler: Option<Box<dyn Handler>>, |
| 19 | + capacity: usize, |
| 20 | + in_flight_requests: AtomicUsize, |
| 21 | + log_at_percentage: usize, |
| 22 | + throttle_at_percentage: usize, |
| 23 | + dl_only_at_percentage: usize, |
| 24 | +} |
| 25 | + |
| 26 | +impl BalanceCapacity { |
| 27 | + pub fn new(capacity: usize) -> Self { |
| 28 | + Self { |
| 29 | + handler: None, |
| 30 | + capacity, |
| 31 | + in_flight_requests: AtomicUsize::new(0), |
| 32 | + log_at_percentage: read_env_percentage("WEB_CAPACITY_LOG_PCT", 20), |
| 33 | + throttle_at_percentage: read_env_percentage("WEB_CAPACITY_THROTTLE_PCT", 70), |
| 34 | + dl_only_at_percentage: read_env_percentage("WEB_CAPACITY_DL_ONLY_PCT", 80), |
| 35 | + } |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +impl AroundMiddleware for BalanceCapacity { |
| 40 | + fn with_handler(&mut self, handler: Box<dyn Handler>) { |
| 41 | + self.handler = Some(handler); |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +impl Handler for BalanceCapacity { |
| 46 | + fn call(&self, request: &mut dyn RequestExt) -> AfterResult { |
| 47 | + // The _drop_on_exit ensures the counter is decremented for all exit paths (including panics) |
| 48 | + let (_drop_on_exit, count) = RequestCounter::add_one(&self.in_flight_requests); |
| 49 | + let handler = self.handler.as_ref().unwrap(); |
| 50 | + let load = 100 * count / self.capacity; |
| 51 | + |
| 52 | + // Begin logging request count so early stages of load increase can be located |
| 53 | + if load >= self.log_at_percentage { |
| 54 | + super::log_request::add_custom_metadata(request, "in_flight_requests", count); |
| 55 | + } |
| 56 | + |
| 57 | + // Download requests are always accepted |
| 58 | + if request.path().starts_with("/api/v1/crates/") && request.path().ends_with("/download") { |
| 59 | + return handler.call(request); |
| 60 | + } |
| 61 | + |
| 62 | + // Reject read-only requests as load nears capacity. Bots are likely to send only safe |
| 63 | + // requests and this helps prioritize requests that users may be reluctant to retry. |
| 64 | + if load >= self.throttle_at_percentage && request.method().is_safe() { |
| 65 | + return over_capacity_response(request); |
| 66 | + } |
| 67 | + |
| 68 | + // As load reaches capacity, all non-download requests are rejected |
| 69 | + if load >= self.dl_only_at_percentage { |
| 70 | + return over_capacity_response(request); |
| 71 | + } |
| 72 | + |
| 73 | + handler.call(request) |
| 74 | + } |
| 75 | +} |
| 76 | + |
| 77 | +fn over_capacity_response(request: &mut dyn RequestExt) -> AfterResult { |
| 78 | + // TODO: Generate an alert so we can investigate |
| 79 | + super::log_request::add_custom_metadata(request, "cause", "over capacity"); |
| 80 | + let body = "Service temporarily unavailable"; |
| 81 | + Response::builder() |
| 82 | + .status(StatusCode::SERVICE_UNAVAILABLE) |
| 83 | + .header(header::CONTENT_LENGTH, body.len()) |
| 84 | + .body(Body::from_static(body.as_bytes())) |
| 85 | + .map_err(box_error) |
| 86 | +} |
| 87 | + |
| 88 | +fn read_env_percentage(name: &str, default: usize) -> usize { |
| 89 | + if let Ok(value) = std::env::var(name) { |
| 90 | + value.parse().unwrap_or(default) |
| 91 | + } else { |
| 92 | + default |
| 93 | + } |
| 94 | +} |
| 95 | + |
| 96 | +// FIXME(JTG): I've copied the following from my `conduit-hyper` crate. Once we transition from |
| 97 | +// `civet`, we could pass the in_flight_request count from `condut-hyper` via a request extension. |
| 98 | + |
| 99 | +/// A struct that stores a reference to an atomic counter so it can be decremented when dropped |
| 100 | +struct RequestCounter<'a> { |
| 101 | + counter: &'a AtomicUsize, |
| 102 | +} |
| 103 | + |
| 104 | +impl<'a> RequestCounter<'a> { |
| 105 | + fn add_one(counter: &'a AtomicUsize) -> (Self, usize) { |
| 106 | + let previous = counter.fetch_add(1, Ordering::SeqCst); |
| 107 | + (Self { counter }, previous + 1) |
| 108 | + } |
| 109 | +} |
| 110 | + |
| 111 | +impl<'a> Drop for RequestCounter<'a> { |
| 112 | + fn drop(&mut self) { |
| 113 | + self.counter.fetch_sub(1, Ordering::SeqCst); |
| 114 | + } |
| 115 | +} |
0 commit comments