rullst 4.0.1

📜🦀🌐 Framework Web FullStack for Rust language 🌐🦀📜
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
pub use crate::Router;
use crate::scheduler::Scheduler;
use rullst_orm::Orm;
use std::future::Future;
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::{Arc, Mutex, RwLock};
use std::task::{Context, Poll};
use tower_service::Service;

#[non_exhaustive]
/// The central application server builder for Rullst.
///
/// Configures and boots the Axum HTTP server, ORM connection pool, task scheduler,
/// hot-reload DLL watcher, traffic shield, and rate limiter in a single fluent chain.
///
/// # Example
/// ```rust,no_run
/// use rullst::{Server, routes, routing::get};
///
/// #[tokio::main]
/// async fn main() {
///     Server::new(routes![get("/" => || async { "OK" })])
///         .with_db("sqlite://app.db")
///         .run(3000)
///         .await
///         .unwrap();
/// }
/// ```
pub struct Server {
    router: Router,
    db_url: Option<String>,
    scheduler: Option<Scheduler>,
    hot_reload_lib: Option<String>,
    shield: Option<crate::resilience::TrafficShield>,
    limiter: Option<crate::resilience::RateLimiter>,
}

impl Server {
    /// Creates a new `Server` from an already-built [`Router`].
    /// Use [`Server::new_hot`] instead to enable hot-reload mode.
    pub fn new(router: Router) -> Self {
        Server {
            router,
            db_url: None,
            scheduler: None,
            hot_reload_lib: None,
            shield: None,
            limiter: None,
        }
    }

    /// Creates a `Server` in **hot-reload** mode that loads the application router from
    /// a compiled `cdylib` dynamic library at the given `lib_path`.
    /// The background file-watcher recompiles and hot-swaps the router on source changes.
    pub fn new_hot<S: Into<String>>(lib_path: S) -> Self {
        if !cfg!(debug_assertions) {
            panic!(
                "CRITICAL SECURITY: Hot-Reloading (new_hot) is strictly disabled in release mode to prevent RCE vulnerabilities via dynamic library injection."
            );
        }

        Server {
            router: Router::new(),
            db_url: None,
            scheduler: None,
            hot_reload_lib: Some(lib_path.into()),
            shield: None,
            limiter: None,
        }
    }

    /// Set a database URL to automatically initialize the Orm connection pool at startup
    pub fn with_db<S: Into<String>>(mut self, db_url: S) -> Self {
        self.db_url = Some(db_url.into());
        self
    }

    /// Attach a task scheduler that runs alongside the HTTP server.
    ///
    /// # Example
    /// ```rust,ignore
    /// use rullst::scheduler::Scheduler;
    ///
    /// let scheduler = Scheduler::new()
    ///     .task("0 0 * * *", || async { cleanup().await });
    ///
    /// Server::new(router)
    ///     .schedule(scheduler)
    ///     .run(3000)
    ///     .await?;
    /// ```
    pub fn schedule(mut self, scheduler: Scheduler) -> Self {
        self.scheduler = Some(scheduler);
        self
    }

    /// Attaches an adaptive TrafficShield to the server to protect against CPU/DB saturation.
    pub fn shield(mut self, shield: crate::resilience::TrafficShield) -> Self {
        self.shield = Some(shield);
        self
    }

    /// Attaches a global RateLimiter to the server.
    pub fn rate_limit(mut self, limiter: crate::resilience::RateLimiter) -> Self {
        self.limiter = Some(limiter);
        self
    }

    /// Start the HTTP server on the specified port
    pub async fn run(mut self, port: u16) -> Result<(), Box<dyn std::error::Error>> {
        let app_config = Self::load_config().await;

        self.init_database(&app_config).await;
        self.start_scheduler();

        let is_dev =
            std::env::var("APP_ENV").unwrap_or_else(|_| "development".to_string()) != "production";
        let addr = Self::setup_networking(port, is_dev);

        if let Some(lib_path) = self.hot_reload_lib.take() {
            self.run_hot_reload(lib_path, addr, is_dev).await
        } else {
            self.run_static(app_config, addr, is_dev).await
        }
    }

