KeyExtractor

Trait KeyExtractor 

Source
pub trait KeyExtractor: Clone {
    type Key: Clone + Hash + Eq;
    type KeyExtractionError: ResponseError + 'static;

    // Required method
    fn extract(
        &self,
        req: &ServiceRequest,
    ) -> Result<Self::Key, Self::KeyExtractionError>;

    // Provided methods
    fn exceed_rate_limit_response(
        &self,
        negative: &NotUntil<QuantaInstant>,
        response: HttpResponseBuilder,
    ) -> HttpResponse { ... }
    fn whitelisted_keys(&self) -> Vec<Self::Key> { ... }
}
Expand description

Generic structure of what is needed to extract a rate-limiting key from an incoming request.

§Example

use actix_governor::{KeyExtractor, SimpleKeyExtractionError};
use actix_web::ResponseError;
use actix_web::dev::ServiceRequest;

#[derive(Clone)]
struct Foo;

// will return 500 error and 'Extract error' as content
impl KeyExtractor for Foo {
    type Key = ();
    type KeyExtractionError = SimpleKeyExtractionError<&'static str>;

    fn extract(&self, _req: &ServiceRequest) -> Result<Self::Key, Self::KeyExtractionError> {
        Err(SimpleKeyExtractionError::new("Extract error"))
    }
}

For more see custom_key_bearer example

Required Associated Types§

Source

type Key: Clone + Hash + Eq

The type of the key.

Source

type KeyExtractionError: ResponseError + 'static

The type of the error that can occur if key extraction from the request fails.

Required Methods§

Source

fn extract( &self, req: &ServiceRequest, ) -> Result<Self::Key, Self::KeyExtractionError>

Extraction method, will return KeyExtractionError response when the extract failed

Provided Methods§

Source

fn exceed_rate_limit_response( &self, negative: &NotUntil<QuantaInstant>, response: HttpResponseBuilder, ) -> HttpResponse

The content you want to show it when the rate limit is exceeded. You can calculate the time at which a caller can expect the next positive rate-limiting result by using NotUntil. The HttpResponseBuilder allows you to build a fully customized HttpResponse in case of an error.

§Example
use actix_governor::{KeyExtractor, SimpleKeyExtractionError};
use actix_web::ResponseError;
use actix_web::dev::ServiceRequest;
use governor::{NotUntil, clock::{Clock, QuantaInstant, DefaultClock}};
use actix_web::{HttpResponse, HttpResponseBuilder};
use actix_web::http::header::ContentType;


#[derive(Clone)]
struct Foo;

// will return 500 error and 'Extract error' as content
impl KeyExtractor for Foo {
    type Key = ();
    type KeyExtractionError = SimpleKeyExtractionError<&'static str>;

    fn extract(&self, _req: &ServiceRequest) -> Result<Self::Key, Self::KeyExtractionError> {
        Err(SimpleKeyExtractionError::new("Extract error"))
    }

    fn exceed_rate_limit_response(
            &self,
            negative: &NotUntil<QuantaInstant>,
            mut response: HttpResponseBuilder,
        ) -> HttpResponse {
            let wait_time = negative
                .wait_time_from(DefaultClock::default().now())
                .as_secs();
            response
                .content_type(ContentType::plaintext())
                .body(format!("Too many requests, retry in {}s", wait_time))
    }
}
Source

fn whitelisted_keys(&self) -> Vec<Self::Key>

Returns a list of whitelisted keys. If a key is in this list, it will never be rate-limited.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§