Skip to main content

tdm_server_rust/runner/
mod.rs

1//! 启动时一次性任务 (Startup Runners)
2//!
3//! 对齐 Java Spring `CommandLineRunner`,在应用启动后、接受请求前执行。
4//!
5//! ## 执行顺序
6//!
7//! 1. [`schema_migration_runner::run`] — PostgreSQL 启动迁移
8//! 2. [`password_encrypt_runner::run`] — 明文密码批量 bcrypt 加密
9//! 3. [`test_member_seed_runner::run`] — 预置测试角色账号(含 Gum979)
10//! 4. [`dev_test_password_runner::run`] — dev/dev-h2 全表口令重置为 `123456`
11//!
12//! ## 幂等性
13//!
14//! 两个 runner 均为幂等操作:
15//! - 密码加密:跳过已加密的密码(以 `$2a$` 或 `$2b$` 开头)
16//! - 测试种子:检测账号是否存在,存在则跳过
17
18pub mod dev_test_password_runner;
19pub mod password_encrypt_runner;
20pub mod schema_migration_runner;
21pub mod test_member_seed_runner;
22
23use sqlx::PgPool;
24
25/// 执行所有启动任务
26///
27/// 在 `AppState::new()` 中数据库连接池建立后立即调用。
28/// 任一任务失败都会阻止应用启动。
29///
30/// # 参数
31///
32/// - `pool`: 数据库连接池
33/// - `profile`: 当前配置档(`dev` / `dev-h2` 会重置测试口令)
34///
35/// # Errors
36///
37/// 任一 runner 失败时返回错误,应用不会继续启动。
38pub async fn run_all(pool: &PgPool, profile: &str) -> anyhow::Result<()> {
39    schema_migration_runner::run(pool).await?;
40    password_encrypt_runner::run(pool).await?;
41    test_member_seed_runner::run(pool).await?;
42    if matches!(profile, "dev" | "dev-h2") {
43        dev_test_password_runner::run(pool).await?;
44    }
45    Ok(())
46}