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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
//! **rustango** — a batteries-included web framework for Rust.
//!
//! It is built on one derive macro and one connection type, and ships a typed
//! ORM with auto-migrations, an auto-generated admin, multi-tenancy, auth
//! (sessions / JWT / OAuth2-OIDC / HMAC / passkeys), serializers and
//! viewsets, signals, caching, media, email, background jobs, scheduled tasks,
//! OpenAPI 3.1, and the usual production middleware.
//!
//! **Postgres, MySQL and SQLite** all use the same [`sql::Pool`] and the same
//! `#[derive(Model)]` types. The backend is a Cargo feature, not a rewrite.
//!
//! Everything is opt-in: take only the features you use, down to the bare ORM
//! with no HTTP stack. Release history is in the
//! [CHANGELOG](https://github.com/ujeenet/rustango/blob/main/CHANGELOG.md).
//!
//! # Install
//!
//! ```toml
//! [dependencies]
//! rustango = "0.60" # Postgres (the default backend)
//! # or pick another backend — see "Choosing a backend" below:
//! rustango = { version = "0.60", default-features = false, features = ["sqlite", "batteries"] }
//! rustango = { version = "0.60", default-features = false, features = ["mysql", "batteries"] }
//! ```
//!
//! `default = ["postgres", "batteries"]`. **`batteries`** is everything except
//! the backend (admin, serializers, auth, jobs, cache, media, middleware, …).
//! You pick the backend separately, so you can keep the batteries and still
//! choose your database. Drop `batteries` for the bare ORM (no axum, no Tera).
//!
//! # A taste
//!
//! ```ignore
//! use rustango::Model;
//! use rustango::sql::{Auto, Pool, FetcherPool};
//!
//! // One derive gives a table, typed columns, migrations, and admin wiring.
//! #[derive(Model, Clone, Debug)]
//! #[rustango(table = "posts")]
//! struct Post {
//! #[rustango(primary_key)]
//! id: Auto<i64>, // server-assigned auto-increment PK
//! #[rustango(max_length = 200)]
//! title: String,
//! body: String,
//! published: bool,
//! }
//!
//! # async fn demo() -> Result<(), Box<dyn std::error::Error>> {
//! // One connection type for every backend — the driver is chosen from the
//! // URL scheme (postgres://…, mysql://…, sqlite://…).
//! let pool = Pool::connect(&std::env::var("DATABASE_URL")?).await?;
//!
//! // Chained queries, compiled to your dialect.
//! let recent: Vec<Post> = Post::objects()
//! .filter("published", true)
//! .order_by_desc("id")
//! .limit(10)
//! .fetch(&pool)
//! .await?;
//! # let _ = recent; Ok(())
//! # }
//! ```
//!
//! # Choosing a backend
//!
//! The same models and queries emit Postgres, MySQL or SQLite SQL. You pick
//! the backend with a Cargo feature and the `DATABASE_URL` scheme.
//!
//! - **Connect with [`sql::Pool::connect`].** It reads the URL scheme and
//! builds the right pool. Prefer it over `sqlx::PgPool::connect(...)`, which
//! only exists when the `postgres` feature is on.
//! - **[`sql::Pool`]** is the enum every rustango API takes (`&Pool`). A
//! concrete `sqlx::PgPool` / `SqlitePool` / `MySqlPool` converts into it
//! with `From`, so you can pass either.
//! - **Enable one backend feature** (`postgres`, `mysql`, or `sqlite`) for a
//! single-database app. Enable several to build one binary that serves any
//! of them.
//! - Multi-tenancy works on all three: [`tenancy::TenantPools`] is generic
//! over the backend. Schema-mode tenancy is Postgres-only, because it uses
//! `SET search_path`.
//!
//! # Feature flags
//!
//! | Feature | Gives you |
//! |---|---|
//! | `postgres` / `mysql` / `sqlite` | The database backend(s). |
//! | `batteries` | The default bundle minus the backend (see [Install](#install)). |
//! | `admin` | Auto-generated admin UI + session auth; `#[derive(ViewSet)]` REST endpoints (also under `tenancy`). |
//! | `tenancy` | Multi-tenant resolver, per-tenant pools, operator console. |
//! | `serializer` | `#[derive(Serializer)]` JSON serializers. |
//! | `jwt` / `oauth2` | Token auth; social / OIDC login. |
//! | `jobs` / `jobs-postgres` | Background jobs (in-memory / durable). |
//! | `cache` / `cache-redis` | Cache layer; Redis backend. |
//! | `storage` / `storage-s3` / `storage-azure` / `media` | File storage + the `Media` model. |
//! | `mcp` | Model Context Protocol server over HTTP. |
//! | `openapi` | OpenAPI 3.1 schema auto-derive. |
//!
//! Every feature is listed in the crate's `Cargo.toml` with a one-line note.
//!
//! # Quick start (scaffolder)
//!
//! ```bash
//! cargo install cargo-rustango
//! cargo rustango new myblog # default: ORM + admin
//! cargo rustango new myapi --template api # JSON-only, no admin
//! cargo rustango new shop --template tenant # multi-tenancy + operator console
//!
//! cd myblog
//! cp .env.example .env # set DATABASE_URL
//! cargo run -- migrate # apply bootstrap migrations
//! cargo run # http://localhost:8080
//! ```
//!
//! # The manage runner
//!
//! One binary serves HTTP and dispatches CLI commands: `cargo run` starts the
//! server, `cargo run -- <verb>` runs a command. A scaffolded `main.rs`:
//!
//! ```ignore
//! #[rustango::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let _ = dotenvy::dotenv();
//! rustango::manage::Cli::new()
//! .api(myblog::urls::api())
//! .tenancy() // optional, with the `tenancy` feature
//! .run()
//! .await
//! }
//! ```
//!
//! Common verbs (each supports `--help`):
//!
//! | Group | Verbs |
//! |---|---|
//! | Migrations | `makemigrations`, `migrate [target]`, `downgrade [N]`, `showmigrations` |
//! | Scaffolders | `startapp`, `make:viewset`, `make:serializer`, `make:form`, `make:job`, `make:middleware`, `make:test` |
//! | System | `about`, `check`, `check --deploy`, `version` |
//! | Tenancy | `create-tenant`, `create-operator`, `create-user`, `list-tenants`, `create-api-key`, `grant-perm`, `audit-cleanup` |
//!
//! # Where to look
//!
//! - Models & queries — [`core`], [`sql`]
//! - Admin — [`admin`]
//! - REST — [`viewset`], [`serializer`]
//! - Multi-tenancy — [`tenancy`]
//! - Auth — [`auth_backends`], [`jwt`], [`sso`]
//! - Background work — [`jobs`], [`scheduler`]
//! - Caching — [`cache`]
//!
//! The workspace [README](https://github.com/ujeenet/rustango) has the full
//! feature matrix and guides.
//! [`examples/cookbook_blog`](https://github.com/ujeenet/rustango/tree/main/crates/rustango/examples/cookbook_blog)
//! is a runnable multi-tenant blog with one chapter per feature.
// Sync argon2 calls in `clippy.toml` must go through the `*_async` variants (#1709).
// Name the real problem first; the empty `match pool` errors still follow (#1509).
compile_error!;
// Lets `::rustango::...` paths emitted by the proc-macro resolve to
// ourselves inside this crate.
extern crate self as rustango;
// ---------------------------------------------------------------- per-backend macro support
//
// `#[derive(Model)]` always emits a call to `__impl_my_from_row!`. The two
// definitions below are gated on rustango's own `mysql` feature: with the
// feature on it expands to a real `sqlx::FromRow<MySqlRow>` impl, with the
// feature off it expands to nothing.
//
// The proc macro cannot see the user's feature set at expansion time, but
// macro_rules expand after it is resolved, so the right arm fires on its own.
// Users need no `mysql = ["rustango/mysql"]` shim feature of their own.
// ---- select_related's aliased-row decoder for MySQL ----
//
// `Model::__rustango_from_aliased_row(row, prefix)` is the per-model helper
// the executor calls when decoding LEFT-JOINed columns into an FK target.
// This is its MySQL-typed twin, using the same hygiene pattern as above.
// ---- LoadRelated dual (PgRow + MySqlRow) impl ----
//
// The MySQL counterpart of the PG `LoadRelated` impl. Same shape, but it
// implements `sql::LoadRelatedMy` over `MySqlRow`.
// ---- SQLite counterparts to the three MySQL macros above ----
//
// Same pattern, gated on `sqlite` instead of `mysql`. The proc-macro always
// emits a call to each; these collapse to nothing when the feature is off.
/// ContentType framework — a runtime handle for "any registered model".
/// Used by permissions, generic foreign keys, soft-FK prefetch and
/// audit-history admin panels.
/// Named multi-database registry + `QuerySet::using(alias)`.
/// Context that follows work off the request thread — see
/// [`task_context::TaskContext`]. `tokio::spawn` inherits no
/// `task_local!`, so deferred work starts with none of its caller's
/// ambient context unless it is carried deliberately.
/// Test-support helpers (schema builders from `Model::SCHEMA` + model
/// factories). Dev-only: `#[cfg(test)]` for this crate's own tests,
/// `feature = "testkit"` for external integration tests.
/// 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`].
/// 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.
/// Fragment caching — cache one rendered piece of a page.
/// [`cache_fragment::cached_render`] checks the cache before it calls your
/// compute closure. It is a handler-side helper rather than a Tera block
/// tag, because Tera has no block-tag extension API.
/// Per-view caching tower layer + `Cache-Control` / `Vary` header
/// builders. Caches a whole successful response and serves it again.
/// Model lifecycle signals — [`signals::connect_post_save`] etc.
/// Receivers register globally per model type and run sequentially.
/// Domain event bus — typed pub-sub for application events, separate from
/// the ORM. Use it for cross-component fan-out (`OrderPlaced` → mail +
/// billing + audit). For per-model lifecycle hooks use [`signals`] instead.
/// See [`events::EventBus`].
/// Model pruning — declarative bulk removal of stale rows. See
/// [`prunable::Prunable`] + [`register_prunable!`].
/// 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 — a fixed-window counter over the
/// [`cache::Cache`] trait. Pair it with `RedisCache` to enforce one limit
/// across several processes. 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 through the [`crate::jobs`] queue, so a
/// temporary SMTP failure retries instead of failing the handler.
/// See [`email_jobs::register_email_job`] + [`email_jobs::dispatch_email`].
/// Laravel-shape `Mailable` trait — an email type as a struct that owns its
/// template and recipient logic. Pairs with
/// [`email_templates::EmailRenderer`] and [`email_jobs`].
/// See [`mailable::Mailable`].
/// JSON:API v1.1 response envelope — wrap a flat `serde_json::Value`
/// (typical [`serializer`] output) in the `{"data": {"type", "id",
/// "attributes": {...}}}` shape clients expect. See
/// [`jsonapi::to_resource`] + [`jsonapi::to_collection`].
/// Shared HMAC-SHA256 / SHA-256 / hex primitives, plus `constant_time_compare`.
/// Internal: for raw HMAC, depend on `hmac` + `sha2` directly. The cfg list
/// covers every feature that needs one of these primitives.
pub
/// Attribute casts — `Cast<C>` field wrapper + `CastValue` trait, with the
/// `EncryptedString` AEAD-at-rest built-in.
/// Lowercase-hex codec, no external deps. It sits outside
/// [`crate::crypto`] so always-on callers (pagination cursors,
/// `row_to_json` binary arms) can use it without the crypto deps.
pub
/// URL / IRI / URI helpers — `url_encode`, `uri_to_iri`, `iri_to_uri`,
/// `escape_uri_path`, `filepath_to_uri`, `urlsafe_base64_encode` /
/// `_decode` and friends. Pure `std`, so it is always compiled.
/// 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`].
/// Pluggable JTI revocation / single-use store. The default is in-memory;
/// implement [`jti_store::JtiStore`] to back it with Redis or a database
/// when you run more than one instance.
/// Multipart file upload helper — wraps axum's multipart extractor +
/// the [`storage::Storage`] trait. See [`uploads::save_uploads`] +
/// [`uploads::UploadConfig`].
/// First-class `Media` model — database-backed file references with
/// direct-browser upload, CDN-aware URLs, soft delete and 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 a worker pool — async work outside the request
/// lifecycle. In-memory by default; `jobs-postgres` adds the database-backed
/// queue. See [`jobs::JobQueue`]; [`jobs::Job::run`] says which context each carries.
/// `catch_unwind` for futures: job handlers, MCP tools, event
/// subscribers and HTTP handlers must not unwind into their caller.
pub
/// Pre-built auth flows — password reset, email verification, magic-link login.
/// See [`auth_flows::PasswordReset`] / [`auth_flows::EmailVerification`].
/// Typed front end for the `tenancy::permissions` engine —
/// `has_perm_for_model::<T>` / `grant_role_perm_for_model::<T>` /
/// `model_codenames_for::<T>`. Ask for a permission by model type instead
/// of typing the codename string. Needs `tenancy`, which owns the tables.
/// Unified `RustangoError` enum + `From` impls for every framework error type.
/// Use in handlers: `async fn handler() -> RustangoResult<Json<X>> { ... }`.
pub use server_error;
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`].
/// Live HTTP server for tests. Binds an `axum::Router` to a random
/// localhost port on a background task. Use it
/// when in-process [`test_client::TestClient`] routing is not enough, for
/// example with Selenium, websockets, or code that reads the host header.
/// 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`].
/// Ambient tenant identity for log lines — the per-request slot the
/// resolver fills and the access log reads back. Without a resolver the
/// slot stays empty and no tenant is logged. See [`tenant_log::record`] /
/// [`tenant_log::current`].
/// Test fixture loader — seed a database from JSON files.
/// See [`fixtures::Fixture`].
/// Bulk-action runner — apply one operation to a set of selected PKs.
/// Works on all three backends. See [`bulk_actions::BulkActionRegistry`]
/// and the 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`].
/// Host-header allowlist middleware — refuses a request whose `Host` is
/// not on the list. See [`host_validation::AllowedHostsLayer`].
/// HTTP → HTTPS redirect middleware, with exempt path prefixes and a
/// trusted proxy header. See [`ssl_redirect::SslRedirectLayer`].
/// 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`].
/// Per-request handler timeout — stops a handler that runs too long and
/// returns `504 Gateway Timeout`, so a stuck query or external call cannot
/// pile up. `Cli::with_settings_from_env()` wires it from
/// `Settings.server.request_timeout_secs`. See
/// [`request_timeout::RequestTimeoutLayer`].
/// Real-IP extraction for apps behind a trusted reverse proxy. Reads
/// `X-Forwarded-For`, `X-Real-IP`, `CF-Connecting-IP` or RFC 7239
/// `Forwarded` and puts the client IP in the 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 — flip a shared flag and new requests get
/// 503 with `Retry-After`, while requests already running finish. Use it
/// to drain traffic before a deploy or migration. See
/// [`maintenance::MaintenanceFlag`] + [`maintenance::MaintenanceLayer`].
/// Trailing-slash redirect middleware — canonicalize URL paths so
/// `/posts` and `/posts/` do not split your traffic.
/// 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 to PUT/PATCH/DELETE from the
/// `X-HTTP-Method-Override` header or a `_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 runs a
/// task at a time. A TTL recovers the lock after a crash, and release is
/// token-checked. 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 OpenTelemetry field names and
/// `traceparent` header propagation. Add `tracing_opentelemetry::layer()`
/// to your subscriber to get 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 through the
/// background job queue, so retries with backoff come for free. See
/// [`webhook_delivery::WebhookSubscription`].
/// Checked outbound HTTP client for config-supplied URLs (#1716).
pub
/// Standardized API error responses. See [`api_errors::ApiError`].
/// Needs only axum, so every HTTP surface can answer in this shape.
/// 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`].
/// Passkey / WebAuthn — credential storage
/// ([`passkey::WebauthnCredential`] plus the store API) and the
/// registration / assertion ceremonies, verified in pure Rust (CBOR +
/// ES256).
/// 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 — makes a fresh random nonce per
/// request, exposes it as `Extension<Nonce>`, and replaces
/// `'nonce-__RUSTANGO_NONCE__'` in the CSP header, so inline
/// `<script nonce="...">` tags pass a strict CSP. See
/// [`csp_nonce::CspNonceLayer`]. Built with `admin` too: `[security]`
/// mounts it so the bundled admin pages pass a strict CSP (#1703).
/// 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`].
pub
/// Per-IP, per-account and global limits in front of every built-in
/// password login. See [`login_throttle::LoginThrottle`].
/// 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 social login. Works with plain OAuth2 providers (GitHub,
/// Discord) and OIDC ones (Google, Microsoft, Keycloak) through their
/// `/userinfo` endpoint. Per-tenant config via [`oauth2::OAuth2Registry`];
/// the optional axum router is [`oauth2::router`] (needs `admin`).
/// SSO (OpenID Connect / social OAuth) login core, independent of the
/// admin. Holds the shared handshake pieces (`ResolvedSso`,
/// `build_provider`, `verified_email`, …) and the DB-backed
/// [`sso::SsoProvider`] model. The admin, the tenant console and member
/// auth all build on it; the `admin-sso` feature adds the admin login
/// wiring.
/// Model Context Protocol (MCP) server — expose tools, prompts and
/// resources to external agents over JSON-RPC 2.0 and Streamable HTTP.
/// Mount with [`mcp::router`] (single tenant) or [`mcp::tenant_router`].
/// Opinionated HTTP client — `reqwest` wrapper with sane timeouts,
/// retry on idempotent verbs / transient failures, default User-Agent.
/// See [`http_client::HttpClient`].
/// HTTP `QUERY` method routing (RFC 10008) — `query(handler)` and
/// `.query()` chaining on axum's `MethodRouter`. See
/// [`http_query::QueryRouterExt`].
/// Method-adaptive params extractor — [`params::Params`] reads the query
/// string on GET/HEAD and the body on QUERY, so one handler serves both.
/// Response compression middleware — gzip and deflate. Honors
/// `Accept-Encoding` and skips bodies that are already compressed. 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. Ships
/// [`extractors::Tenant`], [`extractors::SessionUser`], and
/// [`extractors::SessionOperator`].
/// ModelViewSet — five REST endpoints for any [`Model`] table in
/// about five lines. Runs on all three backends, including the
/// `.serializer()` render extension. See [`viewset::ViewSet`].
///
/// `router(prefix, &PgPool)` keeps a PG-typed pool argument for source
/// compatibility. `tenant_router(prefix)` works on every dialect and needs
/// the `tenancy` feature; the static-pool CRUD ViewSet needs only `admin`.
/// Shared list-endpoint query-parameter helpers — one place that owns the
/// reserved-key skip list, `?ordering=` parsing and `?page_size=` clamping,
/// so `viewset::handle_list` and `template_views::ListView` cannot drift
/// apart.
/// Generic class-based views for HTML templates —
/// `ListView`, `DetailView`, `CreateView`, `UpdateView`, `DeleteView` over
/// `#[derive(Model)]` schemas, rendered with Tera. The HTML sibling of
/// [`viewset`]. Runs on all three backends. See [`template_views`] for
/// usage and the Tera context shape.
/// DEBUG template-error overlay — see [`template_debug`].
/// Sitewide template context processors — see
/// [`template_context_processors`].
/// Custom template filters and functions — see
/// [`template_extensions`].
/// Handler shortcuts — `get_object_or_404` / `get_list_or_404`
/// / `render` / `redirect`. See [`shortcuts`].
/// Human-readable template filters — `intcomma`, `intword`,
/// `naturalsize`, `ordinal`, `apnumber`, `naturaltime`, `naturalday`.
/// See [`humanize`].
/// Number formatter — `numberformat::format(value,
/// decimal_sep, decimal_pos, grouping, thousand_sep)`. Thousands
/// grouping, per-locale separators, optional fixed decimal width.
/// Elapsed-time wording — [`timesince`](timesince::timesince) /
/// [`timeuntil`](timesince::timeuntil), with a `depth` control
/// ("4 days, 6 hours"). The Tera filter wrappers live in [`humanize`].
/// Everyday template filters — `pluralize`,
/// `truncatewords`, `linebreaks`, `default_if_none`. See
/// [`default_filters`].
/// Standalone validators — `validate_email`,
/// `validate_url`, `validate_slug`, `validate_min_length` /
/// `validate_max_length`, `validate_min_value` / `validate_max_value`.
/// See [`validators`].
/// Custom Manager / QuerySet-extension pattern — give a model its own
/// named queries (`Post::published()`) with a Rust extension trait.
/// See [`manager`] for worked examples.
/// Model-inheritance patterns — how to share fields between models:
/// abstract bases, multi-table and proxy shapes. See [`inheritance`].
/// Composite-primary-key patterns — a multi-column key expressed as an
/// `Auto<i64>` surrogate plus `unique_together`. See [`composite_pk`].
/// Named URL reversal — build a URL from a route name and its params,
/// instead of formatting paths by hand. Pair with [`register_url!`].
/// Random-string helpers — `get_random_string`,
/// `get_random_token_urlsafe`. CSPRNG-backed, so they suit session IDs,
/// reset tokens and verification codes.
/// Base36 integer encoding — used in password reset
/// URLs and other URL-friendly opaque IDs. `int_to_base36(n)` +
/// `base36_to_int(s)` round-trip.
/// Base62 integer encoding — the `[0-9A-Za-z]` alphabet, for
/// short URL IDs. Like base36 but case-sensitive, so 6 bits per character.
/// Lorem ipsum generators — placeholder text for demos, test
/// fixtures and template scaffolds. `lorem::words(n)`,
/// `lorem::paragraphs(n)`, `lorem::sentence()`.
/// HTTP date parser and formatter — reads RFC 1123, RFC 850
/// and asctime forms per RFC 7231; writes IMF-fixdate.
/// `http_date::http_date(secs)` + `parse_http_date(s)`.
/// ISO 8601 date / time / datetime / duration parsers —
/// `dateparse::{parse_date, parse_time, parse_datetime, parse_duration}`.
/// Date format-character expander — turns a template format
/// string such as `{{ obj|date:"Y-m-d H:i" }}` into the matching output.
/// Month / weekday name lookups —
/// `month_full(m)`, `month_abbr(m)`, `month_ap(m)`,
/// `weekday_full(d)`, `weekday_abbr(d)`. English-only by design
/// (i18n is a separate concern).
/// Value signer — `signing::Signer::sign(value)` and
/// `signing::TimestampSigner` with a TTL. Use it for signed payloads such
/// as password reset tokens, magic links and signed cookies.
/// `Vary` header merging for the response layers.
pub
/// `Set-Cookie` builder — `Cookie::new(name, value)
/// .path("/").max_age(secs).http_only().secure().same_site(...).build()`
/// returns an axum-ready `HeaderValue`. Use it instead of writing cookie
/// strings by hand.
/// Per-route HTTP method allowlists as tower middleware — `require_GET`,
/// `require_POST`, `require_safe`. A method that is not allowed gets
/// `405 Method Not Allowed` with an `Allow:` header listing the rest.
/// Flash messages — `messages.success/info/warning/error/debug`
/// stored in a signed cookie until the next page renders them.
// Reads and writes cookies through axum, so `_signing` alone (webhook, oauth2) is not enough.
/// Access gates — `login_required` middleware and
/// `?next=` round-trip helpers.
/// Pluggable `AUTHENTICATION_BACKENDS` chain — register an ordered list of
/// [`auth_backends::AuthBackend`] impls; the chain returns the first
/// non-`None` result. Ships `RemoteUserBackend` for SSO proxy setups.
/// Pluggable `AUTH_PASSWORD_VALIDATORS` chain — run an ordered list of
/// [`password_validators::PasswordValidator`]s at signup and password
/// change. Built-ins: `MinimumLengthValidator`, `MaximumLengthValidator`,
/// `NumericPasswordValidator`, `UserAttributeSimilarityValidator`,
/// `CommonPasswordValidator`.
/// Pluggable `PASSWORD_HASHERS` chain with **upgrade-on-login**. The first
/// [`password_hashers::PasswordHasher`] in the list writes new hashes, and
/// every entry verifies its own format. A login that matches an older
/// hasher returns a fresh hash, so you can store the upgrade.
/// Signed-cookie session primitives — an HMAC-SHA256 key wrapper and a
/// `sign(secret, msg)` helper, shared by every layer that sets a signed
/// cookie so the crypto lives in one place. See [`session::SessionSecret`].
/// `csrf` too: its cookie reads `session::secure_cookies` (#1608).
/// Graceful-shutdown signal handling — SIGINT **and** SIGTERM in one place,
/// so no serve path handles only half of them. See
/// [`shutdown::shutdown_signal`].
/// Interactive prompts for `manage` verbs — `ask(prompt)` reads a line and
/// `ask_password(prompt)` reads one without echoing. On non-TTY stdin both
/// return `Ok(None)`, so scripted callers still get the "missing required
/// flag" error.
/// XML sitemap rendering. Write a `Sitemap`
/// impl (or pass a `Vec<SitemapEntry>`) and call
/// [`sitemaps::render_sitemap`]. For large sites,
/// [`sitemaps::render_sitemap_index`] points crawlers at child sitemaps.
/// RSS 2.0 and Atom 1.0 feed rendering.
/// Build a [`syndication::Feed`] with channel metadata and
/// [`syndication::FeedItem`]s, then call [`syndication::render_rss`] or
/// [`syndication::render_atom`].
/// Table-driven HTTP redirects. Build a
/// [`redirects::RedirectMap`] in code or from a CSV and mount
/// [`redirects::redirects_middleware`]. A matching request returns
/// 301/302 with the canonical URL in `Location`, query string kept.
/// Static "flat pages" — about, terms, privacy. Build a
/// [`flatpages::FlatPageMap`] (path → [`flatpages::FlatPage`]) and mount
/// [`flatpages::flatpages_middleware`]. A matching request serves the page
/// body as `text/html`, or a content-type you choose. Tera wrapping is up
/// to you.
/// Test assertion helpers — `assert_contains` /
/// `assert_redirects` / `assert_status` / `assert_messages` over axum
/// responses. The `query_counter` submodule is ORM instrumentation that
/// `sql::executor` bumps on every query, so the module is always compiled
/// and the response assertions carry their own `_axum` gate.
/// Tag-based test filtering — label a test and run a subset with
/// `manage test --tag fast --exclude-tag slow`. Put `tags!("slow")` at the
/// top of a `#[test]` body and it skips itself when
/// `RUSTANGO_TEST_TAGS` / `RUSTANGO_TEST_EXCLUDE_TAGS` filter it out.
/// Shared test fixtures — the [`setup_test_data!`] /
/// [`setup_test_data_async!`] macros build the fixture once per process
/// (per file under `cargo test`, per test under nextest).
/// Test factories — build model instances for tests without repeating
/// struct literals. A [`test_factory::Sequence`] counter plus the
/// [`test_factory::Factory`] trait with `build_batch`.
/// Test-only Settings overlay — installs a
/// per-task [`config::Settings`] overlay, so tests change configuration
/// without touching process-global state. [`test_settings::current`] reads
/// the overlay first and falls back to the real settings.
/// Test-time DB isolation.
/// [`test_db::with_rollback`] runs an async closure in a transaction that
/// always rolls back, so one test's writes never reach the next.
/// `manage dbshell` — spawn `psql` / `mysql` / `sqlite3` for the current
/// `DATABASE_URL`.
/// The development server. [`server::Builder`] owns the boilerplate a
/// tenancy app would otherwise rewrite: DB pool, resolver chain, host
/// dispatch, operator console, bind and serve.
///
/// The single-pool [`server::AppBuilder`] is available without `tenancy`;
/// the multi-tenant [`server::Builder`] is gated on it inside the module.
/// Unified manage runner — one [`manage::Cli`] builder in place of
/// `src/main.rs` + `src/bin/manage.rs` boilerplate. The tenancy variant
/// appears with the `tenancy` feature. The `manage` feature is on by
/// default and pulls in a small axum + tokio surface, so bare-API projects
/// can use the dispatcher without `admin`.
/// `#[rustango::main]` — the application entrypoint. Wraps
/// `#[tokio::main]` and boots `tracing-subscriber` from `RUST_LOG`,
/// falling back to `info,sqlx=warn`. `RUSTANGO__LOGGING__FORMAT=json` logs JSON.
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;
/// Lets the `#[rustango(default_uuid_v7)]` derive arm reach
/// `Uuid::now_v7()` through the rustango facade, so consumer crates need
/// no direct `uuid` dependency. **Not part of the public API.**
pub use uuid as __uuid;
/// Lets `tracing::warn!` calls emitted by `#[derive(Model)]` resolve
/// through the rustango facade. **Not part of the public API.**
pub use tracing as __tracing;
/// Lets `chrono::Utc::now()` emitted by `#[derive(Model)]` on
/// `auto_now_add` / `auto_now` fields resolve through the facade.
/// **Not part of the public API.**
pub use chrono as __chrono;
/// Lets `serde_json::Value` / `to_value` emitted by `#[derive(Model)]`
/// on the audit and diff paths resolve through the facade.
/// **Not part of the public API.**
pub use serde_json as __serde_json;
/// Lets the `serde::Serialize` impls emitted by `#[derive(Serializer)]`
/// resolve through the facade. **Not part of the public API.**
pub use serde as __serde;
/// Lets `rust_decimal::Decimal` emitted by `#[derive(Model)]` at the
/// Decimal-FK default site resolve through the facade.
/// **Not part of the public API.**
pub use rust_decimal as __rust_decimal;
/// Lets the `axum::Router`-returning method emitted by
/// `#[derive(ViewSet)]` resolve through the facade. Gated on `admin`,
/// the feature that brings axum in. **Not part of the public API.**
pub use axum as __axum;
/// `#[derive(Model)]` — populates the `inventory` registry the admin
/// walks, generates `objects()` / typed columns / `insert` / `delete`
/// / `save`.
pub use Model;
/// Re-exported for `register_admin_computed!` and any user code that
/// wants to submit inventory entries via macros that reference
/// `$crate::inventory`. The runtime indirection costs nothing —
/// `inventory` is a thin wrapper around static `ctor`-style entries.
pub use inventory;
/// 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;
/// `Q!()` — compact filter syntax compile-time-resolved against
/// typed columns. Each invocation expands to the equivalent typed-column
/// method call, so field-name typos fail the build. See
/// [`rustango_macros::Q`] for the supported lookup suffixes.
///
/// ```ignore
/// use rustango::{Q, core::Column as _};
///
/// User::objects()
/// .where_(Q!(User.email__icontains = "alice"))
/// .fetch(&pool).await?;
/// // → WHERE "email" ILIKE $1 ($1 = "%alice%")
/// ```
pub use Q;
/// `#[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 under `admin` or `tenancy` (the generated
/// `router(...)` expands to `__axum::Router`, which `admin` provides); the
/// generated `router(...)` works without tenancy, and `tenant_router(...)`
/// adds the multi-tenant path when `tenancy` is also enabled.
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;