MADS.rs
MADS.rs 0.7.0 is a Rust application framework with a framework-neutral core, a scoped Axum HTTP runtime, and explainable PostgreSQL/Diesel conditional defaults. A root module selects one application; startup validates its scoped graph and routes before it starts lifecycle hooks, checks a database, or binds a socket.
CLI quick start
From a project containing one MADS package and binary:
# during development
See the authoritative CLI reference for target selectors, forwarded application arguments, diagnostics, watcher behavior, inspection limits, and database commands.
Standard application
use *;
use UserHttpModule;
;
async
Mads::run is the recommended application entry point. The root module
selects its direct imports and the providers, controllers, routes, guards,
strategies, and official auto-configurations reachable through that graph.
Crates and boundaries
mads-coreowns construction, providers, lifecycle, diagnostics, and generic scalar TOML/dotenv configuration, plus official conditional-default evaluation and redacted inspection reports. It has no database or HTTP dependency.mads-commonowns route validation, Axum delivery, cookies, JWT/Passport, the official Diesel default, PostgreSQL pools, database infrastructure lifecycle, and migration execution.madsis the stable facade. Its defaultcommonfeature exposes the HTTP runtime and persistence; disable default features for the core-only boundary.
[]
= "0.7.0"
= { = "1", = ["derive"] }
[]
= { = "0.5", = ["util"] }
MADS.rs supports Rust 1.85 and uses Rust edition 2024.
The default common feature remains the compatibility aggregate for HTTP and
PostgreSQL; it does not silently enable authentication. For an HTTP API without
Diesel, use default-features = false with features = ["http", "jwt", "cookies", "runtime-tokio"]. jwt alone does not pull in Axum, while
cookies includes HTTP. Passport strategies and Bearer guards require http + jwt; cookie guards additionally require cookies.
Conventional configuration and HTTP
Only Mads::run loads conventional configuration. It reads the process
current working directory in this order:
- optional
.env, used only for interpolation; - optional
mads.tomlas ordinary configuration; - final
MADS_*environment overrides.
Process variables win during ${NAME} interpolation, dotenv loading never
mutates the process environment, and MADS_SERVER__PORT maps to
server.port. Both files may be absent; a present unreadable or malformed file
is a bootstrap failure. MADS does not search parent directories or
CARGO_MANIFEST_DIR.
# mads.toml
[]
= "127.0.0.1" # default
= 3000 # default
[]
= ["https://app.example.com"]
= ["GET", "POST"]
= ["authorization", "content-type"]
= ["x-request-id"]
= false
= 600
Wildcard-capable CORS fields use a scalar, not a one-element list:
[]
= "*"
= ["GET", "POST"]
= "*"
= "*"
CORS is opt-in, validated before lifecycle startup, and applied as the outermost layer to both generated and native routes. Wildcard origins or headers cannot be combined with credentials. It is a browser response-access policy, not authorization or CSRF protection.
Use the tracked .env.example as a local template, copy it to
the ignored .env, and put real secrets in process variables in CI and
production.
Low-level builder
Use the builder when configuration, migrations, hooks, binding, or router
composition must be explicit. It never loads .env, mads.toml, or MADS_*
on its own. The explicit address overrides [server] binding and may use port
zero; merge native Axum routes before passing the raw router to serve_router.
let mut builder = builder_with_config;
builder.?;
builder.database_migrations?;
// builder.lifecycle_hook(MyHook);
let application = builder.build.await?;
let router = build_router?.merge;
serve_router.await?;
For direct in-process router use, call configure_router(&application, router)
after the merge. A builder without root::<AppModule>() intentionally retains
the complete-catalog compatibility behavior.
Database provisioning
This is zero database bootstrap, not zero application configuration. A
provider in the selected application scope that directly requires Database
activates the linked default only after configuration and virtual graph
validation. database_migrations separately registers one embedded source; it
does not create a pool, connect, or run migrations. It is required only when
database.migrate = true; existing pending embedded migrations then run after
readiness, and no pending migrations are a successful no-op. Normal startup
never generates or auto-applies migrations. The explicit mads db generate
command can create one review-required schema-diff migration from src/schema.rs
or recursively loaded src/schema/**/*.rs; inspect the generated up.sql and
down.sql before applying it with mads db migrate.
Inspect the retained, redacted decision records without exposing configuration values:
for report in application.auto_configurations
DatabaseBootstrap remains the explicit native Diesel override. It backs off
the conditional default completely and contributes its database lifecycle as
framework infrastructure. An application-provided Database instead owns its
complete readiness, migration, and shutdown lifecycle:
use ;
let config = new
.source
.build?;
let database = from_config?;
let mut builder = builder_with_config;
builder.database?;
let application = builder.build.await?;
# Ok::
Use the direct mads::diesel and
mads::diesel_migrations re-exports when native Diesel APIs are the right
tool.
serve(application, "127.0.0.1:3000") remains the explicit generated-router
escape hatch. Its address overrides automatic server binding; use
serve_router when the raw generated router has been merged with native Axum
routes.
Passport configuration and JWT profiles
Mads::run supplies the standard conventional source order; the low-level
builder stays explicit. Dotenv sources provide interpolation values, and
ordinary sources merge from first to last; a later scalar or string array
replaces an earlier value at the same key completely. Process variables override
dotenv values during ${NAME} interpolation. EnvSource is scalar-only, so
arrays such as algorithms and audiences belong in TOML or a programmatic
ConfigDocument/MapSource.
# mads.toml
[]
= "${JWT_SECRET}"
= ["HS256"]
= "https://auth.example.com"
= ["mads-api"]
Simple secret mode permits one HMAC algorithm: HS256 by default, or one of
HS384/HS512 when explicitly selected. Minimum secret sizes are 32/48/64 bytes.
For rotation, configure a named key ring; the active key signs and all retained
keys verify by kid:
[]
= "2026-08"
= ["RS256"]
[]
= "RS256"
= "keys/current-private.pem"
= "keys/current-public.pem"
[]
= "RS256"
= "keys/previous-public.pem"
MADS supports HS256/384/512, RS256/384/512, and ES256/384. The configured allowlist—not an untrusted token header—selects eligible algorithms, and every named key is bound to one algorithm. Relative paths from TOML resolve beside that TOML file; paths from environment or programmatic sources resolve from the process working directory.
use Duration;
use *;
let access = jwt.sign?;
let refresh = jwt.sign?;
let verified_access = jwt.?;
let verified_refresh = jwt.?;
Access and refresh tokens have different protected typ values and
token_use claims. They are not interchangeable. Unverified decode APIs are
inspection-only and must never authenticate a request.
Managed strategies, principals, and guards
A custom strategy is both a managed provider and an annotated
PassportStrategy implementation. Framework signature, registered-claim, and
token-kind verification always happens before validate; the strategy sees
verified claims and a credential-sanitized, read-only PassportContext.
jwt is the built-in access strategy and can authorize directly as
ClaimsPrincipal<C>. A custom jwt strategy overrides it. jwt-refresh is not
built in: applications define it with JwtTokenKind::Refresh and own any
persistence, rotation, reuse detection, and revocation.
Trait policies inherit. A method replaces only fields it supplies;
#[guard(skip)] is the sole opt-out. Roles, permissions, and predicates are
ANDed; any/all controls matching inside one role or permission clause, and
every predicate must be a synchronous fn(&UserPrincipal) -> bool. A guard
uses exactly one source. With cookies, select
source = cookie("refresh_token"); there is no Bearer fallback.
Authentication and strategy rejection map to generic 401 Unauthorized with
WWW-Authenticate: Bearer, authorization policy failures to 403 Forbidden,
and operational failures to 500 Internal Server Error. Ordinary malformed
cookie extraction remains 400 Bad Request; a missing, malformed, or duplicate
guard cookie is a generic 401.
Cookie jars compose with response tuples and emit checked Set-Cookie headers:
let cookie = build
.path
.http_only
.secure
.same_site
.max_age
.build;
Ok
For native Axum routes, apply a typed PassportGuard<P> Tower layer. This is a
runtime escape hatch, not static MADS guard metadata, so it cannot activate JWT
auto-configuration. Before PassportGuard::build(), a managed provider must
directly require JwtService, or the builder must explicitly provide a
concrete JwtService; otherwise construction fails with MADS131.
See the complete Passport/JWT example and the v0.5.5 security and release notes.
CLI migrations
From a project root containing mads.toml and migrations/:
mads db migrate # apply pending file migrations
mads db rollback # revert the latest migration from this source
mads db status # report applied and pending versions
mads db generate # create one automatically named, review-required diff
mads db generate never applies its output and has no positional name. It
loads split Diesel schema files recursively and warns when a change needs
manual SQL review. mads db migrate prints applied <version> for work
performed or database is up to date; rollback prints reverted <version>;
status prints individual versions plus an applied/pending summary. Invalid
command syntax exits with 2; configuration, pool, or migration failures exit
with 1.
A typed HTTP route
#[mads::routes] records immutable metadata and emits a typed registration
adapter. #[mads::controller] resolves the managed controller once while the
router is built; handlers do not receive manual State<AppState> or perform
per-request provider resolution.
use *;
;
;
async
Extractors, responses, and routing
The prelude exports Path<T>, Query<T>, Json<T>, Header<T>, Request,
HttpResult<T>, Created<T>, NoContent, build_router, configure_router,
serve, and serve_router.
mads::common::axum remains the native Axum escape hatch for extractors,
responses, routers, middleware, and Tower composition.
MADS route metadata uses /:parameter; the validated adapter translates it to
Axum 0.8 syntax only while registering the route. Invalid metadata and
conflicts fail with MADS030 before router construction. GET also handles
HEAD, OPTIONS is not synthesized, static routes win over parameter routes, and
trailing slashes remain strict. build_router(&application) returns the raw
generated router; merge native routes before configure_router or
serve_router applies final application-wide CORS. Use the configured router
with Tower's ServiceExt::oneshot for in-process route tests without binding a
listener.
Benchmarks
The current benchmark suite covers native Axum/MADS throughput and process-start-to-ready comparisons with Axum, Go/Gin, and NestJS/Fastify.
| Application | Startup P50 | Startup P95 |
|---|---|---|
| Native Axum | 21 ms | 30 ms |
| Go/Gin | 22 ms | 29 ms |
| MADS | 22 ms | 30 ms |
| NestJS/Fastify | 428 ms | 443 ms |
The startup comparison uses 1,000 release-build starts per application and an equivalent PostgreSQL readiness check. In the exploratory throughput suite, every native Axum/MADS saturation range overlaps, while both sustain the fixed 1,000 requests/second target with closely grouped latency.
See BENCHMARK.md for the complete results, methodology, limitations, resource measurements, and interpretation guidance.
Current scope
Version 0.7.0 provides root-module scope, Rust-namespace ownership, direct public cross-module access, scoped providers/controllers/routes/guards/ strategies/auto-configuration, conventional configuration, automatic one-listener HTTP startup, strict application-wide CORS, raw native-router composition, the Cargo-native run/dev CLI, compiled route/graph/doctor inspection, and bounded PostgreSQL schema-diff generation. It preserves the low-level builder and complete-catalog rootless compatibility.
It does not implement trait or interface bindings, Inject<dyn Trait>,
request-validation derives or schemas, login or credential validation, refresh
endpoints or persistence/rotation/revocation, password hashing, CSRF, remote
JWKS, JWE, generic typed configuration, third-party auto-configuration, or
multiple-listener/TLS/HTTP2 server configuration. Database errors are not
automatically mapped to HTTP responses; applications choose their delivery
policy. Input validation, expanded standard HTTP errors, generic typed
configuration, compiler-diagnostic rewriting, and machine-readable CLI output
are v0.8 work.
Development
Run the available release checks locally:
RUSTDOCFLAGS="-D warnings"
CI also provisions PostgreSQL 16 and runs the ignored database suites plus the
85% line-coverage gate. To run those locally, set MADS_TEST_DATABASE_URL to a
PostgreSQL 16 database and use the commands in the v0.5 requirements.
License
MADS.rs is licensed under either the Apache License 2.0 or the MIT License, at your option.