rustf 1.0.0

A simple MVC web framework inspired by Total.js
Documentation
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
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
use crate::config::{AppConfig, TemplateEngine, TemplateStorage};
use crate::context::Context;
use crate::error::Result;
use crate::events::{EventContext, EventEmitter};
use crate::http::{Request, Response, RunningServer, Server};
use crate::middleware::{MiddlewareRegistry, MiddlewareResult};
use crate::models::ModelRegistry;
use crate::routing::{Route, Router};
use crate::shared::SharedRegistry;
use crate::views::ViewEngine;
use crate::workers::WorkerManager;
use ipnetwork::IpNetwork;
use std::collections::HashMap;
use std::net::SocketAddr;
use std::path::{Component, Path, PathBuf};
use std::sync::Arc;
use tokio::net::TcpListener;
use tokio::sync::RwLock;

/// Static files larger than this are streamed rather than read into memory.
///
/// Below it a file is buffered so gzip and other body-inspecting middleware
/// still apply; above it the response holds one 64 KiB chunk at a time. 1 MiB
/// keeps every stylesheet and script bundle on the compressible path while
/// images, fonts and archives stream.
///
/// Streaming changes the memory profile only. The static server does not
/// honour `Range` requests, so seeking in video or resuming an interrupted
/// download is not supported; put such media behind a dedicated file server
/// or CDN.
pub const STATIC_STREAM_THRESHOLD: u64 = 1024 * 1024;

/// Memory-safe RustF application with Arc-based component sharing
///
/// This refactored version uses Arc for safe sharing of framework components
/// between concurrent contexts, eliminating all unsafe code and raw pointers.
pub struct RustF {
    router: Router,
    models: Arc<ModelRegistry>,
    views: Arc<ViewEngine>,
    static_dirs: HashMap<String, PathBuf>,
    middleware: MiddlewareRegistry,
    shared: Arc<SharedRegistry>,
    events: Arc<RwLock<EventEmitter>>,
    workers: Option<Arc<WorkerManager>>,
    pub config: Arc<AppConfig>,
    trusted_proxies: Arc<Vec<IpNetwork>>,
}

impl Default for RustF {
    fn default() -> Self {
        Self::new()
    }
}

