product-os-server 0.0.55

Product OS : Server provides a full functioning advanced server capable of acting as a web server, command and control distributed network, authentication server, crawling server and more. Fully featured with high level of flexibility.
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
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
//! Product OS Server
//!
//! A server library supporting HTTP/HTTPS, TLS, WebSockets,
//! Server-Sent Events (SSE), and command-and-control distributed networking.
//!
//! # Features
//!
//! - **HTTP/HTTPS Servers**: Full-featured web servers with TLS support
//! - **Dual Protocol Support**: Serve both HTTP and HTTPS simultaneously
//! - **Security**: Built-in CSP, CSRF protection, security headers
//! - **Compression**: Gzip, Deflate, and Brotli compression support
//! - **WebSockets**: Native WebSocket handler support
//! - **SSE**: Server-Sent Events for real-time updates
//! - **CORS**: Configurable Cross-Origin Resource Sharing
//! - **Command & Control**: Distributed network capabilities with authentication
//! - **Flexible Executors**: Support for Tokio and custom executors
//! - **no_std Support**: Can be used in embedded environments with appropriate features
//!
//! # Example
//!
//! ```no_run
//! use product_os_server::{ProductOSServer, StatusCode, Response, Body};
//! use product_os_server::ServerConfig;
//! use product_os_async_executor::TokioExecutor;
//!
//! # #[cfg(feature = "executor_tokio")]
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! // Create server with default configuration
//! let config = ServerConfig::new();
//! let mut server: ProductOSServer<(), TokioExecutor, _> = 
//!     ProductOSServer::new_with_config(config);
//!
//! // Add a simple GET handler
//! async fn hello_handler() -> Result<Response<Body>, StatusCode> {
//!     Ok(Response::new(Body::empty()))
//! }
//!
//! server.add_get("/hello", hello_handler);
//!
//! // Start the server (non-blocking)
//! // server.start(false).await?;
//! # Ok(())
//! # }
//! ```
//!
//! # Feature Flags
//!
//! - `core`: Core server functionality (hyper, axum, tracing)
//! - `executor_tokio`: Tokio executor support
//! - `tls`: HTTPS/TLS support via rustls
//! - `dual_server`: Dual HTTP/HTTPS protocol support
//! - `cors`: CORS middleware
//! - `ws`: WebSocket support
//! - `sse`: Server-Sent Events support
//! - `compression`: Response compression (gzip, deflate, brotli)
//! - `cspolicy`: Content Security Policy headers
//! - `csrf`: CSRF protection
//! - `controller`: Command and control distributed networking.
//!   Route handlers use Axum extractors, so this feature requires
//!   `framework_axum` or `flow_axum_compat`. Pure `framework_flow` supports
//!   the controller lifecycle but not the HTTP command endpoints.
//! - `middleware`: Extended middleware support
//! - `extract_headers`: Typed header extraction (requires `framework_axum` or `flow_axum_compat`)
//!
//! # Framework Selection
//!
//! Choose exactly one framework (they are mutually exclusive):
//!
//! | Framework | Cargo flags | Notes |
//! |-----------|-------------|-------|
//! | Axum (default) | `--features framework_axum,core,executor_tokio` | Full feature support |
//! | Flow + Axum compat | `--no-default-features --features flow_axum_compat,core,executor_tokio` | Flow router with Axum types |
//! | Pure Flow | `--no-default-features --features framework_flow,core,executor_tokio` | Minimal, no Axum dependency |
//!
//! **Important:** When using `framework_flow` or `flow_axum_compat`, you must pass
//! `--no-default-features` because the default features include `framework_axum`.
//!
//! # Safety and Security
//!
//! This crate provides security features including:
//! - TLS/HTTPS with rustls
//! - Content Security Policy configuration
//! - CSRF token validation
//! - Security headers (HSTS, X-Frame-Options, etc.)
//! - Authentication for command-and-control operations
//!
//! Always review your configuration for your specific security requirements.

#![no_std]
#![warn(missing_docs)]
#![warn(clippy::unwrap_used)]
#![warn(clippy::expect_used)]
#![warn(clippy::panic)]

extern crate no_std_compat as std;
extern crate alloc;

use core::marker::PhantomData;
use core::str::FromStr;
use std::prelude::v1::*;

/// Error types for server operations.
pub mod error;
pub use error::{ProductOSServerError, Result as ServerResult};

/// Server configuration types (Network, Certificate, Compression, ServerConfig)
pub mod config;
pub use config::{ServerConfig, Network, Certificate, CertificateFiles, CertificateFilesKind, Compression};

#[cfg(feature = "tls")]
mod https_server;

#[cfg(feature = "security_certificates")]
mod certificates;

mod logging;
mod http_server;

#[cfg(feature = "serverless-vercel")]
mod serverless;

#[cfg(feature = "serverless-vercel")]
pub use serverless::{rewrite_vercel_api_path, run_vercel};

#[cfg(all(feature = "framework_flow", feature = "executor_tokio"))]
mod flow_http_server;

#[cfg(all(feature = "framework_flow", feature = "tls", feature = "executor_tokio"))]
mod flow_https_server;

#[cfg(feature = "cspolicy")]
mod csp;

#[cfg(all(feature = "controller", any(feature = "framework_axum", feature = "flow_axum_compat")))]
mod command_handler;

#[cfg(all(feature = "controller", any(feature = "framework_axum", feature = "flow_axum_compat")))]
mod feature_handler;
#[cfg(all(feature = "dual_server", feature = "framework_axum"))]
mod dual_server;

mod server_executor;

#[cfg(any(feature = "oidc", feature = "authentication", feature = "content", feature = "service_handler"))]
mod features_services;

use std::collections::BTreeMap;

use std::sync::Arc;

#[cfg(feature = "controller")]
use parking_lot::Mutex;


#[cfg(feature = "framework_axum")]
pub use product_os_router::{
    Layer, Service, ServiceExt, service_fn,
    Method, ProductOSRouter, ServiceBuilder,
    Json, Form, Path, Query, State, ConnectInfo,
    Body, BodyBytes, Bytes, HttpBody,
    Request, StatusCode, Response, IntoResponse,
    Handler, Uri, BoxError, Scheme
};

#[cfg(all(feature = "flow_axum_compat", not(feature = "framework_axum")))]
pub use product_os_router::{
    Layer, Service, ServiceExt, service_fn,
    Method, ProductOSRouter, ServiceBuilder,
    Json, Form, Path, Query, State, ConnectInfo, ClientAddr,
    Body, BodyBytes, Bytes, HttpBody,
    Request, StatusCode, Response, IntoResponse,
    Handler, Uri, BoxError, Scheme
};

#[cfg(all(feature = "framework_flow", not(feature = "framework_axum"), not(feature = "flow_axum_compat")))]
pub use product_os_router::{
    Layer, Service, ServiceExt, service_fn,
    Method, ProductOSRouter, ServiceBuilder,
    Json, Form, Path, Query, State, ConnectInfo, ClientAddr,
    Body, BodyBytes, Bytes, HttpBody,
    Request, StatusCode, Response, IntoResponse,
    Handler, Uri, BoxError, Scheme
};

#[cfg(feature = "sse")]
pub use product_os_router::{Event, Sse};

#[cfg(all(feature = "sse", feature = "framework_flow", not(feature = "framework_axum"), not(feature = "flow_axum_compat")))]
pub use product_os_router::KeepAlive;

#[cfg(feature = "ws")]
pub use product_os_router::{WebSocket, Message};

#[cfg(all(feature = "ws", any(feature = "framework_axum", feature = "flow_axum_compat")))]
pub use product_os_router::WebSocketUpgrade;

#[cfg(feature = "core")]
pub use product_os_router::Extension;

#[cfg(all(feature = "extract_headers", any(feature = "framework_axum", feature = "flow_axum_compat")))]
pub use axum_extra::typed_header::TypedHeader;

/// Unified typed header extractor available across all frameworks.
///
/// For `framework_flow` / `flow_axum_compat`: this is the native `Headers<T>` extractor.
/// For `framework_axum`: this is an alias for `TypedHeader<T>` from `axum-extra`.
#[cfg(feature = "framework_flow")]
pub use product_os_router::Headers;

#[cfg(all(feature = "extract_headers", feature = "framework_axum", not(feature = "framework_flow")))]
pub use axum_extra::typed_header::TypedHeader as Headers;

pub use product_os_router::{TraceContext, RequestId};

#[cfg(feature = "middleware")]
pub use product_os_router::*;

#[cfg(feature = "controller")]
use product_os_command_control::ProductOSController;

#[cfg(feature = "controller")]
use product_os_store::{ ProductOSKeyValueStore, ProductOSRelationalStore };

#[cfg(all(feature = "core", feature = "framework_axum"))]
use axum::routing::Route;

#[cfg(feature = "framework_axum")]
use product_os_router::Router as AxumRouter;

#[cfg(all(feature = "compression", any(feature = "framework_axum", feature = "flow_axum_compat")))]
use tower_http::compression::CompressionLayer;

#[cfg(feature = "csrf")]
use axum_csrf::{CsrfConfig, CsrfLayer};



#[cfg(feature = "executor_tokio")]
use product_os_async_executor::TokioExecutor;

#[allow(unused_imports)]
use product_os_async_executor::Executor;
#[cfg(feature = "security_certificates")]
use crate::certificates::ProductOSServerCertificates;

/// Default HSTS max-age in seconds (24 hours).
const DEFAULT_HSTS_MAX_AGE: u32 = 86400;

/// Default timeout for controller lock acquisition (10 seconds).
#[cfg(feature = "controller")]
pub(crate) const CONTROLLER_LOCK_TIMEOUT: core::time::Duration = core::time::Duration::from_secs(10);

/// Applies security headers and optional CSRF/CSP middleware to a router.
///
/// This helper is used by both the constructor and `set_security` to avoid duplication.
fn apply_security_headers<S: Clone + Send + Sync + 'static>(
    router: &mut ProductOSRouter<S>,
    host: &str,
    security: &product_os_security::Security,
) {
    if !security.enable {
        return;
    }

    #[cfg(feature = "cspolicy")]
    {
        let csp_config = security
            .csp
            .as_ref()
            .map_or_else(product_os_security::CSPConfig::new, Clone::clone);
        let csp_value = csp::ContentSecurityPolicy::from_csp_config(&csp_config).get_csp();
        router.add_default_header("content-security-policy", &csp_value);
    }

    router.add_default_header("cross-origin-embedder-policy", "require-corp");
    router.add_default_header("cross-origin-opener-policy", "same-origin");
    router.add_default_header("referrer-policy", "strict-origin-when-cross-origin");
    let hsts_value = alloc::format!("max-age={}; includeSubDomains; preload", DEFAULT_HSTS_MAX_AGE);
    router.add_default_header("strict-transport-security", &hsts_value);
    router.add_default_header("x-content-type-options", "nosniff");
    router.add_default_header("x-powered-by", host);

    #[cfg(all(feature = "csrf", any(feature = "framework_axum", feature = "flow_axum_compat")))]
    {
        if security.csrf {
            router.add_middleware(CsrfLayer::new(CsrfConfig::default()));
            #[cfg(feature = "core")]
            tracing::info!("CSRF added as extension middleware");
        }
    }
}

