Crate barnacle_rs

Source
Expand description

Custom rate limiting library with Redis and Axum support

This library provides middleware for API rate limiting and API key validation.

§Features

  • Rate Limiting: Configurable rate limiting with Redis backend
  • API Key Validation: Validate requests using x-api-key header
  • Per-Key Rate Limits: Different rate limits per API key
  • Extensible Design: Custom key stores and rate limiting strategies
  • Redis Integration: Default Redis-based storage for keys and rate limits
  • Axum Middleware: Ready-to-use middleware for Axum web framework

§Basic Usage

use barnacle_rs::{BarnacleLayer, ApiKeyConfig, BarnacleConfig};
#[cfg(feature = "redis")]
use barnacle_rs::{RedisApiKeyStore, RedisBarnacleStore, deadpool_redis};
use std::time::Duration;

// Create Redis stores (requires "redis" feature)
#[cfg(feature = "redis")]
let redis_pool = deadpool_redis::Config::from_url("redis://localhost")
    .create_pool(Some(deadpool_redis::Runtime::Tokio1))?;

#[cfg(feature = "redis")]
let api_key_store = RedisApiKeyStore::new(redis_pool.clone());
#[cfg(feature = "redis")]
let rate_limit_store = RedisBarnacleStore::new(redis_pool);

// Create a Barnacle layer using the builder pattern
#[cfg(feature = "redis")]
let layer: BarnacleLayer<(), RedisBarnacleStore, ()> = BarnacleLayer::builder()
    .with_store(rate_limit_store)
    .with_config(BarnacleConfig::default())
    .build()?;

// Use with Axum router
// let app = axum::Router::new()
//     .route("/api/data", axum::routing::get(handler))
//     .layer(layer);

Re-exports§

pub use tracing;
pub use deadpool_redis;

Structs§

ApiKeyConfig
Configuration for API key middleware
BarnacleConfig
Rate limiter configuration
BarnacleContext
Rate limiting context that includes route information
BarnacleLayer
Generic rate limiting and API key layer
BarnacleResult
Result of an increment attempt
RedisApiKeyStore
RedisBarnacleStore
Implementation of BarnacleStore using Redis with connection pooling. This struct encapsulates Arc internally, so consumers don’t need to wrap it.
StaticApiKeyConfig
Per-key rate limiting configuration for static configurations
StaticApiKeyStore
Static API key store that uses a predefined set of keys Useful for simple configurations where keys are known at compile time

Enums§

BarnacleError
Main error type for the Barnacle library
BarnacleKey
Identification key for rate limiting (e.g., email, api-key, IP)
BarnacleLayerBuilderError
Error type for BarnacleLayerBuilder
ResetOnSuccess

Constants§

BARNACLE_API_KEY_PREFIX
BARNACLE_CUSTOM_PREFIX
BARNACLE_EMAIL_KEY_PREFIX
BARNACLE_IP_PREFIX

Traits§

ApiKeyStore
Trait for API key validation and configuration retrieval
BarnacleStore
Trait to abstract the rate limiter storage backend (e.g., Redis)
KeyExtractable
Trait to extract the key from any payload type