impl RustF {
    fn ensure_private_storage_dirs(config: &AppConfig) {
        for (label, dir) in [
            ("private", config.r#private.directory.as_str()),
            ("uploads", config.uploads.directory.as_str()),
        ] {
            let dir_path = std::path::Path::new(dir);
            if !dir_path.exists() {
                match std::fs::create_dir_all(dir_path) {
                    Ok(()) => log::info!("Created {} directory: {}", label, dir),
                    Err(e) => log::warn!("Could not create {} directory '{}': {}", label, dir, e),
                }
            }
        }

        if let Some(database_url) = config.database.url.as_deref() {
            if let Some(database_dir) = sqlite_parent_dir(database_url) {
                if !database_dir.exists() {
                    match std::fs::create_dir_all(database_dir) {
                        Ok(()) => log::info!(
                            "Created sqlite database directory: {}",
                            database_dir.display()
                        ),
                        Err(e) => log::warn!(
                            "Could not create sqlite database directory '{}': {}",
                            database_dir.display(),
                            e
                        ),
                    }
                }
            }
        }
    }

    fn parse_trusted_proxies(config: &AppConfig) -> Vec<IpNetwork> {
        config
            .server
            .trusted_proxies
            .iter()
            .filter_map(|entry| match entry.parse::<IpNetwork>() {
                Ok(network) => Some(network),
                Err(err) => {
                    log::warn!("Ignoring invalid trusted proxy '{}': {}", entry, err);
                    None
                }
            })
            .collect()
    }

    /// An application with the default configuration, in the environment
    /// named by `RUSTF_ENV` (development when unset). Use `with_args()` or
    /// `from_file()` to load `config.toml`.
    pub fn new() -> Self {
        Self::with_config(AppConfig {
            environment: crate::config::Environment::from_process_env_or_production_on_error(),
            ..AppConfig::default()
        })
    }

    pub fn with_config(config: AppConfig) -> Self {
        // Wrap config in Arc first so we can share it
        let config_arc = Arc::new(config);

        // Create view engine based on configuration: engine + storage
        let views = match (
            config_arc.views.engine.clone(),
            config_arc.views.storage.clone(),
        ) {
            (TemplateEngine::TotalJs, TemplateStorage::Filesystem) => {
                log::info!(
                    "Using Total.js engine with filesystem storage from: {}",
                    config_arc.views.directory
                );
                // Total.js is always available as the built-in engine
                ViewEngine::totaljs_filesystem_with_app_config(
                    &config_arc.views.directory,
                    config_arc.clone(),
                )
            }
            (TemplateEngine::TotalJs, TemplateStorage::Embedded) => {
                log::info!("Using Total.js engine with embedded storage");
                #[cfg(feature = "embedded-views")]
                {
                    ViewEngine::totaljs_embedded_with_app_config(config_arc.clone())
                }
                #[cfg(not(feature = "embedded-views"))]
                {
                    panic!("Embedded templates not available! Enable 'embedded-views' feature")
                }
            }
        };

        let middleware = MiddlewareRegistry::new();

        // Initialize static files from configuration
        let mut static_dirs = HashMap::new();
        static_dirs.insert(
            config_arc.static_files.url_prefix.clone(),
            PathBuf::from(&config_arc.static_files.directory),
        );
        log::debug!(
            "Configured static files: {} -> {}",
            config_arc.static_files.url_prefix,
            config_arc.static_files.directory
        );

        Self::ensure_private_storage_dirs(&config_arc);
        let trusted_proxies = Arc::new(Self::parse_trusted_proxies(&config_arc));

        Self {
            router: Router::new(),
            models: Arc::new(ModelRegistry::new()),
            views: Arc::new(views),
            static_dirs,
            middleware,
            shared: Arc::new(SharedRegistry::new()),
            events: Arc::new(RwLock::new(EventEmitter::new())),
            workers: None,
            config: config_arc,
            trusted_proxies,
        }
    }

    pub fn from_file(config_path: &str) -> Result<Self> {
        let config = AppConfig::from_file(config_path)?;
        Ok(Self::with_config(config))
    }

    pub fn from_env() -> Result<Self> {
        let config = AppConfig::from_env()?;
        Ok(Self::with_config(config))
    }

    /// Create RustF application with enhanced path support
    ///
    /// This method supports both CLI arguments and intelligent path resolution:
    /// - CLI `--config` flag for custom config files
    /// - Development-time auto-detection from target/debug folder
    /// - Full/relative path support in config.toml views.directory
    ///
    /// # Path Resolution Examples
    /// In config.toml:
    /// ```toml
    /// [views]
    /// directory = "views"              # Relative to config file
    /// directory = "./templates"        # Relative to config file
    /// directory = "../shared/views"    # Relative to config file
    /// directory = "/absolute/path"     # Absolute path
    /// ```
    ///
    /// # CLI Examples
    /// ```bash
    /// # Use intelligent config loading (includes dev auto-detection)
    /// ./my-app
    ///
    /// # Specify config file
    /// ./my-app --config /etc/myapp/config.toml
    /// ./my-app -c ../shared-config.toml
    /// ```
    pub fn with_args() -> Result<Self> {
        let args = crate::cli::CliArgs::parse()?;

        let config = if let Some(config_path) = args.config_path() {
            log::info!("Loading configuration from CLI: {}", config_path.display());
            AppConfig::from_file(config_path)?
        } else {
            log::debug!("Using intelligent configuration loading with dev auto-detection");
            AppConfig::load_with_dev_detection()?
        };

        Ok(Self::with_config(config))
    }

    /// Create RustF application with CLI args and a custom default config path
    ///
    /// Similar to `with_args()` but uses a custom default configuration file
    /// when no `--config` flag is provided.
    ///
    /// # Arguments
    /// * `default_config_path` - Default config file to use if no --config flag
    ///
    /// # Examples
    /// ```no_run
    /// # use rustf::prelude::*;
    /// # fn _doctest() -> rustf::Result<()> {
    /// // Use custom default, but allow --config to override
    /// let app = RustF::with_args_and_default("config/production.toml")?;
    /// # Ok(()) }
    /// ```
    pub fn with_args_and_default(default_config_path: &str) -> Result<Self> {
        let args = crate::cli::CliArgs::parse()?;

        let mut config = if let Some(config_path) = args.config_path() {
            log::info!(
                "Loading configuration from CLI arg: {}",
                config_path.display()
            );
            AppConfig::from_file(config_path)?
        } else {
            log::info!(
                "Loading default configuration from: {}",
                default_config_path
            );
            AppConfig::from_file(default_config_path)?
        };

        // Override views directory from CLI if provided and using filesystem storage
        if let Some(views_path) = args.views_path() {
            match config.views.storage {
                crate::config::TemplateStorage::Filesystem => {
                    log::info!(
                        "Overriding views directory from CLI: {}",
                        views_path.display()
                    );
                    config.views.directory = views_path.to_string_lossy().to_string();
                }
                crate::config::TemplateStorage::Embedded => {
                    log::warn!("--views flag ignored: embedded template storage is configured");
                }
            }
        }

        Ok(Self::with_config(config))
    }

    pub fn config(mut self, config: AppConfig) -> Self {
        // Update views directory and rebuild static directory mapping to align with new config
        Arc::get_mut(&mut self.views)
            .expect("Views should not be shared during configuration")
            .set_directory(&config.views.directory);

        self.static_dirs.clear();
        self.static_dirs.insert(
            config.static_files.url_prefix.clone(),
            PathBuf::from(&config.static_files.directory),
        );

        Self::ensure_private_storage_dirs(&config);
        self.trusted_proxies = Arc::new(Self::parse_trusted_proxies(&config));
        self.config = Arc::new(config);
        self
    }

    pub fn controllers(mut self, routes: Vec<Route>) -> Self {
        for route in routes {
            self.router.add_route(route);
        }
        self
    }

    pub fn models<F>(mut self, register_fn: F) -> Self
    where
        F: FnOnce(&mut ModelRegistry),
    {
        let models = Arc::get_mut(&mut self.models)
            .expect("Models should not be shared during configuration");
        register_fn(models);
        self
    }

    /// Register a middleware with the application
    ///
    /// # Example
    /// ```rust,ignore
    /// let app = RustF::new()
    ///     .middleware("auth", AuthMiddleware::new("secret"))
    ///     .middleware("cors", CorsMiddleware::default());
    /// ```
    /// Enable default security middleware (recommended for production)
    ///
    /// This enables:
    /// - Security headers (X-Frame-Options, X-Content-Type-Options, etc.)
    /// - Input validation (SQL injection, XSS detection)
    /// - Content Security Policy with permissive defaults
    ///
    /// Note: Rate limiting is NOT enabled by default as it requires tuning
    ///
    /// # Example
    /// ```rust,ignore
    /// let app = RustF::new()
    ///     .with_default_security()
    ///     .controllers(auto_controllers!());
    /// ```
    pub fn with_default_security(mut self) -> Self {
        use crate::middleware::builtin::{
            CspMiddleware, SecurityHeadersMiddleware, ValidationMiddleware,
        };

        // Add security headers (safe for all apps)
        self.middleware
            .register_outbound("security_headers", SecurityHeadersMiddleware::new());

        // Add input validation (protects against common attacks)
        self.middleware
            .register_inbound("input_validation", ValidationMiddleware::new());

        // Add permissive CSP (report-only mode to avoid breaking existing apps)
        self.middleware
            .register_dual("csp", CspMiddleware::permissive());

        log::info!("Default security middleware enabled (security headers, input validation, CSP in report-only mode)");
        log::info!("For rate limiting, explicitly add: .middleware_from(|r| r.register_dual(\"rate_limit\", RateLimitMiddleware::default()))");

        self
    }

    /// Enable gzip response compression middleware.
    ///
    /// Responses are compressed only when:
    /// - The client sends `Accept-Encoding: gzip`
    /// - The body is at least 256 bytes
    /// - The `Content-Type` is compressible (text, JSON, JS, XML, …)
    /// - The response is not already encoded
    ///
    /// # Example
    /// ```rust,ignore
    /// let app = RustF::new()
    ///     .with_compression()
    ///     .controllers(auto_controllers!());
    /// ```
    pub fn with_compression(mut self) -> Self {
        use crate::middleware::builtin::CompressionMiddleware;
        self.middleware
            .register_outbound("compression", CompressionMiddleware::new());
        log::info!("Gzip compression middleware enabled");
        self
    }

    /// Enable HTTP method-override middleware.
    ///
    /// Upgrades a POST request to PUT/PATCH/DELETE when the request carries
    /// a `_method=<METHOD>` field (in query string or form body). Required
    /// for the HTML forms emitted by `rustf-cli new crud` to work with
    /// their PUT and DELETE routes, since browsers only natively send GET
    /// and POST. Matches the Rails / Express / Phoenix convention.
    ///
    /// # Example
    /// ```rust,ignore
    /// let app = RustF::new()
    ///     .with_method_override()
    ///     .controllers(auto_controllers!());
    /// ```
    pub fn with_method_override(mut self) -> Self {
        use crate::middleware::builtin::MethodOverrideMiddleware;
        self.middleware
            .register_inbound("method_override", MethodOverrideMiddleware::new());
        log::info!("HTTP method-override middleware enabled");
        self
    }

    /// Register multiple middleware from a function (for auto-discovery)
    ///
    /// # Example
    /// ```rust,ignore
    /// let app = RustF::new()
    ///     .middleware_from(auto_middleware!());
    /// ```
    pub fn middleware_from<F>(mut self, register_fn: F) -> Self
    where
        F: FnOnce(&mut MiddlewareRegistry),
    {
        register_fn(&mut self.middleware);
        self
    }

    /// Register multiple shared modules from a function (for auto-discovery)
    ///
    /// # Example
    /// ```rust,ignore
    /// let app = RustF::new()
    ///     .modules_from(auto_modules!());
    /// ```
    pub fn modules_from<F>(mut self, register_fn: F) -> Self
    where
        F: FnOnce(&mut SharedRegistry),
    {
        let shared = Arc::get_mut(&mut self.shared)
            .expect("SharedRegistry should not be shared during configuration");
        register_fn(shared);
        self
    }

    /// Enable workers and initialize the worker manager
    ///
    /// # Example
    /// ```rust,ignore
    /// let app = RustF::new()
    ///     .with_workers();
    /// ```
    pub fn with_workers(mut self) -> Self {
        self.ensure_worker_manager();
        self
    }

    fn ensure_worker_manager(&mut self) {
        if self.workers.is_some() {
            return;
        }

        match WorkerManager::with_config(self.config.clone()) {
            Ok(manager) => {
                let manager = Arc::new(manager);
                if let Err(e) = crate::workers::initialize_with_manager(manager.clone()) {
                    log::error!("Failed to initialize worker system: {}", e);
                } else {
                    self.workers = Some(manager);
                    log::info!("Worker system initialized");
                }
            }
            Err(e) => {
                log::error!("Failed to create worker manager: {}", e);
            }
        }
    }

    /// Register workers from a closure
    ///
    /// # Example
    /// ```rust,ignore
    /// let app = RustF::new()
    ///     .with_workers()
    ///     .workers_from(|manager| {
    ///         manager.spawn("email-sender", email_handler);
    ///         manager.recurring("cleanup", Duration::from_secs(3600), cleanup_handler);
    ///     });
    /// ```
    pub fn workers_from<F, Fut>(mut self, register_fn: F) -> Self
    where
        F: FnOnce(Arc<WorkerManager>) -> Fut + Send + 'static,
        Fut: std::future::Future<Output = Result<()>> + Send + 'static,
    {
        // Enable workers if not already enabled
        self.ensure_worker_manager();

        if let Some(manager) = &self.workers {
            let manager = manager.clone();
            tokio::spawn(async move {
                if let Err(e) = register_fn(manager).await {
                    log::error!("Error registering workers: {}", e);
                }
            });
        }

        self
    }

    /// Get the worker manager if workers are enabled
    pub fn workers(&self) -> Option<&Arc<WorkerManager>> {
        self.workers.as_ref()
    }

    pub fn static_files(mut self, url_prefix: &str, directory: &str) -> Self {
        self.static_dirs
            .insert(url_prefix.to_string(), PathBuf::from(directory));
        self
    }

    pub fn views(mut self, directory: &str) -> Self {
        Arc::get_mut(&mut self.views)
            .expect("Views should not be shared during configuration")
            .set_directory(directory);
        self
    }

    /// Register an event handler with default priority
    ///
    /// # Example
    /// ```rust,ignore
    /// let app = RustF::new()
    ///     .on("ready", |ctx| Box::pin(async move {
    ///         println!("Application ready!");
    ///         Ok(())
    ///     }));
    /// ```
    pub fn on<F>(self, event: &str, handler: F) -> Self
    where
        F: Fn(
                EventContext,
            )
                -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<()>> + Send>>
            + Send
            + Sync
            + 'static,
    {
        // Get mutable access during configuration phase
        if let Ok(mut events) = self.events.try_write() {
            events.on(event, handler);
        } else {
            log::warn!(
                "Could not register event handler for '{}' - events system is locked",
                event
            );
        }
        self
    }

    /// Register an event handler with specific priority
    pub fn on_priority<F>(self, event: &str, priority: i32, handler: F) -> Self
    where
        F: Fn(
                EventContext,
            )
                -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<()>> + Send>>
            + Send
            + Sync
            + 'static,
    {
        // Get mutable access during configuration phase
        if let Ok(mut events) = self.events.try_write() {
            events.on_priority(event, priority, handler);
        } else {
            log::warn!(
                "Could not register event handler for '{}' - events system is locked",
                event
            );
        }
        self
    }

    /// Register multiple event handlers from a function
    ///
    /// # Example
    /// ```rust,ignore
    /// let app = RustF::new()
    ///     .events_from(|emitter| {
    ///         emitter.on("ready", handler1);
    ///         emitter.on("startup", handler2);
    ///     });
    /// ```
    pub fn events_from<F>(self, register_fn: F) -> Self
    where
        F: FnOnce(&mut EventEmitter),
    {
        // Get mutable access during configuration phase
        if let Ok(mut events) = self.events.try_write() {
            register_fn(&mut events);
        } else {
            log::warn!("Could not register event handlers - events system is locked");
        }
        self
    }

    /// Configure event system performance settings
    ///
    /// # Example
    /// ```rust,ignore
    /// let app = RustF::new()
    ///     .event_config(EventEmitterConfig::parallel()
    ///         .with_timeout(Duration::from_secs(60))
    ///         .with_max_concurrent(4));
    /// ```
    pub fn event_config(self, config: crate::events::EventEmitterConfig) -> Self {
        if let Ok(mut events) = self.events.try_write() {
            events.set_config(config);
        } else {
            log::warn!("Could not update event configuration - events system is locked");
        }
        self
    }

    /// Register definitions (providers, helpers, validators, interceptors)
    ///
    /// # Example
    /// ```rust,ignore
    /// let app = RustF::new()
    ///     .definitions(|defs| {
    ///         defs.register_provider(MySessionProvider::new());
    ///         defs.register_helper("custom", MyHelper);
    ///         defs.register_validator("custom", MyValidator);
    ///     });
    /// ```
    pub fn definitions<F>(self, install_fn: F) -> Self
    where
        F: FnOnce(&mut crate::definitions::Definitions),
    {
        // Load definitions during the configuration phase
        futures::executor::block_on(async {
            let mut defs = crate::definitions::get_mut().await;
            install_fn(&mut defs);
            if let Err(e) = defs.initialize().await {
                log::error!("Failed to initialize definitions: {}", e);
            }
        });
        self
    }

    /// Register definitions from a module's install function
    ///
    /// # Example
    /// ```rust,ignore
    /// let app = RustF::new()
    ///     .definitions_from(my_app::definitions::install);
    /// ```
    pub fn definitions_from(self, install_fn: crate::definitions::InstallFn) -> Self {
        self.definitions(install_fn)
    }

    /// Auto-load ALL components WITHOUT builtin middleware
    ///
    /// This is the recommended method for basic setup. It automatically loads:
    ///
    /// **Custom components from conventional directories:**
    /// - `src/controllers/*.rs` → Routes
    /// - `src/models/*.rs` → Database models
    /// - `src/workers/*.rs` → Background workers
    /// - `src/middleware/*.rs` → Custom middleware
    /// - `src/events/*.rs` → Event handlers
    /// - `src/definitions/*.rs` → Helpers & validators
    ///
    /// **Note:** Builtin middleware is NOT enabled by default.
    /// Use `auto_load_with()` to explicitly enable builtin middleware.
    ///
    /// **Session middleware** is enabled by default but can be disabled via config.toml.
    ///
    /// # Example
    /// ```rust,ignore
    /// #[rustf::auto_discover]
    /// #[tokio::main]
    /// async fn main() -> rustf::Result<()> {
    ///     RustF::new()
    ///         .auto_load()  // No builtin middleware
    ///         .start().await
    /// }
    /// ```
    ///
    /// # To Enable Builtin Middleware
    /// Use `auto_load_with()` instead:
    ///
    /// ```rust,ignore
    /// RustF::new()
    ///     .auto_load_with(&["logging", "cors", "rate_limit", "csrf"])
    ///     .start().await
    /// ```
    pub fn auto_load(self) -> Self {
        self.auto_load_with(&[])
    }

    /// Auto-load ALL components with specified builtin middleware
    ///
    /// This is the recommended method for production use. Use this to explicitly enable
    /// the builtin middleware you need for your application.
    ///
    /// **Note:** Session middleware is enabled by default (configurable via config.toml).
    ///
    /// # Arguments
    /// * `builtin_middleware` - Slice of middleware names to enable
    ///
    ///   Available builtin middleware:
    ///   - `"logging"` - Request/response logging
    ///   - `"cors"` - Cross-Origin Resource Sharing
    ///   - `"rate_limit"` - Rate limiting
    ///   - `"csrf"` - CSRF protection
    ///
    /// # Examples
    /// ```rust,ignore
    /// // Production setup with all security middleware
    /// RustF::new()
    ///     .auto_load_with(&["logging", "cors", "rate_limit", "csrf"])
    ///     .start().await
    ///
    /// // API server with logging and CORS only
    /// RustF::new()
    ///     .auto_load_with(&["logging", "cors"])
    ///     .start().await
    ///
    /// // Minimal setup (same as auto_load())
    /// RustF::new()
    ///     .auto_load_with(&[])
    ///     .start().await
    ///
    /// // Web app with CSRF protection
    /// RustF::new()
    ///     .auto_load_with(&["logging", "csrf"])
    ///     .start().await
    /// ```
    ///
    /// # Configuration
    /// Each builtin middleware reads its configuration from `config.toml`:
    ///
    /// ```toml
    /// [middleware.logging]
    /// # Logging is configured via RUST_LOG environment variable
    ///
    /// [middleware.cors]
    /// allow_origin = "*"
    /// allow_methods = ["GET", "POST", "PUT", "DELETE", "OPTIONS"]
    /// allow_credentials = false
    ///
    /// [middleware.rate_limit]
    /// max_requests = 100
    /// window_seconds = 60
    ///
    /// [middleware.csrf]
    /// exempt_routes = ["/api/*", "/webhook/*"]
    /// error_message = "CSRF validation failed"
    /// ```
    pub fn auto_load_with(mut self, builtin_middleware: &[&str]) -> Self {
        if let Some(hooks) = crate::auto::hooks() {
            if let Some(controllers) = hooks.controllers {
                self = self.controllers(controllers());
            }

            if let Some(models) = hooks.models {
                self = self.models(models);
            }

            if let Some(shared) = hooks.shared {
                self = self.modules_from(shared);
            }

            if let Some(definitions) = hooks.definitions {
                self = self.definitions(definitions);
            }

            if let Some(middleware) = hooks.middleware {
                self = self.middleware_from(middleware);
            }

            if let Some(events) = hooks.events {
                self = self.events_from(events);
            }

            if let Some(workers_installer) = hooks.workers {
                self = self.with_workers().workers_from(workers_installer);
            }
        } else {
            log::warn!(
                "Auto-discovery hooks not registered. Ensure #[rustf::auto_discover] is applied to your entry point."
            );
        }

        if !builtin_middleware.is_empty() {
            self = self.load_builtin_middleware(builtin_middleware);
        }

        self
    }

    /// Load builtin middleware with configuration from config.toml
    ///
    /// This is a private helper method that instantiates builtin middleware
    /// using their `.from_config()` methods which read from config.toml.
    fn load_builtin_middleware(self, middleware_names: &[&str]) -> Self {
        self.middleware_from(move |registry| {
            use crate::middleware::builtin::{LoggingMiddleware, CorsMiddleware, RateLimitMiddleware};
            use crate::security::CsrfMiddleware;

            for name in middleware_names {
                match *name {
                    "logging" => {
                        registry.register_dual("logging", LoggingMiddleware::new());
                    }
                    "cors" => {
                        let cors = CorsMiddleware::from_config();
                        registry.register_dual("cors", cors);
                    }
                    "rate_limit" => {
                        let rate_limit = RateLimitMiddleware::from_config();
                        registry.register_dual("rate_limit", rate_limit);
                    }
                    "csrf" => {
                        let csrf = CsrfMiddleware::from_config();
                        registry.register_inbound("csrf", csrf);
                    }
                    unknown => {
                        log::warn!("Unknown builtin middleware '{}' - ignoring. Available: logging, cors, rate_limit, csrf", unknown);
                    }
                }
            }
        })
    }

    async fn initialize_runtime(&mut self) -> Result<()> {
        // Initialize global configuration access (CONF)
        if let Err(e) = crate::configuration::CONF::init((*self.config).clone()) {
            log::error!("Failed to initialize global configuration: {}", e);
            return Err(e);
        }
        log::info!("Global configuration (CONF) initialized");

        // Initialize global repository (APP/MAIN)
        if let Err(e) = crate::repository::APP::init(serde_json::json!({})) {
            log::error!("Failed to initialize global repository (APP/MAIN): {}", e);
            return Err(e);
        }
        log::info!("Global repository (APP/MAIN) initialized");

        // Note: MODULE system is NOT initialized by framework anymore.
        // Developers must explicitly call MODULE::init() in their app code
        // to initialize the module system for explicit named registration.
        // This ensures developers have full control over module registration timing.

        // Emit config.loaded event
        if let Err(e) = self
            .events
            .read()
            .await
            .emit(
                crate::events::events::CONFIG_LOADED,
                None,
                self.config.clone(),
            )
            .await
        {
            log::error!("Error emitting config.loaded event: {}", e);
        }

        // Initialize database connection if configured
        #[cfg(feature = "database")]
        {
            use crate::db::DB;
            if let Err(e) = DB::init(self.config.database.url.as_deref()).await {
                log::error!("Database initialization failed: {}", e);
                return Err(e);
            }

            // Emit database.ready event
            if let Err(e) = self
                .events
                .read()
                .await
                .emit(
                    crate::events::events::DATABASE_READY,
                    None,
                    self.config.clone(),
                )
                .await
            {
                log::error!("Error emitting database.ready event: {}", e);
            }
        }

        // Auto-register session middleware if enabled in config (dual-phase)
        // This must be done after database initialization as it may need DB/Redis connections
        if let Some(session_middleware) =
            crate::session::config_adapter::create_session_middleware(&self.config).await
        {
            self.middleware.register_dual("session", session_middleware);
        }

        // Initialize shared modules
        if let Err(e) = self.shared.initialize_all().await {
            log::error!("Shared modules initialization failed: {}", e);
            return Err(crate::error::Error::internal(format!(
                "Module initialization failed: {}",
                e
            )));
        }

        // Emit modules.ready event
        if let Err(e) = self
            .events
            .read()
            .await
            .emit(
                crate::events::events::MODULES_READY,
                None,
                self.config.clone(),
            )
            .await
        {
            log::error!("Error emitting modules.ready event: {}", e);
        }

        // Initialize global VIEW API for inline template rendering
        if let Err(e) = crate::views::api::initialize_global_view(self.views.clone()) {
            log::warn!("Failed to initialize global VIEW API: {}", e);
        } else {
            log::info!("Global VIEW API initialized");
        }

        // Emit middleware.ready event
        if !self.middleware.is_empty() {
            if let Err(e) = self
                .events
                .read()
                .await
                .emit(
                    crate::events::events::MIDDLEWARE_READY,
                    None,
                    self.config.clone(),
                )
                .await
            {
                log::error!("Error emitting middleware.ready event: {}", e);
            }
        }

        // Emit routes.ready event
        if let Err(e) = self
            .events
            .read()
            .await
            .emit(
                crate::events::events::ROUTES_READY,
                None,
                self.config.clone(),
            )
            .await
        {
            log::error!("Error emitting routes.ready event: {}", e);
        }

        // Emit startup event before starting server
        if let Err(e) = self
            .events
            .read()
            .await
            .emit(crate::events::events::STARTUP, None, self.config.clone())
            .await
        {
            log::error!("Error emitting startup event: {}", e);
        }

        // Emit ready event - framework is fully initialized
        if let Err(e) = self
            .events
            .read()
            .await
            .emit(crate::events::events::READY, None, self.config.clone())
            .await
        {
            log::error!("Error emitting ready event: {}", e);
        }

        Ok(())
    }

    pub async fn serve(mut self, addr: Option<&str>) -> Result<()> {
        self.initialize_runtime().await?;
        let config_addr = self.config.server_address();
        let server_addr = addr.unwrap_or(&config_addr);
        let server = Server::new(self);
        server.serve(server_addr).await
    }

    pub async fn serve_with_handle(mut self, addr: &str) -> Result<RunningServer> {
        self.initialize_runtime().await?;
        Server::new(self).serve_with_handle(addr).await
    }

    pub async fn serve_on_listener(mut self, listener: TcpListener) -> Result<RunningServer> {
        self.initialize_runtime().await?;
        Server::new(self).serve_on_listener(listener).await
    }

    pub async fn start(self) -> Result<()> {
        self.serve(None).await
    }

    /// Perform graceful cleanup during shutdown
    ///
    /// This method is called automatically when the server receives a shutdown signal.
    /// It ensures all resources are properly released in the correct order.
    pub(crate) async fn cleanup(&self) -> Result<()> {
        use std::time::Duration;

        log::info!("Starting graceful shutdown sequence...");

        // 1. Emit shutdown event for custom handlers
        if let Err(e) = self
            .events
            .read()
            .await
            .emit(crate::events::events::SHUTDOWN, None, self.config.clone())
            .await
        {
            log::error!("Error emitting shutdown event: {}", e);
        }

        // Give event handlers a moment to process
        tokio::time::sleep(Duration::from_millis(100)).await;

        // 2. Shutdown workers if enabled
        if let Some(workers) = &self.workers {
            log::info!("Shutting down workers...");
            if let Err(e) = workers.shutdown_all().await {
                log::error!("Error shutting down workers: {}", e);
            }
        }

        // 3. Shutdown shared modules
        log::info!("Shutting down shared modules...");
        if let Err(e) = self.shared.shutdown_all().await {
            log::error!("Error shutting down shared modules: {}", e);
        }

        // 4. Close database connections
        #[cfg(feature = "database")]
        {
            use crate::db::DB;
            if let Err(e) = DB::shutdown().await {
                log::error!("Error closing database connections: {}", e);
            }
        }

        // 4. Cleanup complete
        log::info!("Shutdown complete");

        log::info!("Graceful shutdown complete");
        Ok(())
    }

    pub async fn handle_request<B>(&self, req: hyper::Request<B>) -> Result<Response>
    where
        B: hyper::body::Body,
        B::Error: std::fmt::Display,
    {
        self.handle_request_with_peer(req, None).await
    }

    pub(crate) async fn handle_request_with_peer<B>(
        &self,
        req: hyper::Request<B>,
        peer_addr: Option<SocketAddr>,
    ) -> Result<Response>
    where
        B: hyper::body::Body,
        B::Error: std::fmt::Display,
    {
        let is_head = req.method() == hyper::Method::HEAD;
        let mut response = self.dispatch_request(req, peer_addr).await?;

        // A HEAD response carries the headers a GET would have produced and
        // no body. The handler ran as for GET (a static file may be a
        // multi-megabyte stream at this point), so record the length the body
        // would have had, then discard it before a single byte is sent.
        if is_head {
            let would_have_sent = match &response.body {
                crate::http::Body::Full(bytes) => Some(bytes.len() as u64),
                crate::http::Body::Stream(stream) => stream.size(),
            };
            // Any caller Content-Length is stale once the body is gone
            // (`into_hyper` drops it anyway); the advertised length is the
            // only channel that survives.
            response
                .headers
                .retain(|(name, _)| !name.eq_ignore_ascii_case("content-length"));
            response.body = crate::http::Body::empty();

            // 1xx and 204 never carry Content-Length; a 304's body was already
            // empty and its length (if any) is the validator's business, not
            // this wrapper's. An open-ended stream has no length to advertise.
            let status = response.status;
            let may_advertise = !status.is_informational()
                && status != hyper::StatusCode::NO_CONTENT
                && status != hyper::StatusCode::NOT_MODIFIED;
            if let (true, Some(len)) = (may_advertise, would_have_sent) {
                response = response.advertise_content_length(len);
            }
        }

        Ok(response)
    }

    async fn dispatch_request<B>(
        &self,
        req: hyper::Request<B>,
        peer_addr: Option<SocketAddr>,
    ) -> Result<Response>
    where
        B: hyper::body::Body,
        B::Error: std::fmt::Display,
    {
        let request =
            Request::from_hyper_with_connection(req, peer_addr, Arc::clone(&self.trusted_proxies))
                .await?;

        // Check for static files first (match prefix safely using request path without query)
        let request_path = request.path().to_string();
        for (prefix, dir) in &self.static_dirs {
            if let Some(relative_suffix) = Self::match_static_prefix(&request_path, prefix) {
                // Extract conditional request headers before moving `request`
                let if_none_match = request.headers.get("if-none-match").cloned();
                let if_modified_since = request.headers.get("if-modified-since").cloned();
                return self
                    .serve_static_file(
                        dir,
                        relative_suffix,
                        &request_path,
                        if_none_match.as_deref(),
                        if_modified_since.as_deref(),
                    )
                    .await;
            }
        }

        // Create memory-safe context with Arc references
        let mut context = Context::new(request, Arc::clone(&self.views));

        // Execute middleware chain + route handler. A middleware that returns
        // `Err` gets the same treatment as a handler that does: its status,
        // not a blanket 500.
        let result = match self.execute_middleware_chain(&mut context).await {
            Ok(result) => result,
            Err(e) => return Ok(Self::response_for_error(&context, &e)),
        };

        // Get response from result
        let response = match result {
            MiddlewareResult::Continue => {
                // This should not happen - the final handler should always return Stop
                log::warn!("Middleware chain returned Continue but no more handlers available");
                Response::internal_error()
            }
            MiddlewareResult::Stop(response) => response,
        };

        Ok(response)
    }

    /// Execute the dual-phase middleware chain followed by the route handler
    ///
    /// This implements the inbound/outbound pattern where middleware can process
    /// requests on the way in and responses on the way out.
    async fn execute_middleware_chain(&self, ctx: &mut Context) -> Result<MiddlewareResult> {
        use crate::middleware::InboundAction;
        // Fast path: no middleware registered
        if self.middleware.is_empty() {
            #[allow(unused_mut)]
            let mut result = self.execute_route_handler(ctx).await?;
            // There is no outbound stack to run, but a queued upgrade still
            // has to reach the runtime. Without this, an app with no
            // middleware at all (every builtin is opt-in, and the session
            // middleware is only registered when sessions are enabled) would
            // answer a handshake with `101` and then never upgrade.
            #[cfg(feature = "websocket")]
            if let MiddlewareResult::Stop(ref mut response) = result {
                self.start_pending_upgrade(ctx, response);
            }
            return Ok(result);
        }

        // Get sorted middleware (by priority) — zero-cost slice borrow
        let middleware_list = self.middleware.get_sorted();
        let mut outbound_stack = Vec::new();

        // Phase 1: INBOUND - Process request through middleware
        for (index, middleware) in middleware_list.iter().enumerate() {
            if middleware.inbound.is_none() && middleware.has_outbound() {
                outbound_stack.push(middleware);
                continue;
            }

            // Only process if middleware has inbound phase and should run
            if let Some(ref inbound) = middleware.inbound {
                if inbound.should_run(ctx) {
                    // Process the request (now async)
                    let action = match inbound.process_request(ctx).await {
                        Ok(action) => action,
                        Err(e) => {
                            // The error carries the status (a middleware doing
                            // its own `ctx.require_auth()?` means 401), and the
                            // outbound stack accumulated *so far* still runs
                            // over it, so the response is not sent without the
                            // security headers a successful one would carry.
                            //
                            // This middleware is deliberately not pushed onto
                            // that stack: unlike `InboundAction::Stop`, an
                            // `Err` means its inbound phase did not finish, so
                            // its outbound phase has no state to pair with.
                            //
                            // No `start_pending_upgrade` here, unlike the other
                            // early returns: inbound middleware runs before the
                            // handler, so there is no queued upgrade yet.
                            let response = Self::response_for_error(ctx, &e);
                            ctx.set_response(response);
                            Self::push_remaining_outbound_only(
                                &mut outbound_stack,
                                &middleware_list[index + 1..],
                            );
                            self.run_outbound_stack(ctx, &outbound_stack).await?;
                            return Ok(MiddlewareResult::Stop(
                                ctx.take_response().unwrap_or_else(Response::internal_error),
                            ));
                        }
                    };

                    match action {
                        InboundAction::Continue => {
                            // Check if this middleware wants to process response
                            if middleware.has_outbound() {
                                outbound_stack.push(middleware);
                            }
                        }
                        InboundAction::Stop => {
                            if middleware.has_outbound() {
                                outbound_stack.push(middleware);
                            }

                            // Early return - use response set on context
                            let response =
                                ctx.take_response().unwrap_or_else(Response::internal_error);
                            ctx.set_response(response);
                            Self::push_remaining_outbound_only(
                                &mut outbound_stack,
                                &middleware_list[index + 1..],
                            );
                            self.run_outbound_stack(ctx, &outbound_stack).await?;
                            #[allow(unused_mut)]
                            let mut final_response =
                                ctx.take_response().unwrap_or_else(Response::internal_error);
                            #[cfg(feature = "websocket")]
                            self.start_pending_upgrade(ctx, &mut final_response);
                            return Ok(MiddlewareResult::Stop(final_response));
                        }
                        InboundAction::Capture => {
                            // This middleware wants to process the response
                            outbound_stack.push(middleware);
                        }
                    }
                }
            }
        }

        // Phase 2: Execute the route handler
        let result = self.execute_route_handler(ctx).await?;

        let response = match result {
            MiddlewareResult::Stop(resp) => resp,
            MiddlewareResult::Continue => Response::internal_error(),
        };

        // Set the response in context for outbound middleware to access
        ctx.set_response(response);

        // Phase 3: OUTBOUND - Process response through middleware (in reverse order)
        // Context has all modifications from both inbound middleware and handler
        self.run_outbound_stack(ctx, &outbound_stack).await?;

        // Get the final response from context
        #[allow(unused_mut)]
        let mut final_response = ctx.take_response().unwrap_or_else(Response::internal_error);

        #[cfg(feature = "websocket")]
        self.start_pending_upgrade(ctx, &mut final_response);

        Ok(MiddlewareResult::Stop(final_response))
    }

    /// On an early exit (an inbound `Stop` or `Err`), add the outbound-only
    /// middleware the inbound loop had not reached yet.
    ///
    /// Outbound-only middleware (security headers, CSP, ...) decorates every
    /// response and has no inbound state to pair with, so it must not depend
    /// on where the short-circuiting middleware sits in the priority order.
    /// Without this, an auth middleware at priority -100 returning 401 skips
    /// `SecurityHeadersMiddleware` at priority 0. Dual-phase middleware further
    /// down is still skipped: its inbound phase never ran.
    fn push_remaining_outbound_only<'a>(
        outbound_stack: &mut Vec<&'a crate::middleware::DualPhaseMiddlewareInstance>,
        remaining: &'a [crate::middleware::DualPhaseMiddlewareInstance],
    ) {
        outbound_stack.extend(
            remaining
                .iter()
                .filter(|m| m.inbound.is_none() && m.has_outbound()),
        );
    }

