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
//! rustango — a Django-inspired ORM + admin + multi-tenancy for Rust.
//!
//! ```ignore
//! [dependencies]
//! rustango = { version = "0.7", features = ["tenancy"] }
//! ```
//!
//! Out of the box (`default = ["postgres", "admin"]`) you get the
//! ORM, the migration runner, and the auto-admin. Add `"tenancy"`
//! for the multi-tenant resolver / pools / per-tenant auth pieces.
//! Drop `default-features` for the bare ORM (no axum, no Tera).
//!
//! See the workspace [README](https://github.com/ujeenet/rustango)
//! for the full feature matrix and the Django-shape project layout.
// Lets `::rustango::core::Model` (emitted by the proc-macro) and
// `rustango::sql::Auto<i64>` (used in tenancy source code carried
// over from the pre-collapse layout) resolve to ourselves without
// rewriting either.
extern crate self as rustango;
/// Soft-delete query helpers — `active_filter` / `trashed_filter` /
/// `compose_with_active` / `soft_delete` / `restore` / `purge` for any
/// model carrying `#[rustango(soft_delete)]`. See [`soft_delete`].
/// DRF-style serializer layer — `#[derive(Serializer)]` + [`serializer::ModelSerializer`].
/// Typed JSON output from model instances with field control and validation.
/// Pluggable caching layer — [`cache::Cache`] trait + [`cache::NullCache`] +
/// [`cache::InMemoryCache`]. Redis backend behind the `cache-redis` feature.
/// Django-shape model signals — [`signals::connect_post_save`] etc.
/// Receivers register globally per model type and run sequentially.
/// CORS middleware — [`cors::CorsLayer`] for axum routers.
/// Token-bucket rate limiting middleware — [`rate_limit::RateLimitLayer`].
/// Per-IP, per-header, or global. Returns 429 with `Retry-After` when exhausted.
/// Cache-backed rate limiting middleware — fixed-window counter via the
/// [`cache::Cache`] trait. Pair with `RedisCache` for distributed
/// enforcement across multiple processes / replicas. See
/// [`rate_limit_cache::CacheRateLimitLayer`].
/// Health check endpoints — `/health` (liveness) + `/ready` (readiness).
/// See [`health::health_router`].
/// Email backends — [`email::Mailer`] trait + console/in-memory/null backends.
/// Tera-rendered email helpers — bridge [`crate::email`] mailers and
/// the Tera templating engine. Each email = `<name>.subject.txt` +
/// `<name>.txt` + optional `<name>.html`. See
/// [`email_templates::EmailRenderer`].
/// Send email off the request path via the [`crate::jobs`] queue.
/// Pairs the [`email::Mailer`] trait with the queue's retry-with-
/// backoff so transient SMTP failures don't blow up handlers.
/// See [`email_jobs::register_email_job`] + [`email_jobs::dispatch_email`].
/// Laravel-shape `Mailable` trait — declare an email type as a
/// struct that owns its template + recipient logic. Pairs with
/// [`email_templates::EmailRenderer`] (rendering) and
/// [`email_jobs`] (off-request delivery). See [`mailable::Mailable`].
/// JSON:API v1.1 response envelope adapter — wrap a flat
/// `serde_json::Value` (typical [`serializer`] output) into the
/// `{"data": {"type", "id", "attributes": {...}}}` shape that
/// JSON:API clients expect. See [`jsonapi::to_resource`] +
/// [`jsonapi::to_collection`].
/// HMAC-signed request authentication for service-to-service traffic.
/// AWS-style canonical request signed with SHA-256, replay-bounded
/// by an X-Date tolerance window. See [`hmac_auth::HmacAuthLayer`].
/// Standalone HS256 JWT — sign / verify / decode for magic links,
/// microservice tokens, third-party SSO. See [`jwt::encode`] +
/// [`jwt::decode`].
/// Multipart file upload helper — wraps axum's multipart extractor +
/// the [`storage::Storage`] trait. See [`uploads::save_uploads`] +
/// [`uploads::UploadConfig`].
/// First-class `Media` model — Postgres-backed file references with
/// direct-browser upload, CDN-aware URLs, soft delete + orphan purge.
/// See [`media::Media`] + [`media::MediaManager`].
/// Multi-channel notifications — fan one notification out to mail / database /
/// log / broadcast channels. See [`notifications::notify`].
/// Background job queue with worker pool — async work outside the request
/// lifecycle. Currently in-memory only. See [`jobs::JobQueue`].
/// Pre-built auth flows — password reset, email verification, magic-link login.
/// See [`auth_flows::PasswordReset`] / [`auth_flows::EmailVerification`].
/// Unified `RustangoError` enum + `From` impls for every framework error type.
/// Use in handlers: `async fn handler() -> RustangoResult<Json<X>> { ... }`.
pub use ;
/// File storage backends — [`storage::Storage`] trait + LocalStorage + InMemoryStorage.
/// Test client — fire HTTP requests against an `axum::Router` in tests
/// without binding a real socket. See [`test_client::TestClient`].
/// Typed environment variable readers — `required` / `with_default` /
/// `optional` / `list` / `duration_secs` / `duration_millis`.
/// Internationalization (i18n) — translation lookups + Accept-Language negotiation.
/// See [`i18n::Translator`] and [`i18n::negotiate_language`].
/// HTTP content negotiation — pick the best response format from the
/// client's `Accept` header. See [`content_negotiation::negotiate`].
/// ETag middleware — hashes 2xx response bodies, returns 304 when
/// `If-None-Match` matches. See [`etag::EtagLayer`].
/// In-process scheduled task runner — fire async jobs at fixed intervals.
/// See [`scheduler::Scheduler`].
/// API versioning — extract version from header / query / URL prefix.
/// See [`api_version::VersionStrategy`] and [`api_version::ApiVersion`].
/// Minimal RFC 4180 CSV writer — zero deps. See [`csv::CsvWriter`].
/// axum response wrapper for CSV exports — sets Content-Type +
/// optional Content-Disposition so browsers prompt a "Save as…"
/// download. See [`csv_response::CsvResponse`].
/// Pluggable secrets backend — [`secrets::Secrets`] trait + [`secrets::EnvSecrets`]
/// + [`secrets::InMemorySecrets`].
/// HTTP access log middleware — one tracing event per request with
/// method / path / status / duration / IP. See [`access_log::AccessLogLayer`].
/// Test fixture loader — seed a database from JSON files.
/// See [`fixtures::Fixture`].
/// Bulk-action runner — apply one operation to a set of selected PKs.
/// See [`bulk_actions::BulkActionRegistry`] + built-in actions.
/// TOTP — RFC 6238 time-based one-time passwords for 2FA.
/// See [`totp::generate`] / [`totp::verify`] / [`totp::otpauth_url`].
/// Text utilities — slugify, html_escape, truncate.
/// Request ID middleware — assign per-request correlation IDs,
/// honor inbound `X-Request-Id` for end-to-end propagation. See
/// [`request_id::RequestIdLayer`].
/// IP allowlist / blocklist middleware. See [`ip_filter::IpFilterLayer`].
/// Request body size limit middleware — fast `Content-Length` rejection
/// returning structured `413 Payload Too Large` JSON. Complements
/// axum's per-extractor `DefaultBodyLimit`. See [`body_limit::BodyLimitLayer`].
/// Real-IP extraction for apps behind a trusted reverse proxy
/// (Cloudflare / nginx / ELB / etc). Parses `X-Forwarded-For`,
/// `X-Real-IP`, `CF-Connecting-IP`, or RFC 7239 `Forwarded` and stuffs
/// the resolved client IP into request extensions. See
/// [`real_ip::RealIpLayer`].
/// Idempotency-key middleware (Stripe-shape) — replays a stored
/// successful response when a write request arrives with the same
/// `Idempotency-Key`. Backed by any [`cache::Cache`]. See
/// [`idempotency::IdempotencyLayer`].
/// Maintenance-mode middleware — return 503 with `Retry-After` from a
/// shared atomic flag, so an orchestrator can drain traffic before a
/// deploy / migration without killing in-flight requests. See
/// [`maintenance::MaintenanceFlag`] + [`maintenance::MaintenanceLayer`].
/// Trailing-slash redirect middleware — canonicalize URL paths
/// (Django `APPEND_SLASH` / Rails `trailing_slash` shape).
/// See [`trailing_slash::TrailingSlashLayer`].
/// Static file serving — read files from a directory with sensible
/// `Content-Type`, `Cache-Control`, `Last-Modified`, and 304 support.
/// See [`static_files::StaticFiles`] + [`static_files::static_router`].
/// HTTP method override — rewrite POST → PUT/PATCH/DELETE based on
/// `X-HTTP-Method-Override` header or `_method` form field, so HTML
/// forms can drive REST routes. See [`method_override::MethodOverrideLayer`].
/// RFC 7807 "Problem Details for HTTP APIs" — standardized error
/// responses with `application/problem+json`. Sister to
/// [`api_errors`]. See [`problem_details::ProblemDetails`].
/// Feature flags / killswitches backed by [`cache::Cache`] —
/// boolean killswitch + per-user override + stable percentage rollout.
/// See [`feature_flags::FeatureFlags`].
/// Distributed locks backed by [`cache::Cache`] — "only one worker
/// at a time runs this task" with TTL-based crash recovery and
/// token-checked release. See [`distributed_lock::DistributedLock`].
/// Server-side sessions backed by [`cache::Cache`] — opaque cookie
/// ID, server-stored bag of typed values, revocable per-session.
/// See [`sessions::Session`] + [`sessions::SessionStore`].
/// Prometheus-format metrics — counters + histograms exposed at
/// `/metrics`. Pure-Rust, no Prometheus client crate.
/// See [`metrics::MetricsRegistry`] + [`metrics::metrics_router`].
/// Per-request `tracing` span with W3C / OpenTelemetry-conventional
/// field names + `traceparent` header propagation. Hook
/// `tracing_opentelemetry::layer()` in your subscriber for free
/// distributed tracing. See [`tracing_layer::TracingLayer`].
/// `Server-Timing` header middleware — surface per-request stage
/// durations to the browser DevTools "Network" panel. See
/// [`server_timing::ServerTimingLayer`] + [`server_timing::Timings`].
/// Webhook signature verification (HMAC-SHA256). See [`webhook::verify_signature`].
/// Outbound webhook delivery — POSTs HMAC-signed JSON via the background
/// job queue (so retries with exponential backoff are free). See
/// [`webhook_delivery::WebhookSubscription`].
/// Standardized API error responses. See [`api_errors::ApiError`].
/// Generic API key generation + verification (argon2id-hashed).
/// See [`api_keys::generate_key`] / [`api_keys::verify_key`].
/// Generic password hash/verify + strength heuristic. See [`passwords::hash`].
/// Pagination helpers — RFC 5988 Link headers + cursor params.
/// See [`pagination::LinkHeaderBuilder`].
/// Security headers middleware — HSTS / X-Frame-Options / nosniff /
/// Referrer-Policy / Permissions-Policy / CSP. See [`security_headers::SecurityHeadersLayer`].
/// Per-request CSP nonce middleware — generates a fresh CSPRNG nonce
/// per request, makes it available via `Extension<Nonce>`, and
/// substitutes `'nonce-__RUSTANGO_NONCE__'` in the CSP header so
/// inline `<script nonce="...">` tags pass strict CSP. See
/// [`csp_nonce::CspNonceLayer`].
/// Signed URL helpers — HMAC-SHA256 with optional expiry.
/// See [`signed_url::sign`] / [`signed_url::verify`].
/// First-run welcome page — confidence signal that rustango is wired up.
/// Mount under `/` while bootstrapping; replace once you have content.
/// See [`welcome::welcome_router`].
/// Debug profiling panel at `/__debug__/` — Telescope/Debug-Toolbar-shape.
/// **DEV ONLY** — captures per-request telemetry. See [`debug_panel`].
/// Browser auto-reload — refreshes pages when the server restarts.
/// **DEV ONLY** — pairs with `cargo watch -x run`. See [`livereload`].
/// One-call tracing-subscriber setup. See [`logging::setup`] / [`logging::Setup`].
/// Per-account login lockout — defends against credential stuffing.
/// Cache-backed counter + lock flag. See [`account_lockout::Lockout`].
/// Broadcast event bus — fan-out for SSE / WebSocket / signal-driven push.
/// See [`sse::EventBus`].
/// WebSocket handler scaffold — fan-out via [`sse::EventBus`] with auto
/// JSON encode/decode + keep-alive ping. See [`ws::WsHub`] +
/// [`ws::ws_handler`].
/// OAuth2 / OIDC swiss-knife — social login that works for both pure
/// OAuth2 (GitHub, Discord) and OIDC (Google, Microsoft, Keycloak)
/// providers via the `/userinfo` endpoint. Per-tenant via
/// [`oauth2::OAuth2Registry`]. Optional axum router under [`oauth2::router`]
/// (requires the `admin` feature).
/// Opinionated HTTP client — `reqwest` wrapper with sane timeouts,
/// retry on idempotent verbs / transient failures, default User-Agent.
/// See [`http_client::HttpClient`].
/// Response compression middleware — gzip + deflate via flate2.
/// Honors `Accept-Encoding`, skips already-compressed bodies and binary
/// content-types. See [`compression::CompressionLayer`].
/// OpenAPI 3.1 spec builder + Swagger UI / Redoc viewer routes.
/// Hand-build a spec with [`openapi::OpenApiSpec`] and mount it under
/// [`openapi::router::openapi_router`] (requires the `admin` feature).
/// Per-request extractors for handlers — tenancy-aware DI. Today
/// ships [`extractors::Tenant`]; future slices add `Operator` + `User`.
/// DRF-style ModelViewSet — five REST endpoints for any [`Model`] table
/// in ~5 lines. See [`viewset::ViewSet`].
/// Django-style runserver — [`server::Builder`] owns every line of
/// boilerplate every tenancy app would otherwise rewrite (DB pool,
/// resolver chain, host dispatch, operator console, bind + serve).
/// `#[rustango::main]` — the Django-shape `runserver` entrypoint.
/// Wraps `#[tokio::main]` with a default `tracing-subscriber` boot
/// (env-filter, falling back to `info,sqlx=warn`). Available behind
/// the `runtime` feature, which `tenancy` implies.
pub use main;
/// Internal re-exports for proc-macros that need to name third-party
/// crates without forcing the user to add them to their `Cargo.toml`.
/// Not part of the public API — names here may change between minors.
/// Proc-macros crate, re-exported. End users normally reach
/// [`Model`] and [`embed_migrations`] directly via the facade rather
/// than naming `macros`.
pub use rustango_macros as macros;
/// `#[derive(Model)]` — populates the `inventory` registry the admin
/// walks, generates `objects()` / typed columns / `insert` / `delete`
/// / `save`.
pub use Model;
/// Server-assigned PK wrapper. `id: Auto<i64>` → `BIGSERIAL`. See
/// [`sql::Auto`] for details.
pub use Auto;
/// Bake every migration file in a directory into the binary at
/// compile time, for shipping a single-binary distribution. Pair
/// with [`migrate::migrate_embedded`].
pub use embed_migrations;
/// `#[derive(Form)]` — implements [`forms::Form`] so a struct can be
/// parsed from an HTTP form payload with multi-error validation.
/// Re-exported only when the `forms` feature is on.
pub use Form;
/// `#[derive(ViewSet)]` — generates a `router(prefix, pool) -> axum::Router`
/// associated method on a marker struct, wiring the full CRUD ViewSet in one
/// annotation. Re-exported only when the `tenancy` feature is on.
pub use ViewSet;
/// `#[derive(Serializer)]` — implements [`serializer::ModelSerializer`] on a
/// struct, generating `from_model`, a custom `serde::Serialize` (respecting
/// `write_only`), and `writable_fields`. Re-exported when the `serializer`
/// feature is on.
pub use Serializer;