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