axum_conf/lib.rs
1//! # axum-conf
2//!
3//! A batteries-included library for building production-ready web services with Axum,
4//! designed specifically for Kubernetes deployments.
5//!
6//! Get health probes, metrics, security headers, rate limiting, and more — all
7//! configured through simple TOML.
8//!
9//! **📖 For detailed guides, see the [documentation](../docs/):**
10//! - [Getting Started](../docs/getting-started.md) - Build your first service
11//! - [Architecture](../docs/architecture.md) - How axum-conf works
12//! - [Configuration Reference](../docs/configuration/toml-reference.md) - All options
13//! - [Troubleshooting](../docs/troubleshooting.md) - Common issues
14//!
15//! # Quick Start
16//!
17//! ```rust,no_run
18//! use axum::{Router, routing::get};
19//! use axum_conf::{Config, Result, FluentRouter};
20//!
21//! async fn hello() -> &'static str {
22//! "Hello, World!"
23//! }
24//!
25//! #[tokio::main]
26//! async fn main() -> Result<()> {
27//! let config = Config::default(); // Loads from config/{RUST_ENV}.toml
28//! config.setup_tracing();
29//!
30//! FluentRouter::without_state(config)?
31//! .route("/", get(hello))
32//! .setup_middleware()
33//! .await?
34//! .start()
35//! .await
36//! }
37//! ```
38//!
39//! With `config/dev.toml`:
40//! ```toml
41//! [http]
42//! bind_port = 3000
43//! max_payload_size_bytes = "1MiB"
44//! ```
45//!
46//! Run with `RUST_ENV=dev cargo run`.
47//!
48//! # What You Get
49//!
50//! | Feature | Description | Default |
51//! |---------|-------------|---------|
52//! | Health probes | `/live` and `/ready` endpoints | Enabled |
53//! | Prometheus metrics | Request counts, latencies at `/metrics` | Enabled |
54//! | Request logging | Structured logs with UUIDv7 correlation IDs | Enabled |
55//! | Rate limiting | Per-IP request throttling | 100 req/sec |
56//! | Security headers | X-Frame-Options, X-Content-Type-Options | Enabled |
57//! | Panic recovery | Catches panics, returns 500, keeps running | Enabled |
58//! | Graceful shutdown | Handles SIGTERM, drains connections | 30s timeout |
59//! | Compression | gzip, brotli, deflate, zstd | Available |
60//!
61//! # Cargo Features
62//!
63//! | Feature | Description |
64//! |---------|-------------|
65//! | `postgres` | PostgreSQL connection pooling (enables `rustls`) |
66//! | `keycloak` | OIDC/JWT authentication (enables `session`) |
67//! | `session` | Cookie-based session management |
68//! | `opentelemetry` | Distributed tracing with OTLP export |
69//! | `basic-auth` | HTTP Basic Auth and API key authentication |
70//! | `rustls` | TLS support |
71//!
72//! # Module Organization
73//!
74//! | Module | Description |
75//! |--------|-------------|
76//! | [`config`] | Configuration loading and validation ([`Config`]) |
77//! | [`fluent`] | Router builder and middleware setup ([`FluentRouter`]) |
78//! | `error` | Error types and handling ([`Error`]) |
79//! | `utils` | Utilities ([`ApiVersion`], [`Sensitive`]) |
80//!
81//! # Configuration
82//!
83//! Configuration can be loaded from TOML files, strings, or built programmatically:
84//!
85//! ```rust
86//! use axum_conf::Config;
87//! use std::time::Duration;
88//!
89//! // From file (recommended for production)
90//! let config = Config::default(); // Uses RUST_ENV
91//!
92//! // From string (useful for tests)
93//! let config: Config = r#"
94//! [http]
95//! bind_port = 3000
96//! max_payload_size_bytes = "1KiB"
97//! "#.parse().unwrap();
98//!
99//! // With builder methods
100//! let config = Config::default()
101//! .with_bind_port(8080)
102//! .with_compression(true)
103//! .with_request_timeout(Duration::from_secs(30));
104//! ```
105//!
106//! See [Configuration Reference](../docs/configuration/toml-reference.md) for all options.
107//!
108//! # Error Handling
109//!
110//! The library uses a custom [`Result`] type. Errors convert to structured JSON responses:
111//!
112//! ```json
113//! {
114//! "error_code": "DATABASE_ERROR",
115//! "message": "Database error: connection refused"
116//! }
117//! ```
118//!
119//! # Examples
120//!
121//! ## With Application State
122//!
123//! ```rust,no_run
124//! use axum::{routing::get, extract::State};
125//! use axum_conf::{Config, Result, FluentRouter};
126//! use std::sync::Arc;
127//! use std::sync::atomic::{AtomicU64, Ordering};
128//!
129//! #[derive(Clone)]
130//! struct AppState {
131//! counter: Arc<AtomicU64>,
132//! }
133//!
134//! async fn count(State(state): State<AppState>) -> String {
135//! let n = state.counter.fetch_add(1, Ordering::SeqCst);
136//! format!("Count: {}", n)
137//! }
138//!
139//! #[tokio::main]
140//! async fn main() -> Result<()> {
141//! let config = Config::default();
142//! let state = AppState { counter: Arc::new(AtomicU64::new(0)) };
143//!
144//! FluentRouter::<AppState>::with_state(config, state)?
145//! .route("/count", get(count))
146//! .setup_middleware()
147//! .await?
148//! .start()
149//! .await
150//! }
151//! ```
152//!
153//! ## With PostgreSQL
154//!
155//! Requires the `postgres` feature.
156//!
157//! ```toml
158//! [database]
159//! url = "{{ DATABASE_URL }}"
160//! max_pool_size = 10
161//! ```
162//!
163//! ```rust,ignore
164//! use sqlx::PgPool;
165//! use axum::extract::State;
166//!
167//! async fn get_users(State(pool): State<PgPool>) -> String {
168//! let count: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM users")
169//! .fetch_one(&pool)
170//! .await
171//! .unwrap();
172//! format!("Users: {}", count.0)
173//! }
174//! ```
175//!
176//! See [PostgreSQL Guide](../docs/features/postgres.md) for details.
177//!
178//! ## Middleware Control
179//!
180//! Enable or disable specific middleware:
181//!
182//! ```toml
183//! [http.middleware]
184//! exclude = ["rate-limiting", "compression"]
185//! ```
186//!
187//! See [Middleware Overview](../docs/middleware/overview.md) for the full stack.
188pub mod config;
189mod error;
190pub mod fluent;
191mod utils;
192
193#[cfg(feature = "circuit-breaker")]
194pub mod circuit_breaker;
195
196#[cfg(feature = "openapi")]
197pub mod openapi;
198
199pub use config::*;
200pub use error::*;
201pub use fluent::*;
202pub use utils::*;
203
204#[cfg(feature = "keycloak")]
205pub type Role = String;
206
207pub type Result<T> = std::result::Result<T, Error>;