    async fn load_config() -> crate::config::RullstConfig {
        let mut app_config = crate::config::RullstConfig::new();
        if std::path::Path::new("Rullst.toml").exists() {
            match crate::config::RullstConfig::load_from_file("Rullst.toml").await {
                Ok(c) => {
                    let _ = crate::config::RullstConfig::set_global(c.clone());
                    app_config = c;
                }
                Err(e) => {
                    eprintln!("⚠️ Rullst Warning: Failed to parse Rullst.toml: {}", e);
                    let _ = crate::config::RullstConfig::set_global(app_config.clone());
                }
            }
        } else {
            let _ = crate::config::RullstConfig::set_global(app_config.clone());
        }
        app_config
    }

    async fn init_database(&mut self, app_config: &crate::config::RullstConfig) {
        if self.db_url.is_none() {
            if let Ok(env_db_url) = std::env::var("DATABASE_URL") {
                self.db_url = Some(env_db_url);
            } else if let Some(ref url) = app_config.database.url {
                self.db_url = Some(url.clone());
            }
        }

        if let Some(db_url) = &self.db_url {
            println!("Initializing Orm database pool...");
            match Orm::init(db_url).await {
                Ok(_) => println!("Database initialized successfully."),
                Err(e) => eprintln!(
                    "⚠️ Rullst Warning: Failed to initialize database: {}. Database features will be offline.",
                    e
                ),
            }
        }
    }

    fn start_scheduler(&mut self) {
        if let Some(scheduler) = self.scheduler.take() {
            scheduler.start();
        }
    }

    fn setup_networking(port: u16, is_dev: bool) -> SocketAddr {
        if is_dev && std::env::var("RUST_BACKTRACE").is_err() {
            eprintln!(
                "⚠️  Rullst Dev: Set RUST_BACKTRACE=1 in your environment for richer error traces."
            );
        }

        let host_str = std::env::var("HOST").unwrap_or_else(|_| {
            if is_dev && std::env::var("RULLST_HOST").is_err() {
                "127.0.0.1".to_string()
            } else {
                "0.0.0.0".to_string()
            }
        });
        let addr: SocketAddr = format!("{}:{}", host_str, port)
            .parse()
            .unwrap_or_else(|_| SocketAddr::from(([0, 0, 0, 0], port)));

        if is_dev && addr.ip().is_unspecified() {
            eprintln!(
                "⚠️  Rullst Dev: Self-Healing Console mounted on /_rullst/*\n\
                   Set APP_ENV=production to disable before deploying."
            );
        }

        addr
    }

