Skip to main content

gitpoulpi_hosting/
conditional.rs

1//! Conditional requests and rate-limit back-off, as a transport decorator.
2//!
3//! [`ConditionalTransport`] wraps any [`HttpTransport`] and:
4//!
5//! * remembers the `ETag` of every successful GET and sends it back as
6//!   `If-None-Match`; a `304` is answered from the cached body (so callers
7//!   see a normal 200) and, on GitHub, costs no rate limit;
8//! * reads each host's rate-limit headers -- interpreted per API family,
9//!   because the six products do not mean the same thing by them (see
10//!   [`rate_observation`]) -- and, once a host says "none left", refuses
11//!   further requests to it until the reset time instead of hammering it
12//!   ([`Error::RateLimited`]);
13//! * exposes a short human note ([`ConditionalTransport::rate_note`]) when
14//!   a host is close to its limit, for the TUI's status line.
15//!
16//! Every client is rebuilt per refresh in the TUI, so the cache lives here
17//! (one shared instance), not in the clients.
18
19use std::collections::{BTreeMap, HashMap};
20use std::sync::{Arc, Mutex};
21
22use crate::http::{HttpRequest, HttpResponse, HttpTransport, Method};
23use crate::{Error, Result};
24use gitpoulpi_config::ApiFamily;
25
26/// Below this many calls left, [`ConditionalTransport::rate_note`] speaks up.
27const LOW_WATER: u64 = 20;
28
29/// A bound on cached bodies, so a long session cannot grow without limit.
30/// The Radar asks about five lists per repository, so 64 was gone after a
31/// dozen repositories; when full, the entry untouched the longest goes, not
32/// every entry.
33const MAX_ENTRIES: usize = 512;
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36struct RateState {
37    remaining: u64,
38    /// Unix seconds when the window resets (or the `Retry-After` deadline).
39    reset_at: u64,
40    /// The host said it is close to its limit without giving a count
41    /// (Bitbucket `X-RateLimit-NearLimit`).
42    near: bool,
43}
44
45/// What one answer says about the host's budget, per family.
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub(crate) struct RateObservation {
48    pub remaining: u64,
49    pub reset_at: u64,
50    pub near: bool,
51    /// Why the host is throttling, when it says (`X-RateLimit-Resource`,
52    /// `RateLimit-Reason`), for the status note.
53    pub reason: Option<String>,
54}
55
56struct Cached {
57    etag: String,
58    response: HttpResponse,
59    /// When it was stored or last confirmed (`304`): the smallest goes first.
60    used: u64,
61}
62
63pub struct ConditionalTransport {
64    inner: Arc<dyn HttpTransport>,
65    now: fn() -> u64,
66    cache: Mutex<HashMap<String, Cached>>,
67    rates: Mutex<BTreeMap<String, RateState>>,
68    /// Why a host last throttled us (shown in the note).
69    reasons: Mutex<BTreeMap<String, String>>,
70    /// Hosts whose family is known from a configured profile rather than
71    /// from the public API host names.
72    families: Mutex<HashMap<String, ApiFamily>>,
73    hits: std::sync::atomic::AtomicU64,
74    /// Ticks once per cache write or confirmation; orders `Cached::used`.
75    tick: std::sync::atomic::AtomicU64,
76}
77
78fn unix_now() -> u64 {
79    std::time::SystemTime::now()
80        .duration_since(std::time::UNIX_EPOCH)
81        .map(|d| d.as_secs())
82        .unwrap_or(0)
83}
84
85fn host_of(url: &str) -> String {
86    url.split("://")
87        .nth(1)
88        .unwrap_or(url)
89        .split('/')
90        .next()
91        .unwrap_or("")
92        .to_ascii_lowercase()
93}
94
95fn header<'a>(response: &'a HttpResponse, name: &str) -> Option<&'a str> {
96    response
97        .headers
98        .iter()
99        .find(|(k, _)| k.eq_ignore_ascii_case(name))
100        .map(|(_, v)| v.trim())
101}
102
103/// The family a public API host name belongs to. Anything unknown is read
104/// the GitHub/GitLab way (see [`ConditionalTransport::register_host`] for
105/// self-hosted instances).
106pub(crate) fn family_of_public_host(host: &str) -> ApiFamily {
107    let host = host.split(':').next().unwrap_or(host);
108    if host == "dev.azure.com" || host.ends_with(".visualstudio.com") {
109        ApiFamily::AzureDevops
110    } else if host == "bitbucket.org" || host.ends_with(".bitbucket.org") {
111        ApiFamily::Bitbucket
112    } else if host == "trello.com" || host.ends_with(".trello.com") {
113        ApiFamily::Trello
114    } else if host.ends_with(".atlassian.net") || host == "api.atlassian.com" {
115        ApiFamily::Jira
116    } else if host == "linear.app" || host.ends_with(".linear.app") {
117        ApiFamily::Linear
118    } else if host.ends_with(".youtrack.cloud") || host.ends_with(".myjetbrains.com") {
119        ApiFamily::YouTrack
120    } else if host == "codeberg.org" || host == "gitea.com" {
121        ApiFamily::Gitea
122    } else if host == "gitlab.com" || host.ends_with(".gitlab.com") {
123        ApiFamily::Gitlab
124    } else {
125        ApiFamily::Github
126    }
127}
128
129fn number(response: &HttpResponse, names: &[&str]) -> Option<u64> {
130    names
131        .iter()
132        .find_map(|n| header(response, n))
133        .and_then(|v| v.parse::<u64>().ok())
134}
135
136/// Reads one answer's rate-limit headers the way its family means them.
137///
138/// * GitHub / GitLab: `x-ratelimit-*` / `ratelimit-*` call counts, plus
139///   `Retry-After` on a 429/403.
140/// * Azure DevOps: `X-RateLimit-Remaining` counts TSTUs (a cost unit), not
141///   calls, so it is never read as a budget; only `Retry-After` on a 429
142///   blocks, and `X-RateLimit-Resource` is kept as the reason.
143/// * Bitbucket: `X-RateLimit-NearLimit: true` is the only early warning;
144///   a 429 blocks (default one minute).
145/// * Jira: a 429 with `Retry-After` blocks until then; `RateLimit-Reason`
146///   is the reason. No count is read.
147/// * Linear: `x-ratelimit-requests-remaining` is the call count and
148///   `x-ratelimit-requests-reset` the epoch second the bucket refills.
149/// * YouTrack, Redmine, Gerrit: a 429 with `Retry-After` blocks; no count is read.
150/// * Trello: `x-rate-limit-api-token-remaining` is the call count; the
151///   bucket refills after `x-rate-limit-api-token-interval-ms`.
152pub(crate) fn rate_observation(
153    family: ApiFamily,
154    response: &HttpResponse,
155    now: u64,
156) -> Option<RateObservation> {
157    let retry_after = number(response, &["retry-after"]);
158    let throttled = is_rate_limited_for(family, response);
159    let blocked = |default_wait: u64, reason: Option<&str>| RateObservation {
160        remaining: 0,
161        reset_at: now + retry_after.unwrap_or(default_wait),
162        near: false,
163        reason: reason.map(str::to_string),
164    };
165    match family {
166        ApiFamily::Github | ApiFamily::Gitlab => {
167            let remaining = number(response, &["x-ratelimit-remaining", "ratelimit-remaining"]);
168            let reset = number(response, &["x-ratelimit-reset", "ratelimit-reset"]);
169            match (remaining, reset, retry_after) {
170                (_, _, Some(secs)) if response.status == 429 || response.status == 403 => {
171                    Some(RateObservation {
172                        remaining: 0,
173                        reset_at: now + secs,
174                        near: false,
175                        reason: None,
176                    })
177                }
178                (Some(rem), Some(reset), _) => Some(RateObservation {
179                    remaining: rem,
180                    reset_at: reset,
181                    near: false,
182                    reason: None,
183                }),
184                (Some(rem), None, _) => Some(RateObservation {
185                    remaining: rem,
186                    reset_at: now + 60,
187                    near: false,
188                    reason: None,
189                }),
190                _ => None,
191            }
192        }
193        ApiFamily::AzureDevops => {
194            throttled.then(|| blocked(60, header(response, "x-ratelimit-resource")))
195        }
196        ApiFamily::Jira => throttled.then(|| blocked(60, header(response, "ratelimit-reason"))),
197        // No headers of their own: a rate limit is a proxy's or the
198        // instance's 429 (Codeberg's anti-abuse layer), with `Retry-After`.
199        ApiFamily::Gitea => throttled.then(|| blocked(60, None)),
200        ApiFamily::YouTrack | ApiFamily::Redmine | ApiFamily::Gerrit => {
201            throttled.then(|| blocked(60, None))
202        }
203        ApiFamily::Linear => {
204            if throttled {
205                return Some(blocked(60, None));
206            }
207            let remaining = number(response, &["x-ratelimit-requests-remaining"])?;
208            let reset = number(response, &["x-ratelimit-requests-reset"]).unwrap_or(now + 60);
209            Some(RateObservation {
210                remaining,
211                reset_at: reset,
212                near: false,
213                reason: None,
214            })
215        }
216        ApiFamily::Bitbucket => {
217            if throttled {
218                Some(blocked(60, None))
219            } else if header(response, "x-ratelimit-nearlimit")
220                .is_some_and(|v| v.eq_ignore_ascii_case("true"))
221            {
222                Some(RateObservation {
223                    remaining: LOW_WATER,
224                    reset_at: now + 60,
225                    near: true,
226                    reason: None,
227                })
228            } else {
229                None
230            }
231        }
232        ApiFamily::Trello => {
233            let interval = number(response, &["x-rate-limit-api-token-interval-ms"])
234                .map(|ms| ms.div_ceil(1000))
235                .unwrap_or(10);
236            if throttled {
237                return Some(RateObservation {
238                    remaining: 0,
239                    reset_at: now + retry_after.unwrap_or(interval),
240                    near: false,
241                    reason: None,
242                });
243            }
244            number(response, &["x-rate-limit-api-token-remaining"]).map(|remaining| {
245                RateObservation {
246                    remaining,
247                    reset_at: now + interval,
248                    near: false,
249                    reason: None,
250                }
251            })
252        }
253        // A folder has no rate limit.
254        ApiFamily::LocalMarkdown => None,
255    }
256}
257
258/// Reads both hosts' spellings: GitHub `x-ratelimit-*`, GitLab
259/// `ratelimit-*`, plus `Retry-After` (seconds) on a throttled answer.
260pub(crate) fn rate_state(response: &HttpResponse, now: u64) -> Option<(u64, u64)> {
261    rate_observation(ApiFamily::Github, response, now).map(|o| (o.remaining, o.reset_at))
262}
263
264/// Is this answer the host's "slow down" (as opposed to a scope problem)?
265pub(crate) fn is_rate_limited(response: &HttpResponse) -> bool {
266    is_rate_limited_for(ApiFamily::Github, response)
267}
268
269/// [`is_rate_limited`] for one family: Azure DevOps, Jira, Bitbucket and
270/// Trello only ever say it with a 429 (a 403 there is a permission).
271pub(crate) fn is_rate_limited_for(family: ApiFamily, response: &HttpResponse) -> bool {
272    match family {
273        ApiFamily::Github | ApiFamily::Gitlab => match response.status {
274            429 => true,
275            403 => {
276                header(response, "x-ratelimit-remaining") == Some("0")
277                    || header(response, "retry-after").is_some()
278            }
279            _ => false,
280        },
281        _ => response.status == 429,
282    }
283}
284
285pub(crate) fn wait_text(secs: u64) -> String {
286    match secs {
287        0..=59 => format!("{secs}s"),
288        60..=3599 => format!("{}m", secs.div_ceil(60)),
289        _ => format!("{}h", secs.div_ceil(3600)),
290    }
291}
292
293impl ConditionalTransport {
294    pub fn new(inner: Arc<dyn HttpTransport>) -> Self {
295        Self::with_clock(inner, unix_now)
296    }
297
298    /// Like [`Self::new`] with an injected clock, for tests.
299    pub fn with_clock(inner: Arc<dyn HttpTransport>, now: fn() -> u64) -> Self {
300        Self {
301            inner,
302            now,
303            cache: Mutex::new(HashMap::new()),
304            rates: Mutex::new(BTreeMap::new()),
305            reasons: Mutex::new(BTreeMap::new()),
306            families: Mutex::new(HashMap::new()),
307            hits: Default::default(),
308            tick: Default::default(),
309        }
310    }
311
312    /// Tells the transport which family a (self-hosted) host belongs to, so
313    /// its headers are read the right way: call it for each configured
314    /// profile. Public API hosts need no registration.
315    pub fn register_host(&self, host: &str, family: ApiFamily) {
316        self.families
317            .lock()
318            .unwrap()
319            .insert(host.to_ascii_lowercase(), family);
320    }
321
322    fn family_of(&self, host: &str) -> ApiFamily {
323        self.families
324            .lock()
325            .unwrap()
326            .get(host)
327            .copied()
328            .unwrap_or_else(|| family_of_public_host(host))
329    }
330
331    /// How many requests were answered `304 Not Modified` so far.
332    pub fn not_modified_count(&self) -> u64 {
333        self.hits.load(std::sync::atomic::Ordering::Relaxed)
334    }
335
336    /// A short status-line message when some host is low on (or out of)
337    /// calls, else `None`.
338    pub fn rate_note(&self) -> Option<String> {
339        let now = (self.now)();
340        let rates = self.rates.lock().unwrap();
341        let reasons = self.reasons.lock().unwrap();
342        rates
343            .iter()
344            .filter(|(_, s)| s.reset_at > now && s.remaining <= LOW_WATER)
345            .map(|(host, s)| {
346                let wait = wait_text(s.reset_at - now);
347                if s.remaining == 0 {
348                    match reasons.get(host) {
349                        Some(why) => {
350                            format!("{host}: rate limit reached ({why}), paused for {wait}")
351                        }
352                        None => format!("{host}: rate limit reached, paused for {wait}"),
353                    }
354                } else if s.near {
355                    format!("{host}: rate limit nearly reached, resets in {wait}")
356                } else {
357                    format!(
358                        "{host}: rate limit low ({} left), resets in {wait}",
359                        s.remaining
360                    )
361                }
362            })
363            .next()
364    }
365
366    fn blocked(&self, host: &str) -> Option<u64> {
367        let now = (self.now)();
368        let rates = self.rates.lock().unwrap();
369        rates
370            .get(host)
371            .filter(|s| s.remaining == 0 && s.reset_at > now)
372            .map(|s| s.reset_at - now)
373    }
374
375    fn cache_key(request: &HttpRequest) -> String {
376        let auth = request
377            .headers
378            .iter()
379            .find(|(k, _)| k.eq_ignore_ascii_case("authorization"))
380            .map(|(_, v)| v.as_str())
381            .unwrap_or("");
382        format!("{auth}\n{}", request.url)
383    }
384}
385
386#[async_trait::async_trait]
387impl HttpTransport for ConditionalTransport {
388    async fn send(&self, mut request: HttpRequest) -> Result<HttpResponse> {
389        let host = host_of(&request.url);
390        let family = self.family_of(&host);
391        let is_get = request.method == Method::Get;
392        if let Some(wait) = self.blocked(&host) {
393            return Err(Error::RateLimited {
394                host,
395                retry_in_secs: wait,
396            });
397        }
398        let key = Self::cache_key(&request);
399        if is_get {
400            if let Some(c) = self.cache.lock().unwrap().get(&key) {
401                request
402                    .headers
403                    .push(("If-None-Match".to_string(), c.etag.clone()));
404            }
405        }
406        let response = self.inner.send(request).await?;
407        let now = (self.now)();
408        let observed = rate_observation(family, &response, now);
409        match &observed {
410            Some(o) => {
411                self.rates.lock().unwrap().insert(
412                    host.clone(),
413                    RateState {
414                        remaining: o.remaining,
415                        reset_at: o.reset_at,
416                        near: o.near,
417                    },
418                );
419                match &o.reason {
420                    Some(why) => {
421                        self.reasons
422                            .lock()
423                            .unwrap()
424                            .insert(host.clone(), why.clone());
425                    }
426                    None => {
427                        self.reasons.lock().unwrap().remove(&host);
428                    }
429                }
430            }
431            // A calm answer from a family that reports nothing when calm
432            // ends an earlier warning; GitHub/GitLab keep their old rule
433            // (a header-less answer leaves the last count alone).
434            None if !matches!(family, ApiFamily::Github | ApiFamily::Gitlab)
435                && !is_rate_limited_for(family, &response) =>
436            {
437                self.rates.lock().unwrap().remove(&host);
438                self.reasons.lock().unwrap().remove(&host);
439            }
440            None => {}
441        }
442        if is_rate_limited_for(family, &response) {
443            let wait = observed
444                .as_ref()
445                .map(|o| o.reset_at.saturating_sub(now))
446                .unwrap_or(60)
447                .max(1);
448            // Make sure the back-off sticks even if the host sent no
449            // remaining-count header.
450            self.rates.lock().unwrap().insert(
451                host.clone(),
452                RateState {
453                    remaining: 0,
454                    reset_at: now + wait,
455                    near: false,
456                },
457            );
458            return Err(Error::RateLimited {
459                host,
460                retry_in_secs: wait,
461            });
462        }
463        if is_get && response.status == 304 {
464            if let Some(c) = self.cache.lock().unwrap().get_mut(&key) {
465                self.hits.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
466                c.used = self.tick.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
467                let mut cached = c.response.clone();
468                // Keep the fresh pagination/rate headers, serve the old body.
469                for (k, v) in response.headers {
470                    cached.headers.insert(k, v);
471                }
472                return Ok(cached);
473            }
474        }
475        if is_get && response.status == 200 {
476            if let Some(etag) = header(&response, "etag") {
477                let mut cache = self.cache.lock().unwrap();
478                if cache.len() >= MAX_ENTRIES && !cache.contains_key(&key) {
479                    let oldest = cache
480                        .iter()
481                        .min_by_key(|(_, c)| c.used)
482                        .map(|(k, _)| k.clone());
483                    if let Some(oldest) = oldest {
484                        cache.remove(&oldest);
485                    }
486                }
487                cache.insert(
488                    key,
489                    Cached {
490                        etag: etag.to_string(),
491                        response: response.clone(),
492                        used: self.tick.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
493                    },
494                );
495            }
496        }
497        Ok(response)
498    }
499}
500
501#[cfg(feature = "network")]
502static SHARED: std::sync::OnceLock<Arc<ConditionalTransport>> = std::sync::OnceLock::new();
503
504/// The process-wide caching network transport (created on first use).
505#[cfg(feature = "network")]
506pub fn shared_network_transport() -> Result<Arc<ConditionalTransport>> {
507    if let Some(t) = SHARED.get() {
508        return Ok(t.clone());
509    }
510    let inner = Arc::new(crate::http::ReqwestTransport::new()?);
511    let t = Arc::new(ConditionalTransport::new(inner));
512    Ok(SHARED.get_or_init(|| t).clone())
513}
514
515/// The shared transport's rate note, without creating the transport.
516#[cfg(feature = "network")]
517pub fn shared_rate_note() -> Option<String> {
518    SHARED.get().and_then(|t| t.rate_note())
519}
520
521#[cfg(not(feature = "network"))]
522pub fn shared_rate_note() -> Option<String> {
523    None
524}
525
526#[cfg(test)]
527mod tests {
528    use super::*;
529    use std::cell::Cell;
530
531    // Per test thread, so parallel tests cannot move each other's clock.
532    thread_local! {
533        static NOW: Cell<u64> = const { Cell::new(1_000) };
534    }
535    fn clock() -> u64 {
536        NOW.with(Cell::get)
537    }
538
539    fn block_on<F: std::future::Future>(f: F) -> F::Output {
540        tokio::runtime::Builder::new_current_thread()
541            .build()
542            .unwrap()
543            .block_on(f)
544    }
545
546    /// Scripted transport: pops answers in order and records requests.
547    struct Script {
548        answers: Mutex<Vec<HttpResponse>>,
549        seen: Mutex<Vec<HttpRequest>>,
550    }
551    impl Script {
552        fn new(answers: Vec<HttpResponse>) -> Arc<Self> {
553            Arc::new(Self {
554                answers: Mutex::new(answers),
555                seen: Default::default(),
556            })
557        }
558    }
559    #[async_trait::async_trait]
560    impl HttpTransport for Script {
561        async fn send(&self, request: HttpRequest) -> Result<HttpResponse> {
562            self.seen.lock().unwrap().push(request);
563            Ok(self.answers.lock().unwrap().remove(0))
564        }
565    }
566
567    fn resp(status: u16, body: &str, headers: &[(&str, &str)]) -> HttpResponse {
568        HttpResponse {
569            status,
570            headers: headers
571                .iter()
572                .map(|(k, v)| (k.to_string(), v.to_string()))
573                .collect(),
574            body: body.to_string(),
575        }
576    }
577
578    #[test]
579    fn a_304_is_served_from_the_cached_body_and_sends_if_none_match() {
580        let inner = Script::new(vec![
581            resp(200, "[1]", &[("etag", "\"abc\"")]),
582            resp(304, "", &[]),
583        ]);
584        let t = ConditionalTransport::with_clock(inner.clone(), clock);
585        let url = "https://api.github.com/repos/a/b/pulls?state=open";
586        let first = block_on(t.send(HttpRequest::get(url))).unwrap();
587        assert_eq!(first.body, "[1]");
588        let second = block_on(t.send(HttpRequest::get(url))).unwrap();
589        assert_eq!(second.status, 200);
590        assert_eq!(second.body, "[1]");
591        assert_eq!(t.not_modified_count(), 1);
592        let seen = inner.seen.lock().unwrap();
593        assert!(seen[0].headers.iter().all(|(k, _)| k != "If-None-Match"));
594        assert!(seen[1]
595            .headers
596            .contains(&("If-None-Match".to_string(), "\"abc\"".to_string())));
597    }
598
599    #[test]
600    fn a_full_cache_drops_its_oldest_entry_not_all_of_them() {
601        let urls: Vec<String> = (0..MAX_ENTRIES + 5)
602            .map(|i| format!("https://api.github.com/repos/a/b{i}/pulls"))
603            .collect();
604        let mut answers: Vec<HttpResponse> = urls
605            .iter()
606            .map(|_| resp(200, "[]", &[("etag", "\"e\"")]))
607            .collect();
608        // The probes below: a recent entry and a long-evicted one.
609        answers.push(resp(304, "", &[]));
610        answers.push(resp(200, "[]", &[("etag", "\"e\"")]));
611        let inner = Script::new(answers);
612        let t = ConditionalTransport::with_clock(inner.clone(), clock);
613        for url in &urls {
614            block_on(t.send(HttpRequest::get(url))).unwrap();
615        }
616        // An entry from the first half survived (the old behaviour cleared
617        // everything the moment the cache filled).
618        block_on(t.send(HttpRequest::get(&urls[10]))).unwrap();
619        block_on(t.send(HttpRequest::get(&urls[0]))).unwrap();
620        let seen = inner.seen.lock().unwrap();
621        let conditional = |i: usize| {
622            seen[i]
623                .headers
624                .iter()
625                .any(|(k, _)| k.eq_ignore_ascii_case("If-None-Match"))
626        };
627        assert!(conditional(urls.len()), "entry 10 is still cached");
628        assert!(!conditional(urls.len() + 1), "entry 0 was the oldest");
629    }
630
631    #[test]
632    fn an_exhausted_host_is_not_hammered_until_its_reset() {
633        NOW.with(|n| n.set(1_000));
634        let inner = Script::new(vec![resp(
635            200,
636            "[]",
637            &[
638                ("x-ratelimit-remaining", "0"),
639                ("x-ratelimit-reset", "1300"),
640            ],
641        )]);
642        let t = ConditionalTransport::with_clock(inner.clone(), clock);
643        let url = "https://api.github.com/user";
644        block_on(t.send(HttpRequest::get(url))).unwrap();
645        let err = block_on(t.send(HttpRequest::get(url))).unwrap_err();
646        assert!(matches!(
647            err,
648            Error::RateLimited {
649                retry_in_secs: 300,
650                ..
651            }
652        ));
653        assert_eq!(inner.seen.lock().unwrap().len(), 1, "no second request");
654        assert!(t.rate_note().unwrap().contains("paused for 5m"));
655        // After the reset it asks again.
656        NOW.with(|n| n.set(1_301));
657        inner
658            .answers
659            .lock()
660            .unwrap()
661            .push(resp(200, "[]", &[("x-ratelimit-remaining", "4999")]));
662        assert!(block_on(t.send(HttpRequest::get(url))).is_ok());
663        assert!(t.rate_note().is_none());
664    }
665
666    #[test]
667    fn a_low_count_warns_but_still_sends() {
668        NOW.with(|n| n.set(2_000));
669        let inner = Script::new(vec![resp(
670            200,
671            "[]",
672            &[("ratelimit-remaining", "7"), ("ratelimit-reset", "2600")],
673        )]);
674        let t = ConditionalTransport::with_clock(inner, clock);
675        block_on(t.send(HttpRequest::get("https://gitlab.example.com/api/v4/x"))).unwrap();
676        let note = t.rate_note().unwrap();
677        assert!(
678            note.contains("gitlab.example.com") && note.contains("7 left"),
679            "{note}"
680        );
681    }
682
683    #[test]
684    fn a_429_with_retry_after_becomes_a_rate_limit_error() {
685        NOW.with(|n| n.set(3_000));
686        let inner = Script::new(vec![resp(429, "slow down", &[("retry-after", "30")])]);
687        let t = ConditionalTransport::with_clock(inner, clock);
688        let err = block_on(t.send(HttpRequest::get("https://gitlab.com/api/v4/x"))).unwrap_err();
689        assert!(matches!(
690            err,
691            Error::RateLimited {
692                retry_in_secs: 30,
693                ..
694            }
695        ));
696    }
697
698    #[test]
699    fn a_plain_403_stays_a_scope_problem() {
700        let r = resp(403, "{}", &[("x-ratelimit-remaining", "100")]);
701        assert!(!is_rate_limited(&r));
702        assert!(is_rate_limited(&resp(
703            403,
704            "{}",
705            &[("x-ratelimit-remaining", "0")]
706        )));
707    }
708
709    #[test]
710    fn azure_tstu_counts_never_trip_the_low_water_note() {
711        NOW.with(|n| n.set(4_000));
712        let inner = Script::new(vec![
713            resp(
714                200,
715                "{}",
716                &[
717                    ("X-RateLimit-Remaining", "3"),
718                    ("X-RateLimit-Resource", "git"),
719                    ("X-RateLimit-Reset", "4100"),
720                ],
721            ),
722            resp(200, "{}", &[("X-RateLimit-Remaining", "0")]),
723        ]);
724        let t = ConditionalTransport::with_clock(inner.clone(), clock);
725        let url = "https://dev.azure.com/org/_apis/projects";
726        block_on(t.send(HttpRequest::get(url))).unwrap();
727        assert!(t.rate_note().is_none(), "TSTUs are not calls");
728        // Even "0 left" in TSTUs does not stop the next call.
729        block_on(t.send(HttpRequest::get(url))).unwrap();
730        assert!(t.rate_note().is_none());
731    }
732
733    #[test]
734    fn azure_backs_off_on_429_and_names_the_resource() {
735        NOW.with(|n| n.set(4_000));
736        let inner = Script::new(vec![resp(
737            429,
738            "",
739            &[("Retry-After", "45"), ("X-RateLimit-Resource", "git")],
740        )]);
741        let t = ConditionalTransport::with_clock(inner.clone(), clock);
742        let url = "https://dev.azure.com/org/_apis/projects";
743        let err = block_on(t.send(HttpRequest::get(url))).unwrap_err();
744        assert!(matches!(
745            err,
746            Error::RateLimited {
747                retry_in_secs: 45,
748                ..
749            }
750        ));
751        let note = t.rate_note().unwrap();
752        assert!(
753            note.contains("dev.azure.com") && note.contains("git"),
754            "{note}"
755        );
756        assert!(block_on(t.send(HttpRequest::get(url))).is_err());
757        assert_eq!(
758            inner.seen.lock().unwrap().len(),
759            1,
760            "blocked until the deadline"
761        );
762    }
763
764    #[test]
765    fn an_azure_403_is_a_permission_problem_even_with_zero_tstus_left() {
766        let r = resp(403, "{}", &[("x-ratelimit-remaining", "0")]);
767        assert!(!is_rate_limited_for(ApiFamily::AzureDevops, &r));
768        assert!(is_rate_limited_for(ApiFamily::Github, &r));
769        assert!(is_rate_limited_for(
770            ApiFamily::AzureDevops,
771            &resp(429, "", &[])
772        ));
773    }
774
775    #[test]
776    fn bitbucket_near_limit_speaks_up_but_still_sends() {
777        NOW.with(|n| n.set(5_000));
778        let inner = Script::new(vec![
779            resp(200, "{}", &[("X-RateLimit-NearLimit", "true")]),
780            resp(200, "{}", &[]),
781        ]);
782        let t = ConditionalTransport::with_clock(inner.clone(), clock);
783        let url = "https://api.bitbucket.org/2.0/user";
784        block_on(t.send(HttpRequest::get(url))).unwrap();
785        let note = t.rate_note().unwrap();
786        assert!(
787            note.contains("api.bitbucket.org") && note.contains("nearly"),
788            "{note}"
789        );
790        // Still asked; the next calm answer clears the note.
791        block_on(t.send(HttpRequest::get(url))).unwrap();
792        assert!(t.rate_note().is_none());
793    }
794
795    #[test]
796    fn trello_counts_the_token_bucket() {
797        NOW.with(|n| n.set(6_000));
798        let inner = Script::new(vec![
799            resp(
800                200,
801                "[]",
802                &[
803                    ("x-rate-limit-api-token-remaining", "5"),
804                    ("x-rate-limit-api-token-interval-ms", "10000"),
805                ],
806            ),
807            resp(
808                200,
809                "[]",
810                &[
811                    ("x-rate-limit-api-token-remaining", "0"),
812                    ("x-rate-limit-api-token-interval-ms", "10000"),
813                ],
814            ),
815        ]);
816        let t = ConditionalTransport::with_clock(inner.clone(), clock);
817        let url = "https://api.trello.com/1/boards/x/cards";
818        block_on(t.send(HttpRequest::get(url))).unwrap();
819        let note = t.rate_note().unwrap();
820        assert!(
821            note.contains("api.trello.com") && note.contains("5 left"),
822            "{note}"
823        );
824        block_on(t.send(HttpRequest::get(url))).unwrap();
825        let err = block_on(t.send(HttpRequest::get(url))).unwrap_err();
826        assert!(matches!(
827            err,
828            Error::RateLimited {
829                retry_in_secs: 10,
830                ..
831            }
832        ));
833    }
834
835    #[test]
836    fn jira_429_blocks_until_the_retry_after_deadline_and_keeps_the_reason() {
837        NOW.with(|n| n.set(7_000));
838        let inner = Script::new(vec![
839            resp(
840                429,
841                "",
842                &[
843                    ("Retry-After", "120"),
844                    ("RateLimit-Reason", "jira-burst-based"),
845                ],
846            ),
847            resp(200, "{}", &[]),
848        ]);
849        let t = ConditionalTransport::with_clock(inner.clone(), clock);
850        let url = "https://acme.atlassian.net/rest/api/3/myself";
851        let err = block_on(t.send(HttpRequest::get(url))).unwrap_err();
852        assert!(matches!(
853            err,
854            Error::RateLimited {
855                retry_in_secs: 120,
856                ..
857            }
858        ));
859        assert!(t.rate_note().unwrap().contains("jira-burst-based"));
860        NOW.with(|n| n.set(7_060));
861        assert!(block_on(t.send(HttpRequest::get(url))).is_err());
862        assert_eq!(inner.seen.lock().unwrap().len(), 1);
863        NOW.with(|n| n.set(7_121));
864        assert!(block_on(t.send(HttpRequest::get(url))).is_ok());
865        assert!(t.rate_note().is_none());
866    }
867
868    #[test]
869    fn jira_ignores_generic_count_headers() {
870        NOW.with(|n| n.set(7_000));
871        let inner = Script::new(vec![resp(200, "{}", &[("ratelimit-remaining", "1")])]);
872        let t = ConditionalTransport::with_clock(inner, clock);
873        block_on(t.send(HttpRequest::get(
874            "https://acme.atlassian.net/rest/api/3/myself",
875        )))
876        .unwrap();
877        assert!(t.rate_note().is_none());
878    }
879
880    #[test]
881    fn a_self_hosted_host_is_read_by_its_registered_family() {
882        NOW.with(|n| n.set(8_000));
883        let inner = Script::new(vec![resp(200, "{}", &[("X-RateLimit-Remaining", "2")])]);
884        let t = ConditionalTransport::with_clock(inner, clock);
885        t.register_host("tfs.corp.example", ApiFamily::AzureDevops);
886        block_on(t.send(HttpRequest::get("https://tfs.corp.example/tfs/c/_apis/x"))).unwrap();
887        assert!(t.rate_note().is_none());
888    }
889}