toxi/lib.rs
1//! # Toxi Web Framework
2//!
3//! **Toxi** is a modular, batteries-included web framework for Rust.
4//! Built on `hyper` and `tokio`, it provides a complete stack for building
5//! production HTTP services — routing, ORM, authentication, real-time
6//! communication, background jobs, caching, storage, templates, email,
7//! and OpenAPI generation.
8//!
9//! ## Quick Start
10//!
11//! ```toml
12//! [dependencies]
13//! toxi = { version = "3.1.0", features = ["full"] }
14//! tokio = { version = "1", features = ["full"] }
15//! serde = { version = "1", features = ["derive"] }
16//! ```
17//!
18//! ```rust,no_run
19//! use toxi::prelude::*;
20//!
21//! async fn hello(_req: Request) -> Result<Response> {
22//! Ok(Response::text("Hello, Toxi!"))
23//! }
24//!
25//! #[tokio::main]
26//! async fn main() -> Result<()> {
27//! let mut app = Application::new(Config::load().unwrap());
28//! app.router_mut().get("/", hello);
29//! app.run().await
30//! }
31//! ```
32//!
33//! ## Feature Flags
34//!
35//! Enable only what you need via Cargo features:
36//!
37//! | Feature | Crate | Description |
38//! |-------------|---------------------|---------------------------------------|
39//! | `database` | `toxi-db` | ORM with relationships & migrations |
40//! | `auth` | `toxi-auth` | JWT, OAuth2, RBAC, 2FA, API keys |
41//! | `queue` | `toxi-queue` | Background job orchestration |
42//! | `cache` | `toxi-cache` | In-memory and Redis caching |
43//! | `realtime` | `toxi-realtime` | WebSocket and SSE |
44//! | `templates` | `toxi-template` | Server-side rendering |
45//! | `mail` | `toxi-mail` | SMTP email delivery |
46//! | `storage` | `toxi-storage` | Local and S3 file storage |
47//! | `security` | `toxi-security` | Crypto primitives |
48//! | `utils` | `toxi-utils` | String, date, validation helpers |
49//! | `graphql` | `toxi-graphql` | GraphQL integration |
50//! | `plugin` | `toxi-plugin` | Plugin lifecycle hooks |
51//! | `full` | all of the above | Every optional crate |
52//!
53//! ## Modular by Design
54//!
55//! Each crate in the Toxi ecosystem can be used independently:
56//!
57//! ```toml
58//! # Minimal: just routing and HTTP
59//! [dependencies]
60//! toxi-core = "3.1.0"
61//!
62//! # Add database when needed
63//! [dependencies]
64//! toxi-core = "3.1.0"
65//! toxi-db = "3.1.0"
66//! ```
67//!
68//! ## Key Concepts
69//!
70//! - **Extractors** — Typed data pulled from requests (`Json<T>`, `Path<T>`, `State<T>`, etc.)
71//! - **Handlers** — Async functions whose parameters are extractors
72//! - **Middleware** — Tower-compatible layers (CORS, logging, compression, rate limiting)
73//! - **HTTP/2** — First-class support via ALPN or `Server::with_http_version`
74//!
75//! ## Learn More
76//!
77//! - [GitHub](https://github.com/meshackbahati/toxi)
78//! - [API Documentation](https://docs.rs/toxi)
79
80// ── Core re-exports ──────────────────────────────────────────────────
81
82/// Re-export all items from [`toxi_core`].
83pub use toxi_core::*;
84
85/// Re-export the `extract` module from [`toxi_core`].
86pub use toxi_core::extract;
87
88/// Re-export [`toxi_middleware`] as `middleware`.
89pub use toxi_middleware as middleware;
90
91/// Re-export [`toxi_config`] as `config`.
92pub use toxi_config as config;
93
94/// Re-export [`ToxiRequest`] and [`ToxiResponse`].
95pub use toxi_core::types::{ToxiRequest, ToxiResponse};
96
97// ── Macro re-exports ─────────────────────────────────────────────────
98
99/// Re-export `impl_handler_for_fn!` — extend handler arity beyond the
100/// built-in 12 extractors:
101///
102/// ```rust,ignore
103/// // Enable 13 and 14 extractor handlers
104/// toxi::impl_handler_for_fn!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14);
105/// ```
106pub use toxi_core::impl_handler_for_fn;
107
108/// Re-export `json_response!` — create a JSON response from inline JSON:
109///
110/// ```rust,ignore
111/// use toxi::prelude::*;
112///
113/// async fn health() -> Result<Response> {
114/// Ok(json_response!({ "status": "ok" }))
115/// }
116/// ```
117pub use toxi_core::json_response;
118
119// ── Optional crate re-exports (behind feature flags) ─────────────────
120
121#[cfg(feature = "database")]
122/// Re-export [`toxi_db`] as `db` — ORM with relationships, migrations,
123/// soft deletes, and eager loading.
124pub use toxi_db as db;
125
126#[cfg(feature = "auth")]
127/// Re-export [`toxi_auth`] as `auth` — JWT, OAuth2, RBAC, 2FA, and API keys.
128pub use toxi_auth as auth;
129
130#[cfg(feature = "queue")]
131/// Re-export [`toxi_queue`] as `queue` — background job orchestration
132/// with Postgres and Redis backends.
133pub use toxi_queue as queue;
134
135#[cfg(feature = "cache")]
136/// Re-export [`toxi_cache`] as `cache` — in-memory and Redis caching.
137pub use toxi_cache as cache;
138
139#[cfg(feature = "realtime")]
140/// Re-export [`toxi_realtime`] as `realtime` — WebSocket, SSE, and
141/// event broadcasting.
142pub use toxi_realtime as realtime;
143
144#[cfg(feature = "templates")]
145/// Re-export [`toxi_template`] as `template` — server-side rendering.
146pub use toxi_template as template;
147
148#[cfg(feature = "mail")]
149/// Re-export [`toxi_mail`] as `mail` — SMTP email delivery.
150pub use toxi_mail as mail;
151
152#[cfg(feature = "storage")]
153/// Re-export [`toxi_storage`] as `storage` — local and S3 file storage.
154pub use toxi_storage as storage;
155
156#[cfg(feature = "security")]
157/// Re-export [`toxi_security`] as `security` — cryptographic primitives.
158pub use toxi_security as security;
159
160#[cfg(feature = "utils")]
161/// Re-export [`toxi_utils`] as `utils` — string, date, and validation helpers.
162pub use toxi_utils as utils;
163
164// ── Prelude ──────────────────────────────────────────────────────────
165
166/// Convenience re-exports for ergonomic imports.
167///
168/// ```rust,ignore
169/// use toxi::prelude::*;
170/// ```
171pub mod prelude {
172 // Core
173 /// Core framework types: `Application`, `Router`, `Server`, `Handler`,
174 /// `Error`, `Result`, `Request`, `Response`, extractors, and more.
175 pub use toxi_core::{
176 Application, Router, Server, Handler, IntoHandler, handler_fn,
177 Error, Result,
178 Request, Response,
179 StatusCode, mpsc, BodyExt,
180 CorsConfig, HttpVersion,
181 extract::{Json, Path, Query, State, FromRequest, Form, Cookies, Body, WebSocketUpgrade, PathParams},
182 };
183
184 // Middleware
185 /// Middleware types: `ServiceBuilder`, `LoggerLayer`, `CorsLayer`,
186 /// `CompressionLayer`, `CacheLayer`, `MetricsLayer`.
187 pub use toxi_middleware::{
188 ServiceBuilder, LoggerLayer, CorsLayer, CompressionLayer,
189 CacheLayer, CacheMiddleware, CacheConfig, CacheLayerBuilder,
190 MetricsLayer,
191 };
192
193 // Config
194 /// Application configuration loaded from `toxi.toml` or environment variables.
195 pub use toxi_config::Config;
196
197 // Response helpers
198 /// Response helper functions: `json!({...})`, `text("...")`, `html("...")`,
199 /// `ok()`, `no_content()`.
200 pub use toxi_core::response::helpers::{json, text, html, ok, no_content};
201
202 // Database
203 #[cfg(feature = "database")]
204 /// Database types: `Database`, `Model`, `Migration`, `DbPool`, `DbTransaction`,
205 /// `OrmError`, `Pagination`, `SortDirection`.
206 pub use toxi_db::{Database, Model, Migration, DbPool, DbTransaction, Result as DbResult, OrmError, Pagination, SortDirection};
207
208 #[cfg(feature = "database")]
209 /// Commonly used `sqlx` types re-exported for convenience so you don't
210 /// need to depend on `sqlx` directly.
211 pub use toxi_db::sqlx::{
212 query, query_as, query_scalar,
213 FromRow, Row,
214 Encode, Decode, Type,
215 AnyPool, Any,
216 postgres::{PgPool, PgRow},
217 mysql::{MySqlPool, MySqlRow},
218 sqlite::{SqlitePool, SqliteRow},
219 Column,
220 Acquire, Executor,
221 };
222
223 // Auth
224 #[cfg(feature = "auth")]
225 /// Auth types: `Permission`, `Role`.
226 pub use toxi_auth::{Permission, Role};
227
228 // Queue
229 #[cfg(feature = "queue")]
230 /// Queue types: `Queue`, `Job`, `PostgresBackend`.
231 pub use toxi_queue::{Queue, Job, PostgresBackend};
232
233 // Cache
234 #[cfg(feature = "cache")]
235 /// Cache trait and backends.
236 pub use toxi_cache::Cache;
237
238 // Realtime
239 #[cfg(feature = "realtime")]
240 /// WebSocket manager for real-time connections.
241 pub use toxi_realtime::WebSocketManager;
242
243 // GraphQL
244 #[cfg(feature = "graphql")]
245 /// GraphQL handler and schema types.
246 pub use toxi_graphql::{GraphQLHandler, GraphQLSchema};
247
248 // Plugin
249 #[cfg(feature = "plugin")]
250 /// Plugin manager, trait, and info types.
251 pub use toxi_plugin::{PluginManager, Plugin, PluginInfo};
252
253 // Serde
254 /// `Serialize` and `Deserialize` derive macros.
255 pub use serde::{Serialize, Deserialize};
256
257 /// `serde_json::json!` macro for inline JSON construction.
258 pub use serde_json::json;
259
260 /// Build a CORS layer from configuration.
261 pub use crate::config_helper::cors_layer_from_config;
262}
263
264/// Configuration helper utilities.
265pub mod config_helper;
266
267/// Re-export of [`cors_layer_from_config`].
268pub use config_helper::cors_layer_from_config;