1use 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
14pub 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
51pub struct App {
53 config: Config,
54}
55
56impl App {
57 pub fn new(config: Config) -> Self {
58 Self { config }
59 }
60
61 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 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
107pub fn iniciar_tracing() {
109 let _ = tracing_subscriber::fmt()
110 .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
111 .try_init();
112}
113
114fn 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
122pub 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
137pub 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 let app = App::new(Config::default());
184
185 let result = app
187 .intentar_servir(|_| async { Err::<Route, _>("the database is down") })
188 .await;
189
190 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 let client = TestClient::new(wrap(
200 &allowing("http://localhost:5173"),
201 Route::new().at("/api/x", poem::get(hello)),
202 ));
203
204 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 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 let client = TestClient::new(wrap(
221 &allowing("http://localhost:5173"),
222 Route::new().at("/api/x", poem::get(hello)),
223 ));
224
225 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 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 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 let live = client.get("/health").send().await;
250 let ready = client.get("/health/ready").send().await;
251
252 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 let client = TestClient::new(rutas(
261 OpenApiService::new((), "app", "1.0"),
262 &Config::default(),
263 siempre_disponible(),
264 ));
265
266 let response = client.get("/").send().await;
268
269 response.assert_status_is_ok();
271 response.assert_content_type("text/html; charset=utf-8");
272 }
273}