footing 0.1.4

Feature-gated foundations for Rust backend services
Documentation
use std::time::{Duration, Instant};

use axum::http::{HeaderName, Request};

use super::*;
use crate::result::{ClassifyError, ErrorKind};

#[test]
fn token_bucket_denies_after_capacity_and_refills() {
    let config = RateLimitConfig::new(2, 1, Duration::from_secs(10)).unwrap();
    let limiter = TokenBucketRateLimiter::new(config);
    let now = Instant::now();

    assert!(limiter.check_at("user", now).unwrap().is_allowed());
    assert!(limiter.check_at("user", now).unwrap().is_allowed());
    assert!(!limiter.check_at("user", now).unwrap().is_allowed());
    assert!(
        limiter
            .check_at("user", now + Duration::from_secs(10))
            .unwrap()
            .is_allowed()
    );
}

#[test]
fn rate_limit_debug_does_not_expose_bucket_or_fixed_keys() {
    let config = RateLimitConfig::new(2, 1, Duration::from_secs(10)).unwrap();
    let limiter = TokenBucketRateLimiter::new(config);
    let private_key = "private-account-rate-limit-key";
    limiter
        .check(private_key.to_owned())
        .expect("rate limit check should succeed");

    let output = format!(
        "{limiter:?} {:?}",
        RateLimitKeySource::Fixed(private_key.to_owned())
    );
    assert!(output.contains("bucket_count"));
    assert!(output.contains("[REDACTED]"));
    assert!(!output.contains(private_key));
}

#[test]
fn rate_limit_config_rejects_zero_refill_interval() {
    let error = RateLimitConfig::new(2, 1, Duration::ZERO)
        .expect_err("zero refill interval must be rejected at construction");
    assert!(matches!(error, RateLimitError::InvalidRefillInterval));
}

#[test]
fn token_bucket_uses_bounded_overflow_bucket_for_excess_keys() {
    let limiter = TokenBucketRateLimiter::with_max_buckets(
        RateLimitConfig::new(1, 1, Duration::from_secs(10)).unwrap(),
        2,
    )
    .unwrap();
    let now = Instant::now();

    assert!(limiter.check_at("first", now).unwrap().is_allowed());
    assert!(limiter.check_at("second", now).unwrap().is_allowed());
    assert!(limiter.check_at("third", now).unwrap().is_allowed());
    assert!(
        !limiter.check_at("fourth", now).unwrap().is_allowed(),
        "all excess keys should share one bounded overflow bucket"
    );
    assert_eq!(limiter.bucket_count().unwrap(), 2);
    assert!(!limiter.check_at("first", now).unwrap().is_allowed());
    assert_eq!(limiter.bucket_count().unwrap(), 2);

    assert!(
        limiter
            .check_at("third", now + Duration::from_secs(10))
            .unwrap()
            .is_allowed()
    );
    assert_eq!(limiter.bucket_count().unwrap(), 1);
}

#[test]
fn header_key_source_hashes_and_bounds_untrusted_values() {
    let source = RateLimitKeySource::Header(HeaderName::from_static("x-account-id"));
    let private_value = "private-account-identifier";
    let request = Request::builder()
        .header("x-account-id", private_value)
        .body(())
        .expect("request should build");

    let key = source.key_for(&request).expect("header key should exist");
    assert!(key.starts_with("header:"));
    assert!(!key.contains(private_value));
    assert_eq!(source.key_for(&request).as_deref(), Some(key.as_str()));

    let oversized = Request::builder()
        .header(
            "x-account-id",
            "x".repeat(MAX_RATE_LIMIT_HEADER_VALUE_BYTES + 1),
        )
        .body(())
        .expect("request should build");
    assert!(source.key_for(&oversized).is_none());
}

#[test]
fn retry_after_header_seconds_rounds_subsecond_delays_up() {
    assert_eq!(retry_after_header_seconds(Duration::ZERO), 0);
    assert_eq!(retry_after_header_seconds(Duration::from_millis(1)), 1);
    assert_eq!(retry_after_header_seconds(Duration::from_millis(1500)), 2);
    assert_eq!(retry_after_header_seconds(Duration::from_secs(3)), 3);
}

#[test]
fn rate_limit_decision_encodes_allowed_and_denied_invariants() {
    let allowed = RateLimitDecision::allowed(7);
    assert!(allowed.is_allowed());
    assert_eq!(allowed.remaining(), 7);
    assert_eq!(allowed.retry_after(), None);

    let denied = RateLimitDecision::denied(Duration::from_secs(3));
    assert!(!denied.is_allowed());
    assert_eq!(denied.remaining(), 0);
    assert_eq!(denied.retry_after(), Some(Duration::from_secs(3)));
}

#[test]
fn rate_limit_errors_are_classified() {
    assert_eq!(
        RateLimitError::InvalidCapacity.error_kind(),
        ErrorKind::Validation
    );
    assert_eq!(
        RateLimitError::StoreUnavailable.error_kind(),
        ErrorKind::Unavailable
    );
    assert_eq!(
        RateLimitError::StoreUnavailable.error_code(),
        "rate_limit_store_unavailable"
    );
}