Crate ignitia

Crate ignitia 

Source
Expand description

Β§Ignitia - A Blazing Fast Rust Web Framework πŸ”₯

Ignitia is a high-performance, production-ready web framework for Rust that ignites your web development experience with exceptional speed, memory safety, and developer ergonomics. Built on modern async Rust with Tokio and Hyper, Ignitia provides a complete toolkit for building scalable web applications, APIs, and real-time services with full HTTP/1.1, HTTP/2, HTTPS, and WebSocket support.

Β§πŸ”₯ Key Features

Β§Multi-Protocol Excellence

  • HTTP/1.1 & HTTP/2: Full support with automatic protocol negotiation via ALPN
  • HTTPS/TLS: Production-ready TLS with certificate management and modern cipher suites
  • WebSocket: Native WebSocket protocol with connection management and message routing
  • H2C Support: HTTP/2 over cleartext connections for development and internal services

Β§Performance Optimized

  • 155K+ RPS Capable: Optimized for extreme throughput with zero-cost abstractions
  • Sub-millisecond Latency: Fast request processing with efficient routing and middleware
  • Connection Pooling: Advanced connection management and resource optimization
  • Memory Efficient: Smart buffer management and minimal heap allocations
  • Radix Tree Routing: O(k) route lookup complexity where k is path length
  • Lock-Free Reads: Atomic router swapping for zero-downtime updates

Β§Developer Experience

  • Type-Safe Routing: Compile-time route validation with automatic parameter extraction
  • Rich Extractors: JSON, forms, headers, cookies, query params, and custom extractors
  • Composable Middleware: Flexible middleware pipeline for cross-cutting concerns
  • Comprehensive Error Handling: Structured error types with detailed diagnostics
  • Hot Reloading: Runtime route updates without connection drops

Β§Production Features

  • Advanced CORS: Regex-based origin matching with fine-grained control
  • Security Headers: Built-in security middleware with configurable policies
  • Rate Limiting: Token bucket algorithm with distributed support
  • Observability: Structured logging, metrics, and request tracing
  • Multipart Forms: File upload support with streaming and size limits
  • WebSocket Rooms: Built-in room system for broadcast messaging

Β§πŸš€ Quick Start Guide

Add Ignitia to your Cargo.toml with desired features:

[dependencies]
ignitia = { version = "0.2.4", features = ["tls", "websocket"] }
tokio = { version = "1.40", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }

Β§Simple HTTP Server

use ignitia::prelude::*;

#[tokio::main]
async fn main() -> Result<()> {
    let router = Router::new()
        .get("/", || async {
            Ok(Response::text("Hello, Ignitia! πŸ”₯"))
        })
        .get("/health", || async {
            Ok(Response::json(serde_json::json!({"status": "healthy"}))?)
        })
        .post("/echo", |body: String| async move {
            Ok(Response::text(format!("Echo: {}", body)))
        });

    let addr = "127.0.0.1:8080".parse()?;
    Server::new(router, addr).ignitia().await
}

Β§Advanced HTTP/2 Configuration

use ignitia::{Router, Server, ServerConfig, Http2Config};
use std::time::Duration;

#[tokio::main]
async fn main() -> ignitia::Result<()> {
    let router = Router::new()
        .get("/", || async { Ok(ignitia::Response::text("HTTP/2 Ready! πŸš€")) });

    // Configure HTTP/2 with optimizations
    let config = ServerConfig {
        http1_enabled: true,
        http2: Http2Config {
            enabled: true,
            enable_prior_knowledge: true, // H2C support
            max_concurrent_streams: Some(1000),
            initial_connection_window_size: Some(1024 * 1024), // 1MB
            keep_alive_interval: Some(Duration::from_secs(60)),
            adaptive_window: true,
            ..Default::default()
        },
        auto_protocol_detection: true,
        max_request_body_size: 16 * 1024 * 1024, // 16MB
        ..Default::default()
    };

    let addr = "127.0.0.1:8080".parse()?;
    Server::with_config(router, addr, config).ignitia().await
}

Β§πŸ”’ HTTPS and TLS Support

Ignitia provides comprehensive TLS support with modern security standards:

Β§Basic HTTPS Setup

use ignitia::prelude::*;

