Skip to main content

luxid_core/
app.rs

1//! Application assembly and startup.
2
3use crate::adapter::RouteHandler;
4use crate::config::Config;
5use crate::container::{Container, Providers};
6use crate::error::Result;
7use crate::middleware::Middleware;
8use crate::router::{Method, RouteInfo, Router};
9
10const DEFAULT_ADDR: &str = "127.0.0.1:3000";
11
12pub struct App {
13    router: Router,
14    addr: String,
15    providers: Providers,
16    config: Config,
17}
18
19impl Default for App {
20    fn default() -> Self {
21        Self::new()
22    }
23}
24
25impl App {
26    pub fn new() -> Self {
27        Self {
28            router: Router::new(),
29            addr: default_addr(),
30            providers: Providers::new(),
31            // Environment only until told otherwise; `luxid new` generates an
32            // `app::build` that loads `luxid.toml` over it.
33            config: Config::from_env(),
34        }
35    }
36
37    #[must_use]
38    pub fn bind(mut self, addr: impl Into<String>) -> Self {
39        self.addr = addr.into();
40        self
41    }
42
43    /// Configuration available to every action as `ctx.config`.
44    #[must_use]
45    pub fn config(mut self, config: Config) -> Self {
46        self.config = config;
47        self
48    }
49
50    /// Service bindings for the application.
51    #[must_use]
52    pub fn providers(mut self, providers: Providers) -> Self {
53        self.providers = providers;
54        self
55    }
56
57    /// Middleware applied to every route, outermost first.
58    #[must_use]
59    pub fn middleware<M: Middleware>(mut self, middleware: M) -> Self {
60        self.router.middleware(middleware);
61        self
62    }
63
64    #[must_use]
65    pub fn routes(mut self, register: impl FnOnce(&mut Router)) -> Self {
66        register(&mut self.router);
67        self
68    }
69
70    /// The resolved routing table. Backs `luxid routes`, so an unexpected 404
71    /// is answerable without reading the source.
72    pub fn route_table(&self) -> Vec<RouteInfo> {
73        self.router.describe()
74    }
75
76    /// The OpenAPI 3.1 document for this application's routes.
77    pub fn openapi(&self, title: &str, version: &str) -> serde_json::Value {
78        crate::openapi::document(title, version, &self.route_table())
79    }
80
81    /// Build the service without binding a port, so tests exercise the same
82    /// routing, container and adapter code as production.
83    ///
84    /// This deliberately skips eager singleton resolution: a test that binds
85    /// only the services it needs should not have to satisfy the whole
86    /// application graph. Use [`App::try_into_service`] when you want that
87    /// validation.
88    pub fn into_service(self) -> salvo::Service {
89        salvo::Service::new(self.into_parts().0)
90    }
91
92    /// As [`App::into_service`], but validates the provider graph first.
93    pub fn try_into_service(self) -> Result<salvo::Service> {
94        let (router, services) = self.into_parts();
95        services.eager_init()?;
96
97        Ok(salvo::Service::new(router))
98    }
99
100    pub async fn run(self) -> Result<()> {
101        let addr = self.addr.clone();
102        let (router, services) = self.into_parts();
103
104        // Validate the graph before taking the port, so a misconfigured app
105        // fails at startup naming the type rather than 500-ing on first
106        // request.
107        services.eager_init()?;
108
109        let acceptor = {
110            use salvo::conn::Listener as _;
111            salvo::conn::TcpListener::new(addr.clone()).bind().await
112        };
113
114        println!("luxid listening on http://{addr}");
115        salvo::Server::new(acceptor).serve(router).await;
116
117        Ok(())
118    }
119
120    /// The router and container this app assembles into.
121    ///
122    /// The CLI needs the container to reach the database without starting a
123    /// server.
124    pub fn into_parts(self) -> (salvo::Router, Container) {
125        let services = self.providers.build();
126        let mut root = salvo::Router::new();
127
128        let flattened = self.router.flatten();
129
130        // Static mounts first: salvo matches in registration order, and a
131        // wildcard asset route must not shadow the application's own routes.
132        for mount in flattened.statics {
133            root = root.push(
134                salvo::Router::with_path(format!("{}/{{**path}}", mount.path))
135                    .get(salvo::serve_static::StaticDir::new([mount.dir]).auto_list(false)),
136            );
137        }
138
139        for route in flattened.routes {
140            let handler = RouteHandler::new(
141                route.middleware,
142                route.action,
143                services.clone(),
144                self.config.clone(),
145            );
146            let leaf = salvo::Router::with_path(&route.path);
147
148            let leaf = match route.method {
149                Method::Get => leaf.get(handler),
150                Method::Post => leaf.post(handler),
151                Method::Put => leaf.put(handler),
152                Method::Patch => leaf.patch(handler),
153                Method::Delete => leaf.delete(handler),
154                Method::Options => leaf.options(handler),
155            };
156
157            root = root.push(leaf);
158        }
159
160        (root, services)
161    }
162}
163
164/// `LUXID_ADDR` wins; otherwise `PORT` on all interfaces (the shape most
165/// platforms inject); otherwise localhost:3000.
166fn default_addr() -> String {
167    if let Ok(addr) = std::env::var("LUXID_ADDR") {
168        return addr;
169    }
170    if let Ok(port) = std::env::var("PORT") {
171        return format!("0.0.0.0:{port}");
172    }
173    DEFAULT_ADDR.to_owned()
174}