puerto_web/lib.rs
1//! The HTTP shell every Puerto project shares (ADR-0017): the server with graceful shutdown, the
2//! health probes, the configuration read from the environment, CORS, the error body and bearer
3//! auth.
4//!
5//! A generated project calls it; it never calls the project. `main.rs` is
6//!
7//! ```ignore
8//! #[tokio::main]
9//! async fn main() -> Result<(), puerto_web::Error> {
10//! let config = puerto_web::Config::from_env()?;
11//! puerto_web::App::new(config)
12//! .intentar_servir(api::generado::bootstrap::construir_app)
13//! .await
14//! }
15//! ```
16//!
17//! and `generado/bootstrap.rs` — over the `cableado` composition root — builds the routes with
18//! [`rutas`].
19
20pub mod app;
21pub mod auth;
22pub mod config;
23pub mod health;
24pub mod respuesta_error;
25
26pub use app::{App, rutas};
27pub use config::{Config, ErrorConfig};
28pub use health::SondaDisponibilidad;
29/// `#[requiere_rol("admin")]` on a handler that takes `auth: BearerAuth` — see [`auth`].
30pub use puerto_macros::requiere_rol;
31pub use respuesta_error::{IntoRespuestaError, RespuestaError};
32
33/// Why the application did not start or stopped serving.
34#[derive(thiserror::Error)]
35#[non_exhaustive]
36pub enum Error {
37 #[error(transparent)]
38 Config(#[from] ErrorConfig),
39 #[error("servidor: {0}")]
40 Servidor(#[from] std::io::Error),
41 /// What `build` answered instead of the routes (`App::intentar_servir`): a database that is down, a
42 /// variable that is missing. Its message is the whole report.
43 #[error("{0}")]
44 Arranque(String),
45}
46
47/// `main` returns this error, and Rust prints what `main` returns with `Debug`: the message is what
48/// the person starting the server needs to read.
49impl std::fmt::Debug for Error {
50 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51 std::fmt::Display::fmt(self, f)
52 }
53}
54
55#[cfg(test)]
56mod tests {
57 use super::*;
58
59 #[test]
60 fn should_print_the_readable_message_when_main_returns_the_error() {
61 // Arrange
62 let error = Error::from(Config::from_variables(|_| Some("abc".into())).unwrap_err());
63
64 // Act
65 let printed = format!("{error:?}");
66
67 // Assert
68 assert_eq!(
69 printed,
70 "SERVICE_PORT=\"abc\" no es válida: se esperaba un número de puerto (0-65535)"
71 );
72 }
73}