#[tokio::main]
async fn main() -> Result<()> {
    let router = Router::new()
        .get("/", || async { Ok(Response::text("Secure Hello! πŸ”’")) });

    let addr = "127.0.0.1:8443".parse()?;
    Server::new(router, addr)
        .enable_https("server.crt", "server.key")?
        .ignitia()
        .await
}

Β§Advanced TLS Configuration

#[cfg(feature = "tls")]
use ignitia::{TlsConfig, TlsVersion};

#[cfg(feature = "tls")]
let tls_config = TlsConfig::new("cert.pem", "key.pem")
    .with_alpn_protocols(vec!["h2", "http/1.1"]) // HTTP/2 priority
    .with_protocol_versions(&[TlsVersion::TlsV12, TlsVersion::TlsV13])
    .with_cipher_suites(&["TLS_AES_256_GCM_SHA384", "TLS_CHACHA20_POLY1305_SHA256"])
    .enable_client_cert_verification();

#[cfg(feature = "tls")]
Server::new(router, addr)
    .with_tls(tls_config)?
    .ignitia()
    .await

§🌐 Advanced CORS Configuration

Comprehensive CORS support for secure cross-origin requests:

Β§Production CORS Setup

use ignitia::{CorsMiddleware, Method, Router, Response};

let cors = CorsMiddleware::new()
    .allowed_origins(&["https://myapp.com", "https://admin.myapp.com"])
    .allowed_methods(&[Method::GET, Method::POST, Method::PUT, Method::DELETE])
    .allowed_headers(&["Content-Type", "Authorization", "X-API-Key"])
    .expose_headers(&["X-Total-Count", "X-Rate-Limit-Remaining"])
    .allow_credentials()
    .max_age(86400) // 24 hours
    .build()?;

let router = Router::new()
    .middleware(cors)
    .get("/api/users", || async { Ok(Response::json(vec!["user1", "user2"])?) });

Β§Regex-Based Origin Matching

use ignitia::CorsMiddleware;

let cors = CorsMiddleware::new()
    .allowed_origin_regex(r"https://.*\.myapp\.com") // All subdomains
    .allowed_origin_regex(r"https://localhost:\d+") // Local development ports
    .build()?;

Β§πŸ“‘ WebSocket Support

Full-featured WebSocket implementation with HTTP/2 compatibility:

Β§Advanced WebSocket Server

#[cfg(feature = "websocket")]
use ignitia::websocket::{websocket_handler, Message, WebSocketConnection};
use std::sync::Arc;
use tokio::sync::Mutex;
use std::collections::HashMap;

#[cfg(feature = "websocket")]
type ClientMap = Arc<Mutex<HashMap<String, WebSocketConnection>>>;

#[cfg(feature = "websocket")]
let clients: ClientMap = Arc::new(Mutex::new(HashMap::new()));

#[cfg(feature = "websocket")]
let router = Router::new()
    // Simple echo WebSocket
    .websocket("/ws/echo", websocket_handler(|mut ws: WebSocketConnection| async move {
        while let Some(message) = ws.recv().await {
            match message {
                Message::Text(text) => {
                    ws.send_text(format!("Echo: {}", text)).await?;
                }
                Message::Binary(data) => {
                    ws.send_bytes(data).await?;
                }
                Message::Ping(data) => {
                    ws.send_pong(data).await?;
                }
                Message::Close(_) => break,
                _ => {}
            }
        }
        Ok(())
    }));

Β§πŸ—οΈ Framework Architecture

Ignitia’s layered architecture supports multiple protocols and advanced features:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Application Layer                                                           β”‚
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚   Routes    β”‚ β”‚ Middleware  β”‚ β”‚    CORS     β”‚ β”‚     WebSocket           β”‚ β”‚
β”‚ β”‚ & Handlers  β”‚ β”‚  Pipeline   β”‚ β”‚Configurationβ”‚ β”‚      Handlers           β”‚ β”‚
β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Ignitia Framework                                                           β”‚
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚   Router    β”‚ β”‚   Server    β”‚ β”‚     TLS     β”‚ β”‚      WebSocket          β”‚ β”‚
β”‚ β”‚  Radix Tree β”‚ β”‚ HTTP/1.1+2  β”‚ β”‚ ALPN & Cert β”‚ β”‚  Connection Management  β”‚ β”‚
β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Runtime Layer (Tokio)                                                       β”‚
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚    HTTP     β”‚ β”‚     TLS     β”‚ β”‚     TCP     β”‚ β”‚     Async I/O           β”‚ β”‚
β”‚ β”‚   (Hyper)   β”‚ β”‚  (Rustls)   β”‚ β”‚  Listeners  β”‚ β”‚     & Futures           β”‚ β”‚
β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Β§πŸ”§ Feature Configuration