    async fn run_hot_reload(
        self,
        lib_path: String,
        addr: SocketAddr,
        is_dev: bool,
    ) -> Result<(), Box<dyn std::error::Error>> {
        if !cfg!(debug_assertions) {
            panic!("CRITICAL SECURITY: Hot-Reloading is strictly disabled in release mode!");
        }

        println!("\x1b[36m⚡ Inicializando Rullst em Modo Hot-Reloading via dylib...\x1b[0m");

        let (initial_router, library) = match load_dylib_router(&lib_path, is_dev) {
            Ok(r) => r,
            Err(e) => {
                println!(
                    "\x1b[31m❌ Falha ao carregar dylib inicial: {}. Certifique-se de que a biblioteca dinâmica foi compilada rodando 'cargo build --lib'.\x1b[0m",
                    e
                );
                return Err(e);
            }
        };

        let current_router = Arc::new(RwLock::new(initial_router));
        let active_libraries = Arc::new(Mutex::new(vec![library]));

        let (tx, rx) = std::sync::mpsc::channel();
        use notify::{RecommendedWatcher, RecursiveMode, Watcher};
        let mut watcher = RecommendedWatcher::new(
            move |res| {
                if let Ok(event) = res {
                    let _ = tx.send(event);
                }
            },
            notify::Config::default(),
        )?;

        if std::path::Path::new("src").exists() {
            watcher.watch(std::path::Path::new("src"), RecursiveMode::Recursive)?;
        }

        let current_router_clone = current_router.clone();
        let active_libraries_clone = active_libraries.clone();
        let lib_path_clone = lib_path.clone();

        std::thread::spawn(move || {
            let mut last_build = std::time::Instant::now();
            while let Ok(_event) = rx.recv() {
                std::thread::sleep(std::time::Duration::from_millis(300));
                while rx.try_recv().is_ok() {}

                if last_build.elapsed() < std::time::Duration::from_secs(1) {
                    continue;
                }

                let (tx, rx_build) = std::sync::mpsc::channel();
                let current_dir =
                    std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."));
                std::thread::spawn(move || {
                    let res = std::process::Command::new("cargo")
                        .arg("build")
                        .arg("--lib")
                        .current_dir(current_dir)
                        .status();
                    let _ = tx.send(res);
                });

                let build_success = match rx_build.recv_timeout(std::time::Duration::from_secs(120))
                {
                    Ok(Ok(status)) => status.success(),
                    Ok(Err(e)) => {
                        eprintln!("⚠️ Rullst Hot-Reload: failed to execute cargo build: {}", e);
                        false
                    }
                    Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
                        eprintln!("⚠️ Rullst Hot-Reload: cargo build timed out after 120 seconds!");
                        false
                    }
                    Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => false,
                };

                if build_success {
                    println!(
                        "\x1b[32m✨ Rullst Hot-Reload: Recompilado com sucesso! Carregando dylib...\x1b[0m"
                    );
                    match load_dylib_router(&lib_path_clone, is_dev) {
                        Ok((new_router, new_lib)) => {
                            match current_router_clone.write() {
                                Ok(mut guard) => *guard = new_router,
                                Err(poisoned) => *poisoned.into_inner() = new_router,
                            };

                            let mut active_libs = active_libraries_clone
                                .lock()
                                .unwrap_or_else(|p| p.into_inner());
                            active_libs.push(new_lib);
                            if active_libs.len() > 3 {
                                active_libs.remove(0);
                            }

                            println!(
                                "\x1b[32m🚀 Rullst Hot-Reload: Roteamento atualizado e hot-swapped instantaneamente!\x1b[0m"
                            );
                        }
                        Err(e) => {
                            println!(
                                "\x1b[31m❌ Rullst Hot-Reload: Erro ao carregar dylib recém-compilada: {}\x1b[0m",
                                e
                            );
                        }
                    }
                } else {
                    println!(
                        "\x1b[31m❌ Rullst Hot-Reload: Falha ao compilar o código fonte. Corrija os erros para aplicar o hot-swap.\x1b[0m"
                    );
                }

                last_build = std::time::Instant::now();
            }
        });

        let hotswap_service = HotSwapService {
            current_router,
            shield: self.shield,
            limiter: self.limiter,
        };

        println!(
            "Rullst framework serving on http://{} (Hot-Reload Ativo)",
            addr
        );
        println!(
            "🚀 Visit: http://localhost:{} to see the result!",
            addr.port()
        );

        let listener = tokio::net::TcpListener::bind(addr).await?;
        axum::serve(listener, hotswap_service).await?;

        Ok(())
    }

    async fn run_static(
        self,
        app_config: crate::config::RullstConfig,
        addr: SocketAddr,
        is_dev: bool,
    ) -> Result<(), Box<dyn std::error::Error>> {
        let mut app = self.router.into_axum();

        app = app.layer(axum::Extension(app_config.security.clone()));

        if !app_config.security.cors_allow_origins.is_empty() {
            use tower_http::cors::CorsLayer;
            let origins: Vec<axum::http::HeaderValue> = app_config
                .security
                .cors_allow_origins
                .iter()
                .filter_map(|o| o.parse().ok())
                .collect();
            app = app.layer(CorsLayer::new().allow_origin(origins));
        }

        if std::path::Path::new("static").exists() {
            app = app
                .nest_service(
                    "/static",
                    tower_http::services::ServeDir::new("static").precompressed_br(),
                )
                .layer(axum::middleware::from_fn(zstd_static_middleware));
        }

        if is_dev {
            app = app
                .route(
                    "/_rullst/explain",
                    axum::routing::get(crate::error_console::handle_explain),
                )
                .route(
                    "/_rullst/autofix",
                    axum::routing::post(crate::error_console::handle_autofix),
                )
                .layer(axum::middleware::from_fn(
                    crate::error_console::catch_panic_middleware,
                ));
        }

        if let Some(limiter) = self.limiter {
            app = app.layer(axum::middleware::from_fn(move |req, next| {
                crate::resilience::rate_limit_middleware(limiter.clone(), req, next)
            }));
        }

        if let Some(shield) = self.shield {
            app = app.layer(axum::middleware::from_fn(move |req, next| {
                crate::resilience::backpressure_middleware(shield.clone(), req, next)
            }));
        }

        if !is_dev {
            if app_config.security.enable_pii_masking {
                app = app.layer(axum::middleware::from_fn(
                    crate::security::pii_masking_middleware,
                ));
            }
            app = app
                .layer(axum::middleware::from_fn(
                    crate::security::headers_middleware,
                ))
                .layer(axum::middleware::from_fn(crate::security::csrf_middleware))
                .layer(axum::middleware::from_fn(crate::security::waf_middleware));
        }

        println!("Rullst framework serving on http://{}", addr);
        println!(
            "🚀 Visit: http://localhost:{} to see the result!",
            addr.port()
        );

        let listener = tokio::net::TcpListener::bind(addr).await?;
        axum::serve(listener, app).await?;

        Ok(())
    }
}

