Skip to main content

puerto_web/
app.rs

1//! The server: what `main.rs` starts and `bootstrap.rs` builds the routes for.
2
3use std::convert::Infallible;
4use std::fmt::Display;
5use std::time::Duration;
6
7use poem::{
8    Endpoint, EndpointExt, IntoEndpoint, Route, Server, listener::TcpListener, middleware::Tracing,
9};
10use poem_openapi::{OpenApi, OpenApiService};
11
12use crate::{Config, Error, health, health::SondaDisponibilidad};
13
14/// How long in-flight requests get to finish once a shutdown signal arrives. Keep it below the
15/// orchestrator's kill timeout (`docker stop` waits 10s by default) so requests drain instead of
16/// being cut.
17pub const PLAZO_APAGADO: Duration = Duration::from_secs(8);
18
19const BANNER: &str = r#"
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    P  U  E  R  T  O"#;
50
51/// The running application: tracing, the banner, the listener, CORS and graceful shutdown.
52pub struct App {
53    config: Config,
54}
55
56impl App {
57    pub fn new(config: Config) -> Self {
58        Self { config }
59    }
60
61    /// Sets up tracing (`RUST_LOG`), prints the banner, builds the routes with `build` and serves
62    /// them on `SERVICE_PORT` until Ctrl-C or SIGTERM, then drains in-flight requests for
63    /// [`PLAZO_APAGADO`]. For a `build` that cannot fail; see [`App::intentar_servir`].
64    pub async fn servir<F, Fut, E>(self, build: F) -> Result<(), Error>
65    where
66        F: FnOnce(Config) -> Fut,
67        Fut: Future<Output = E>,
68        E: IntoEndpoint + 'static,
69        E::Endpoint: 'static,
70    {
71        self.intentar_servir(|config| async move { Ok::<_, Infallible>(build(config).await) })
72            .await
73    }
74
75    /// [`App::servir`] with a `build` that can fail — the project's
76    /// `api::generado::bootstrap::construir_app`, which connects to the database. Its error is logged and
77    /// returned as [`Error::Arranque`]: `main` prints it and exits 1, nothing is bound.
78    pub async fn intentar_servir<F, Fut, E, X>(self, build: F) -> Result<(), Error>
79    where
80        F: FnOnce(Config) -> Fut,
81        Fut: Future<Output = Result<E, X>>,
82        X: Display,
83        E: IntoEndpoint + 'static,
84        E::Endpoint: 'static,
85    {
86        iniciar_tracing();
87
88        if self.config.banner() {
89            println!("{BANNER}");
90            println!("    puerto v{}\n", env!("CARGO_PKG_VERSION"));
91        }
92
93        let puerto = self.config.puerto();
94        let built = build(self.config.clone()).await.map_err(|e| {
95            let mensaje = e.to_string();
96            tracing::error!(error = %mensaje, "el arranque falló");
97            Error::Arranque(mensaje)
98        })?;
99        let endpoint = wrap(&self.config, built);
100        Server::new(TcpListener::bind(format!("0.0.0.0:{puerto}")))
101            .run_with_graceful_shutdown(endpoint, senal_apagado(), Some(PLAZO_APAGADO))
102            .await?;
103        Ok(())
104    }
105}
106
107/// Logs to stdout, filtered by `RUST_LOG`. A subscriber the project installed itself wins.
108pub fn iniciar_tracing() {
109    let _ = tracing_subscriber::fmt()
110        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
111        .try_init();
112}
113
114/// What every request goes through, outermost last: request tracing, then CORS.
115fn wrap<E: IntoEndpoint>(config: &Config, endpoint: E) -> impl Endpoint + use<E>
116where
117    E::Endpoint: 'static,
118{
119    endpoint.into_endpoint().with(Tracing).with(config.cors())
120}
121
122/// The routes every project serves: its API under `/api`, the Swagger UI at `/`, and the health
123/// probes at `/health` and `/health/ready`. `api` is built by the project, which knows its own name
124/// and version.
125pub fn rutas<T: OpenApi + 'static>(
126    api: OpenApiService<T, ()>,
127    config: &Config,
128    ready: SondaDisponibilidad,
129) -> Route {
130    let api = api.server(format!("http://localhost:{}/api", config.puerto()));
131    let ui = api.swagger_ui();
132    health::montar(Route::new(), ready)
133        .nest("/api", api)
134        .nest("/", ui)
135}
136
137/// Resolves on Ctrl-C or SIGTERM — what `docker stop` and Kubernetes send. The listener then stops
138/// accepting and in-flight requests get `PLAZO_APAGADO` to finish. The worker
139/// (`puerto-events`) drains its loops on the same signal.
140pub async fn senal_apagado() {
141    let ctrl_c = async {
142        let _ = tokio::signal::ctrl_c().await;
143    };
144
145    #[cfg(unix)]
146    let terminate = async {
147        match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
148            Ok(mut signal) => {
149                signal.recv().await;
150            }
151            Err(_) => std::future::pending::<()>().await,
152        }
153    };
154    #[cfg(not(unix))]
155    let terminate = std::future::pending::<()>();
156
157    tokio::select! {
158        _ = ctrl_c => {},
159        _ = terminate => {},
160    }
161    tracing::info!("señal de apagado recibida, vaciando");
162}
163
164#[cfg(test)]
165mod tests {
166    use poem::{handler, http::StatusCode, test::TestClient};
167
168    use super::*;
169    use crate::health::{siempre_disponible, sondear};
170
171    #[handler]
172    fn hello() -> &'static str {
173        "hello"
174    }
175
176    fn allowing(origin: &str) -> Config {
177        Config::default().con_origenes_cors_permitidos(vec![origin.to_string()])
178    }
179
180    #[tokio::test]
181    async fn should_stop_with_the_build_error_when_the_app_cannot_be_built() {
182        // Arrange
183        let app = App::new(Config::default());
184
185        // Act
186        let result = app
187            .intentar_servir(|_| async { Err::<Route, _>("the database is down") })
188            .await;
189
190        // Assert: `main` prints the error with `Debug` and exits 1.
191        let error = result.unwrap_err();
192        assert!(matches!(error, Error::Arranque(_)), "{error:?}");
193        assert_eq!(format!("{error:?}"), "the database is down");
194    }
195
196    #[tokio::test]
197    async fn should_allow_a_preflight_when_the_origin_is_configured() {
198        // Arrange
199        let client = TestClient::new(wrap(
200            &allowing("http://localhost:5173"),
201            Route::new().at("/api/x", poem::get(hello)),
202        ));
203
204        // Act
205        let response = client
206            .options("/api/x")
207            .header("Origin", "http://localhost:5173")
208            .header("Access-Control-Request-Method", "GET")
209            .send()
210            .await;
211
212        // Assert
213        response.assert_status_is_ok();
214        response.assert_header("access-control-allow-origin", "http://localhost:5173");
215    }
216
217    #[tokio::test]
218    async fn should_refuse_a_preflight_when_the_origin_is_not_configured() {
219        // Arrange
220        let client = TestClient::new(wrap(
221            &allowing("http://localhost:5173"),
222            Route::new().at("/api/x", poem::get(hello)),
223        ));
224
225        // Act
226        let response = client
227            .options("/api/x")
228            .header("Origin", "https://evil.example.com")
229            .header("Access-Control-Request-Method", "GET")
230            .send()
231            .await;
232
233        // Assert
234        response.assert_status(StatusCode::FORBIDDEN);
235        response.assert_header_is_not_exist("access-control-allow-origin");
236    }
237
238    #[tokio::test]
239    async fn should_serve_the_health_probes_next_to_the_api() {
240        // Arrange
241        let rutas = rutas(
242            OpenApiService::new((), "app", "1.0"),
243            &Config::default(),
244            sondear(|| async { false }),
245        );
246        let client = TestClient::new(rutas);
247
248        // Act
249        let live = client.get("/health").send().await;
250        let ready = client.get("/health/ready").send().await;
251
252        // Assert
253        live.assert_status_is_ok();
254        ready.assert_status(StatusCode::SERVICE_UNAVAILABLE);
255    }
256
257    #[tokio::test]
258    async fn should_serve_the_swagger_ui_at_the_root() {
259        // Arrange
260        let client = TestClient::new(rutas(
261            OpenApiService::new((), "app", "1.0"),
262            &Config::default(),
263            siempre_disponible(),
264        ));
265
266        // Act
267        let response = client.get("/").send().await;
268
269        // Assert
270        response.assert_status_is_ok();
271        response.assert_content_type("text/html; charset=utf-8");
272    }
273}