allframe_core/lib.rs
1//! # AllFrame Core
2//!
3//! [](https://crates.io/crates/allframe-core)
4//! [](https://docs.rs/allframe-core)
5//! [](https://github.com/all-source-os/all-frame)
6//!
7//! **The Composable Rust API Framework** - Protocol-agnostic routing, CQRS/ES,
8//! resilience patterns, and beautiful API documentation.
9//!
10//! AllFrame is the first Rust web framework designed, built, and evolved
11//! exclusively through **Test-Driven Development (TDD)** with 450+ tests.
12//!
13//! ## Features at a Glance
14//!
15//! | Feature | Description |
16//! |---------|-------------|
17//! | 🔀 **Protocol-Agnostic** | Write once, expose via REST, GraphQL, and gRPC |
18//! | 📖 **Auto Documentation** | Scalar UI, GraphiQL, gRPC Explorer built-in |
19//! | 🔄 **CQRS/Event Sourcing** | 85% boilerplate reduction with CommandBus, Projections, Sagas |
20//! | 🛡️ **Resilience Patterns** | Retry, Circuit Breaker, Rate Limiting |
21//! | 🔒 **Security Utilities** | Safe logging, credential obfuscation |
22//! | 💉 **Compile-time DI** | Dependency injection resolved at compile time |
23//! | 📊 **OpenTelemetry** | Automatic tracing and metrics |
24//!
25//! ## Quick Start
26//!
27//! Add to your `Cargo.toml`:
28//!
29//! ```toml
30//! [dependencies]
31//! allframe = "0.1"
32//! tokio = { version = "1", features = ["full"] }
33//! ```
34//!
35//! ### Basic Router Example
36//!
37//! ```rust
38//! use allframe_core::router::{Router, RestAdapter, ProtocolAdapter};
39//!
40//! #[tokio::main]
41//! async fn main() {
42//! // Create a router
43//! let mut router = Router::new();
44//!
45//! // Register handlers - works with any protocol!
46//! router.register("get_users", || async {
47//! r#"[{"id": 1, "name": "Alice"}]"#.to_string()
48//! });
49//!
50//! router.register("create_user", || async {
51//! r#"{"id": 2, "name": "Bob"}"#.to_string()
52//! });
53//!
54//! // Expose via REST
55//! let mut rest = RestAdapter::new();
56//! rest.route("GET", "/users", "get_users");
57//! rest.route("POST", "/users", "create_user");
58//!
59//! println!("Router configured with {} handlers", 2);
60//! }
61//! ```
62//!
63//! ### Protocol-Agnostic Handler
64//!
65//! ```rust
66//! use allframe_core::router::{Router, RestAdapter, GraphQLAdapter, GrpcAdapter};
67//!
68//! // Same handler, multiple protocols!
69//! let mut router = Router::new();
70//! router.register("get_user", || async {
71//! r#"{"id": 42, "name": "John"}"#.to_string()
72//! });
73//!
74//! // REST: GET /users/42
75//! let mut rest = RestAdapter::new();
76//! rest.route("GET", "/users/:id", "get_user");
77//!
78//! // GraphQL: query { user(id: 42) { name } }
79//! let mut graphql = GraphQLAdapter::new();
80//! graphql.query("user", "get_user");
81//!
82//! // gRPC: UserService.GetUser
83//! let mut grpc = GrpcAdapter::new();
84//! grpc.unary("UserService", "GetUser", "get_user");
85//! ```
86//!
87//! ## Feature Flags
88//!
89//! AllFrame uses feature flags to minimize binary size. Only enable what you need:
90//!
91//! | Feature | Description | Default |
92//! |---------|-------------|---------|
93//! | `router` | Protocol-agnostic routing | ✅ |
94//! | `router-graphql` | GraphQL adapter with async-graphql | ❌ |
95//! | `router-grpc` | gRPC adapter with tonic | ❌ |
96//! | `di` | Compile-time dependency injection | ✅ |
97//! | `cqrs` | CQRS + Event Sourcing infrastructure | ✅ |
98//! | `otel` | OpenTelemetry tracing | ✅ |
99//! | `health` | Health check endpoints | ✅ |
100//! | `resilience` | Retry, Circuit Breaker, Rate Limiting | ❌ |
101//! | `security` | Safe logging, credential obfuscation | ❌ |
102//!
103//! ### Feature Examples
104//!
105//! ```toml
106//! # Minimal REST API
107//! allframe = { version = "0.1", default-features = false, features = ["router"] }
108//!
109//! # Full-stack with resilience
110//! allframe = { version = "0.1", features = ["resilience", "security"] }
111//!
112//! # Multi-protocol gateway
113//! allframe = { version = "0.1", features = ["router-graphql", "router-grpc"] }
114//! ```
115//!
116//! ## Module Overview
117//!
118//! - [`router`] - Protocol-agnostic request routing (REST, GraphQL, gRPC)
119//! - [`shutdown`] - Graceful shutdown utilities
120//! - [`cache`] - Caching infrastructure
121//! - `cqrs` - CQRS + Event Sourcing (requires `cqrs` feature)
122//! - `resilience` - Retry, Circuit Breaker, Rate Limiting (requires `resilience` feature)
123//! - `security` - Safe logging and credential obfuscation (requires `security` feature)
124//! - `di` - Compile-time dependency injection (requires `di` feature)
125//! - `otel` - OpenTelemetry instrumentation (requires `otel` feature)
126//! - `health` - Health check infrastructure (requires `health` feature)
127//!
128//! ## Examples
129//!
130//! See the [examples directory](https://github.com/all-source-os/all-frame/tree/main/crates/allframe-core/examples)
131//! for complete working examples:
132//!
133//! - `scalar_docs.rs` - REST API with Scalar documentation
134//! - `graphql_docs.rs` - GraphQL API with GraphiQL playground
135//! - `resilience.rs` - Retry, Circuit Breaker, Rate Limiting
136//! - `graceful_shutdown.rs` - Production shutdown handling
137//!
138//! ## Learn More
139//!
140//! - [GitHub Repository](https://github.com/all-source-os/all-frame)
141//! - [Feature Flags Guide](https://github.com/all-source-os/all-frame/blob/main/docs/guides/FEATURE_FLAGS.md)
142//! - [CQRS Documentation](https://github.com/all-source-os/all-frame/blob/main/docs/phases/PHASE5_COMPLETE.md)
143
144#![deny(warnings)]
145#![deny(missing_docs)]
146#![deny(unsafe_code)]
147// Enable doc_cfg for showing feature requirements on docs.rs
148#![cfg_attr(docsrs, feature(doc_cfg))]
149
150/// Clean Architecture enforcement with compile-time dependency injection.
151///
152/// The `arch` module provides traits and utilities for enforcing Clean Architecture
153/// patterns in your application. Use the `#[inject]` macro to wire up dependencies.
154///
155/// # Example
156///
157/// ```rust,ignore
158/// use allframe::arch::*;
159///
160/// #[inject]
161/// struct MyService {
162/// repo: Arc<dyn UserRepository>,
163/// }
164/// ```
165#[cfg(feature = "di")]
166#[cfg_attr(docsrs, doc(cfg(feature = "di")))]
167pub mod arch;
168
169/// CQRS + Event Sourcing infrastructure with 85% boilerplate reduction.
170///
171/// This module provides production-ready CQRS primitives:
172/// - [`cqrs::CommandBus`] - Type-safe command dispatch (90% less code)
173/// - [`cqrs::EventStore`] - Event storage with replay capability
174/// - [`cqrs::ProjectionRegistry`] - Automatic projection updates (90% less code)
175/// - [`cqrs::SagaOrchestrator`] - Distributed transaction handling (75% less code)
176///
177/// # Example
178///
179/// ```rust,ignore
180/// use allframe::cqrs::{CommandBus, Event, EventStore};
181///
182/// #[derive(Clone)]
183/// struct CreateUser { name: String }
184///
185/// let bus = CommandBus::new();
186/// bus.dispatch(CreateUser { name: "Alice".into() }).await?;
187/// ```
188#[cfg(feature = "cqrs")]
189#[cfg_attr(docsrs, doc(cfg(feature = "cqrs")))]
190pub mod cqrs;
191
192/// OpenTelemetry automatic instrumentation for distributed tracing.
193///
194/// Use the `#[traced]` macro to automatically instrument your functions:
195///
196/// ```rust,ignore
197/// use allframe::otel::traced;
198///
199/// #[traced]
200/// async fn fetch_user(id: &str) -> User {
201/// // Automatically creates a span with function name
202/// }
203/// ```
204#[cfg(feature = "otel")]
205#[cfg_attr(docsrs, doc(cfg(feature = "otel")))]
206pub mod otel;
207
208/// Cache abstraction with in-memory and Redis backends.
209///
210/// Provides a unified caching interface with configurable TTL and eviction.
211pub mod cache;
212
213/// Compile-time dependency injection infrastructure.
214///
215/// Build dependency graphs that are resolved at compile time for zero runtime overhead.
216///
217/// # Example
218///
219/// ```rust,ignore
220/// use allframe::di::{ContainerBuilder, Provider};
221///
222/// let container = ContainerBuilder::new()
223/// .register::<DatabasePool>()
224/// .register::<UserRepository>()
225/// .build();
226/// ```
227#[cfg(feature = "di")]
228#[cfg_attr(docsrs, doc(cfg(feature = "di")))]
229pub mod di;
230
231/// Health check infrastructure for Kubernetes-ready services.
232///
233/// Provides liveness and readiness probes with dependency health aggregation.
234///
235/// # Example
236///
237/// ```rust,ignore
238/// use allframe::health::{HealthServer, HealthCheck};
239///
240/// let server = HealthServer::new()
241/// .add_check("database", db_check)
242/// .add_check("cache", cache_check);
243///
244/// server.serve(8080).await;
245/// ```
246#[cfg(feature = "health")]
247#[cfg_attr(docsrs, doc(cfg(feature = "health")))]
248pub mod health;
249
250/// Protocol-agnostic request routing for REST, GraphQL, and gRPC.
251///
252/// Write handlers once, expose them via any protocol:
253///
254/// # Example
255///
256/// ```rust
257/// use allframe_core::router::{Router, RestAdapter, GraphQLAdapter, GrpcAdapter};
258///
259/// let mut router = Router::new();
260/// router.register("get_user", || async { r#"{"id": 1}"#.to_string() });
261///
262/// // Same handler, three protocols!
263/// let mut rest = RestAdapter::new();
264/// rest.route("GET", "/users/:id", "get_user");
265///
266/// let mut graphql = GraphQLAdapter::new();
267/// graphql.query("user", "get_user");
268///
269/// let mut grpc = GrpcAdapter::new();
270/// grpc.unary("UserService", "GetUser", "get_user");
271/// ```
272///
273/// Also includes documentation generators:
274/// - `scalar_html` - Scalar UI for REST APIs
275/// - `graphiql_html` - GraphiQL playground for GraphQL
276/// - `grpc_explorer_html` - gRPC Explorer
277pub mod router;
278
279/// Graceful shutdown utilities for production services.
280///
281/// Handle SIGTERM/SIGINT signals and coordinate clean shutdown across tasks.
282///
283/// # Example
284///
285/// ```rust,ignore
286/// use allframe::shutdown::{ShutdownSignal, GracefulShutdownExt};
287///
288/// let signal = ShutdownSignal::new();
289///
290/// // In your main loop
291/// tokio::select! {
292/// _ = server.run() => {},
293/// _ = signal.recv() => {
294/// server.perform_shutdown().await;
295/// }
296/// }
297/// ```
298pub mod shutdown;
299
300/// Resilience patterns: Retry, Circuit Breaker, and Rate Limiting.
301///
302/// Production-ready patterns for fault-tolerant microservices:
303///
304/// # Example
305///
306/// ```rust,ignore
307/// use allframe::resilience::{RetryExecutor, CircuitBreaker, RateLimiter};
308///
309/// // Retry with exponential backoff
310/// let retry = RetryExecutor::new(RetryConfig::default());
311/// let result = retry.execute("api_call", || async {
312/// external_api.call().await
313/// }).await;
314///
315/// // Circuit breaker for fail-fast
316/// let cb = CircuitBreaker::new("payments", CircuitBreakerConfig::default());
317/// let result = cb.call(|| payment_service.charge()).await;
318///
319/// // Rate limiting
320/// let limiter = RateLimiter::new(100, 10); // 100 RPS, burst of 10
321/// if limiter.check().is_ok() {
322/// process_request().await;
323/// }
324/// ```
325#[cfg(feature = "resilience")]
326#[cfg_attr(docsrs, doc(cfg(feature = "resilience")))]
327pub mod resilience;
328
329/// Security utilities for safe logging and credential obfuscation.
330///
331/// Prevent accidental credential leaks in logs:
332///
333/// # Example
334///
335/// ```rust,ignore
336/// use allframe::security::{obfuscate_url, Sensitive};
337///
338/// let url = "https://user:password@api.example.com/v1/users";
339/// println!("Connecting to: {}", obfuscate_url(url));
340/// // Output: "Connecting to: https://api.example.com"
341///
342/// let api_key = Sensitive::new("sk_live_abcd1234");
343/// println!("Using key: {:?}", api_key);
344/// // Output: "Using key: ***"
345/// ```
346#[cfg(feature = "security")]
347#[cfg_attr(docsrs, doc(cfg(feature = "security")))]
348pub mod security;
349
350/// gRPC server infrastructure with TLS support.
351///
352/// Production-ready gRPC server with health checks and reflection.
353#[cfg(feature = "router-grpc")]
354#[cfg_attr(docsrs, doc(cfg(feature = "router-grpc")))]
355pub mod grpc;
356
357/// Authentication primitives with layered feature flags.
358///
359/// This module provides authentication infrastructure that can be used
360/// independently or integrated with your web framework:
361///
362/// - **`auth`**: Core traits only (zero dependencies)
363/// - **`auth-jwt`**: JWT validation with HS256/RS256 support
364/// - **`auth-axum`**: Axum extractors and middleware
365/// - **`auth-tonic`**: gRPC interceptors
366///
367/// # Example
368///
369/// ```rust,ignore
370/// use allframe_core::auth::{JwtValidator, JwtConfig, Authenticator};
371///
372/// let validator = JwtValidator::<Claims>::new(
373/// JwtConfig::hs256("secret").with_issuer("my-app")
374/// );
375///
376/// let claims = validator.authenticate("eyJ...").await?;
377/// ```
378#[cfg(feature = "auth")]
379#[cfg_attr(docsrs, doc(cfg(feature = "auth")))]
380pub mod auth;
381
382// ============================================================================
383// Re-exported dependencies
384// ============================================================================
385// These re-exports allow consumers to use common dependencies without adding
386// them explicitly to their Cargo.toml. This ensures version consistency and
387// reduces boilerplate in downstream crates.
388
389// ============================================================================
390// Re-exported macros
391// ============================================================================
392/// Re-export circuit_breaker attribute macro
393#[cfg(feature = "resilience")]
394pub use allframe_macros::circuit_breaker;
395/// Re-export rate_limited attribute macro
396#[cfg(feature = "resilience")]
397pub use allframe_macros::rate_limited;
398/// Re-export retry attribute macro
399#[cfg(feature = "resilience")]
400pub use allframe_macros::retry;
401/// Re-export GrpcError derive macro for automatic tonic::Status conversion
402#[cfg(feature = "router-grpc")]
403pub use allframe_macros::GrpcError;
404/// Re-export HealthCheck derive macro for automatic health check implementation
405#[cfg(feature = "di")]
406pub use allframe_macros::HealthCheck;
407/// Re-export Obfuscate derive macro for safe logging
408#[cfg(feature = "security")]
409pub use allframe_macros::Obfuscate;
410/// Re-export async_graphql for GraphQL support
411#[cfg(feature = "router-graphql")]
412pub use async_graphql;
413/// Re-export async_graphql_parser for GraphQL parsing
414#[cfg(feature = "router-graphql")]
415pub use async_graphql_parser;
416/// Re-export async_trait for async trait definitions
417pub use async_trait;
418/// Re-export backoff for retry/resilience patterns
419#[cfg(feature = "resilience")]
420pub use backoff;
421/// Re-export chrono for date/time handling
422#[cfg(feature = "utils")]
423pub use chrono;
424/// Re-export dashmap for concurrent hash maps
425#[cfg(feature = "cache-memory")]
426pub use dashmap;
427/// Re-export futures for async utilities
428#[cfg(feature = "router-grpc")]
429pub use futures;
430/// Re-export governor for rate limiting
431#[cfg(feature = "rate-limit")]
432pub use governor;
433/// Re-export hyper for HTTP primitives
434#[cfg(feature = "health")]
435pub use hyper;
436/// Re-export moka for high-performance caching
437#[cfg(feature = "cache-memory")]
438pub use moka;
439/// Re-export opentelemetry for full observability
440#[cfg(feature = "otel-otlp")]
441pub use opentelemetry;
442/// Re-export opentelemetry_otlp for OTLP exporter
443#[cfg(feature = "otel-otlp")]
444pub use opentelemetry_otlp;
445/// Re-export opentelemetry_sdk for SDK configuration
446#[cfg(feature = "otel-otlp")]
447pub use opentelemetry_sdk;
448/// Re-export parking_lot for efficient synchronization primitives
449#[cfg(feature = "utils")]
450pub use parking_lot;
451/// Re-export prometheus for metrics
452#[cfg(feature = "metrics")]
453pub use prometheus;
454/// Re-export prost for protobuf support
455#[cfg(feature = "router-grpc")]
456pub use prost;
457/// Re-export prost_types for well-known protobuf types
458#[cfg(feature = "router-grpc")]
459pub use prost_types;
460/// Re-export rand for random number generation
461#[cfg(feature = "utils")]
462pub use rand;
463/// Re-export redis for Redis client
464#[cfg(feature = "cache-redis")]
465pub use redis;
466/// Re-export reqwest for HTTP client functionality
467#[cfg(feature = "http-client")]
468pub use reqwest;
469/// Re-export serde for serialization
470pub use serde;
471/// Re-export serde_json for JSON handling
472pub use serde_json;
473/// Re-export tokio for async runtime
474pub use tokio;
475/// Re-export tokio_stream for async streams
476#[cfg(feature = "router-grpc")]
477pub use tokio_stream;
478/// Re-export tonic for gRPC support
479#[cfg(feature = "router-grpc")]
480pub use tonic;
481/// Re-export tonic_reflection for gRPC reflection
482#[cfg(feature = "router-grpc")]
483pub use tonic_reflection;
484/// Re-export tracing for observability
485#[cfg(feature = "otel")]
486pub use tracing;
487/// Re-export tracing_opentelemetry for tracing integration
488#[cfg(feature = "otel-otlp")]
489pub use tracing_opentelemetry;
490/// Re-export tracing_subscriber for log configuration
491#[cfg(feature = "otel-otlp")]
492pub use tracing_subscriber;
493/// Re-export url for URL parsing
494#[cfg(feature = "utils")]
495pub use url;
496
497/// Prelude module for convenient imports
498///
499/// Commonly used imports for AllFrame applications
500pub mod prelude {
501 /// Re-export cache utilities
502 pub use crate::cache::{Cache, CacheConfig, CacheKey, MemoryCache};
503 /// Re-export DI utilities
504 #[cfg(feature = "di")]
505 pub use crate::di::{
506 AsyncInit, AsyncInitWith, ContainerBuilder, DependencyError, DependencyRegistry, FromEnv,
507 Provider, Scope,
508 };
509 /// Re-export gRPC server utilities
510 #[cfg(feature = "router-grpc")]
511 pub use crate::grpc::{GrpcServer, GrpcServerBuilder, GrpcServerError, TlsConfig};
512 /// Re-export health check utilities
513 #[cfg(feature = "health")]
514 pub use crate::health::{
515 Dependency, DependencyStatus, HealthCheck, HealthReport, HealthServer, OverallStatus,
516 SimpleHealthCheck,
517 };
518 pub use crate::router::{
519 GraphQLAdapter, GrpcAdapter, GrpcRequest, GrpcStatus, Method, ProtocolAdapter, RestAdapter,
520 RestRequest, RestResponse, RouteMetadata, Router, ToJsonSchema,
521 };
522 #[cfg(feature = "router")]
523 pub use crate::router::{GraphQLConfig, GrpcConfig, RestConfig, RouterConfig, ServerConfig};
524 /// Re-export shutdown utilities
525 pub use crate::shutdown::{
526 GracefulShutdown, GracefulShutdownExt, ShutdownAwareTaskSpawner, ShutdownSignal,
527 ShutdownToken,
528 };
529 /// Re-export GrpcError for convenient error handling
530 #[cfg(feature = "router-grpc")]
531 pub use crate::GrpcError;
532}
533
534#[cfg(test)]
535mod tests {
536 #[test]
537 fn test_allframe_core_exists() {
538 // This test verifies the crate compiles
539 assert!(true);
540 }
541}