/// Tower service that atomically swaps the Axum router at runtime during hot-reload development.
/// Wraps the router in an `Arc<RwLock<>>` so handlers continue serving in-flight requests
/// while the new router is being compiled and installed.
#[derive(Clone)]
pub struct HotSwapService {
    current_router: Arc<RwLock<axum::Router>>,
    shield: Option<crate::resilience::TrafficShield>,
    limiter: Option<crate::resilience::RateLimiter>,
}

impl<'a, L: axum::serve::Listener> Service<axum::serve::IncomingStream<'a, L>> for HotSwapService {
    type Response = HotSwapService;
    type Error = std::convert::Infallible;
    type Future = std::future::Ready<Result<Self::Response, Self::Error>>;

    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }

    fn call(&mut self, _req: axum::serve::IncomingStream<'a, L>) -> Self::Future {
        std::future::ready(Ok(self.clone()))
    }
}

impl Service<axum::extract::Request> for HotSwapService {
    type Response = axum::response::Response;
    type Error = std::convert::Infallible;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;

    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }

    fn call(&mut self, req: axum::extract::Request) -> Self::Future {
        // H-1: Recover from poisoned RwLock instead of panicking
        let mut router = match self.current_router.read() {
            Ok(guard) => guard.clone(),
            Err(poisoned) => poisoned.into_inner().clone(),
        };

        if let Some(ref limiter) = self.limiter {
            let lim = limiter.clone();
            router = router.layer(axum::middleware::from_fn(move |req, next| {
                crate::resilience::rate_limit_middleware(lim.clone(), req, next)
            }));
        }

        if let Some(ref shield) = self.shield {
            let sh = shield.clone();
            router = router.layer(axum::middleware::from_fn(move |req, next| {
                crate::resilience::backpressure_middleware(sh.clone(), req, next)
            }));
        }
        use tower::ServiceExt;
        let fut = router.oneshot(req);
        Box::pin(async move {
            let handle = tokio::spawn(async move { fut.await });
            match handle.await {
                Ok(Ok(res)) => Ok(res),
                Ok(Err(_)) => {
                    // H-2: Handle oneshot error gracefully
                    match axum::response::Response::builder()
                        .status(axum::http::StatusCode::INTERNAL_SERVER_ERROR)
                        .body(axum::body::Body::empty())
                    {
                        Ok(res) => Ok(res),
                        Err(_) => {
                            let mut res = axum::response::Response::new(axum::body::Body::empty());
                            *res.status_mut() = axum::http::StatusCode::INTERNAL_SERVER_ERROR;
                            Ok(res)
                        }
                    }
                }
                Err(join_err) => {
                    // I-2: If a panic occurred during the oneshot invocation, catch it and present the Self-Healing Console
                    let message = if join_err.is_panic() {
                        let panic_payload = join_err.into_panic();
                        if let Some(s) = panic_payload.downcast_ref::<&str>() {
                            s.to_string()
                        } else if let Some(s) = panic_payload.downcast_ref::<String>() {
                            s.clone()
                        } else {
                            "Unhandled application panic".to_string()
                        }
                    } else {
                        "Request task was cancelled or aborted".to_string()
                    };

                    let backtrace = std::backtrace::Backtrace::capture();
                    let html_content =
                        crate::error_console::render_console_html(&message, &backtrace).await;

                    match axum::response::Response::builder()
                        .status(axum::http::StatusCode::INTERNAL_SERVER_ERROR)
                        .header(axum::http::header::CONTENT_TYPE, "text/html; charset=utf-8")
                        .body(axum::body::Body::from(html_content))
                    {
                        Ok(res) => Ok(res),
                        Err(_) => {
                            let mut res = axum::response::Response::new(axum::body::Body::empty());
                            *res.status_mut() = axum::http::StatusCode::INTERNAL_SERVER_ERROR;
                            Ok(res)
                        }
                    }
                }
            }
        })
    }
}

