rate-limits

Crates.iorate-limits
lib.rsrate-limits
version0.5.0
sourcesrc
created_at2022-03-27 00:19:52.626951
updated_at2023-03-15 20:26:15.194782
descriptionA parser for HTTP rate limit headers
homepagehttps://github.com/mre/rate-limits
repositoryhttps://github.com/mre/rate-limits
max_upload_size
id557064
size37,405
Matthias Endler (mre)

documentation

https://docs.rs/rate-limits

README

rate-limits

docs.rs

A crate for parsing HTTP rate limit headers as per the IETF draft. Inofficial implementations like the Github rate limit headers are also supported on a best effort basis. See vendor list for support.

use indoc::indoc;
use std::str::FromStr;
use time::{OffsetDateTime, Duration};
use rate_limits::{Vendor, RateLimit, ResetTime};

let headers = indoc! {"
    x-ratelimit-limit: 5000
    x-ratelimit-remaining: 4987
    x-ratelimit-reset: 1350085394
"};

assert_eq!(
    RateLimit::from_str(headers).unwrap(),
    RateLimit {
        limit: 5000,
        remaining: 4987,
        reset: ResetTime::DateTime(
            OffsetDateTime::from_unix_timestamp(1350085394).unwrap()
        ),
        window: Some(Duration::HOUR),
        vendor: Vendor::Github
    },
);

Also takes the Retry-After header into account when calculating the reset time.

http::HeaderMap is supported as well:

use std::str::FromStr;
use time::{OffsetDateTime, Duration};
use rate_limits::{Vendor, RateLimit, ResetTime};
use http::header::HeaderMap;

let mut headers = HeaderMap::new();
headers.insert("X-RATELIMIT-LIMIT", "5000".parse().unwrap());
headers.insert("X-RATELIMIT-REMAINING", "4987".parse().unwrap());
headers.insert("X-RATELIMIT-RESET", "1350085394".parse().unwrap());

assert_eq!(
    RateLimit::new(headers).unwrap(),
    RateLimit {
        limit: 5000,
        remaining: 4987,
        reset: ResetTime::DateTime(
            OffsetDateTime::from_unix_timestamp(1350085394).unwrap()
        ),
        window: Some(Duration::HOUR),
        vendor: Vendor::Github
    },
);

Other resources:

License: Apache-2.0/MIT

Commit count: 54

cargo fmt