armature_core/
lib.rs

1//! # Armature Core
2//!
3//! Core library for the Armature HTTP framework - a modern, type-safe web framework for Rust
4//! inspired by Angular and NestJS.
5//!
6//! This crate provides the foundational types, traits, and runtime components
7//! for building web applications with Armature.
8//!
9//! ## Features
10//!
11//! - **HTTP Handling**: Request/Response types with fluent builders
12//! - **Routing**: Path parameters, query strings, and constraints
13//! - **Dependency Injection**: Type-safe DI container
14//! - **Middleware**: Composable request/response processing
15//! - **Guards**: Authentication and authorization
16//! - **Resilience**: Circuit breakers, retries, bulkheads, and timeouts
17//! - **Logging**: Structured logging with tracing integration
18//! - **Health Checks**: Readiness and liveness probes
19//! - **WebSocket & SSE**: Real-time communication support
20//!
21//! ## Quick Start
22//!
23//! ### HTTP Request Handling
24//!
25//! ```
26//! use armature_core::HttpRequest;
27//!
28//! // Create an HTTP request
29//! let request = HttpRequest::new("GET".to_string(), "/api/users".to_string());
30//!
31//! assert_eq!(request.method, "GET");
32//! assert_eq!(request.path, "/api/users");
33//!
34//! // Access path and query parameters
35//! let mut post = HttpRequest::new("POST".to_string(), "/api/users/123".to_string());
36//! post.path_params.insert("id".to_string(), "123".to_string());
37//! post.query_params.insert("format".to_string(), "json".to_string());
38//! post.body = b"{\"name\":\"John\"}".to_vec();
39//!
40//! assert_eq!(post.param("id"), Some(&"123".to_string()));
41//! assert_eq!(post.query("format"), Some(&"json".to_string()));
42//! ```
43//!
44//! ### HTTP Response Builder
45//!
46//! ```
47//! use armature_core::HttpResponse;
48//! use serde_json::json;
49//!
50//! // JSON response (shorthand)
51//! let response = HttpResponse::json(&json!({"message": "Hello"})).unwrap();
52//! assert_eq!(response.status, 200);
53//!
54//! // HTML response
55//! let html = HttpResponse::html("<h1>Welcome</h1>");
56//! assert_eq!(html.status, 200);
57//!
58//! // Redirect
59//! let redirect = HttpResponse::redirect("https://example.com");
60//! assert_eq!(redirect.status, 302);
61//!
62//! // With fluent builder
63//! let custom = HttpResponse::ok()
64//!     .content_type("application/xml")
65//!     .cache_control("max-age=3600")
66//!     .with_body(b"<xml/>".to_vec());
67//! ```
68//!
69//! ### Dependency Injection
70//!
71//! ```
72//! use armature_core::Container;
73//!
74//! #[derive(Clone, Default)]
75//! struct Config { debug: bool }
76//!
77//! #[derive(Clone)]
78//! struct UserService { config: std::sync::Arc<Config> }
79//!
80//! let container = Container::new();
81//!
82//! // Register services
83//! container.register(Config { debug: true });
84//!
85//! // Resolve services
86//! let config = container.require::<Config>();
87//! assert!(config.debug);
88//!
89//! // Get or use default
90//! let config2 = container.get_or_default::<Config>();
91//! ```
92//!
93//! ### Error Handling
94//!
95//! ```
96//! use armature_core::Error;
97//!
98//! // Create errors with convenience methods
99//! let err = Error::not_found("User not found");
100//! assert_eq!(err.status_code(), 404);
101//! assert!(err.is_client_error());
102//!
103//! let err = Error::validation("Email is required");
104//! assert_eq!(err.status_code(), 400);
105//!
106//! // Get help suggestions
107//! let err = Error::unauthorized("Invalid token");
108//! if let Some(help) = err.help() {
109//!     println!("Help: {}", help);
110//! }
111//! ```
112//!
113//! ## Module Overview
114//!
115//! | Module | Description |
116//! |--------|-------------|
117//! | [`application`] | Application bootstrap and lifecycle |
118//! | [`container`] | Dependency injection container |
119//! | [`routing`] | Request routing and handlers |
120//! | [`middleware`] | Middleware chain processing |
121//! | [`guard`] | Route guards for authorization |
122//! | [`resilience`] | Circuit breaker, retry, bulkhead patterns |
123//! | [`health`] | Health check endpoints |
124//! | [`logging`] | Structured logging |
125//! | [`websocket`] | WebSocket support |
126//! | [`sse`] | Server-Sent Events |
127
128pub mod application;
129pub mod arena;
130pub mod batch;
131pub mod body;
132pub mod body_limits;
133pub mod body_parser;
134pub mod buffer_pool;
135pub mod cache_local;
136pub mod connection;
137pub mod connection_manager;
138pub mod connection_tuning;
139pub mod container;
140pub mod cow_state;
141pub mod epoll_tuning;
142pub mod error;
143pub mod extensions;
144pub mod extractors;
145pub mod fast_response;
146pub mod form;
147pub mod guard;
148pub mod handler;
149pub mod headers;
150pub mod health;
151pub mod hmr;
152pub mod http;
153pub mod http2;
154pub mod http3;
155pub mod interceptor;
156pub mod io_uring;
157pub mod json;
158pub mod lifecycle;
159pub mod load_balancer;
160pub mod logging;
161pub mod memory_opt;
162pub mod middleware;
163pub mod module;
164pub mod numa;
165pub mod pagination;
166pub mod pipeline;
167pub mod read_buffer;
168pub mod read_state;
169pub mod resilience;
170pub mod response_buffer;
171pub mod response_pipeline;
172pub mod route_cache;
173pub mod route_constraint;
174pub mod route_group;
175pub mod route_params;
176pub mod route_registry;
177pub mod routing;
178pub mod runtime_config;
179pub mod serialization_pool;
180pub mod shutdown;
181pub mod simd_parser;
182pub mod small_vec;
183pub mod socket_batch;
184pub mod sse;
185pub mod static_assets;
186pub mod status;
187pub mod streaming;
188pub mod timeout;
189pub mod tls;
190pub mod tower_compat;
191pub mod traits;
192pub mod vectored_io;
193pub mod websocket;
194pub mod worker;
195pub mod write_coalesce;
196pub mod zero_cost;
197
198/// Micro-framework API for lightweight applications
199///
200/// Provides an Actix-style API without the full module/controller system.
201pub mod micro;
202
203// Re-export commonly used types
204pub use application::*;
205pub use body_limits::*;
206pub use connection::{
207    Connection, ConnectionConfig, ConnectionEvent, ConnectionPool, ConnectionRecycler,
208    ConnectionState, ConnectionStats, PoolHandle, Recyclable, RecyclableConnection, RecyclePool,
209    RecyclePoolConfig, RecycleStats, RecyclerStats, StateMachineExecutor, TransitionAction,
210    TransitionError, connection_stats, recycle_stats,
211};
212pub use container::*;
213pub use error::*;
214pub use extensions::Extensions;
215pub use extractors::{
216    Body, ContentType, Form, FromRequest, FromRequestNamed, Header, Headers, Method, Path,
217    PathParams, Query, RawBody, State,
218};
219pub use form::*;
220pub use guard::*;
221pub use handler::{BoxedHandler, Handler, IntoHandler, OptimizedHandlerFn};
222pub use headers::{Header as HeaderEntry, HeaderMap, INLINE_HEADERS};
223pub use health::*;
224pub use hmr::*;
225pub use http::*;
226pub use http2::*;
227pub use http3::*;
228pub use interceptor::*;
229pub use lifecycle::*;
230pub use logging::*;
231pub use middleware::*;
232pub use module::*;
233pub use numa::{
234    GlobalNumaStats, NumaAllocStats, NumaAllocator, NumaBuffer, NumaConfig, NumaError, NumaNode,
235    NumaPolicy, bind_to_local_node, bind_to_node, cached_numa_config, current_numa_node,
236    init_worker_numa, num_numa_nodes, numa_available, numa_stats,
237};
238pub use pagination::*;
239pub use read_buffer::{
240    AdaptiveBufferSizer, BufferSizingStats, ContentCategory, DEFAULT_INITIAL_BUFFER, HUGE_BUFFER,
241    LARGE_BUFFER, MAX_BUFFER, MEDIUM_BUFFER, MIN_BUFFER, PayloadTracker, ReadBufferConfig,
242    SMALL_BUFFER, TINY_BUFFER, buffer_sizing_stats,
243};
244pub use resilience::{
245    BackoffStrategy, Bulkhead, BulkheadConfig, BulkheadError, BulkheadStats, CircuitBreaker,
246    CircuitBreakerConfig, CircuitBreakerError, CircuitBreakerStats, CircuitState, Fallback,
247    FallbackBuilder, FallbackChain, Retry, RetryConfig, RetryError, Timeout as ResilienceTimeout,
248    TimeoutConfig, TimeoutError, fallback_default, fallback_value,
249};
250pub use response_buffer::{
251    DEFAULT_RESPONSE_CAPACITY, LARGE_RESPONSE_CAPACITY, MEDIUM_RESPONSE_CAPACITY, ResponseBuffer,
252    ResponseBuilder,
253};
254pub use response_pipeline::{
255    ConnectionPipeline, GlobalPipelineStats, ResponseBatch, ResponseItem, ResponseQueue,
256    ResponseQueueStats, ResponseWriterConfig, ResponseWriterStats, global_pipeline_stats,
257    writer_stats,
258};
259pub use route_constraint::*;
260pub use route_group::*;
261pub use route_registry::{OptimizedRouteHandler, RouteEntry, RouteHandlerFn};
262pub use routing::{OptimizedHandler, Route, Router}; // Explicit exports to avoid ambiguous HandlerFn
263pub use shutdown::*;
264pub use sse::*;
265pub use static_assets::*;
266pub use status::*;
267pub use timeout::*;
268pub use tls::*;
269pub use traits::*;
270pub use vectored_io::{
271    MAX_IO_SLICES, ResponseChunks, VectoredIoStats, VectoredResponse, status_line, vectored_stats,
272};
273pub use websocket::*;
274pub use worker::{
275    AffinityConfig, AffinityError, AffinityMode, AffinityStats, StateFactory, WorkerCache,
276    WorkerConfig, WorkerHandle, WorkerRouter, WorkerState, WorkerStateStats, WorkerStats,
277    affinity_stats, affinity_supported, clear_worker_router, clear_worker_state,
278    get_thread_affinity, has_worker_router, init_worker_router, init_worker_state,
279    init_worker_with_affinity, next_worker_id, num_cpus, num_physical_cpus, set_thread_affinity,
280    total_workers, worker_id, worker_state_stats, worker_stats,
281};
282pub use write_coalesce::{
283    CoalesceConfig, CoalesceStats, ConnectionWriteBuffer, DEFAULT_COALESCE_CAPACITY,
284    DEFAULT_FLUSH_THRESHOLD, DEFAULT_FLUSH_TIMEOUT_US, MAX_COALESCE_BUFFER, MIN_COALESCE_SIZE,
285    MultiBufferCoalescer, WriteCoalescer, WriteResult, coalesce_stats,
286};
287
288// Re-export inventory for route registration macros
289pub use inventory;