/// Applies response compression middleware to a router.
///
/// This helper is used by both the constructor and `set_compression` to avoid duplication.
/// Note: `DecompressionLayer` was intentionally removed -- it decompresses *responses*
/// (client-side concern) and was undoing the server's compression.  If server-side
/// request-body decompression is ever needed, use `RequestDecompressionLayer` instead.
#[cfg(all(feature = "compression", any(feature = "framework_axum", feature = "flow_axum_compat")))]
fn apply_compression<S: Clone + Send + Sync + 'static>(
    router: &mut ProductOSRouter<S>,
    compression_config: &crate::config::Compression,
) {
    if !compression_config.enable {
        return;
    }
    let mut compression = CompressionLayer::new();
    if compression_config.gzip { compression = compression.gzip(true); }
    if compression_config.deflate { compression = compression.deflate(true); }
    if compression_config.brotli { compression = compression.br(true); }
    router.add_middleware(compression);
}

#[cfg(all(feature = "compression", feature = "framework_flow", not(feature = "framework_axum"), not(feature = "flow_axum_compat")))]
fn apply_compression<S: Clone + Send + Sync + 'static>(
    router: &mut ProductOSRouter<S>,
    compression_config: &crate::config::Compression,
) {
    if !compression_config.enable {
        return;
    }
    if compression_config.deflate {
        #[cfg(feature = "core")]
        tracing::warn!("Flow compression does not support deflate encoding; deflate will be ignored");
    }
    use product_os_router::flow_impl::middleware::compression::{CompressionLayer as FlowCompressionLayer, CompressionConfig};
    let config = CompressionConfig {
        min_size: 256,
        gzip: compression_config.gzip,
        brotli: compression_config.brotli,
        zstd: false,
    };
    router.add_middleware(FlowCompressionLayer::new(config));
}

/// Specifies which async executor implementation to use for the server.
///
/// Currently, only Tokio is fully supported. Embassy is reserved for future
/// embedded system support.
pub enum ExecutorType {
    /// Use the Tokio async runtime. This is the recommended and fully-supported executor.
    Tokio,
    /// Use the Embassy async runtime (for embedded / no_std environments).
    /// **Note:** Embassy support is experimental and not yet fully implemented.
    Embassy,
}




/// The main server struct for Product OS Server
///
/// `ProductOSServer` provides a complete web server implementation with support for:
/// - HTTP and HTTPS protocols
/// - Routing and middleware
/// - TLS/SSL via rustls
/// - WebSockets and Server-Sent Events
/// - Command-and-control distributed networking (with `controller` feature)
/// - Compression, CORS, CSRF, and security headers
///
/// # Type Parameters
///
/// - `S`: The shared state type (must be `Clone + Send + Sync + 'static`)
/// - `E`: The executor type implementing `Executor` traits
/// - `X`: The underlying executor context type
///
/// # Examples
///
/// ## Basic HTTP Server
///
/// ```no_run
/// use product_os_server::{ProductOSServer, StatusCode, Response, Body};
/// use product_os_server::ServerConfig;
/// use product_os_async_executor::TokioExecutor;
///
/// # #[cfg(feature = "executor_tokio")]
/// # async fn example() {
/// let config = ServerConfig::new();
/// let mut server: ProductOSServer<(), TokioExecutor, _> = 
///     ProductOSServer::new_with_config(config);
///
/// async fn handler() -> Result<Response<Body>, StatusCode> {
///     Ok(Response::new(Body::empty()))
/// }
///
/// server.add_get("/", handler);
/// # }
/// ```
///
/// ## Server with Shared State
///
/// ```no_run
/// use product_os_server::{ProductOSServer, StatusCode, Response};
/// use product_os_server::ServerConfig;
/// use product_os_async_executor::TokioExecutor;
///
/// # #[cfg(feature = "executor_tokio")]
/// # async fn example() {
/// #[derive(Clone)]
/// struct AppState {
///     counter: std::sync::Arc<parking_lot::Mutex<i32>>,
/// }
///
/// let state = AppState {
///     counter: std::sync::Arc::new(parking_lot::Mutex::new(0)),
/// };
///
/// let config = ServerConfig::new();
/// let mut server: ProductOSServer<AppState, TokioExecutor, _> = 
///     ProductOSServer::new_with_state_with_config(config, state);
/// # }
/// ```
pub struct ProductOSServer<S, E, X>
where
    E: product_os_async_executor::Executor<X> + product_os_async_executor::ExecutorPerform<X> + product_os_async_executor::Timer
{
    router: ProductOSRouter<S>,

    config: crate::config::ServerConfig,
    #[cfg(feature = "security_certificates")]
    certificates:  product_os_security::certificates::Certificates,

    #[cfg(feature = "controller")]
    controller: Option<Arc<Mutex<ProductOSController>>>,

    #[allow(dead_code)]
    executor: Arc<E>,
    executor_underlying: PhantomData<X>,

    #[cfg(feature = "compression")]
    compression_applied: bool,
}

#[cfg(feature = "executor_tokio")]
impl<X> ProductOSServer<(), TokioExecutor, X>
where
    TokioExecutor: product_os_async_executor::Executor<X>, TokioExecutor: product_os_async_executor::ExecutorPerform<X>
{
    /// Creates a new server with the given configuration and no shared state.
    ///
    /// This is a convenience constructor for Tokio-based servers that automatically
    /// creates and initializes the Tokio executor.
    ///
    /// # Arguments
    ///
    /// * `config` - Server configuration including network settings, security options, etc.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use product_os_server::ProductOSServer;
    /// use product_os_server::ServerConfig;
    /// use product_os_async_executor::TokioExecutor;
    ///
    /// # #[cfg(feature = "executor_tokio")]
    /// # fn example() {
    /// let config = ServerConfig::new();
    /// let server: ProductOSServer<(), TokioExecutor, _> = 
    ///     ProductOSServer::new_with_config(config);
    /// # }
    /// ```
    #[allow(clippy::panic)]
    pub fn new_with_config(config: crate::config::ServerConfig) -> Self {
        let executor = match TokioExecutor::context_sync() {
            Ok(exec) => Arc::new(exec),
            Err(e) => ::std::panic!("Failed to create Tokio executor context: {:?}. Ensure a Tokio runtime is active.", e),
        };
        ProductOSServer::new_with_executor_with_state_with_config(Some(executor), config, ())
    }

    /// Creates a new server with default configuration and no shared state.
    ///
    /// This constructor uses default configuration settings and creates a Tokio executor.
    ///
    /// # Arguments
    ///
    /// * `executor` - Optional executor Arc. If None, a new executor will be created.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use product_os_server::ProductOSServer;
    /// use product_os_async_executor::TokioExecutor;
    ///
    /// # #[cfg(feature = "executor_tokio")]
    /// # fn example() {
    /// let server: ProductOSServer<(), TokioExecutor, _> = 
    ///     ProductOSServer::new(None);
    /// # }
    /// ```
    #[allow(clippy::panic)]
    pub fn new(_executor: Option<Arc<TokioExecutor>>) -> Self {
        let executor = match TokioExecutor::context_sync() {
            Ok(exec) => Arc::new(exec),
            Err(e) => ::std::panic!("Failed to create Tokio executor context: {:?}. Ensure a Tokio runtime is active.", e),
        };
        ProductOSServer::new_with_executor_with_state(Some(executor), ())
    }
}



impl<E, X> ProductOSServer<(), E, X>
where
    E: product_os_async_executor::Executor<X> + product_os_async_executor::ExecutorPerform<X> + product_os_async_executor::Timer + 'static
{
    /// Creates a new server with a custom executor and configuration.
    ///
    /// This constructor allows specifying a custom executor for handling async operations.
    ///
    /// # Arguments
    ///
    /// * `executor` - Optional executor Arc. If None, will panic.
    /// * `config` - Server configuration
    pub fn new_with_executor_with_config(executor: Option<Arc<E>>, config: crate::config::ServerConfig) -> Self {
        ProductOSServer::new_with_executor_with_state_with_config(executor, config, ())
    }

    /// Creates a new server with a custom executor and default configuration.
    ///
    /// # Arguments
    ///
    /// * `executor` - Optional executor Arc. If None, will panic.
    pub fn new_with_executor(executor: Option<Arc<E>>) -> Self {
        ProductOSServer::new_with_executor_with_state(executor, ())
    }

    #[cfg(feature = "controller")]
    /// Adds a feature to the server.
    ///
    /// # Panics
    ///
    /// Panics if no controller is configured. Use `try_add_feature` for a non-panicking alternative.
    #[deprecated(since = "0.0.53", note = "Use try_add_feature which returns Result instead of panicking")]
    pub async fn add_feature(&mut self, feature_arc: Arc<dyn product_os_capabilities::Feature>, base_path: Option<String>) {
        self.try_add_feature(feature_arc, base_path).await
            .unwrap_or_else(|e| ::std::panic!("{}", e));
    }

    #[cfg(feature = "controller")]
    /// Adds a feature to the server, returning an error if no controller is configured.
    ///
    /// Features provide modular functionality that can be dynamically added to the server.
    /// Requires the `controller` feature and `framework_axum` or `flow_axum_compat`
    /// for the HTTP command endpoints to be registered.
    ///
    /// # Arguments
    ///
    /// * `feature_arc` - Arc-wrapped feature implementation
    /// * `base_path` - Optional base path for mounting the feature's routes
    ///
    /// # Errors
    ///
    /// Returns `ControllerError` if no controller is configured on the server.
    pub async fn try_add_feature(&mut self, feature_arc: Arc<dyn product_os_capabilities::Feature>, base_path: Option<String>) -> crate::error::Result<()> {
        match &self.controller {
            None => {
                Err(ProductOSServerError::ControllerError {
                    operation: "add_feature".to_string(),
                    message: alloc::format!("Feature {} failed to add to server: no controller", feature_arc.identifier()),
                })
            }
            Some(c) => {
                let controller_unlocked = c.clone();
                let mut controller = controller_unlocked.lock();

                let feature_base_path = base_path.unwrap_or_default();

                controller.add_feature(feature_arc.clone(), feature_base_path, &mut self.router).await;
                #[cfg(feature = "core")]
                tracing::info!("Feature {} successfully added to server", feature_arc.identifier());
                Ok(())
            }
        }
    }

    #[cfg(feature = "controller")]
    /// Adds a mutable feature to the server.
    ///
    /// # Panics
    ///
    /// Panics if no controller is configured. Use `try_add_feature_mut` for a non-panicking alternative.
    #[deprecated(since = "0.0.53", note = "Use try_add_feature_mut which returns Result instead of panicking")]
    pub async fn add_feature_mut(&mut self, feature_arc_mut: Arc<Mutex<dyn product_os_capabilities::Feature>>, base_path: Option<String>) {
        self.try_add_feature_mut(feature_arc_mut, base_path).await
            .unwrap_or_else(|e| ::std::panic!("{}", e));
    }

    #[cfg(feature = "controller")]
    /// Adds a mutable feature to the server, returning an error if no controller is configured.
    ///
    /// Similar to `try_add_feature`, but accepts a mutable feature wrapped in an `Arc<Mutex>`.
    ///
    /// # Arguments
    ///
    /// * `feature_arc_mut` - Arc-wrapped mutex containing the feature implementation
    /// * `base_path` - Optional base path for mounting the feature's routes
    ///
    /// # Errors
    ///
    /// Returns `ControllerError` if no controller is configured on the server.
    pub async fn try_add_feature_mut(&mut self, feature_arc_mut: Arc<Mutex<dyn product_os_capabilities::Feature>>, base_path: Option<String>) -> crate::error::Result<()> {
        match &self.controller {
            None => {
                let feature_locked = feature_arc_mut.lock();
                Err(ProductOSServerError::ControllerError {
                    operation: "add_feature_mut".to_string(),
                    message: alloc::format!("Feature {} failed to add to server: no controller", feature_locked.identifier()),
                })
            }
            Some(c) => {
                let controller_unlocked = c.clone();
                let mut controller = controller_unlocked.lock();

                let feature_base_path = base_path.unwrap_or_default();

                controller.add_feature_mut(feature_arc_mut.clone(), feature_base_path, &mut self.router).await;
                let feature_locked = feature_arc_mut.lock();
                #[cfg(feature = "core")]
                tracing::info!("Feature {} successfully added to server", feature_locked.identifier());
                Ok(())
            }
        }
    }
}