fn load_dylib_router(
    lib_path: &str,
    is_dev: bool,
) -> Result<(axum::Router, libloading::Library), Box<dyn std::error::Error>> {
    let lib_extension = if cfg!(target_os = "windows") {
        "dll"
    } else if cfg!(target_os = "macos") {
        "dylib"
    } else {
        "so"
    };

    let full_lib_path = if lib_path.ends_with(".dll")
        || lib_path.ends_with(".so")
        || lib_path.ends_with(".dylib")
    {
        lib_path.to_string()
    } else {
        format!("{}.{}", lib_path, lib_extension)
    };

    let path_buf = std::path::Path::new(&full_lib_path);
    if !path_buf.exists() {
        return Err(format!("Dylib not found at: {}", full_lib_path).into());
    }

    let parent = path_buf.parent().unwrap_or(std::path::Path::new("."));
    let filename = path_buf
        .file_stem()
        .and_then(|s| s.to_str())
        .ok_or_else(|| {
            std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "Caminho da dylib inválido ou caracteres não UTF-8 detectados",
            )
        })?;

    // Clean up older active files that are no longer locked by any process
    let expected_prefix = format!("{}_active_", filename);
    if let Ok(entries) = std::fs::read_dir(parent) {
        for entry in entries.flatten() {
            let path = entry.path();
            if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
                if name.starts_with(&expected_prefix) && name.ends_with(lib_extension) {
                    let _ = std::fs::remove_file(path);
                }
            }
        }
    }

    // L-1: Use UUID v4 instead of nanosecond timestamp to guarantee filename uniqueness
    //       even on systems with low-resolution clocks.
    let unique_id = uuid::Uuid::new_v4().as_simple().to_string();
    let temp_filename = format!("{}_active_{}.{}", filename, unique_id, lib_extension);
    let temp_path = parent.join(temp_filename);

    // Copy the dylib file to prevent locking issues
    std::fs::copy(&full_lib_path, &temp_path)?;

    // SAFETY: The code below performs dynamic library loading and raw pointer extraction.
    // Invariant requirements for safety:
    //  - The dynamically loaded library must expose a symbol `rullst_router_init`
    //    with signature `unsafe extern "C" fn() -> *mut Router`.
    //  - The `rullst_router_init` function must allocate a `Box<Router>` and return
    //    the raw pointer produced by `Box::into_raw`. The caller here uses
    //    `Box::from_raw` to take ownership of that pointer; therefore the
    //    library MUST NOT keep or free that pointer after returning it.
    //  - The loaded library must be ABI-compatible with the host Router layout.
    //  - The `temp_path` copy must remain available on disk for the lifetime of
    //    any references into the loaded library. We keep the returned `Library`
    //    object to ensure the library remains mapped until dropped by the caller.
    //  - Calls into the plugin must be synchronized appropriately by the host if
    //    the plugin is not internally thread-safe.
    //
    // This block is `unsafe` because it relies on the above invariants; any
    // future changes to router ABI or plugin implementations must be reflected
    // here and documented. Review and audit this section when upgrading
    // `libloading`, `Router` types, or changing the plugin API.
    let lib = unsafe { libloading::Library::new(&temp_path)? };
    if let Err(e) = std::fs::remove_file(&temp_path) {
        #[cfg(not(target_os = "windows"))]
        eprintln!(
            "⚠️ Rullst: failed to remove temporary dylib file at {:?}: {}",
            temp_path, e
        );
        #[cfg(target_os = "windows")]
        {
            // On Windows, sharing violation (error code 32) is normal, so we only log other errors.
            if e.raw_os_error() != Some(32) {
                eprintln!(
                    "⚠️ Rullst: failed to remove temporary dylib file at {:?}: {}",
                    temp_path, e
                );
            }
        }
    }
    let init_fn: libloading::Symbol<unsafe extern "C" fn() -> *mut Router> =
        unsafe { lib.get(b"rullst_router_init")? };
    let router_ptr = unsafe { init_fn() };

    // Convert *mut Router back to Router box and extract it
    let rullst_router = unsafe { *Box::from_raw(router_ptr) };

    // Convert Rullst Router to Axum Router
    let mut axum_router = rullst_router.into_axum();

    // Serve static files from "static" directory if it exists
    if std::path::Path::new("static").exists() {
        axum_router = axum_router
            .nest_service(
                "/static",
                tower_http::services::ServeDir::new("static").precompressed_br(),
            )
            .layer(axum::middleware::from_fn(zstd_static_middleware));
    }

    // Attach development explain / console routes
    if is_dev {
        axum_router = axum_router
            .route(
                "/_rullst/explain",
                axum::routing::get(crate::error_console::handle_explain),
            )
            .route(
                "/_rullst/autofix",
                axum::routing::post(crate::error_console::handle_autofix),
            )
            .layer(axum::middleware::from_fn(
                crate::error_console::catch_panic_middleware,
            ));
    }

    Ok((axum_router, lib))
}