Ignitia uses Cargo features for optional functionality:

Β§Available Features

  • tls: Enables HTTPS/TLS support with certificate management and ALPN protocol negotiation
  • websocket: Enables WebSocket protocol support with connection management and message routing
  • self-signed: Enables self-signed certificate generation for development environments
  • default: No additional features (HTTP/1.1 and HTTP/2 over cleartext only)

§🎯 Performance Benchmarks

Ignitia is optimized for exceptional performance:

Β§Throughput (Requests/Second)

  • Simple JSON API: 155,000+ RPS (Radix mode)
  • Static file serving: 140,000+ RPS
  • WebSocket connections: 25,000+ concurrent
  • HTTPS with TLS 1.3: 110,000+ RPS

Β§Latency (99th percentile)

  • HTTP/1.1: < 0.8ms
  • HTTP/2: < 1.0ms
  • HTTPS: < 1.3ms
  • WebSocket message: < 0.5ms

Β§Resource Usage

  • Memory per connection: ~2KB
  • CPU overhead: < 3% at 100K RPS
  • Binary size: ~4MB (with all features)

Β§πŸ“š Core Concepts

Β§Request/Response Lifecycle

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Ignitia Request Pipeline                                        β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

1. Connection Accept (TCP/TLS)
   β”œβ”€ Protocol Detection (HTTP/1.1, HTTP/2, WebSocket)
   β”œβ”€ TLS Handshake (if HTTPS)
   └─ Connection Pooling

2. Request Parsing
   β”œβ”€ Header Parsing and Validation
   β”œβ”€ Body Streaming (with size limits)
   └─ Protocol-specific Processing

3. Middleware Pipeline (Request Phase)
   β”œβ”€ CORS Preflight Handling
   β”œβ”€ Authentication/Authorization
   β”œβ”€ Rate Limiting
   β”œβ”€ Request ID Generation
   └─ Custom middleware

4. Route Resolution
   β”œβ”€ Path Matching (radix tree O(k) lookup)
   β”œβ”€ Parameter Extraction
   β”œβ”€ Handler Selection
   └─ WebSocket Upgrade Detection

5. Handler Execution
   β”œβ”€ Extractor Processing
   β”œβ”€ Business Logic
   └─ Response Generation

6. Middleware Pipeline (Response Phase)
   β”œβ”€ Error Handling
   β”œβ”€ Response Headers (Security, CORS)
   β”œβ”€ Compression
   └─ Logging

7. Response Transmission
   β”œβ”€ Protocol-specific Formatting
   β”œβ”€ Connection Management
   └─ Metrics Collection

Β§Routing Modes

Ignitia supports two routing modes optimized for different use cases:

  • Performance: O(k) lookup where k is path length
  • Best for: Applications with 50+ routes
  • Features: Compressed prefix tree, efficient parameter extraction
  • Memory: Optimized for large route sets
Β§Base Mode
  • Performance: O(n) linear matching where n is route count
  • Best for: Applications with < 50 routes
  • Features: Simple regex-based matching
  • Memory: Lower overhead for small apps

Β§πŸ“– Module Documentation

Β§Core Modules

  • cookie: HTTP cookie handling with secure defaults and session management
  • error: Comprehensive error handling with structured error types and custom responses
  • extension: Type-safe request/response extensions for sharing data between middleware
  • handler: Request handlers, extractors, and handler trait implementations
  • middleware: Middleware system including CORS, authentication, logging, and security
  • multipart: Multipart form data parsing with file upload support
  • request: HTTP request representation with efficient parsing and validation
  • response: HTTP response building with content negotiation and streaming
  • router: High-performance route matching with parameter extraction and middleware composition
  • server: Multi-protocol server with HTTP/1.1, HTTP/2, TLS, and WebSocket support
  • utils: Utility functions for common web development tasks

Β§Feature-Gated Modules

  • websocket: WebSocket protocol support with connection management (requires websocket feature)

§🀝 Contributing

We welcome contributions! Please see our Contributing Guidelines for information on:

  • Setting up the development environment
  • Running tests and benchmarks
  • Code style and documentation standards
  • Submitting pull requests
  • Reporting issues and feature requests