#[cfg(feature = "executor_tokio")]
impl<S, X> ProductOSServer<S, TokioExecutor, X>
where
    S: Clone + Send + Sync + 'static,
    TokioExecutor: product_os_async_executor::Executor<X>, TokioExecutor: product_os_async_executor::ExecutorPerform<X>
{
    /// Creates a new server with state and configuration (Tokio executor).
    ///
    /// # Arguments
    ///
    /// * `config` - Server configuration
    /// * `state` - Shared state available to all handlers
    #[allow(clippy::panic)]
    pub fn new_with_state_with_config(config: crate::config::ServerConfig, state: S) -> Self {
        let executor = match TokioExecutor::context_sync() {
            Ok(exec) => Arc::new(exec),
            Err(e) => ::std::panic!("Failed to create Tokio executor context: {:?}. Ensure a Tokio runtime is active.", e),
        };
        ProductOSServer::new_with_executor_with_state_with_config(Some(executor), config, state)
    }

    /// Creates a new server with state and default configuration (Tokio executor).
    ///
    /// # Arguments
    ///
    /// * `state` - Shared state available to all handlers
    #[allow(clippy::panic)]
    pub fn new_with_state(state: S) -> Self {
        let executor = match TokioExecutor::context_sync() {
            Ok(exec) => Arc::new(exec),
            Err(e) => ::std::panic!("Failed to create Tokio executor context: {:?}. Ensure a Tokio runtime is active.", e),
        };
        ProductOSServer::new_with_executor_with_state(Some(executor), state)
    }
}