    /// Hand a queued WebSocket upgrade to the runtime, if the response that is
    /// actually going out is still the `101`.
    ///
    /// Deliberately the last thing that happens: outbound middleware runs after
    /// the handler and can replace the response. Spawning any earlier would
    /// leave a task waiting on an upgrade that is never going to happen,
    /// because the client received a `403` (or anything else) instead.
    #[cfg(feature = "websocket")]
    fn start_pending_upgrade(&self, ctx: &mut Context, final_response: &mut Response) {
        let Some(pending) = ctx.take_pending_upgrade() else {
            return;
        };

        // Shutdown may have begun while this request was in the handler or in
        // outbound middleware. Re-checking here, immediately before the task is
        // registered, is what keeps a late upgrade from escaping the drain.
        if crate::websocket::upgrade::is_shutting_down() {
            log::info!(
                "WebSocket upgrade on {} refused: the server is shutting down",
                ctx.req.path()
            );
            *final_response = Response::new(hyper::StatusCode::SERVICE_UNAVAILABLE)
                .with_header("Content-Type", "text/plain; charset=utf-8")
                .with_body(
                    "The server is shutting down and is not accepting WebSocket connections."
                        .as_bytes()
                        .to_vec(),
                );
            return;
        }

        if pending.matches(final_response) {
            // hyper resolves `OnUpgrade` only after this `101` has been
            // written, so the task simply parks until the response is on
            // the wire. `spawn_tracked` refuses if shutdown began in the
            // meantime, which is the only remaining way this could race.
            if !crate::websocket::upgrade::spawn_tracked(pending) {
                log::info!(
                    "WebSocket upgrade on {} refused: the server began shutting down",
                    ctx.req.path()
                );
                *final_response = Response::new(hyper::StatusCode::SERVICE_UNAVAILABLE)
                    .with_header("Content-Type", "text/plain; charset=utf-8")
                    .with_body(
                        "The server is shutting down and is not accepting WebSocket connections."
                            .as_bytes()
                            .to_vec(),
                    );
            }
        } else {
            log::error!(
                "WebSocket upgrade on {} was discarded: the response going out is no longer the \
                 negotiated 101 (status {}). `ctx.websocket`/`ctx.socket` must be the last call \
                 in the handler, and outbound middleware must not alter a 101 or its \
                 Upgrade/Connection/Sec-WebSocket-Accept headers.",
                ctx.req.path(),
                final_response.status
            );
        }
    }