async fn zstd_static_middleware(
    mut req: axum::extract::Request,
    next: axum::middleware::Next,
) -> axum::response::Response {
    let path = req.uri().path().to_string();
    if path.starts_with("/static/") {
        if let Some(accept_encoding) = req.headers().get(axum::http::header::ACCEPT_ENCODING) {
            if let Ok(accept_str) = accept_encoding.to_str() {
                if accept_str.contains("zstd") {
                    let local_path_str = format!("{}.zst", &path[1..]);
                    if tokio::fs::metadata(&local_path_str)
                        .await
                        .map(|m| m.is_file())
                        .unwrap_or(false)
                    {
                        let original_ext = std::path::Path::new(&path)
                            .extension()
                            .and_then(|ext| ext.to_str())
                            .unwrap_or("")
                            .to_string();

                        let new_uri = format!("{}.zst", path);
                        if let Ok(uri) = new_uri.parse::<axum::http::Uri>() {
                            *req.uri_mut() = uri;

                            let mut response = next.run(req).await;

                            response.headers_mut().insert(
                                axum::http::header::CONTENT_ENCODING,
                                axum::http::header::HeaderValue::from_static("zstd"),
                            );

                            let mime_type = match original_ext.as_str() {
                                "html" => "text/html; charset=utf-8",
                                "css" => "text/css; charset=utf-8",
                                "js" => "application/javascript; charset=utf-8",
                                "json" => "application/json; charset=utf-8",
                                "svg" => "image/svg+xml",
                                "wasm" => "application/wasm",
                                "xml" => "application/xml; charset=utf-8",
                                "txt" => "text/plain; charset=utf-8",
                                _ => "",
                            };

                            if !mime_type.is_empty() {
                                if let Ok(val) =
                                    axum::http::header::HeaderValue::from_str(mime_type)
                                {
                                    response
                                        .headers_mut()
                                        .insert(axum::http::header::CONTENT_TYPE, val);
                                }
                            }

                            return response;
                        }
                    }
                }
            }
        }
    }

    next.run(req).await
}

// ─── Dependency Shielding cascades (Roadmap Milestone 8) ────────────────────
pub use axum::{
    body::{Body, Bytes},
    extract::{Extension, Form, Json, Path, Query, Request, State},
    http::{HeaderMap, HeaderValue, Method, StatusCode, Uri, header},
    middleware::{self, Next, from_fn},
    response::{Html, IntoResponse, Redirect, Response},
    routing::{delete, get, patch, post, put},
};

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use crate::Router;
    use crate::scheduler::Scheduler;

    #[test]
    fn test_server_builder() {
        let router = Router::new();
        let server = Server::new(router).with_db("sqlite://test.db");

        assert_eq!(server.db_url, Some("sqlite://test.db".to_string()));
        assert!(server.scheduler.is_none());
    }

    #[test]
    fn test_server_scheduler_attach() {
        let router = Router::new();
        let scheduler = Scheduler::new();
        let server = Server::new(router).schedule(scheduler);

        assert!(server.scheduler.is_some());
    }

    #[tokio::test]
    async fn test_server_resilience_attach() {
        let router = Router::new();
        let shield = crate::resilience::TrafficShield::new(
            crate::resilience::TrafficShieldConfig::new().with_db_probe(false),
        );
        let limiter = crate::resilience::RateLimiter::new(
            crate::resilience::RateLimitConfig::per_second(10.0),
        );
        let server = Server::new(router).shield(shield).rate_limit(limiter);

        assert!(server.shield.is_some());
        assert!(server.limiter.is_some());
    }
}