impl<S, E, X> ProductOSServer<S, E, X>
where
    S: Clone + Send + Sync + 'static,
    E: product_os_async_executor::Executor<X> + product_os_async_executor::ExecutorPerform<X> + product_os_async_executor::Timer + 'static
{
    /// Creates a new server with custom executor, state, and configuration.
    ///
    /// This is the most flexible constructor, allowing full customization of executor,
    /// state, and configuration.
    ///
    /// # Arguments
    ///
    /// * `executor` - Optional executor Arc. If None, will panic.
    /// * `config` - Server configuration including network, security, compression settings
    /// * `state` - Shared state that will be available to all handlers
    #[allow(clippy::panic)]
    pub fn new_with_executor_with_state_with_config(executor: Option<Arc<E>>, config: crate::config::ServerConfig, state: S) -> Self {
        #[cfg(feature = "core")]
        let _ = logging::set_global_logger(logging::define_logging(config.log_level()));
        #[cfg(feature = "core")]
        tracing::info!("Log Level: {}", config.log_level());

        let mut router = ProductOSRouter::new_with_state(state);

        // Setup certificates
        #[cfg(feature = "security_certificates")]
        let certificates = ProductOSServerCertificates::setup_certificates(&config.certificate);

        // Parse security config from raw JSON
        let security_config: Option<product_os_security::Security> = config.security.as_ref()
            .and_then(|v| {
                serde_json::from_value(v.clone()).map_err(|e| {
                    #[cfg(feature = "core")]
                    tracing::warn!("Failed to parse security config: {}", e);
                    e
                }).ok()
            });
        if let Some(ref security) = security_config {
            apply_security_headers(&mut router, &config.network.host, security);
        }

        #[cfg(feature = "controller")]
            let mut option_controller_mutex = None;

        #[cfg(feature = "controller")]
        {
            // Parse command_control and store configs from raw JSON
            let cc_config: Option<product_os_command_control::CommandControl> = config.command_control.as_ref()
                .and_then(|v| serde_json::from_value(v.clone()).map_err(|e| {
                    #[cfg(feature = "core")]
                    tracing::warn!("Failed to parse command_control config: {}", e);
                    e
                }).ok());
            let store_config: Option<product_os_store::Stores> = config.store.as_ref()
                .and_then(|v| serde_json::from_value(v.clone()).map_err(|e| {
                    #[cfg(feature = "core")]
                    tracing::warn!("Failed to parse store config: {}", e);
                    e
                }).ok());

            match &cc_config {
                None => {}
                Some(command_control) => {
                    if command_control.enable {
                        // Setup stores
                        match &store_config {
                            None => {}
                            Some(store) => {
                                match &store.key_value {
                                    None => {}
                                    Some(key_value_config) => {
                                        if let Ok(mut key_value) = ProductOSKeyValueStore::try_new(key_value_config).map_err(|e| {
                                            #[cfg(feature = "core")]
                                            tracing::error!("Failed to create key value store: {:?}", e);
                                        }) {
                                            match key_value.connect() {
                                                Ok(_) => {
                                                    #[cfg(feature = "core")]
                                                    tracing::info!("Successfully connected to key value database: {:?}", key_value_config.kind);
                                                }
                                                Err(e) => {
                                                    #[cfg(feature = "core")]
                                                    tracing::error!("Connect to key value database error: {:?}", e);
                                                }
                                            }
                                            key_value.set_group("product-os-node");

                                            let key_value_store = Arc::new(key_value);

                                            if let Some(relational_config) = &store.relational {
                                                if let Ok(mut relational) = ProductOSRelationalStore::try_new(relational_config).map_err(|e| {
                                                    #[cfg(feature = "core")]
                                                    tracing::error!("Failed to create relational store: {:?}", e);
                                                }) {
                                                    match relational.connect_sync() {
                                                        Ok(_) => {
                                                            #[cfg(feature = "core")]
                                                            tracing::info!("Successfully connected to relational database: {:?}", relational_config.kind);
                                                        }
                                                        Err(e) => {
                                                            #[cfg(feature = "core")]
                                                            tracing::error!("Connect to relational database error: {:?}", e);
                                                        }
                                                    };

                                                    // ----- Add Route Handlers

                                                    #[cfg(any(feature = "framework_axum", feature = "flow_axum_compat"))]
                                                    {
                                                        command_handler::command_responder(&mut router);
                                                        feature_handler::feature_responder(&mut router, None);
                                                    }


                                                    // ----- Add Middleware

                                                    #[cfg(any(feature = "postgres_store", feature = "sqlite_store"))]
                                                    let controller = ProductOSController::new(command_control.clone(), certificates.clone(), Some(key_value_store.clone()), Some(Arc::new(relational)));
                                                    #[cfg(not(any(feature = "postgres_store", feature = "sqlite_store")))]
                                                    let controller = {
                                                        let _ = relational;
                                                        ProductOSController::new(command_control.clone(), certificates.clone(), Some(key_value_store.clone()), None)
                                                    };
                                                    let controller_mutex = Arc::new(Mutex::new(controller));

                                                    #[cfg(any(feature = "framework_axum", feature = "flow_axum_compat"))]
                                                    router.add_extension(controller_mutex.clone());
                                                    #[cfg(feature = "core")]
                                                    tracing::info!("Controller added as extension middleware");
                                                    option_controller_mutex = Some(controller_mutex);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        let executor = match executor {
            Some(exec) => exec,
            None => {
                #[cfg(feature = "core")]
                tracing::error!("Unable to create executor context - no executor available");
                match E::context_sync() {
                    Ok(exec) => Arc::new(exec),
                    Err(e) => ::std::panic!("Failed to create default executor context: {:?}. An executor must be available.", e),
                }
            }
        };

        // Return Server
        Self {
            router,

            config,
            #[cfg(feature = "security_certificates")]
            certificates,

            #[cfg(feature = "controller")]
            controller: option_controller_mutex,

            executor,
            executor_underlying: PhantomData,

            #[cfg(feature = "compression")]
            compression_applied: false,
        }
    }

    /// Creates a new server with custom executor and state.
    ///
    /// Uses default configuration.
    ///
    /// # Arguments
    ///
    /// * `executor` - Optional executor Arc. If None, will panic.
    /// * `state` - Shared state available to all handlers
    #[allow(clippy::panic)]
    pub fn new_with_executor_with_state(executor: Option<Arc<E>>, state: S) -> Self {
        let config = crate::config::ServerConfig::new();

        let router = ProductOSRouter::new_with_state(state);

        #[cfg(feature = "core")]
        {
            let log_level = config.log_level();
            let _ = logging::set_global_logger(logging::define_logging(log_level));
            tracing::info!("Log Level: {}", config.log_level());
        }

        // Setup certificates
        #[cfg(feature = "security_certificates")]
        let certificates = ProductOSServerCertificates::setup_certificates(&config.certificate);

        let executor = match executor {
            Some(exec) => exec,
            None => {
                #[cfg(feature = "core")]
                tracing::error!("Unable to create executor context - no executor available");
                match E::context_sync() {
                    Ok(exec) => Arc::new(exec),
                    Err(e) => ::std::panic!("Failed to create default executor context: {:?}. An executor must be available.", e),
                }
            }
        };

        // Return Server
        Self {
            router,

            config,
            #[cfg(feature = "security_certificates")]
            certificates,

            #[cfg(feature = "controller")]
            controller: None,

            executor,
            executor_underlying: PhantomData,

            #[cfg(feature = "compression")]
            compression_applied: false,
        }
    }

    /// Sets the logging level.
    ///
    /// # Arguments
    ///
    /// * `log_level` - The tracing level (TRACE, DEBUG, INFO, WARN, ERROR)
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use product_os_server::ProductOSServer;
    /// # use product_os_server::ServerConfig;
    /// # use product_os_async_executor::TokioExecutor;
    /// # #[cfg(feature = "executor_tokio")]
    /// # fn example() {
    /// # let config = ServerConfig::new();
    /// # let mut server: ProductOSServer<(), TokioExecutor, _> = 
    /// #     ProductOSServer::new_with_config(config);
    /// server.set_logging(tracing::Level::DEBUG);
    /// # }
    /// ```
    #[cfg(feature = "core")]
    pub fn set_logging(&mut self, log_level: tracing::Level) {
        let _ = logging::set_global_logger(logging::define_logging(log_level));
        tracing::info!("Log Level: {}", self.config.log_level());
    }

    /// Sets or updates the TLS certificate configuration.
    ///
    /// # Arguments
    ///
    /// * `certificate_config` - Optional certificate configuration. If None, will generate self-signed.
    #[cfg(feature = "security_certificates")]
    pub fn set_certificate(&mut self, certificate_config: &Option<crate::config::Certificate>) {
        self.certificates = ProductOSServerCertificates::setup_certificates(certificate_config);
    }

    /// Sets or updates the security configuration.
    ///
    /// This includes settings for security headers, CSRF protection, etc.
    ///
    /// # Arguments
    ///
    /// * `security` - Optional security configuration. If None, security features are disabled.
    pub fn set_security(&mut self, security: Option<product_os_security::Security>) {
        if let Some(security) = security {
            apply_security_headers(&mut self.router, &self.config.network.host, &security);
        }
    }

    /// Sets or updates the compression configuration.
    ///
    /// This configures the compression middleware for HTTP responses.
    /// Supports gzip, deflate, and brotli compression.
    ///
    /// # Arguments
    ///
    /// * `compression_config` - Optional compression configuration. If None, compression is disabled.
    #[cfg(feature = "compression")]
    pub fn set_compression(&mut self, compression_config: Option<crate::config::Compression>) {
        if let Some(ref compress) = compression_config {
            apply_compression(&mut self.router, compress);
            self.compression_applied = true;
        }
    }

    /// Applies deferred compression middleware if configured but not yet applied.
    ///
    /// This must be called after all routes are registered (but before serving)
    /// because Axum's `Router::layer()` only wraps routes that already exist.
    #[cfg(feature = "compression")]
    fn ensure_compression(&mut self) {
        if self.compression_applied {
            return;
        }
        if let Some(ref compress) = self.config.compression.clone() {
            apply_compression(&mut self.router, &compress);
            self.compression_applied = true;
        }
    }

    /// Sets or replaces the controller.
    ///
    /// # Arguments
    ///
    /// * `controller` - Optional controller mutex. If None, removes the controller.
    #[cfg(feature = "controller")]
    pub fn set_controller(&mut self, controller: Option<Arc<Mutex<ProductOSController>>>) {
        self.controller = controller;
    }

    /// Adds a service to the server.
    ///
    /// # Panics
    ///
    /// Panics if no controller is configured. Use `try_add_service` for a non-panicking alternative.
    #[cfg(feature = "controller")]
    #[deprecated(since = "0.0.54", note = "Use try_add_service which returns Result instead of panicking")]
    pub async fn add_service(&mut self, service_arc: Arc<dyn product_os_capabilities::Service>) {
        self.try_add_service(service_arc).await
            .unwrap_or_else(|e| ::std::panic!("{}", e));
    }

    /// Adds a service to the server, returning an error if no controller is configured.
    ///
    /// Services are background tasks that run alongside the server.
    ///
    /// # Arguments
    ///
    /// * `service_arc` - Arc-wrapped service implementation
    ///
    /// # Errors
    ///
    /// Returns `ControllerError` if no controller is configured on the server.
    #[cfg(feature = "controller")]
    pub async fn try_add_service(&mut self, service_arc: Arc<dyn product_os_capabilities::Service>) -> crate::error::Result<()> {
        match &self.controller {
            None => {
                Err(ProductOSServerError::ControllerError {
                    operation: "add_service".to_string(),
                    message: alloc::format!("Service {} failed to add to server: no controller", service_arc.identifier()),
                })
            }
            Some(c) => {
                let controller_unlocked = c.clone();
                let mut controller = controller_unlocked.lock();

                controller.add_service(service_arc.clone()).await;
                #[cfg(feature = "core")]
                tracing::info!("Service {} successfully added to server", service_arc.identifier());
                Ok(())
            }
        }
    }

    /// Adds a mutable service to the server.
    ///
    /// # Panics
    ///
    /// Panics if no controller is configured. Use `try_add_service_mut` for a non-panicking alternative.
    #[cfg(feature = "controller")]
    #[deprecated(since = "0.0.54", note = "Use try_add_service_mut which returns Result instead of panicking")]
    pub async fn add_service_mut(&mut self, service_arc_mut: Arc<Mutex<dyn product_os_capabilities::Service>>) {
        self.try_add_service_mut(service_arc_mut).await
            .unwrap_or_else(|e| ::std::panic!("{}", e));
    }

    /// Adds a mutable service to the server, returning an error if no controller is configured.
    ///
    /// Similar to `try_add_service`, but accepts a mutable service wrapped in an `Arc<Mutex>`.
    ///
    /// # Arguments
    ///
    /// * `service_arc_mut` - Arc-wrapped mutex containing the service implementation
    ///
    /// # Errors
    ///
    /// Returns `ControllerError` if no controller is configured on the server.
    #[cfg(feature = "controller")]
    pub async fn try_add_service_mut(&mut self, service_arc_mut: Arc<Mutex<dyn product_os_capabilities::Service>>) -> crate::error::Result<()> {
        match &self.controller {
            None => {
                let service_locked = service_arc_mut.lock();
                Err(ProductOSServerError::ControllerError {
                    operation: "add_service_mut".to_string(),
                    message: alloc::format!("Service {} failed to add to server: no controller", service_locked.identifier()),
                })
            }
            Some(c) => {
                let controller_unlocked = c.clone();
                let mut controller = controller_unlocked.lock();

                controller.add_service_mut(service_arc_mut.clone()).await;
                let service_locked = service_arc_mut.lock();
                #[cfg(feature = "core")]
                tracing::info!("Service {} successfully added to server", service_locked.identifier());
                Ok(())
            }
        }
    }

    /*
    #[cfg(all(feature = "controller", feature = "support_feature_service"))]
    pub async fn add_feature_service(&mut self, feature_service_arc: Arc<dyn product_os_capabilities::FeatureService>, base_path: Option<String>) {
        self.add_feature(feature_service_arc.clone(), base_path);
        self.add_service(feature_service_arc);
    }

    #[cfg(all(feature = "controller", feature = "support_feature_service"))]
    pub async fn add_feature_service_mut(&mut self, feature_service_arc_mut: Arc<Mutex<dyn product_os_capabilities::FeatureService>>, base_path: Option<String>) {
        self.add_feature_mut(feature_service_arc_mut.clone(), base_path);
        self.add_service_mut(feature_service_arc_mut);
    }
    */

    /// Gets the controller.
    ///
    /// # Panics
    ///
    /// Panics if no controller is configured. Use `try_get_controller` for a non-panicking alternative.
    #[cfg(feature = "controller")]
    #[deprecated(since = "0.0.53", note = "Use try_get_controller which returns Result instead of panicking")]
    pub fn get_controller(&self) -> Arc<Mutex<ProductOSController>> {
        self.try_get_controller()
            .unwrap_or_else(|e| ::std::panic!("{}", e))
    }

    /// Gets the controller, returning an error if none is configured.
    ///
    /// # Returns
    ///
    /// An `Arc<Mutex<ProductOSController>>` if a controller is configured.
    ///
    /// # Errors
    ///
    /// Returns `ControllerError` if no controller is configured.
    #[cfg(feature = "controller")]
    pub fn try_get_controller(&self) -> crate::error::Result<Arc<Mutex<ProductOSController>>> {
        match &self.controller {
            None => Err(ProductOSServerError::ControllerError {
                operation: "get_controller".to_string(),
                message: "No controller configured on this server".to_string(),
            }),
            Some(c) => Ok(c.clone()),
        }
    }

    /// Retrieves a mutable reference to the router.
    ///
    /// This allows direct manipulation of the underlying router for advanced use cases.
    ///
    /// # Returns
    ///
    /// A mutable reference to the `ProductOSRouter`.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use product_os_server::ProductOSServer;
    /// # use product_os_server::ServerConfig;
    /// # use product_os_async_executor::TokioExecutor;
    /// # #[cfg(feature = "executor_tokio")]
    /// # fn example() {
    /// # let config = ServerConfig::new();
    /// # let mut server: ProductOSServer<(), TokioExecutor, _> = 
    /// #     ProductOSServer::new_with_config(config);
    /// let router = server.get_router();
    /// // Perform advanced router operations
    /// # }
    /// ```
    pub fn get_router(&mut self) -> &mut ProductOSRouter<S> {
        &mut self.router
    }

    /// Adds a route with an Axum `MethodRouter`. Requires `framework_axum`.
    #[cfg(feature = "framework_axum")]
    #[deprecated(since = "0.0.55", note = "Use add_get/add_post/add_handler instead for framework-agnostic routing")]
    pub fn add_route(&mut self, path: &str, service_handler: product_os_router::MethodRouter<S>) {
        self.router.add_route(path, service_handler);
    }

    /// Sets a fallback handler using an Axum `MethodRouter`. Requires `framework_axum`.
    #[cfg(feature = "framework_axum")]
    #[deprecated(since = "0.0.55", note = "Use set_fallback_handler instead for framework-agnostic routing")]
    pub fn set_fallback(&mut self, service_handler: product_os_router::MethodRouter<S>) {
        self.router.set_fallback(service_handler);
    }

    /// Adds a GET request handler.
    ///
    /// Convenience method for adding a handler that responds to GET requests.
    ///
    /// # Arguments
    ///
    /// * `path` - The URL path (e.g., "/api/users")
    /// * `handler` - The async function handling the request
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use product_os_server::{ProductOSServer, Response, StatusCode, Body};
    /// # use product_os_server::ServerConfig;
    /// # use product_os_async_executor::TokioExecutor;
    /// # #[cfg(feature = "executor_tokio")]
    /// # fn example() {
    /// # let config = ServerConfig::new();
    /// # let mut server: ProductOSServer<(), TokioExecutor, _> = 
    /// #     ProductOSServer::new_with_config(config);
    /// async fn get_users() -> Result<Response<Body>, StatusCode> {
    ///     Ok(Response::new(Body::empty()))
    /// }
    ///
    /// server.add_get("/api/users", get_users);
    /// # }
    /// ```
    pub fn add_get<H, T>(&mut self, path: &str, handler: H)
        where
            H: Handler<T, S>,
            T: 'static
    {
        self.router.add_get(path, handler);
    }

    /// Adds a POST request handler.
    ///
    /// Convenience method for adding a handler that responds to POST requests.
    ///
    /// # Arguments
    ///
    /// * `path` - The URL path (e.g., "/api/users")
    /// * `handler` - The async function handling the request
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use product_os_server::{ProductOSServer, Response, StatusCode, Json, Body};
    /// # use product_os_server::ServerConfig;
    /// # use product_os_async_executor::TokioExecutor;
    /// # use serde::{Deserialize, Serialize};
    /// # #[cfg(feature = "executor_tokio")]
    /// # fn example() {
    /// # let config = ServerConfig::new();
    /// # let mut server: ProductOSServer<(), TokioExecutor, _> = 
    /// #     ProductOSServer::new_with_config(config);
    /// # #[derive(Deserialize, Serialize)]
    /// # struct User { name: String }
    /// async fn create_user(Json(user): Json<User>) -> Result<Response<Body>, StatusCode> {
    ///     Ok(Response::new(Body::empty()))
    /// }
    ///
    /// server.add_post("/api/users", create_user);
    /// # }
    /// ```
    pub fn add_post<H, T>(&mut self, path: &str, handler: H)
        where
            H: Handler<T, S>,
            T: 'static
    {
        self.router.add_post(path, handler);
    }

    /// Adds a handler for a specific HTTP method and path.
    ///
    /// # Arguments
    ///
    /// * `path` - The URL path
    /// * `method` - The HTTP method (GET, POST, PUT, DELETE, etc.)
    /// * `handler` - The async function to handle the request
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use product_os_server::{ProductOSServer, Response, StatusCode, Method};
    /// # use product_os_server::ServerConfig;
    /// # use product_os_async_executor::TokioExecutor;
    /// # #[cfg(feature = "executor_tokio")]
    /// # fn example() {
    /// # let config = ServerConfig::new();
    /// # let mut server: ProductOSServer<(), TokioExecutor, _> = 
    /// #     ProductOSServer::new_with_config(config);
    /// async fn patch_handler() -> Result<Response<product_os_server::Body>, StatusCode> {
    ///     Ok(Response::new(product_os_server::Body::empty()))
    /// }
    /// server.add_handler("/resource", Method::PATCH, patch_handler);
    /// # }
    /// ```
    pub fn add_handler<H, T>(&mut self, path: &str, method: Method, handler: H)
        where
            H: Handler<T, S>,
            T: 'static
    {
        self.router.add_handler(path, method, handler);
    }

    /// Sets a fallback handler that will be called for unmatched routes.
    ///
    /// # Arguments
    ///
    /// * `handler` - The async function to handle unmatched requests
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use product_os_server::{ProductOSServer, Response, StatusCode};
    /// # use product_os_server::ServerConfig;
    /// # use product_os_async_executor::TokioExecutor;
    /// # #[cfg(feature = "executor_tokio")]
    /// # fn example() {
    /// # let config = ServerConfig::new();
    /// # let mut server: ProductOSServer<(), TokioExecutor, _> = 
    /// #     ProductOSServer::new_with_config(config);
    /// async fn not_found() -> Result<Response<product_os_server::Body>, StatusCode> {
    ///     Err(StatusCode::NOT_FOUND)
    /// }
    /// server.set_fallback_handler(not_found);
    /// # }
    /// ```
    pub fn set_fallback_handler<H, T>(&mut self, handler: H)
        where
            H: Handler<T, S>,
            T: 'static
    {
        self.router.set_fallback_handler(handler);
    }

    /// Adds a CORS-enabled handler for a specific HTTP method and path.
    ///
    /// Wraps the handler with CORS middleware.
    ///
    /// # Arguments
    ///
    /// * `path` - The URL path
    /// * `method` - The HTTP method
    /// * `handler` - The async function handling the request
    #[cfg(feature = "cors")]
    pub fn add_cors_handler<H, T>(&mut self, path: &str, method: Method, handler: H)
        where
            H: Handler<T, S>,
            T: 'static
    {
        self.router.add_cors_handler(path, method, handler);
    }

    /// Adds a WebSocket handler for the specified path (Axum / flow_axum_compat).
    #[cfg(all(feature = "ws", any(feature = "framework_axum", feature = "flow_axum_compat")))]
    pub fn add_ws_handler<H, T>(&mut self, path: &str, ws_handler: H)
        where
            H: Handler<T, S>,
            T: 'static
    {
        self.router.add_ws_handler(path, ws_handler);
    }

    /// Adds a native Flow WebSocket handler for the specified path.
    ///
    /// The handler receives a `WebSocket` after the HTTP upgrade has been
    /// performed at the server level.
    #[cfg(all(feature = "ws", feature = "framework_flow", not(feature = "framework_axum"), not(feature = "flow_axum_compat")))]
    pub fn add_ws_handler<F, Fut>(&mut self, path: &str, handler: F)
    where
        F: Fn(product_os_router::flow_impl::ws::WebSocket) -> Fut + Send + Sync + Clone + 'static,
        Fut: std::future::Future<Output = ()> + Send + 'static,
    {
        self.router.add_ws_handler(path, handler);
    }

    /// Adds a Server-Sent Events (SSE) handler for the specified path.
    ///
    /// SSE handlers are added as GET routes since SSE uses HTTP GET requests.
    ///
    /// # Arguments
    ///
    /// * `path` - The URL path for SSE connections
    /// * `sse_handler` - The handler producing SSE events
    #[cfg(feature = "sse")]
    pub fn add_sse_handler<H, T>(&mut self, path: &str, sse_handler: H)
        where
            H: Handler<T, S>,
            T: 'static
    {
        self.router.add_sse_handler(path, sse_handler);
    }

    /// Adds multiple handlers for different HTTP methods on the same path.
    ///
    /// # Arguments
    ///
    /// * `path` - The URL path
    /// * `handlers` - A map of HTTP methods to their handlers
    ///
    /// # Examples
    ///
    /// ```ignore
    /// // Note: This API requires handlers of the same type. In practice,
    /// // use add_get, add_post, etc. for different handler implementations.
    /// # use product_os_server::{ProductOSServer, Response, StatusCode, Method, Body};
    /// # use product_os_server::ServerConfig;
    /// # use product_os_async_executor::TokioExecutor;
    /// # use std::collections::BTreeMap;
    /// # #[cfg(feature = "executor_tokio")]
    /// # fn example() {
    /// # let config = ServerConfig::new();
    /// # let mut server: ProductOSServer<(), TokioExecutor, _> = 
    /// #     ProductOSServer::new_with_config(config);
    /// async fn handler() -> Result<Response<Body>, StatusCode> {
    ///     Ok(Response::new(Body::empty()))
    /// }
    /// 
    /// // Use add_handler for each method instead:
    /// server.add_handler("/resource", Method::GET, handler);
    /// server.add_handler("/resource", Method::POST, handler);
    /// # }
    /// ```
    pub fn add_handlers<H, T>(&mut self, path: &str, handlers: BTreeMap<Method, H>)
        where
            H: Handler<T, S>,
            T: 'static
    {
        self.router.add_handlers(path, handlers);
    }

    /// Adds multiple CORS-enabled handlers for different HTTP methods on the same path.
    ///
    /// # Arguments
    ///
    /// * `path` - The URL path
    /// * `handlers` - A map of HTTP methods to their handlers
    #[cfg(feature = "cors")]
    pub fn add_cors_handlers<H, T>(&mut self, path: &str, handlers: BTreeMap<Method, H>)
        where
            H: Handler<T, S>,
            T: 'static
    {
        self.router.add_cors_handlers(path, handlers);
    }

    /// Adds a global CORS middleware layer that applies to all routes.
    ///
    /// This permits any origin, any HTTP method, and any request header,
    /// making it suitable for development servers and APIs consumed by
    /// third-party front-ends.  For production you may want to use
    /// [`add_middleware`] with a more restrictive `CorsLayer` instead.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// # use product_os_server::ProductOSServer;
    /// # use product_os_async_executor::TokioExecutor;
    /// // Enable permissive CORS on all routes
    /// server.add_cors_middleware();
    /// ```
    #[cfg(feature = "cors")]
    pub fn add_cors_middleware(&mut self) {
        self.router.add_cors_middleware();
    }

    /// Adds middleware to the server (`framework_axum` variant).
    ///
    /// The `Layer` must wrap `axum::routing::Route`, which is an Axum-specific type.
    /// For framework-agnostic middleware, prefer Tower layers via the router directly.
    #[cfg(all(feature = "core", feature = "framework_axum"))]
    pub fn add_middleware<L, ResBody>(&mut self, middleware: L)
        where
            L: Layer<Route> + Clone + Send + Sync + 'static,
            L::Service: Service<Request<Body>, Response = Response<ResBody>> + Clone + Send + Sync + 'static,
            <L::Service as Service<Request<Body>>>::Future: Send + 'static,
            <L::Service as Service<Request<Body>>>::Error: Into<BoxError> + 'static,
            ResBody: HttpBody<Data = Bytes> + Send + 'static,
            ResBody::Error: Into<BoxError>,
    {
        self.router.add_middleware(middleware);
    }

    /// Adds middleware to the server (`flow_axum_compat` variant).
    ///
    /// The `Layer` wraps `NextService<S>` from the Flow router.
    #[cfg(all(feature = "core", feature = "framework_flow", feature = "flow_axum_compat"))]
    pub fn add_middleware<L, ResBody>(&mut self, middleware: L)
        where
            L: Layer<product_os_router::flow_impl::router::NextService<S>>
                + Clone + Send + Sync + 'static,
            L::Service: Service<Request<Body>, Response = Response<ResBody>>
                + Clone + Send + Sync + 'static,
            <L::Service as Service<Request<Body>>>::Future: Send + 'static,
            <L::Service as Service<Request<Body>>>::Error: Into<BoxError> + Send + 'static,
            ResBody: HttpBody<Data = Bytes> + Send + 'static,
            ResBody::Error: Into<BoxError>,
    {
        self.router.add_middleware(middleware);
    }

    /// Sets the entire router, replacing the existing one.
    ///
    /// # Arguments
    ///
    /// * `router` - The new router to use
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use product_os_server::{ProductOSServer, ProductOSRouter};
    /// # use product_os_server::ServerConfig;
    /// # use product_os_async_executor::TokioExecutor;
    /// # #[cfg(feature = "executor_tokio")]
    /// # fn example() {
    /// # let config = ServerConfig::new();
    /// # let mut server: ProductOSServer<(), TokioExecutor, _> = 
    /// #     ProductOSServer::new_with_config(config);
    /// let new_router = ProductOSRouter::new();
    /// server.set_router(new_router);
    /// # }
    /// ```
    pub fn set_router(&mut self, router: ProductOSRouter<S>)
    where
        S: Clone + Send + Sync + 'static
    {
        self.router = router;
    }


    /// Creates and starts a dual protocol (HTTP/HTTPS) server.
    #[cfg(all(feature = "dual_server", feature = "framework_axum"))]
    pub async fn create_dual_service_server(&mut self, serve_on_main_thread: bool, listen_all_interfaces: bool, custom_port: Option<u16>, custom_router: Option<ProductOSRouter<S>>, with_connect_info: bool, _force_secure: bool) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        #[cfg(feature = "compression")]
        self.ensure_compression();
        #[cfg(feature = "tls")]
        {
            let certificates = Some(self.certificates.to_owned());

            let router: AxumRouter = match custom_router {
                None => self.router.clone().into_axum_router(),
                Some(r) => r.into_axum_router()
            };

            let address = self.config.socket_address(custom_port, listen_all_interfaces);

            if serve_on_main_thread {
                dual_server::create_dual_tokio_service(address, certificates, router, with_connect_info).await?;
            }
            else {
                if let Err(e) = server_executor::ServerExecutor::spawn(self.executor.clone(), async move {
                    match dual_server::create_dual_tokio_service(address, certificates, router, with_connect_info).await {
                        Ok(_) => {}
                        Err(e) => tracing::error!("Error starting HTTPS server: {}", e)
                    }
                }) {
                    tracing::error!("Failed to spawn dual server task: {}", e);
                }
            }
        }

        #[cfg(not(feature = "tls"))]
        {
            tracing::info!("TLS feature is not enabled - please include the \"tls\" feature in your toml config file");
        }

        Ok(())
    }


    /// Creates and starts an HTTPS server.
    #[cfg(feature = "framework_axum")]
    pub async fn create_https_server(&mut self, serve_on_main_thread: bool, listen_all_interfaces: bool, custom_port: Option<u16>, custom_router: Option<ProductOSRouter<S>>, with_connect_info: bool) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        #[cfg(feature = "compression")]
        self.ensure_compression();
        #[cfg(all(feature = "tls", feature = "executor_tokio"))]
        {
            let certificates = Some(self.certificates.to_owned());

            let router: AxumRouter = match custom_router {
                None => self.router.clone().into_axum_router(),
                Some(r) => r.into_axum_router()
            };

            let address = self.config.socket_address(custom_port, listen_all_interfaces);

            if serve_on_main_thread {
                https_server::create_https_tokio_service(address, certificates, router, with_connect_info).await?;
            }
            else {
                if let Err(e) = server_executor::ServerExecutor::spawn(self.executor.clone(), async move {
                    match https_server::create_https_tokio_service(address, certificates, router, with_connect_info).await {
                        Ok(_) => {}
                        Err(e) => tracing::error!("Error starting HTTPS server: {}", e)
                    }
                }) {
                    tracing::error!("Failed to spawn HTTPS server task: {}", e);
                }
            }
        }
        #[cfg(not(feature = "tls"))]
        {
            // Mark parameters as used to avoid warnings when tls feature is disabled
            let _ = (serve_on_main_thread, listen_all_interfaces, custom_port, custom_router, with_connect_info);
            #[cfg(feature = "core")]
            tracing::info!("TLS feature is not enabled - please include the \"tls\" feature in your toml config file");
        }

        Ok(())
    }

    /// Creates and starts an HTTP server.
    #[cfg(feature = "framework_axum")]
    pub async fn create_http_server(&mut self, serve_on_main_thread: bool, listen_all_interfaces: bool, custom_port: Option<u16>, custom_router: Option<ProductOSRouter<S>>, with_connect_info: bool) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        #[cfg(feature = "compression")]
        self.ensure_compression();
        #[cfg(feature = "executor_tokio")]
        {
            let router: AxumRouter = match custom_router {
                None => self.router.clone().into_axum_router(),
                Some(r) => r.into_axum_router()
            };

            let address = self.config.socket_address(custom_port, listen_all_interfaces);

            if serve_on_main_thread {
                http_server::create_http_tokio_service(address, router, with_connect_info).await?;
            }
            else {
                if let Err(e) = server_executor::ServerExecutor::spawn(self.executor.clone(), async move {
                    match http_server::create_http_tokio_service(address, router, with_connect_info).await {
                        Ok(_) => {}
                        Err(e) => tracing::error!("Error starting HTTP server: {}", e)
                    }
                }) {
                    tracing::error!("Failed to spawn HTTP server task: {}", e);
                }
            }
        }
        #[cfg(not(feature = "executor_tokio"))]
        {
            let _ = (serve_on_main_thread, listen_all_interfaces, custom_port, custom_router, with_connect_info);
            #[cfg(feature = "core")]
            tracing::info!("executor_tokio feature is not enabled for HTTP server");
        }

        Ok(())
    }


    /// Creates and starts an HTTPS server using the Flow router.
    #[cfg(all(feature = "framework_flow", feature = "executor_tokio"))]
    pub async fn create_https_server(
        &mut self,
        serve_on_main_thread: bool,
        listen_all_interfaces: bool,
        custom_port: Option<u16>,
        custom_router: Option<ProductOSRouter<S>>,
        with_connect_info: bool,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        #[cfg(feature = "compression")]
        self.ensure_compression();
        #[cfg(feature = "tls")]
        {
            let certs = Some(self.certificates.to_owned());
            let router = custom_router.unwrap_or_else(|| self.router.clone());
            let address = self.config.socket_address(custom_port, listen_all_interfaces);

            if serve_on_main_thread {
                flow_https_server::create_flow_https_service(address, certs, router, with_connect_info).await?;
            } else {
                if let Err(e) = server_executor::ServerExecutor::spawn(self.executor.clone(), async move {
                    if let Err(e) = flow_https_server::create_flow_https_service(address, certs, router, with_connect_info).await {
                        tracing::error!("Error starting Flow HTTPS server: {}", e);
                    }
                }) {
                    tracing::error!("Failed to spawn Flow HTTPS server task: {}", e);
                }
            }
        }
        #[cfg(not(feature = "tls"))]
        {
            let _ = (serve_on_main_thread, listen_all_interfaces, custom_port, custom_router, with_connect_info);
            #[cfg(feature = "core")]
            tracing::info!("TLS feature is not enabled - please include the \"tls\" feature in your toml config file");
        }

        Ok(())
    }

    /// Creates and starts an HTTP server using the Flow router.
    #[cfg(all(feature = "framework_flow", feature = "executor_tokio"))]
    pub async fn create_http_server(
        &mut self,
        serve_on_main_thread: bool,
        listen_all_interfaces: bool,
        custom_port: Option<u16>,
        custom_router: Option<ProductOSRouter<S>>,
        with_connect_info: bool,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        #[cfg(feature = "compression")]
        self.ensure_compression();
        let router = custom_router.unwrap_or_else(|| self.router.clone());
        let address = self.config.socket_address(custom_port, listen_all_interfaces);

        if serve_on_main_thread {
            flow_http_server::create_flow_http_service(address, router, with_connect_info).await?;
        } else {
            if let Err(e) = server_executor::ServerExecutor::spawn(self.executor.clone(), async move {
                if let Err(e) = flow_http_server::create_flow_http_service(address, router, with_connect_info).await {
                    tracing::error!("Error starting Flow HTTP server: {}", e);
                }
            }) {
                tracing::error!("Failed to spawn Flow HTTP server task: {}", e);
            }
        }

        Ok(())
    }

    /// Initializes data stores.
    ///
    /// Internal method for store initialization. Currently a no-op but reserved
    /// for future store initialization logic.
    pub async fn init_stores(&mut self) {
        // Do nothing for now
    }

    /// Gets the relational store.
    ///
    /// # Panics
    ///
    /// Panics if no controller is configured. Use `try_get_relational_store` for a non-panicking alternative.
    #[cfg(feature = "controller")]
    #[deprecated(since = "0.0.54", note = "Use try_get_relational_store which returns Result instead of panicking")]
    pub fn get_relational_store(&mut self) -> Result<Arc<ProductOSRelationalStore>, ()> {
        self.try_get_relational_store().map_err(|_| ())
    }

    /// Gets the relational store, returning an error if the controller is missing or locked.
    ///
    /// # Errors
    ///
    /// Returns `ControllerError` if no controller is configured, or `LockError` if
    /// the controller lock could not be acquired.
    #[cfg(feature = "controller")]
    pub fn try_get_relational_store(&mut self) -> crate::error::Result<Arc<ProductOSRelationalStore>> {
        let controller_arc = self.try_get_controller()?;
        controller_arc.try_lock_for(CONTROLLER_LOCK_TIMEOUT)
            .map(|mut controller| controller.get_relational_store())
            .ok_or_else(|| ProductOSServerError::LockError { resource: "controller".to_string() })
    }

    /// Gets the key-value store.
    ///
    /// # Panics
    ///
    /// Panics if no controller is configured. Use `try_get_key_value_store` for a non-panicking alternative.
    #[cfg(feature = "controller")]
    #[deprecated(since = "0.0.54", note = "Use try_get_key_value_store which returns Result instead of panicking")]
    pub fn get_key_value_store(&mut self) -> Result<Arc<ProductOSKeyValueStore>, ()> {
        self.try_get_key_value_store().map_err(|_| ())
    }

    /// Gets the key-value store, returning an error if the controller is missing or locked.
    ///
    /// # Errors
    ///
    /// Returns `ControllerError` if no controller is configured, or `LockError` if
    /// the controller lock could not be acquired.
    #[cfg(feature = "controller")]
    pub fn try_get_key_value_store(&mut self) -> crate::error::Result<Arc<ProductOSKeyValueStore>> {
        let controller_arc = self.try_get_controller()?;
        controller_arc.try_lock_for(CONTROLLER_LOCK_TIMEOUT)
            .map(|mut controller| controller.get_key_value_store())
            .ok_or_else(|| ProductOSServerError::LockError { resource: "controller".to_string() })
    }

    /// Gets the server configuration.
    ///
    /// # Returns
    ///
    /// A clone of the current server configuration.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use product_os_server::ProductOSServer;
    /// # use product_os_server::ServerConfig;
    /// # use product_os_async_executor::TokioExecutor;
    /// # #[cfg(feature = "executor_tokio")]
    /// # fn example() {
    /// # let config = ServerConfig::new();
    /// # let server: ProductOSServer<(), TokioExecutor, _> = 
    /// #     ProductOSServer::new_with_config(config);
    /// let current_config = server.get_config();
    /// println!("Server port: {}", current_config.network.port);
    /// # }
    /// ```
    pub fn get_config(&self) -> crate::config::ServerConfig {
        self.config.clone()
    }

    /// Updates the server configuration.
    ///
    /// # Arguments
    ///
    /// * `config` - The new configuration to apply
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use product_os_server::ProductOSServer;
    /// # use product_os_server::ServerConfig;
    /// # use product_os_async_executor::TokioExecutor;
    /// # #[cfg(feature = "executor_tokio")]
    /// # fn example() {
    /// # let config = ServerConfig::new();
    /// # let mut server: ProductOSServer<(), TokioExecutor, _> = 
    /// #     ProductOSServer::new_with_config(config);
    /// let mut new_config = ServerConfig::new();
    /// new_config.network.port = 8080;
    /// server.update_config(new_config);
    /// # }
    /// ```
    pub fn update_config(&mut self, config: crate::config::ServerConfig) {
        self.config = config;
    }

    /// Gets the base URL of the server.
    ///
    /// Returns the URL where the server is accessible, constructed from the
    /// configuration's host and port settings.
    ///
    /// # Returns
    ///
    /// A `Uri` representing the server's base URL.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use product_os_server::ProductOSServer;
    /// # use product_os_server::ServerConfig;
    /// # use product_os_async_executor::TokioExecutor;
    /// # #[cfg(feature = "executor_tokio")]
    /// # fn example() {
    /// # let config = ServerConfig::new();
    /// # let server: ProductOSServer<(), TokioExecutor, _> = 
    /// #     ProductOSServer::new_with_config(config);
    /// let base_url = server.get_base_url();
    /// println!("Server available at: {}", base_url);
    /// # }
    /// ```
    #[allow(clippy::panic)]
    #[deprecated(since = "0.0.53", note = "Use try_get_base_url() which returns Result instead of panicking")]
    pub fn get_base_url(&self) -> Uri {
        self.try_get_base_url()
            .unwrap_or_else(|e| ::std::panic!("Failed to parse base URL: {:?}", e))
    }

    /// Returns the base URL as a `Uri`, or an error if URL parsing fails.
    ///
    /// This is the non-panicking version of `get_base_url`.
    pub fn try_get_base_url(&self) -> crate::error::Result<Uri> {
        let url = self.config.try_url_address()?;
        Uri::from_str(&url)
            .map_err(|e| ProductOSServerError::ConfigurationError {
                component: "base_url".to_string(),
                message: alloc::format!("Failed to parse URL as URI: {}", e),
            })
    }


    /// Starts the server.
    ///
    /// Initializes and starts the HTTP/HTTPS server(s) based on the configuration.
    /// Handles:
    /// - Starting HTTPS server if TLS is configured
    /// - Starting HTTP server for insecure connections (if allowed)
    /// - Setting up dual protocol servers
    /// - Initializing the command-and-control system (if controller feature is enabled)
    ///
    /// # Arguments
    ///
    /// * `serve_on_main_thread` - If true, blocks the main thread; if false, spawns background tasks
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` if the server starts successfully, or an error if initialization fails.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use product_os_server::ProductOSServer;
    /// # use product_os_server::ServerConfig;
    /// # use product_os_async_executor::TokioExecutor;
    /// # #[cfg(feature = "executor_tokio")]
    /// # async fn example() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    /// # let config = ServerConfig::new();
    /// # let mut server: ProductOSServer<(), TokioExecutor, _> = 
    /// #     ProductOSServer::new_with_config(config);
    /// // Start server in background
    /// server.start(false).await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Note
    ///
    /// When `serve_on_main_thread` is true and the controller feature is enabled,
    /// this method will block indefinitely after starting the controller.
    #[cfg(all(feature = "core", feature = "framework_axum"))]
    pub async fn start(&mut self, serve_on_main_thread: bool) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        #[cfg(feature = "compression")]
        self.ensure_compression();
        let with_connect_info = self.config.network.connect_info;
        // ----- Start Server
        if self.config.is_secure() {
            #[cfg(feature = "controller")]
            {
                if self.config.network.allow_insecure {
                    if !&self.config.network.insecure_use_different_port {
                        #[cfg(feature = "dual_server")]
                        self.create_dual_service_server(false, self.config.network.listen_all_interfaces, Some(self.config.insecure_port()), None, false, self.config.network.insecure_force_secure).await?;
                    }
                    else {
                        if self.config.network.insecure_force_secure {
                            let secure_cfg = ForceSecureConfig {
                                host: self.config.network.host.clone(),
                                port: self.config.network.port,
                            };
                            let router = AxumRouter::new()
                                .fallback(product_os_router::MethodRouter::new()
                                    .get(force_secure_handler)
                                    .post(force_secure_handler)
                                    .put(force_secure_handler)
                                    .patch(force_secure_handler)
                                    .delete(force_secure_handler)
                                    .trace(force_secure_handler)
                                    .head(force_secure_handler)
                                    .options(force_secure_handler))
                                .layer(axum::extract::Extension(secure_cfg));

                            let address = self.config.socket_address(Some(self.config.insecure_port()), self.config.network.listen_all_interfaces);
                            http_server::create_http_tokio_service(address, router, with_connect_info).await?;
                        }
                        else {
                            self.create_http_server(false, self.config.network.listen_all_interfaces, Some(self.config.insecure_port()), None, with_connect_info).await?;
                        }
                    }
                }

                self.create_https_server(false, self.config.network.listen_all_interfaces, None, None, with_connect_info).await?;
            }
            #[cfg(not(feature = "controller"))]
            {
                if self.config.network.allow_insecure {
                    if self.config.network.insecure_force_secure {
                        let secure_cfg = ForceSecureConfig {
                            host: self.config.network.host.clone(),
                            port: self.config.network.port,
                        };
                        let router = AxumRouter::new()
                            .fallback(product_os_router::MethodRouter::new()
                                .get(force_secure_handler)
                                .post(force_secure_handler)
                                .put(force_secure_handler)
                                .patch(force_secure_handler)
                                .delete(force_secure_handler)
                                .trace(force_secure_handler)
                                .head(force_secure_handler)
                                .options(force_secure_handler))
                            .layer(axum::extract::Extension(secure_cfg));

                        let address = self.config.socket_address(Some(self.config.network.insecure_port), self.config.network.listen_all_interfaces);
                        http_server::create_http_tokio_service(address, router, with_connect_info).await?;
                    }
                    else {
                        self.create_http_server(serve_on_main_thread, self.config.network.listen_all_interfaces, Some(self.config.network.insecure_port), None, with_connect_info).await?;
                    }
                }

                self.create_https_server(serve_on_main_thread, self.config.network.listen_all_interfaces, None, None, with_connect_info).await?;
            }
        }
        else {
            #[cfg(feature = "controller")]
            {
                self.create_http_server(false, self.config.network.listen_all_interfaces, None, None, with_connect_info).await?;
            }
            #[cfg(not(feature = "controller"))]
            {
                self.create_http_server(serve_on_main_thread, self.config.network.listen_all_interfaces, None, None, with_connect_info).await?;
            }
        };

        #[cfg(feature = "controller")]
        {
            self.init_stores().await;

            let cc_cfg: Option<product_os_command_control::CommandControl> = self.parse_command_control_config();
            let command_control_config = cc_cfg.ok_or_else(|| -> Box<dyn std::error::Error + Send + Sync> {
                alloc::format!("No controller config").into()
            })?;

            if command_control_config.enable {
                let controller_arc = self.try_get_controller().map_err(|e| -> Box<dyn std::error::Error + Send + Sync> {
                    alloc::format!("{}", e).into()
                })?;
                let controller_unlocked = controller_arc.clone();
                let executor = self.executor.clone();

                if serve_on_main_thread {
                    product_os_command_control::run_controller(controller_unlocked, executor).await;
                    match tokio::signal::ctrl_c().await {
                        Ok(()) => {
                            #[cfg(feature = "core")]
                            tracing::info!("Shutdown signal received, stopping server...");
                        }
                        Err(e) => {
                            #[cfg(feature = "core")]
                            tracing::error!("Failed to listen for shutdown signal: {:?}", e);
                        }
                    }
                }
                else {
                    if let Err(e) = server_executor::ServerExecutor::spawn(self.executor.clone(), async move {
                        product_os_command_control::run_controller(controller_unlocked, executor).await;
                    }) {
                        #[cfg(feature = "core")]
                        tracing::error!("Failed to spawn controller task: {}", e);
                    }
                }
            }
        }

        Ok(())
    }

    /// Start the server using the Flow framework.
    ///
    /// Supports HTTP, HTTPS (with `tls` feature), dual protocol, controller
    /// startup, and custom ports -- mirroring the Axum `start()` behaviour.
    #[cfg(all(feature = "core", feature = "framework_flow", not(feature = "framework_axum"), feature = "executor_tokio"))]
    pub async fn start(&mut self, serve_on_main_thread: bool) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        #[cfg(feature = "compression")]
        self.ensure_compression();
        let with_connect_info = self.config.network.connect_info;
        let router = self.router.clone();

        if self.config.is_secure() {
            // Start insecure HTTP redirect / mirror if allowed
            if self.config.network.allow_insecure {
                let insecure_addr = self.config.socket_address(
                    Some(self.config.insecure_port()),
                    self.config.network.listen_all_interfaces,
                );
                let insecure_router = if self.config.network.insecure_force_secure {
                    build_flow_force_secure_router::<S>(
                        ForceSecureConfig {
                            host: self.config.network.host.clone(),
                            port: self.config.network.port,
                        },
                        self.router.get_state(),
                    )
                } else {
                    router.clone()
                };
                if let Err(e) = server_executor::ServerExecutor::spawn(self.executor.clone(), async move {
                    if let Err(e) = flow_http_server::create_flow_http_service(insecure_addr, insecure_router, with_connect_info).await {
                        tracing::error!("Error starting insecure Flow HTTP server: {}", e);
                    }
                }) {
                    tracing::error!("Failed to spawn insecure HTTP task: {}", e);
                }
            }

            // Start HTTPS server
            #[cfg(feature = "tls")]
            {
                let address = self.config.socket_address(None, self.config.network.listen_all_interfaces);
                let certs = Some(self.certificates.to_owned());

                if serve_on_main_thread {
                    #[cfg(not(feature = "controller"))]
                    {
                        flow_https_server::create_flow_https_service(address, certs, router, with_connect_info).await?;
                    }
                    #[cfg(feature = "controller")]
                    {
                        let https_router = router.clone();
                        if let Err(e) = server_executor::ServerExecutor::spawn(self.executor.clone(), async move {
                            if let Err(e) = flow_https_server::create_flow_https_service(address, certs, https_router, with_connect_info).await {
                                tracing::error!("Error starting Flow HTTPS server: {}", e);
                            }
                        }) {
                            tracing::error!("Failed to spawn HTTPS task: {}", e);
                        }
                    }
                } else {
                    if let Err(e) = server_executor::ServerExecutor::spawn(self.executor.clone(), async move {
                        if let Err(e) = flow_https_server::create_flow_https_service(address, certs, router, with_connect_info).await {
                            tracing::error!("Error starting Flow HTTPS server: {}", e);
                        }
                    }) {
                        tracing::error!("Failed to spawn HTTPS task: {}", e);
                    }
                }
            }
            #[cfg(not(feature = "tls"))]
            {
                tracing::info!("TLS feature is not enabled - please include the \"tls\" feature in your toml config file");
            }
        } else {
            // Plain HTTP
            let address = self.config.socket_address(None, self.config.network.listen_all_interfaces);
            if serve_on_main_thread {
                #[cfg(not(feature = "controller"))]
                {
                    flow_http_server::create_flow_http_service(address, router, with_connect_info).await?;
                }
                #[cfg(feature = "controller")]
                {
                    let http_router = router.clone();
                    if let Err(e) = server_executor::ServerExecutor::spawn(self.executor.clone(), async move {
                        if let Err(e) = flow_http_server::create_flow_http_service(address, http_router, with_connect_info).await {
                            tracing::error!("Error starting Flow HTTP server: {}", e);
                        }
                    }) {
                        tracing::error!("Failed to spawn HTTP task: {}", e);
                    }
                }
            } else {
                if let Err(e) = server_executor::ServerExecutor::spawn(self.executor.clone(), async move {
                    if let Err(e) = flow_http_server::create_flow_http_service(address, router, with_connect_info).await {
                        tracing::error!("Error starting Flow HTTP server: {}", e);
                    }
                }) {
                    tracing::error!("Failed to spawn HTTP task: {}", e);
                }
            }
        }

        // Controller startup
        #[cfg(feature = "controller")]
        {
            self.init_stores().await;

            let cc_cfg: Option<product_os_command_control::CommandControl> = self.parse_command_control_config();
            let command_control_config = cc_cfg.ok_or_else(|| -> Box<dyn std::error::Error + Send + Sync> {
                alloc::format!("No controller config").into()
            })?;

            if command_control_config.enable {
                let controller_arc = self.try_get_controller().map_err(|e| -> Box<dyn std::error::Error + Send + Sync> {
                    alloc::format!("{}", e).into()
                })?;
                let controller_unlocked = controller_arc.clone();
                let executor = self.executor.clone();

                if serve_on_main_thread {
                    product_os_command_control::run_controller(controller_unlocked, executor).await;
                    match tokio::signal::ctrl_c().await {
                        Ok(()) => {
                            tracing::info!("Shutdown signal received, stopping server...");
                        }
                        Err(e) => {
                            tracing::error!("Failed to listen for shutdown signal: {:?}", e);
                        }
                    }
                } else {
                    if let Err(e) = server_executor::ServerExecutor::spawn(self.executor.clone(), async move {
                        product_os_command_control::run_controller(controller_unlocked, executor).await;
                    }) {
                        tracing::error!("Failed to spawn controller task: {}", e);
                    }
                }
            }
        }

        Ok(())
    }

    /// Parses the command-and-control configuration from the raw JSON value.
    #[cfg(feature = "controller")]
    fn parse_command_control_config(&self) -> Option<product_os_command_control::CommandControl> {
        self.config.command_control.as_ref()
            .and_then(|v| serde_json::from_value(v.clone()).map_err(|e| {
                #[cfg(feature = "core")]
                tracing::warn!("Failed to parse command_control config: {}", e);
                e
            }).ok())
    }

    /// Parses and validates the command-and-control configuration, returning an error
    /// if missing or disabled.
    #[cfg(feature = "controller")]
    fn require_enabled_command_control(&self, operation: &str) -> Result<product_os_command_control::CommandControl, ProductOSServerError> {
        let config = self.parse_command_control_config()
            .ok_or_else(|| ProductOSServerError::ControllerError {
                operation: operation.to_string(),
                message: "No controller config".to_string(),
            })?;
        if !config.enable {
            return Err(ProductOSServerError::ControllerError {
                operation: operation.to_string(),
                message: "Controller not enabled".to_string(),
            });
        }
        Ok(config)
    }

    /// Starts all registered services.
    ///
    /// # Errors
    ///
    /// Returns `ControllerError` if the controller is not configured, not enabled,
    /// cannot be locked, or if starting services fails.
    #[cfg(feature = "controller")]
    pub async fn start_services(&mut self) -> Result<(), ProductOSServerError> {
        self.require_enabled_command_control("start_services")?;
        let controller_arc = self.try_get_controller()?;
        let mut controller = controller_arc.try_lock_for(CONTROLLER_LOCK_TIMEOUT)
            .ok_or_else(|| ProductOSServerError::LockError { resource: "controller".to_string() })?;
        controller.start_services().await
            .map_err(|e| ProductOSServerError::ControllerError {
                operation: "start_services".to_string(),
                message: alloc::format!("Failed to start services: {:?}", e),
            })
    }

    /// Starts a specific service by its identifier.
    ///
    /// # Arguments
    ///
    /// * `identifier` - The unique identifier of the service to start
    ///
    /// # Errors
    ///
    /// Returns `ControllerError` if the controller is not configured, not enabled,
    /// cannot be locked, or if starting the service fails.
    #[cfg(feature = "controller")]
    pub async fn start_service(&mut self, identifier: &str) -> Result<(), ProductOSServerError> {
        self.require_enabled_command_control("start_service")?;
        let controller_arc = self.try_get_controller()?;
        let mut controller = controller_arc.try_lock_for(CONTROLLER_LOCK_TIMEOUT)
            .ok_or_else(|| ProductOSServerError::LockError { resource: "controller".to_string() })?;
        controller.start_service(identifier).await
            .map_err(|e| ProductOSServerError::ControllerError {
                operation: "start_service".to_string(),
                message: alloc::format!("Failed to start service '{}': {:?}", identifier, e),
            })
    }

    /// Stops a specific service by its identifier.
    ///
    /// # Arguments
    ///
    /// * `identifier` - The unique identifier of the service to stop
    ///
    /// # Errors
    ///
    /// Returns `ControllerError` if the controller is not configured, not enabled,
    /// cannot be locked, or if stopping the service fails.
    #[cfg(feature = "controller")]
    pub async fn stop_service(&mut self, identifier: &str) -> Result<(), ProductOSServerError> {
        self.require_enabled_command_control("stop_service")?;
        let controller_arc = self.try_get_controller()?;
        let mut controller = controller_arc.try_lock_for(CONTROLLER_LOCK_TIMEOUT)
            .ok_or_else(|| ProductOSServerError::LockError { resource: "controller".to_string() })?;
        controller.stop_service(identifier).await
            .map_err(|e| ProductOSServerError::ControllerError {
                operation: "stop_service".to_string(),
                message: alloc::format!("Failed to stop service '{}': {:?}", identifier, e),
            })
    }
}




/// Configuration passed to the force-secure redirect handler via an `Extension`.
#[cfg(feature = "core")]
#[derive(Clone, Debug)]
struct ForceSecureConfig {
    host: String,
    port: u16,
}

/// Redirects HTTP requests to their HTTPS equivalent using the configured host and port.
///
/// Builds a full `https://host:port/path?query` URL and issues a 301 Permanent Redirect.
#[cfg(all(feature = "core", feature = "framework_axum"))]
async fn force_secure_handler(
    Extension(secure_cfg): Extension<ForceSecureConfig>,
    request: Request<Body>,
) -> Response<BodyBytes> {
    let uri = request.uri();
    let path = uri.path();
    let query = uri.query().map(|q| alloc::format!("?{}", q)).unwrap_or_default();

    let https_url = if secure_cfg.port == 443 {
        alloc::format!("https://{}{}{}", secure_cfg.host, path, query)
    } else {
        alloc::format!("https://{}:{}{}{}", secure_cfg.host, secure_cfg.port, path, query)
    };

    let (parts, _) = axum::response::Redirect::permanent(https_url.as_str()).into_response().into_parts();

    let mut response_builder = Response::builder().status(parts.status);
    for (key, value) in parts.headers.iter() {
        response_builder = response_builder.header(key.to_owned(), value.to_owned());
    }

    response_builder.body(BodyBytes::empty()).unwrap_or_else(|_e| Response::new(BodyBytes::empty()))
}

/// Build a Flow redirect router that 301-redirects all HTTP requests to their
/// HTTPS equivalent using the given host/port. Returns a `ProductOSRouter<S>`
/// suitable for the insecure HTTP listener.
#[cfg(all(feature = "core", feature = "framework_flow", not(feature = "framework_axum")))]
fn build_flow_force_secure_router<S: Clone + Send + Sync + 'static>(
    secure_cfg: ForceSecureConfig,
    state: S,
) -> ProductOSRouter<S> {
    let mut redirect_router = ProductOSRouter::<S>::new_with_state(state);
    let cfg = secure_cfg;
    redirect_router.set_fallback_handler(move |request: Request<Body>| {
        let cfg = cfg.clone();
        async move {
            let uri = request.uri();
            let path = uri.path();
            let query = uri.query()
                .map(|q| alloc::format!("?{}", q))
                .unwrap_or_default();

            let https_url = if cfg.port == 443 {
                alloc::format!("https://{}{}{}", cfg.host, path, query)
            } else {
                alloc::format!("https://{}:{}{}{}", cfg.host, cfg.port, path, query)
            };

            Response::builder()
                .status(StatusCode::MOVED_PERMANENTLY)
                .header("location", https_url)
                .body(Body::empty())
                .unwrap()
        }
    });
    redirect_router
}