Skip to main content

next_rust_server/
runtime.rs

1//! Process entry point used by `next_rust::main!()`.
2
3use next_rust_core::{Config, Environment};
4
5use crate::app::{App, AppBuilder, Routes};
6
7/// Load `.env` files, configure logging and run the app.
8///
9/// Command-line flags understood by the generated binary:
10///
11/// * *(none)* – serve
12/// * `--export` – render every static page, print a JSON report and exit
13///   (writes nothing; used by `next-rust build` as a check)
14/// * `--routes` – print the compiled route table and exit
15pub fn run(routes: Routes) {
16    run_with(App::new(routes))
17}
18
19/// Like [`run`], with a customized builder:
20///
21/// ```ignore
22/// fn main() {
23///     next_rust::run_with(App::new(routes()).middleware(request_id()));
24/// }
25/// ```
26pub fn run_with(builder: AppBuilder) {
27    let env = Environment::from_env();
28    let config: Config = match crate::app::discover_config(builder.project_root(), builder.embedded()) {
29        Ok(c) => c,
30        Err(e) => {
31            eprintln!("error: {e}");
32            std::process::exit(1);
33        }
34    };
35    match next_rust_core::env::EnvVars::load(&config.root, env, &config.env.public_prefix) {
36        Ok(vars) => vars.apply_to_process(),
37        Err(e) if env.is_dev() => eprintln!("warning: could not read .env files: {e}"),
38        Err(_) => {}
39    }
40    // Logging is configured when the app is built (see AppBuilder::build).
41
42    let args: Vec<String> = std::env::args().skip(1).collect();
43    let runtime = match tokio::runtime::Builder::new_multi_thread().enable_all().build() {
44        Ok(r) => r,
45        Err(e) => {
46            eprintln!("error: failed to start async runtime: {e}");
47            std::process::exit(1);
48        }
49    };
50    let app = match builder.config(config).environment(env).build() {
51        Ok(app) => app,
52        Err(e) => {
53            eprintln!("error: {e}");
54            std::process::exit(1);
55        }
56    };
57
58    if args.iter().any(|a| a == "--routes") {
59        for (kind, pattern, source) in app.route_table() {
60            println!("{kind:<5} {pattern:<40} {source}");
61        }
62        return;
63    }
64    if args.iter().any(|a| a == "--export") {
65        let result = runtime.block_on(app.export());
66        match result {
67            Ok(report) => {
68                println!("{}", serde_json::to_string(&report).unwrap_or_default());
69                return;
70            }
71            Err(e) => {
72                eprintln!("static generation failed:\n{e}");
73                std::process::exit(1);
74            }
75        }
76    }
77    if !env.is_dev() {
78        let warm = app.clone();
79        runtime.spawn(async move {
80            if let Err(e) = warm.prerender().await {
81                crate::log::error(&format!("pre-rendering static pages failed:\n{e}"));
82            }
83        });
84    }
85    if let Err(e) = runtime.block_on(app.serve()) {
86        eprintln!("error: {e}");
87        std::process::exit(1);
88    }
89}