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` – pre-render static pages into the build output and exit
13/// * `--routes` – print the compiled route table and exit
14pub fn run(routes: Routes) {
15    run_with(App::new(routes))
16}
17
18/// Like [`run`], with a customized builder:
19///
20/// ```ignore
21/// fn main() {
22///     next_rust::run_with(App::new(routes()).middleware(request_id()));
23/// }
24/// ```
25pub fn run_with(builder: AppBuilder) {
26    let env = Environment::from_env();
27    let config: Config = match crate::app::discover_config(builder.project_root()) {
28        Ok(c) => c,
29        Err(e) => {
30            eprintln!("error: {e}");
31            std::process::exit(1);
32        }
33    };
34    match next_rust_core::env::EnvVars::load(&config.root, env, &config.env.public_prefix) {
35        Ok(vars) => vars.apply_to_process(),
36        Err(e) if env.is_dev() => eprintln!("warning: could not read .env files: {e}"),
37        Err(_) => {}
38    }
39    // Logging is configured when the app is built (see AppBuilder::build).
40
41    let args: Vec<String> = std::env::args().skip(1).collect();
42    let runtime = match tokio::runtime::Builder::new_multi_thread().enable_all().build() {
43        Ok(r) => r,
44        Err(e) => {
45            eprintln!("error: failed to start async runtime: {e}");
46            std::process::exit(1);
47        }
48    };
49    let app = match builder.config(config).environment(env).build() {
50        Ok(app) => app,
51        Err(e) => {
52            eprintln!("error: {e}");
53            std::process::exit(1);
54        }
55    };
56
57    if args.iter().any(|a| a == "--routes") {
58        for (kind, pattern, source) in app.route_table() {
59            println!("{kind:<5} {pattern:<40} {source}");
60        }
61        return;
62    }
63    if args.iter().any(|a| a == "--export") {
64        let result = runtime.block_on(app.export());
65        match result {
66            Ok(report) => {
67                println!("{}", serde_json::to_string(&report).unwrap_or_default());
68                return;
69            }
70            Err(e) => {
71                eprintln!("static generation failed:\n{e}");
72                std::process::exit(1);
73            }
74        }
75    }
76    if let Err(e) = runtime.block_on(app.serve()) {
77        eprintln!("error: {e}");
78        std::process::exit(1);
79    }
80}