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    crate::banner::mark_process_start();
28    let env = Environment::from_env();
29    let config: Config =
30        match crate::app::discover_config(builder.project_root(), builder.embedded(), builder.toml_parser()) {
31            Ok(c) => c,
32            Err(e) => {
33                eprintln!("error: {e}");
34                std::process::exit(1);
35            }
36        };
37    match next_rust_core::env::EnvVars::load(&config.root, env, &config.env.public_prefix) {
38        Ok(vars) => vars.apply_to_process(),
39        Err(e) if env.is_dev() => eprintln!("warning: could not read .env files: {e}"),
40        Err(_) => {}
41    }
42    // Logging is configured when the app is built (see AppBuilder::build).
43
44    let args: Vec<String> = std::env::args().skip(1).collect();
45    let runtime = match tokio::runtime::Builder::new_multi_thread().enable_all().build() {
46        Ok(r) => r,
47        Err(e) => {
48            eprintln!("error: failed to start async runtime: {e}");
49            std::process::exit(1);
50        }
51    };
52    let app = match builder.config(config).environment(env).build() {
53        Ok(app) => app,
54        Err(e) => {
55            eprintln!("error: {e}");
56            std::process::exit(1);
57        }
58    };
59
60    if args.iter().any(|a| a == "--routes") {
61        for (kind, pattern, source) in app.route_table() {
62            println!("{kind:<5} {pattern:<40} {source}");
63        }
64        return;
65    }
66    if args.iter().any(|a| a == "--export") {
67        let result = runtime.block_on(app.export());
68        match result {
69            Ok(report) => {
70                println!("{}", serde_json::to_string(&report).unwrap_or_default());
71                return;
72            }
73            Err(e) => {
74                eprintln!("static generation failed:\n{e}");
75                std::process::exit(1);
76            }
77        }
78    }
79    if !env.is_dev() {
80        let warm = app.clone();
81        runtime.spawn(async move {
82            if let Err(e) = warm.prerender().await {
83                crate::log::error(&format!("pre-rendering static pages failed:\n{e}"));
84            }
85        });
86    }
87    if let Err(e) = runtime.block_on(app.serve()) {
88        eprintln!("error: {e}");
89        std::process::exit(1);
90    }
91}