    async fn run_outbound_stack(
        &self,
        ctx: &mut Context,
        outbound_stack: &[&crate::middleware::DualPhaseMiddlewareInstance],
    ) -> Result<()> {
        for middleware in outbound_stack.iter().rev() {
            if let Some(ref outbound) = middleware.outbound {
                outbound.process_response(ctx).await?;
            }
        }

        Ok(())
    }

    /// Turn an error raised during request handling into the response the
    /// client should see.
    ///
    /// A 5xx is a fault worth the error log and the full chain; a 4xx is a
    /// normal outcome of a bad request and is logged at debug so that a burst
    /// of them cannot be used to flood the log.
    fn response_for_error(ctx: &Context, error: &crate::error::Error) -> Response {
        if error.status_code() >= 500 {
            log::error!(
                "Request handling error: {}",
                crate::error::ErrorChain::new(error).format_for_log()
            );
        } else {
            log::debug!(
                "{} {} -> {}: {}",
                ctx.req.method,
                ctx.req.path(),
                error.status_code(),
                error
            );
        }
        Response::from_error(error, ctx.req.wants_json())
    }

    /// Execute the route handler (final step in the chain)
    async fn execute_route_handler(&self, ctx: &mut Context) -> Result<MiddlewareResult> {
        // Try to match route. Use `path()` (not the raw `uri`) so HTTP/2 — where
        // the URI is the absolute `http://host/path` form — routes like HTTP/1.
        // HEAD is served by the GET handler when no HEAD route exists; the
        // body is discarded in `handle_request_with_peer`.
        let matched = self
            .router
            .match_route(&ctx.req.method, ctx.req.path())
            .or_else(|| {
                if ctx.req.method.eq_ignore_ascii_case("HEAD") {
                    self.router.match_route("GET", ctx.req.path())
                } else {
                    None
                }
            });
        if let Some((route_info, params)) = matched {
            // Check XHR constraint if the route requires it
            if route_info.xhr_only && !ctx.is_xhr() {
                return Ok(MiddlewareResult::Stop(
                    Response::forbidden(Some("This endpoint requires an AJAX (XHR) request"))
                        .with_header("Content-Type", "application/json")
                        .with_body(r#"{"error":"This endpoint requires an AJAX (XHR) request"}"#),
                ));
            }

            // A `SOCKET` route is registered as `GET`, because the opening
            // handshake is one. A `GET` that is *not* a handshake must never
            // reach the handler: it would call `ctx.websocket`, get a rejection
            // response back, and look like a mysterious 4xx. Answer it here
            // with the status that says what to do instead.
            #[cfg(feature = "websocket")]
            if route_info.socket.is_some() && !ctx.req.is_websocket_upgrade() {
                return Ok(MiddlewareResult::Stop(
                    crate::websocket::handshake::upgrade_required(
                        "This endpoint speaks WebSocket. Connect with ws:// or wss://.",
                    ),
                ));
            }

            ctx.req.params = params;
            ctx.socket_options = route_info.socket;

            // Run controller-level `before` hook if any (wired via the
            // `routes![before: ..., ...]` macro arm). If it returns
            // `Stop`, skip the handler and return the response the hook
            // already wrote to ctx.res.
            if let Some(before) = route_info.before {
                use crate::routing::BeforeAction;
                match before(ctx).await {
                    Ok(BeforeAction::Stop) => {
                        let response = ctx.take_response().unwrap_or_else(Response::internal_error);
                        return Ok(MiddlewareResult::Stop(response));
                    }
                    Ok(BeforeAction::Continue) => { /* fall through to handler */ }
                    Err(e) => return Ok(MiddlewareResult::Stop(Self::response_for_error(ctx, &e))),
                }
            }

            // Handler modifies context in place (sets response). An error is
            // not a crash: `ctx.require_auth()?` means 401, `?` on a
            // validation error means 400. Turn it into that response here so
            // outbound middleware still runs over it, and so whatever partial
            // response the handler had written is discarded.
            if let Err(e) = (route_info.handler)(ctx).await {
                return Ok(MiddlewareResult::Stop(Self::response_for_error(ctx, &e)));
            }

            // Get the response from context or return 500 if not set
            let response = ctx.take_response().unwrap_or_else(Response::internal_error);

            Ok(MiddlewareResult::Stop(response))
        } else {
            Ok(MiddlewareResult::Stop(Response::not_found()))
        }
    }

    async fn serve_static_file(
        &self,
        base_dir: &PathBuf,
        relative_suffix: &str,
        full_request_path: &str,
        if_none_match: Option<&str>,
        if_modified_since: Option<&str>,
    ) -> Result<Response> {
        let cache_enabled = self.config.static_files.cache_enabled;
        let cache_max_age = self.config.static_files.cache_max_age;

        // 1. Try the embedded assets provider first — but only when the configured
        //    storage is `embedded`. The `embedded-views` feature merely compiles the
        //    provider in; config decides whether it actually serves. This keeps static
        //    assets consistent with views (same switch) and lets dev builds serve
        //    public/ from disk without a rebuild even when the feature is enabled.
        if matches!(self.config.views.storage, TemplateStorage::Embedded) {
            if let Some(provider) = crate::views::embed_provider::get_assets_provider() {
                // Normalise the lookup key: prefer the suffix without prefix,
                // fall back to the full path (without leading slash).
                let candidates: &[&str] =
                    &[relative_suffix, full_request_path.trim_start_matches('/')];
                for key in candidates {
                    if key.is_empty() {
                        continue;
                    }
                    if let Some(data) = provider.get(key) {
                        let content_type = Self::infer_content_type(Path::new(key));
                        let response = if cache_enabled {
                            use std::collections::hash_map::DefaultHasher;
                            use std::hash::{Hash, Hasher};
                            let mut hasher = DefaultHasher::new();
                            data.hash(&mut hasher);
                            let etag = format!("\"embed-{:x}\"", hasher.finish());
                            if if_none_match == Some(etag.as_str()) {
                                Response::not_modified()
                                    .with_header("ETag", &etag)
                                    .with_header("X-Content-Type-Options", "nosniff")
                                    .with_header(
                                        "Cache-Control",
                                        &format!("public, max-age={}", cache_max_age),
                                    )
                            } else {
                                Response::ok()
                                    .with_header("Content-Type", content_type)
                                    .with_header("X-Content-Type-Options", "nosniff")
                                    .with_header(
                                        "Cache-Control",
                                        &format!("public, max-age={}", cache_max_age),
                                    )
                                    .with_header("ETag", &etag)
                                    .with_header("Content-Length", &data.len().to_string())
                                    .with_body(data)
                            }
                        } else {
                            Response::ok()
                                .with_header("Content-Type", content_type)
                                .with_header("X-Content-Type-Options", "nosniff")
                                .with_header("Cache-Control", "no-store, no-cache")
                                .with_body(data)
                        };
                        return Ok(response);
                    }
                }
            }
        }

        let canonical_base = match base_dir.canonicalize() {
            Ok(path) => path,
            Err(_) => return Ok(Response::not_found()),
        };

        // 2. Try the suffix after the prefix first (preferred behaviour)
        if let Some(candidate) = Self::sanitize_and_join(&canonical_base, relative_suffix) {
            if let Some(response) = Self::try_read_static_file(
                &candidate,
                &canonical_base,
                cache_enabled,
                cache_max_age,
                if_none_match,
                if_modified_since,
            )
            .await?
            {
                return Ok(response);
            }
        }

        // 3. Fall back to historical behaviour (prefix included) for compatibility
        let trimmed_full = full_request_path.trim_start_matches('/');
        if let Some(candidate) = Self::sanitize_and_join(&canonical_base, trimmed_full) {
            if let Some(response) = Self::try_read_static_file(
                &candidate,
                &canonical_base,
                cache_enabled,
                cache_max_age,
                if_none_match,
                if_modified_since,
            )
            .await?
            {
                return Ok(response);
            }
        }

        Ok(Response::not_found())
    }

    fn match_static_prefix<'a>(path: &'a str, prefix: &'a str) -> Option<&'a str> {
        if prefix.is_empty() {
            return None;
        }

        let mut normalized_prefix = prefix;
        if normalized_prefix == "/" {
            return Some(path.trim_start_matches('/'));
        }

        if !normalized_prefix.starts_with('/') {
            return None;
        }

        if normalized_prefix.len() > 1 && normalized_prefix.ends_with('/') {
            normalized_prefix = &normalized_prefix[..normalized_prefix.len() - 1];
        }

        if path == normalized_prefix {
            return Some("");
        }

        if let Some(rest) = path.strip_prefix(normalized_prefix) {
            if rest.starts_with('/') {
                return Some(&rest[1..]);
            }
        }

        None
    }

    fn sanitize_and_join(base: &Path, candidate: &str) -> Option<PathBuf> {
        if candidate.is_empty() {
            return None;
        }

        let mut clean = PathBuf::new();
        for component in Path::new(candidate).components() {
            match component {
                Component::Normal(segment) => clean.push(segment),
                Component::CurDir => continue,
                _ => return None, // Reject parent dirs or root prefixes
            }
        }

        Some(base.join(clean))
    }

    async fn try_read_static_file(
        path: &Path,
        canonical_base: &Path,
        cache_enabled: bool,
        cache_max_age: u64,
        if_none_match: Option<&str>,
        if_modified_since: Option<&str>,
    ) -> Result<Option<Response>> {
        use std::time::{SystemTime, UNIX_EPOCH};

        // Prove the path is inside the static root and names a regular file
        // *before* opening anything. Opening first would touch a symlink's
        // escaped target, and opening a FIFO or device blocks the thread it
        // runs on until a writer shows up.
        let canonical_path = match tokio::fs::canonicalize(path).await {
            Ok(path) => path,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(e) => return Err(e.into()),
        };
        if !canonical_path.starts_with(canonical_base) {
            return Ok(None);
        }
        match tokio::fs::metadata(&canonical_path).await {
            Ok(meta) if meta.is_file() => {}
            Ok(_) => return Ok(None),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(e) => return Err(e.into()),
        }

        let file = match tokio::fs::File::open(&canonical_path).await {
            Ok(f) => f,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(e) => return Err(e.into()),
        };

        // fstat() on the open fd: the size and mtime that go into the ETag
        // and Content-Length describe the file actually being served, even if
        // it was replaced between the checks above and the open.
        let metadata = file.metadata().await?;
        if !metadata.is_file() {
            return Ok(None);
        }

        let content_type = Self::infer_content_type(&canonical_path);

        if cache_enabled {
            let mtime = metadata
                .modified()
                .unwrap_or(SystemTime::UNIX_EPOCH)
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs();
            let etag = format!("\"{:x}-{:x}\"", mtime, metadata.len());
            let last_modified = Self::format_http_date(mtime);

            // 304 checks — file is already open but we return before reading content
            if let Some(client_etag) = if_none_match {
                if client_etag == etag {
                    return Ok(Some(
                        Response::not_modified()
                            .with_header("ETag", &etag)
                            .with_header("X-Content-Type-Options", "nosniff")
                            .with_header(
                                "Cache-Control",
                                &format!("public, max-age={}", cache_max_age),
                            ),
                    ));
                }
            }
            if let Some(ims_header) = if_modified_since {
                if let Some(ims_ts) = Self::parse_http_date(ims_header) {
                    if mtime <= ims_ts {
                        return Ok(Some(
                            Response::not_modified()
                                .with_header("ETag", &etag)
                                .with_header("X-Content-Type-Options", "nosniff")
                                .with_header(
                                    "Cache-Control",
                                    &format!("public, max-age={}", cache_max_age),
                                ),
                        ));
                    }
                }
            }

            // Cache miss — body from the already-open fd. `Content-Length`
            // comes from the body in both branches: hyper derives it for a
            // buffered body, `into_hyper` emits the declared size for a stream.
            let body = Self::static_file_body(file, metadata.len()).await?;

            Ok(Some(
                Response::ok()
                    .with_header("Content-Type", content_type)
                    .with_header("X-Content-Type-Options", "nosniff")
                    .with_header(
                        "Cache-Control",
                        &format!("public, max-age={}", cache_max_age),
                    )
                    .with_header("ETag", &etag)
                    .with_header("Last-Modified", &last_modified)
                    .with_body(body),
            ))
        } else {
            // No caching — body from the already-open fd
            let body = Self::static_file_body(file, metadata.len()).await?;

            Ok(Some(
                Response::ok()
                    .with_header("Content-Type", content_type)
                    .with_header("X-Content-Type-Options", "nosniff")
                    .with_header("Cache-Control", "no-store, no-cache")
                    .with_body(body),
            ))
        }
    }

    /// Build the body for a static file that is already open.
    ///
    /// Small files are read fully so outbound middleware can still see the
    /// bytes — gzip in particular, which matters far more for a 40 KiB
    /// stylesheet than for a video. Files above
    /// [`STATIC_STREAM_THRESHOLD`] are streamed in 64 KiB chunks instead:
    /// per-request memory stays flat, and compressing a multi-megabyte asset
    /// on every request would cost more CPU than the bytes it saves.
    async fn static_file_body(mut file: tokio::fs::File, size: u64) -> Result<crate::http::Body> {
        use tokio::io::AsyncReadExt;

        if size > STATIC_STREAM_THRESHOLD {
            return Ok(crate::http::Body::from_file(file, size));
        }

        let mut content = Vec::with_capacity(size as usize);
        file.read_to_end(&mut content).await?;
        Ok(content.into())
    }

    /// Format a Unix timestamp as an RFC 7231 HTTP date string.
    fn format_http_date(timestamp: u64) -> String {
        crate::utils::http_date::format_http_date(timestamp)
    }

    /// Parse an HTTP date header (RFC 7231, RFC 850, or asctime) to a Unix timestamp.
    fn parse_http_date(date_str: &str) -> Option<u64> {
        crate::utils::http_date::parse_http_date(date_str)
    }

    fn infer_content_type(path: &Path) -> &'static str {
        let ext = path
            .extension()
            .and_then(|ext| ext.to_str())
            .map(|ext| ext.to_ascii_lowercase())
            .unwrap_or_default();

        match ext.as_str() {
            "html" => "text/html",
            "css" => "text/css",
            "js" => "application/javascript",
            "png" => "image/png",
            "jpg" | "jpeg" => "image/jpeg",
            "gif" => "image/gif",
            "svg" => "image/svg+xml",
            "webp" => "image/webp",
            "json" => "application/json",
            "txt" => "text/plain",
            "ico" => "image/x-icon",
            _ => "application/octet-stream",
        }
    }
}

