♻️ (pagetop): initialize() devuelve Result sin panic
`Extension::initialize()` devuelve `Result<(), BoxError>`; `BoxError` es un nuevo alias. Si una extensión falla, `prepare()` registra el error con sus causas, vuelca las trazas, lo repite en stderr y termina con código 1, sin panic! ni cambiar su firma.
This commit is contained in:
parent
728a5c83dc
commit
d3a9be7550
14 changed files with 199 additions and 110 deletions
|
|
@ -24,5 +24,6 @@ pagetop.workspace = true
|
|||
sea-orm.workspace = true
|
||||
sea-schema.workspace = true
|
||||
serde.workspace = true
|
||||
thiserror.workspace = true
|
||||
tokio.workspace = true
|
||||
url.workspace = true
|
||||
|
|
|
|||
|
|
@ -78,8 +78,9 @@ impl Extension for MyApp {
|
|||
]
|
||||
}
|
||||
|
||||
async fn initialize(&self) {
|
||||
install_migrations!(m20240101_000001_create_users);
|
||||
async fn initialize(&self) -> Result<(), BoxError> {
|
||||
install_migrations!(m20240101_000001_create_users)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -79,8 +79,9 @@ impl Extension for MyApp {
|
|||
]
|
||||
}
|
||||
|
||||
async fn initialize(&self) {
|
||||
install_migrations!(m20240101_000001_create_users);
|
||||
async fn initialize(&self) -> Result<(), BoxError> {
|
||||
install_migrations!(m20240101_000001_create_users)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -176,7 +177,7 @@ use pagetop::prelude::*;
|
|||
|
||||
include_locales!(LOCALES_SEAORM);
|
||||
|
||||
use sea_orm::{ConnectOptions, Database, DatabaseConnection};
|
||||
use sea_orm::{ConnectOptions, Database, DatabaseConnection, DbErr};
|
||||
use url::Url;
|
||||
|
||||
use std::sync::OnceLock;
|
||||
|
|
@ -189,6 +190,30 @@ pub mod migration;
|
|||
|
||||
static DBCONN: OnceLock<DatabaseConnection> = OnceLock::new();
|
||||
|
||||
/// Errores que detienen el arranque de la aplicación al conectar con la base de datos o al aplicar
|
||||
/// las migraciones.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum DbError {
|
||||
/// No se ha configurado el motor de base de datos (`database.db_type`).
|
||||
#[error("database.db_type is not configured: use \"mysql\", \"postgres\" or \"sqlite\"")]
|
||||
TypeNotConfigured,
|
||||
/// No se puede construir la URL de conexión con los ajustes de la sección `[database]`.
|
||||
#[error("invalid database URL: check db_host and db_name in config")]
|
||||
InvalidUrl,
|
||||
/// No se puede conectar con la base de datos.
|
||||
#[error("cannot connect to database \"{name}\"")]
|
||||
Connection {
|
||||
/// Nombre de la base de datos (`database.db_name`).
|
||||
name: String,
|
||||
/// Error devuelto al conectar.
|
||||
#[source]
|
||||
source: DbErr,
|
||||
},
|
||||
/// Una migración, o su reversión, ha fallado.
|
||||
#[error("migration failed")]
|
||||
Migration(#[source] DbErr),
|
||||
}
|
||||
|
||||
/// Implementa la extensión.
|
||||
pub struct SeaORM;
|
||||
|
||||
|
|
@ -206,57 +231,60 @@ impl Extension for SeaORM {
|
|||
Some(&config::SETTINGS)
|
||||
}
|
||||
|
||||
async fn initialize(&self) {
|
||||
trace::info!(
|
||||
"Connecting to database \"{}\" using a pool of {} connections",
|
||||
&config::SETTINGS.db_name,
|
||||
&config::SETTINGS.max_pool_size
|
||||
);
|
||||
|
||||
let db_uri: String = match config::SETTINGS.db_type {
|
||||
config::DbType::Unset => panic!(
|
||||
"database.db_type is not configured: use \"mysql\", \"postgres\" or \"sqlite\""
|
||||
),
|
||||
config::DbType::Mysql | config::DbType::Postgres => {
|
||||
let scheme = if matches!(config::SETTINGS.db_type, config::DbType::Mysql) {
|
||||
"mysql"
|
||||
} else {
|
||||
"postgres"
|
||||
};
|
||||
let mut tmp_uri = Url::parse(&format!(
|
||||
"{}://{}/{}",
|
||||
scheme,
|
||||
&config::SETTINGS.db_host,
|
||||
&config::SETTINGS.db_name
|
||||
))
|
||||
.expect("Invalid database URL: check db_host and db_name in config");
|
||||
tmp_uri
|
||||
.set_username(config::SETTINGS.db_user.as_str())
|
||||
.expect("Failed to set db_user in connection URL");
|
||||
tmp_uri
|
||||
// https://github.com/launchbadge/sqlx/issues/1624
|
||||
.set_password(Some(config::SETTINGS.db_pass.as_str()))
|
||||
.expect("Failed to set db_pass in connection URL");
|
||||
if let Some(port) = config::SETTINGS.db_port {
|
||||
tmp_uri
|
||||
.set_port(Some(port))
|
||||
.expect("Failed to set db_port in connection URL");
|
||||
}
|
||||
tmp_uri.to_string()
|
||||
}
|
||||
config::DbType::Sqlite => {
|
||||
format!("sqlite://{}", &config::SETTINGS.db_name)
|
||||
}
|
||||
};
|
||||
|
||||
let conn = Database::connect::<ConnectOptions>({
|
||||
let mut db_opt = ConnectOptions::new(db_uri);
|
||||
db_opt.max_connections(config::SETTINGS.max_pool_size);
|
||||
db_opt
|
||||
})
|
||||
.await
|
||||
.expect("Failed to connect to database");
|
||||
|
||||
DBCONN.set(conn).expect("DBCONN already initialized");
|
||||
async fn initialize(&self) -> Result<(), BoxError> {
|
||||
// Preparar la aplicación varias veces en el mismo proceso (las pruebas lo hacen) reutiliza
|
||||
// la conexión ya abierta.
|
||||
if DBCONN.get().is_none() {
|
||||
let conn = connect().await?;
|
||||
// Si otra preparación simultánea se adelanta, se queda la suya y se descarta ésta.
|
||||
let _ = DBCONN.set(conn);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// Abre el pool de conexiones con los ajustes de la sección `[database]`.
|
||||
async fn connect() -> Result<DatabaseConnection, DbError> {
|
||||
let settings = &*config::SETTINGS;
|
||||
let db_uri: String = match settings.db_type {
|
||||
config::DbType::Unset => return Err(DbError::TypeNotConfigured),
|
||||
config::DbType::Mysql | config::DbType::Postgres => {
|
||||
let scheme = if matches!(settings.db_type, config::DbType::Mysql) {
|
||||
"mysql"
|
||||
} else {
|
||||
"postgres"
|
||||
};
|
||||
let mut uri = Url::parse(&format!(
|
||||
"{}://{}/{}",
|
||||
scheme, settings.db_host, settings.db_name
|
||||
))
|
||||
.map_err(|_| DbError::InvalidUrl)?;
|
||||
// Sin servidor en la URL (p. ej. con `db_host` vacío) no se pueden fijar el usuario,
|
||||
// la contraseña ni el puerto.
|
||||
uri.set_username(&settings.db_user)
|
||||
.map_err(|()| DbError::InvalidUrl)?;
|
||||
// https://github.com/launchbadge/sqlx/issues/1624
|
||||
uri.set_password(Some(&settings.db_pass))
|
||||
.map_err(|()| DbError::InvalidUrl)?;
|
||||
if let Some(port) = settings.db_port {
|
||||
uri.set_port(Some(port)).map_err(|()| DbError::InvalidUrl)?;
|
||||
}
|
||||
uri.to_string()
|
||||
}
|
||||
config::DbType::Sqlite => format!("sqlite://{}", settings.db_name),
|
||||
};
|
||||
|
||||
trace::info!(
|
||||
"Connecting to database \"{}\" using a pool of {} connections",
|
||||
settings.db_name,
|
||||
settings.max_pool_size
|
||||
);
|
||||
let mut options = ConnectOptions::new(db_uri);
|
||||
options.max_connections(settings.max_pool_size);
|
||||
Database::connect(options)
|
||||
.await
|
||||
.map_err(|source| DbError::Connection {
|
||||
name: settings.db_name.clone(),
|
||||
source,
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -162,6 +162,8 @@ pub use sea_orm::sea_query::*;
|
|||
|
||||
use pagetop::core::TypeInfo;
|
||||
|
||||
use crate::DbError;
|
||||
|
||||
impl<M: MigrationTrait> MigrationName for M {
|
||||
fn name(&self) -> &str {
|
||||
// Extrae el módulo contenedor, descartando el segmento final "Migration".
|
||||
|
|
@ -181,30 +183,27 @@ pub type MigrationItem = Box<dyn MigrationTrait>;
|
|||
pub trait MigratorBase {
|
||||
/// Ejecuta las migraciones pendientes en orden ascendente.
|
||||
///
|
||||
/// Provoca un `panic!` si alguna migración falla, evitando que la aplicación arranque con un
|
||||
/// esquema de base de datos inconsistente.
|
||||
async fn run_up();
|
||||
/// Devuelve [`DbError::Migration`] si alguna migración falla. Propagado desde
|
||||
/// [`Extension::initialize()`](pagetop::core::extension::Extension::initialize), detiene el
|
||||
/// arranque y evita que la aplicación funcione con un esquema de base de datos inconsistente.
|
||||
async fn run_up() -> Result<(), DbError>;
|
||||
|
||||
/// Revierte todas las migraciones en orden descendente.
|
||||
///
|
||||
/// Provoca un `panic!` si alguna reversión falla.
|
||||
async fn run_down();
|
||||
/// Devuelve [`DbError::Migration`] si alguna reversión falla.
|
||||
async fn run_down() -> Result<(), DbError>;
|
||||
}
|
||||
|
||||
#[pagetop::async_trait]
|
||||
impl<M: MigratorTrait> MigratorBase for M {
|
||||
async fn run_up() {
|
||||
async fn run_up() -> Result<(), DbError> {
|
||||
let conn = SchemaManagerConnection::Connection(super::db::dbconn());
|
||||
if let Err(e) = Self::up(conn, None).await {
|
||||
panic!("Migration upgrade failed: {e}");
|
||||
}
|
||||
Self::up(conn, None).await.map_err(DbError::Migration)
|
||||
}
|
||||
|
||||
async fn run_down() {
|
||||
async fn run_down() -> Result<(), DbError> {
|
||||
let conn = SchemaManagerConnection::Connection(super::db::dbconn());
|
||||
if let Err(e) = Self::down(conn, None).await {
|
||||
panic!("Migration downgrade failed: {e}");
|
||||
}
|
||||
Self::down(conn, None).await.map_err(DbError::Migration)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -214,6 +213,9 @@ impl<M: MigratorTrait> MigratorBase for M {
|
|||
/// registrados en la tabla `seaql_migrations`. Se invoca habitualmente desde
|
||||
/// [`Extension::initialize`](pagetop::core::extension::Extension::initialize).
|
||||
///
|
||||
/// Devuelve `Result<(), DbError>`: con `?`, una migración que falla ([`DbError::Migration`])
|
||||
/// detiene el arranque de la aplicación.
|
||||
///
|
||||
/// **Requisito:** cada módulo de migración debe declararse como submódulo público bajo un módulo
|
||||
/// `migration` accesible desde el punto de llamada, y exportar `pub struct Migration` que
|
||||
/// implemente [`MigrationTrait`]. El macro genera rutas de la forma
|
||||
|
|
@ -231,11 +233,12 @@ impl<M: MigratorTrait> MigratorBase for M {
|
|||
///
|
||||
/// #[async_trait]
|
||||
/// impl Extension for MyExt {
|
||||
/// async fn initialize(&self) {
|
||||
/// async fn initialize(&self) -> Result<(), BoxError> {
|
||||
/// install_migrations!(
|
||||
/// m20240101_000001_create_users,
|
||||
/// m20240115_000002_add_email_index,
|
||||
/// );
|
||||
/// )?;
|
||||
/// Ok(())
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
|
|
@ -254,31 +257,31 @@ macro_rules! install_migrations {
|
|||
m
|
||||
}
|
||||
}
|
||||
Migrator::run_up().await;
|
||||
Migrator::run_up().await
|
||||
}};
|
||||
}
|
||||
|
||||
/// Revierte las migraciones de una extensión en orden inverso al de su aplicación.
|
||||
///
|
||||
/// Ejecuta el método `down` de cada migración indicada. Si el método `down` de alguna migración
|
||||
/// devuelve un error, provoca un `panic!`. Complementario a
|
||||
/// [`install_migrations!`](crate::install_migrations).
|
||||
/// Ejecuta el método `down` de cada migración indicada y devuelve `Result<(), DbError>`. Si el
|
||||
/// método `down` de alguna migración devuelve un error, devuelve [`DbError::Migration`].
|
||||
/// Complementario a [`install_migrations!`](crate::install_migrations).
|
||||
///
|
||||
/// **Requisito:** los módulos de migración deben declararse como en
|
||||
/// [`install_migrations!`](crate::install_migrations). Todos los módulos indicados **deben
|
||||
/// implementar `down`**; la implementación por defecto devuelve error, lo que provoca un pánico en
|
||||
/// `run_down`.
|
||||
/// implementar `down`**; la implementación por defecto devuelve un error.
|
||||
///
|
||||
/// En `src/lib.rs`:
|
||||
/// ```rust,ignore
|
||||
/// #[async_trait]
|
||||
/// impl Extension for MyExt {
|
||||
/// async fn uninitialize(&self) {
|
||||
/// uninstall_migrations!(
|
||||
/// m20240101_000001_create_users,
|
||||
/// m20240115_000002_add_email_index,
|
||||
/// );
|
||||
/// }
|
||||
/// use pagetop_seaorm::DbError;
|
||||
///
|
||||
/// mod migration;
|
||||
///
|
||||
/// async fn reset_schema() -> Result<(), DbError> {
|
||||
/// uninstall_migrations!(
|
||||
/// m20240101_000001_create_users,
|
||||
/// m20240115_000002_add_email_index,
|
||||
/// )
|
||||
/// }
|
||||
/// ```
|
||||
#[macro_export]
|
||||
|
|
@ -296,6 +299,6 @@ macro_rules! uninstall_migrations {
|
|||
m
|
||||
}
|
||||
}
|
||||
Migrator::run_down().await;
|
||||
Migrator::run_down().await
|
||||
}};
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue