//! 已接受任务在执行前撤权;核对真实物理队列和业务行,不用延时猜测执行结果。 use super::*; use dever_runtime::{ auth::tenant::Backend, database::{Database, Error, Parameter, Sql, config::Config}, task, }; pub(super) fn exercise( root: &Path, binary: &Path, settings: &Path, port: u16, headers: [&str; 3], binding: &str, command: impl Fn(&str, Option<&str>) -> std::process::Output, ) { let value: serde_json::Value = serde_json::from_slice(&fs::read(settings).unwrap()).unwrap(); let database: Config = serde_json::from_value(value["database"][binding].clone()).unwrap(); let component = |enabled| { success(command( "dever.tenant.component", Some(&serde_json::json!({"tenant":1,"component":"demo","enabled":enabled}).to_string()), )); }; let count = "/demo/service/front/main/count"; let submit = "/demo/service/front/main/submit"; let [first, second, third] = headers; let server = Server::mode(binary, settings, port, "all"); assert_eq!( server .call("POST", submit, r#"{"title":"job-one"}"#, first) .0, 200 ); let until = Instant::now() + Duration::from_secs(5); while server.call("GET", count, "", first).1["data"] != 2 { assert!(Instant::now() < until, "tenant Job did not complete"); std::thread::sleep(Duration::from_millis(10)); } assert_eq!(server.call("GET", count, "", second).1["data"], 0); // worker 启动后再准备第三个租户;池上限不能导致每租户常驻 worker。 success(command("dever.tenant.migrate", Some(r#"{"tenant":3}"#))); success(command( "dever.auth.owner", Some(r#"{"site":"front","user_id":1,"tenant":3}"#), )); success(command( "dever.tenant.component", Some(r#"{"tenant":3,"component":"demo","enabled":true}"#), )); assert_eq!( server .call("POST", submit, r#"{"title":"job-three"}"#, third) .0, 200 ); let until = Instant::now() + Duration::from_secs(5); while server.call("GET", count, "", third).1["data"] != 1 { assert!(Instant::now() < until, "worker did not discover new tenant"); std::thread::sleep(Duration::from_millis(10)); } assert_eq!(server.call("GET", count, "", second).1["data"], 0); server.stop(); // API 单独运行,确保撤权发生在接受之后、Worker 领取之前。 let server = Server::start(binary, settings, port); let (status, blocked) = server.call( "POST", submit, r#"{"title":"must-not-write-after-disable"}"#, first, ); assert_eq!(status, 200, "{blocked}"); component(false); assert_eq!(server.call("GET", count, "", first).0, 403); let (status, other) = server.call( "POST", submit, r#"{"title":"other-tenant-still-works"}"#, third, ); assert_eq!(status, 200, "{other}"); server.stop(); let server = Server::mode(binary, settings, port, "all"); assert_jobs( root, &database, &[ (1, blocked["data"].as_str().unwrap(), "blocked", 2), (3, other["data"].as_str().unwrap(), "completed", 2), ], ); assert_eq!(server.call("GET", count, "", first).0, 403); assert_eq!(server.call("GET", count, "", second).1["data"], 0); assert_eq!(server.call("GET", count, "", third).1["data"], 2); component(true); assert_eq!(server.call("GET", count, "", first).1["data"], 2); let (status, recovered) = server.call("POST", submit, r#"{"title":"new-job-after-enable"}"#, first); assert_eq!(status, 200, "{recovered}"); // 恢复只能允许新任务,不能重新执行已经 blocked 的旧任务。 assert_jobs( root, &database, &[ (1, recovered["data"].as_str().unwrap(), "completed", 3), (1, blocked["data"].as_str().unwrap(), "blocked", 3), ], ); assert_eq!(server.call("GET", count, "", first).1["data"], 3); assert_eq!(server.call("GET", count, "", third).1["data"], 2); server.stop(); } fn assert_jobs(root: &Path, config: &Config, expected: &[(i64, &str, &str, i64)]) { task::run(true, 8, async |scope| { // 测试直接读取已准备的物理库作独立断言;位置和驱动配置沿用正式入口。 let backend = config.tenant_backend(root, scope, false, &[config]).await?; let until = Instant::now() + Duration::from_secs(5); for &(tenant, id, state, rows) in expected { let database = physical_database(&backend, tenant).await?; let mut executor = database.acquire().await?; loop { let actual = executor .query_one( scope, Sql::same("SELECT state FROM _dever_job WHERE id=$1"), vec![Parameter::Text(id.into())], |row| row.get::(0), ) .await?; if actual.as_deref() == Some(state) { break; } assert!( Instant::now() < until, "tenant {tenant} Job {id}: {actual:?}, expected {state}" ); tokio::time::sleep(Duration::from_millis(10)).await; } let actual = executor .query_one( scope, Sql::same("SELECT COUNT(*) FROM demo_service"), vec![], |row| row.get::(0), ) .await? .unwrap(); assert_eq!(actual, rows, "tenant {tenant} persisted rows"); } Ok::<_, Error>(()) }) .unwrap() .unwrap(); } /// 直接打开已准备的物理库,独立核对落盘;共用正式配置解析出的路径和驱动参数。 pub(super) async fn physical_database(backend: &Backend, tenant: i64) -> Result { match backend { Backend::Sqlite { directory, options, cache_size_kib, } => { Database::sqlite( &directory.join(format!("{tenant}.sqlite")), false, *options, *cache_size_kib, ) .await } Backend::Postgres { config, tls, prefix, options, } => { let mut config = config.as_ref().clone(); config.dbname(format!("{prefix}_{tenant}")); Database::postgres(config, tls.clone(), *options).await } } }