fn sqlite_parent_dir(database_url: &str) -> Option<&Path> {
    let raw = database_url.strip_prefix("sqlite://")?;
    if raw.is_empty() || raw == ":memory:" {
        return None;
    }

    let path = Path::new(raw);
    path.parent()
        .filter(|parent| !parent.as_os_str().is_empty())
}

#[cfg(test)]
mod tests {
    use super::RustF;
    use tempfile::TempDir;

    #[tokio::test]
    async fn app_static_serving_sets_nosniff_header() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("app.js");
        tokio::fs::write(&file_path, b"console.log('ok');")
            .await
            .unwrap();

        let canonical_base = temp_dir.path().canonicalize().unwrap();
        let response =
            RustF::try_read_static_file(&file_path, &canonical_base, false, 0, None, None)
                .await
                .unwrap()
                .unwrap();

        assert!(response
            .headers
            .iter()
            .any(|(name, value)| name == "X-Content-Type-Options" && value == "nosniff"));
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn app_static_serving_rejects_symlink_escape() {
        use std::os::unix::fs::symlink;

        let public_dir = TempDir::new().unwrap();
        let outside_dir = TempDir::new().unwrap();
        let outside_file = outside_dir.path().join("secret.txt");
        tokio::fs::write(&outside_file, b"secret").await.unwrap();

        let link_path = public_dir.path().join("outside-link");
        symlink(outside_dir.path(), &link_path).unwrap();

        let canonical_base = public_dir.path().canonicalize().unwrap();
        let escaped_path = link_path.join("secret.txt");
        let response =
            RustF::try_read_static_file(&escaped_path, &canonical_base, false, 0, None, None)
                .await
                .unwrap();

        assert!(response.is_none());
    }
}