Β§πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

Β§πŸ”— Resources

Re-exportsΒ§

pub use cookie::Cookie;
pub use cookie::CookieJar;
pub use cookie::SameSite;
pub use error::CustomError;
pub use error::Error;
pub use error::ErrorExt;
pub use error::ErrorHandler;
pub use error::ErrorHandlerType;
pub use error::ErrorHandlerWithRequest;
pub use error::ErrorResponse;
pub use error::Result;
pub use extension::Extension;
pub use extension::Extensions;
pub use handler::extractor::Body;
pub use handler::extractor::Cookies;
pub use handler::extractor::Form;
pub use handler::extractor::Headers;
pub use handler::extractor::Json;
pub use handler::extractor::Method as IgnitiaMethod;
pub use handler::extractor::Path;
pub use handler::extractor::Query;
pub use handler::extractor::State;
pub use handler::extractor::Uri;
pub use handler::handler_fn;
pub use handler::into_handler;
pub use handler::raw_handler;
pub use handler::Handler;
pub use handler::HandlerFn;
pub use handler::IntoHandler;
pub use handler::RawRequest;
pub use middleware::BodySizeLimitBuilder;
pub use middleware::BodySizeLimitMiddleware;
pub use middleware::CompressionMiddleware;
pub use middleware::CorsMiddleware;
pub use middleware::IdGenerator;
pub use middleware::LoggerMiddleware;
pub use middleware::Middleware;
pub use middleware::Next;
pub use middleware::RateLimitConfig;
pub use middleware::RateLimitInfo;
pub use middleware::RateLimitStats;
pub use middleware::RateLimitingMiddleware;
pub use middleware::RequestIdMiddleware;
pub use middleware::SecurityMiddleware;
pub use request::Request;
pub use response::CacheControl;
pub use response::Html;
pub use response::IntoResponse;
pub use response::Response;
pub use response::ResponseBuilder;
pub use router::LayeredHandler;
pub use router::Route;
pub use router::Router;
pub use server::Http2Config;
pub use server::PerformanceConfig;
pub use server::PoolConfig;
pub use server::Server;
pub use server::ServerConfig;
pub use multipart::Field;
pub use multipart::FileField;
pub use multipart::Multipart;
pub use multipart::MultipartConfig;
pub use multipart::MultipartError;
pub use multipart::TextField;
pub use server::tls::TlsConfig;tls
pub use server::tls::TlsError;tls
pub use server::tls::TlsVersion;tls
pub use websocket::handle_websocket_upgrade;websocket
pub use websocket::is_websocket_request;websocket
pub use websocket::upgrade_connection;websocket
pub use websocket::websocket_batch_handler;websocket
pub use websocket::websocket_handler;websocket
pub use websocket::websocket_message_handler;websocket
pub use websocket::BatchMessageHandler;websocket
pub use websocket::CloseFrame;websocket
pub use websocket::Message;websocket
pub use websocket::MessageType;websocket
pub use websocket::OptimizedMessageHandler;websocket
pub use websocket::WebSocketConnection;websocket
pub use websocket::WebSocketHandler;websocket

ModulesΒ§

cookie
Cookie Handling Module
error
Error Handling Module
extension
Extension System Module
handler
Handler module for the Ignitia web framework.
info
Framework information and build details Framework information and build metadata.
middleware
Middleware system for the Ignitia web framework.
multipart
Multipart Form Data Support
prelude
Prelude module for convenient imports
request
HTTP Request Handling Module
response
HTTP Response Generation Module
router
Router Module - High-Performance Request Routing
server
High-performance HTTP/HTTPS server implementation with advanced optimizations
utils
Utility Functions and Helpers
websocketwebsocket
WebSocket Support Module

MacrosΒ§

define_error
Macro for easily defining custom error enums with automatic trait implementations.

StructsΒ§

HeaderMap
HTTP types from the http crate A set of HTTP headers
HeaderValue
HTTP types from the http crate Represents an HTTP header field value.
Method
HTTP types from the http crate The Request Method (VERB)
StatusCode
HTTP types from the http crate An HTTP status code (status-code in RFC 9110 et al.).

ConstantsΒ§

NAME
The name of the Ignitia framework
VERSION
The current version of the Ignitia framework

Attribute MacrosΒ§

async_trait
Async trait support for defining async traits