Expand description
§Armature Core
Core library for the Armature HTTP framework - a modern, type-safe web framework for Rust inspired by Angular and NestJS.
This crate provides the foundational types, traits, and runtime components for building web applications with Armature.
§Features
- HTTP Handling: Request/Response types with fluent builders
- Routing: Path parameters, query strings, and constraints
- Dependency Injection: Type-safe DI container
- Middleware: Composable request/response processing
- Guards: Authentication and authorization
- Resilience: Circuit breakers, retries, bulkheads, and timeouts
- Logging: Structured logging with tracing integration
- Health Checks: Readiness and liveness probes
- WebSocket & SSE: Real-time communication support
§Quick Start
§HTTP Request Handling
use armature_core::HttpRequest;
// Create an HTTP request
let request = HttpRequest::new("GET".to_string(), "/api/users".to_string());
assert_eq!(request.method, "GET");
assert_eq!(request.path, "/api/users");
// Access path and query parameters
let mut post = HttpRequest::new("POST".to_string(), "/api/users/123".to_string());
post.path_params.insert("id".to_string(), "123".to_string());
post.query_params.insert("format".to_string(), "json".to_string());
post.body = b"{\"name\":\"John\"}".to_vec();
assert_eq!(post.param("id"), Some(&"123".to_string()));
assert_eq!(post.query("format"), Some(&"json".to_string()));§HTTP Response Builder
use armature_core::HttpResponse;
use serde_json::json;
// JSON response (shorthand)
let response = HttpResponse::json(&json!({"message": "Hello"})).unwrap();
assert_eq!(response.status, 200);
// HTML response
let html = HttpResponse::html("<h1>Welcome</h1>");
assert_eq!(html.status, 200);
// Redirect
let redirect = HttpResponse::redirect("https://example.com");
assert_eq!(redirect.status, 302);
// With fluent builder
let custom = HttpResponse::ok()
.content_type("application/xml")
.cache_control("max-age=3600")
.with_body(b"<xml/>".to_vec());§Dependency Injection
use armature_core::Container;
#[derive(Clone, Default)]
struct Config { debug: bool }
#[derive(Clone)]
struct UserService { config: std::sync::Arc<Config> }
let container = Container::new();
// Register services
container.register(Config { debug: true });
// Resolve services
let config = container.require::<Config>();
assert!(config.debug);
// Get or use default
let config2 = container.get_or_default::<Config>();§Error Handling
use armature_core::Error;
// Create errors with convenience methods
let err = Error::not_found("User not found");
assert_eq!(err.status_code(), 404);
assert!(err.is_client_error());
let err = Error::validation("Email is required");
assert_eq!(err.status_code(), 400);
// Get help suggestions
let err = Error::unauthorized("Invalid token");
if let Some(help) = err.help() {
println!("Help: {}", help);
}§Module Overview
| Module | Description |
|---|---|
application | Application bootstrap and lifecycle |
container | Dependency injection container |
routing | Request routing and handlers |
middleware | Middleware chain processing |
guard | Route guards for authorization |
resilience | Circuit breaker, retry, bulkhead patterns |
health | Health check endpoints |
logging | Structured logging |
websocket | WebSocket support |
sse | Server-Sent Events |
Re-exports§
pub use connection::Connection;pub use connection::ConnectionConfig;pub use connection::ConnectionEvent;pub use connection::ConnectionPool;pub use connection::ConnectionRecycler;pub use connection::ConnectionState;pub use connection::ConnectionStats;pub use connection::PoolHandle;pub use connection::Recyclable;pub use connection::RecyclableConnection;pub use connection::RecyclePool;pub use connection::RecyclePoolConfig;pub use connection::RecycleStats;pub use connection::RecyclerStats;pub use connection::StateMachineExecutor;pub use connection::TransitionAction;pub use connection::TransitionError;pub use connection::connection_stats;pub use connection::recycle_stats;pub use extensions::Extensions;pub use extractors::Body;pub use extractors::ContentType;pub use extractors::Form;pub use extractors::FromRequest;pub use extractors::FromRequestNamed;pub use extractors::Header;pub use extractors::Headers;pub use extractors::Method;pub use extractors::Path;pub use extractors::PathParams;pub use extractors::Query;pub use extractors::RawBody;pub use extractors::State;pub use handler::BoxedHandler;pub use handler::Handler;pub use handler::IntoHandler;pub use handler::OptimizedHandlerFn;pub use headers::Header as HeaderEntry;pub use headers::HeaderMap;pub use headers::INLINE_HEADERS;pub use numa::GlobalNumaStats;pub use numa::NumaAllocStats;pub use numa::NumaAllocator;pub use numa::NumaBuffer;pub use numa::NumaConfig;pub use numa::NumaError;pub use numa::NumaNode;pub use numa::NumaPolicy;pub use numa::bind_to_local_node;pub use numa::bind_to_node;pub use numa::cached_numa_config;pub use numa::current_numa_node;pub use numa::init_worker_numa;pub use numa::num_numa_nodes;pub use numa::numa_available;pub use numa::numa_stats;pub use read_buffer::AdaptiveBufferSizer;pub use read_buffer::BufferSizingStats;pub use read_buffer::ContentCategory;pub use read_buffer::DEFAULT_INITIAL_BUFFER;pub use read_buffer::HUGE_BUFFER;pub use read_buffer::LARGE_BUFFER;pub use read_buffer::MAX_BUFFER;pub use read_buffer::MEDIUM_BUFFER;pub use read_buffer::MIN_BUFFER;pub use read_buffer::PayloadTracker;pub use read_buffer::ReadBufferConfig;pub use read_buffer::SMALL_BUFFER;pub use read_buffer::TINY_BUFFER;pub use read_buffer::buffer_sizing_stats;pub use resilience::BackoffStrategy;pub use resilience::Bulkhead;pub use resilience::BulkheadConfig;pub use resilience::BulkheadError;pub use resilience::BulkheadStats;pub use resilience::CircuitBreaker;pub use resilience::CircuitBreakerConfig;pub use resilience::CircuitBreakerError;pub use resilience::CircuitBreakerStats;pub use resilience::CircuitState;pub use resilience::Fallback;pub use resilience::FallbackBuilder;pub use resilience::FallbackChain;pub use resilience::Retry;pub use resilience::RetryConfig;pub use resilience::RetryError;pub use resilience::Timeout as ResilienceTimeout;pub use resilience::TimeoutConfig;pub use resilience::TimeoutError;pub use resilience::fallback_default;pub use resilience::fallback_value;pub use response_buffer::DEFAULT_RESPONSE_CAPACITY;pub use response_buffer::LARGE_RESPONSE_CAPACITY;pub use response_buffer::MEDIUM_RESPONSE_CAPACITY;pub use response_buffer::ResponseBuffer;pub use response_buffer::ResponseBuilder;pub use response_pipeline::ConnectionPipeline;pub use response_pipeline::GlobalPipelineStats;pub use response_pipeline::ResponseBatch;pub use response_pipeline::ResponseItem;pub use response_pipeline::ResponseQueue;pub use response_pipeline::ResponseQueueStats;pub use response_pipeline::ResponseWriterConfig;pub use response_pipeline::ResponseWriterStats;pub use response_pipeline::global_pipeline_stats;pub use response_pipeline::writer_stats;pub use route_registry::OptimizedRouteHandler;pub use route_registry::RouteEntry;pub use route_registry::RouteHandlerFn;pub use routing::OptimizedHandler;pub use routing::Route;pub use routing::Router;pub use vectored_io::MAX_IO_SLICES;pub use vectored_io::ResponseChunks;pub use vectored_io::VectoredIoStats;pub use vectored_io::VectoredResponse;pub use vectored_io::status_line;pub use vectored_io::vectored_stats;pub use worker::AffinityConfig;pub use worker::AffinityError;pub use worker::AffinityMode;pub use worker::AffinityStats;pub use worker::StateFactory;pub use worker::WorkerCache;pub use worker::WorkerConfig;pub use worker::WorkerHandle;pub use worker::WorkerRouter;pub use worker::WorkerState;pub use worker::WorkerStateStats;pub use worker::WorkerStats;pub use worker::affinity_stats;pub use worker::affinity_supported;pub use worker::clear_worker_router;pub use worker::clear_worker_state;pub use worker::get_thread_affinity;pub use worker::has_worker_router;pub use worker::init_worker_router;pub use worker::init_worker_state;pub use worker::init_worker_with_affinity;pub use worker::next_worker_id;pub use worker::num_cpus;pub use worker::num_physical_cpus;pub use worker::set_thread_affinity;pub use worker::total_workers;pub use worker::worker_id;pub use worker::worker_state_stats;pub use worker::worker_stats;pub use write_coalesce::CoalesceConfig;pub use write_coalesce::CoalesceStats;pub use write_coalesce::ConnectionWriteBuffer;pub use write_coalesce::DEFAULT_COALESCE_CAPACITY;pub use write_coalesce::DEFAULT_FLUSH_THRESHOLD;pub use write_coalesce::DEFAULT_FLUSH_TIMEOUT_US;pub use write_coalesce::MAX_COALESCE_BUFFER;pub use write_coalesce::MIN_COALESCE_SIZE;pub use write_coalesce::MultiBufferCoalescer;pub use write_coalesce::WriteCoalescer;pub use write_coalesce::WriteResult;pub use write_coalesce::coalesce_stats;pub use inventory;pub use application::*;pub use body_limits::*;pub use container::*;pub use error::*;pub use form::*;pub use guard::*;pub use health::*;pub use hmr::*;pub use http::*;pub use http2::*;pub use http3::*;pub use interceptor::*;pub use lifecycle::*;pub use logging::*;pub use middleware::*;pub use module::*;pub use pagination::*;pub use route_constraint::*;pub use route_group::*;pub use shutdown::*;pub use sse::*;pub use static_assets::*;pub use status::*;pub use timeout::*;pub use tls::*;pub use traits::*;pub use websocket::*;
Modules§
- application
- arena
- Per-Request Arena Allocator
- batch
- HTTP Request Batching
- body
- Zero-Copy HTTP Body Handling
- body_
limits - Request body size limits configuration and middleware.
- body_
parser - Zero-Copy Request Body Parsing
- buffer_
pool - Thread-Local
BytesMutBuffer Pool - cache_
local - Cache-Local State Management
- connection
- Optimized Connection State Machine
- connection_
manager - Connection Manager - Dynamic Connection and Buffer Tuning
- connection_
tuning - Connection Tuning and Optimization
- container
- Dependency injection container
- cow_
state - Copy-on-Write State Management
- epoll_
tuning - Epoll Tuning and Optimization
- error
- extensions
- Type-safe request extensions for zero-cost state extraction.
- extractors
- Request parameter extractors
- fast_
response - Fast HTTP Response Creation
- form
- Form processing and multipart support
- guard
- handler
- headers
- SmallVec-Based HTTP Header Storage
- health
- Health check module for application monitoring and Kubernetes probes.
- hmr
- Hot Module Reload (HMR) System
- http
- http2
- HTTP/2 Support
- http3
- HTTP/3 (QUIC) Support
- interceptor
- io_
uring io_uringBackend for High-Performance I/O (Linux 5.1+)- json
- High-Performance JSON Serialization and Deserialization
- lifecycle
- Lifecycle hook system for Armature framework.
- load_
balancer - Worker Load Balancing
- logging
- Comprehensive logging system for Armature
- memory_
opt - Memory Optimization Utilities
- micro
- Micro-framework API for lightweight applications
- middleware
- module
- Module system for organizing and composing application components.
- numa
- NUMA-Aware Memory Allocation
- pagination
- Pagination, filtering, sorting, and field selection utilities
- pipeline
- HTTP/1.1 Pipelining Support
- read_
buffer - Read Buffer Sizing Module
- read_
state - Read-Optimized State Management
- resilience
- Resilience Patterns
- response_
buffer - Pre-Allocated Response Buffer
- response_
pipeline - Response Pipelining Module
- route_
cache - Route Matching Cache and Static Route Optimization
- route_
constraint - Route constraints for parameter validation
- route_
group - Route groups for organizing routes with shared configuration
- route_
params - Zero-Allocation Route Parameter Extraction
- route_
registry - Route registry for compile-time route collection using inventory
- routing
- runtime_
config - Async Runtime Configuration and Optimization
- serialization_
pool - Serialization Buffer Pool
- shutdown
- Graceful shutdown support for Armature applications
- simd_
parser - SIMD-Optimized HTTP Parsing
- small_
vec - Small Vector Optimizations
- socket_
batch - Batched Socket Operations
- sse
- static_
assets - Static asset serving with configurable caching and compression.
- status
- streaming
- Streaming HTTP Responses
- timeout
- Request timeout configuration and utilities.
- tls
- TLS/HTTPS support for Armature
- tower_
compat - Tower Service and HTTP Crate Compatibility
- traits
- Core traits for the Armature framework
- vectored_
io - Vectored I/O for HTTP Responses
- websocket
- worker
- Per-Worker State Management
- write_
coalesce - Write Buffer Coalescing Module
- zero_
cost - Zero-Cost Abstractions for High-Performance HTTP Handling
Macros§
- body
- Extract body from request as the specified type
- guard_
registration - Helper macro to create guard registrations
- header
- Extract header from request
- json
- Create a JSON value using serde_json’s json! macro.
- path
- Extract path parameter from request
- provider_
registration - Helper macro to create provider registrations
- query
- Extract query parameters from request as the specified type
- register_
route - Macro to register a route handler with the inventory (legacy)
- register_
route_ optimized - Macro to register an optimized route handler with the inventory
- with_
worker_ router - Initialize worker router and execute code.