//! 同一真实租户项目的并发负载;只在隔离测试目录准备数据,不替换 HTTP、权限或 Job。 use super::*; use dever_runtime::{ database::{Error, Parameter, Sql, config::Config as DatabaseConfig}, task, }; use std::sync::Barrier; use std::sync::atomic::{AtomicBool, Ordering}; mod cache; mod metrics; #[derive(Clone, Copy, serde::Serialize)] pub(super) struct Config { pub tenants: usize, rows: i64, clients: usize, requests: usize, pub seconds: u64, pub warmup_seconds: u64, pub fixed_resources: bool, pub evaluate_slo: bool, pub http_connections: usize, pub replica: bool, } impl Config { pub fn smoke() -> Self { Self { tenants: 4, rows: 32, clients: 8, requests: 32, seconds: 0, warmup_seconds: 0, fixed_resources: false, evaluate_slo: false, http_connections: 128, replica: false, } } pub fn replica_soak() -> Self { Self { replica: true, http_connections: 4, ..Self::large() } } pub fn replica_probe() -> Self { Self { seconds: 120, warmup_seconds: 30, evaluate_slo: false, ..Self::replica_soak() } } pub fn large() -> Self { Self { tenants: 32, rows: 32768, clients: 128, requests: usize::MAX, seconds: 3600, warmup_seconds: 60, fixed_resources: true, evaluate_slo: true, http_connections: 8, replica: false, } } pub fn capacity() -> Self { Self { requests: 32, seconds: 0, warmup_seconds: 0, evaluate_slo: false, ..Self::large() } } pub fn burst() -> Self { Self { requests: 1024, ..Self::capacity() } } pub fn contention() -> Self { Self { seconds: 120, requests: usize::MAX, http_connections: 128, ..Self::capacity() } } } #[test] #[ignore = "bounded allocation diagnostic with the same 512 KiB connection cache as the one-hour load"] fn bounded_cache_capacity() { exercise( "api-tenant-cache-capacity", serde_json::json!({"type":"sqlite","path":"data/control.db","tenant_directory":"data/tenants","max_connections":2,"cache_size_kib":512}), Run::Load(Config::capacity()), ); } #[test] #[ignore = "two-minute diagnostic using the existing HTTP connection bound, same workload and resources"] fn bounded_contention() { let mut config = Config::contention(); config.http_connections = 8; exercise( "api-tenant-contention-bounded", serde_json::json!({"type":"sqlite","path":"data/control.db","tenant_directory":"data/tenants","max_connections":2}), Run::Load(config), ); } #[test] #[ignore = "two-minute native SQLite cache budget diagnostic; unchanged workload and resource limits"] fn bounded_cache_contention() { let mut config = Config::contention(); config.http_connections = 8; exercise( "api-tenant-cache-bounded", serde_json::json!({"type":"sqlite","path":"data/control.db","tenant_directory":"data/tenants","max_connections":2,"cache_size_kib":512}), Run::Load(config), ); } #[test] #[ignore = "two-minute cache comparison with 3200000 initial Model rows; diagnostic only"] fn bounded_cache_growth() { let mut config = Config::contention(); config.http_connections = 8; config.rows = 100000; for (label, cache) in [("default", None), ("512", Some(512))] { exercise( &format!("api-tenant-cache-grown-{label}"), serde_json::json!({"type":"sqlite","path":"data/control.db","tenant_directory":"data/tenants","max_connections":2,"cache_size_kib":cache}), Run::Load(config), ); } } const COUNT: &str = "/demo/service/front/main/count"; const PAGE: &str = "/demo/service/front/main/page"; const CREATE: &str = "/demo/service/front/main/create"; const SUBMIT: &str = "/demo/service/front/main/submit"; fn prepare( config: Config, root: &Path, database: &DatabaseConfig, command: impl Fn(&str, Option<&str>) -> std::process::Output, ) -> Vec<(i64, String)> { let tenants = task::run(database.needs_io(), 16, async |scope| { let database = database.open(root, false).await?; let mut executor = database.acquire().await?; for id in 4..=config.tenants as i64 { executor .execute( scope, Sql::same("INSERT INTO demo_service_tenant(created_at,slug) VALUES (0,$1)"), vec![Parameter::Text(format!("load-{id}"))], ) .await?; } executor .query( scope, Sql::same("SELECT id,slug FROM demo_service_tenant ORDER BY id LIMIT $1"), vec![Parameter::Integer(config.tenants as i64)], |row| Ok((row.get::(0)?, row.get::(1)?)), ) .await }) .unwrap() .unwrap(); assert_eq!(tenants.len(), config.tenants); let manage = |name, input: serde_json::Value| success(command(name, Some(&input.to_string()))); for (id, _) in &tenants { // 前两个租户已经由共享功能用例准备;其余也走正式管理入口。 if *id > 2 { manage("dever.tenant.migrate", serde_json::json!({"tenant":id})); manage( "dever.auth.owner", serde_json::json!({"site":"front","user_id":1,"tenant":id}), ); manage( "dever.tenant.component", serde_json::json!({"tenant":id,"component":"demo","enabled":true}), ); } task::run(database.needs_io(), 16, async |scope| { let backend = database.tenant_backend(root, scope, false, &[database]).await?; let database = recovery::physical_database(&backend, *id).await?; let mut executor = database.acquire().await?; executor.execute(scope, Sql { sqlite: "WITH RECURSIVE rows(n) AS (VALUES(1) UNION ALL SELECT n+1 FROM rows WHERE n(()) }).unwrap().unwrap(); } if config.replica { // 初始迁移和批量种入属于准备阶段,结束后才开始模拟正常运行。 task::run(true, 16, async |scope| { database .open(root, false) .await? .acquire() .await? .execute(scope, Sql::same("CHECKPOINT"), vec![]) .await }) .unwrap() .unwrap(); } tenants } struct Samples { tenant: usize, writes: i64, jobs: i64, latency: Vec<(u64, u64, u16)>, } fn client( config: Config, index: usize, headers: &[(i64, String)], server: &Server, barrier: &Barrier, begin: Instant, stop: &AtomicBool, ) -> Samples { let tenant = index % config.tenants; let (id, headers) = &headers[tenant]; let prefix = format!("tenant/{id}/"); let mut samples = Samples { tenant, writes: 0, jobs: 0, latency: Vec::new(), }; barrier.wait(); for sequence in 0..config.requests { if config.seconds != 0 && (stop.load(Ordering::Relaxed) || begin.elapsed().as_secs() >= config.warmup_seconds + config.seconds) { break; } let title = format!("{prefix}客户端/{index}/{sequence}"); let start = Instant::now(); let (expected, answer) = match sequence % 10 { 0 => { samples.writes += 1; ( 200, server.call( "POST", CREATE, &serde_json::json!({"title":title,"accept":true}).to_string(), headers, ), ) } 1 => { samples.jobs += 1; ( 200, server.call( "POST", SUBMIT, &serde_json::json!({"title":title}).to_string(), headers, ), ) } 2 => ( 409, server.call( "POST", CREATE, &serde_json::json!({"title":title,"accept":false}).to_string(), headers, ), ), _ => (200, server.call("GET", PAGE, "", headers)), }; let elapsed = start.elapsed().as_nanos() as u64; assert_eq!( answer.0, expected, "client {index}, request {sequence}: {}", answer.1 ); match sequence % 10 { 0 => { assert_eq!(answer.1["data"]["title"], title); assert!(answer.1["data"]["id"].as_i64().unwrap() > 0); } 1 => assert!(!answer.1["data"].as_str().unwrap().is_empty()), 2 => {} _ => { let page = &answer.1["data"]; assert!(page["total"].as_i64().unwrap() >= config.rows); let items = page["items"].as_array().unwrap(); assert_eq!(items.len(), 10); assert!( items .iter() .all(|row| row["title"].as_str().unwrap().starts_with(&prefix)) ); } } samples .latency .push((begin.elapsed().as_millis() as u64, elapsed, expected)); } samples } fn verify( root: &Path, database: &DatabaseConfig, headers: &[(i64, String)], counts: &[(i64, i64)], rows: i64, samples: &[Samples], ) { task::run(database.needs_io(), 16, async |scope| { let backend = database.tenant_backend(root, scope, false, &[database]).await?; for ((id, _), (writes, jobs)) in headers.iter().zip(counts) { let database = recovery::physical_database(&backend, *id).await?; let mut executor = database.acquire().await?; let value = executor.query_one(scope, Sql::same("SELECT COUNT(*),COUNT(DISTINCT title),SUM(CASE WHEN title NOT LIKE $1 THEN 1 ELSE 0 END) FROM demo_service"), vec![Parameter::Text(format!("tenant/{id}/%"))], |row| Ok((row.get::(0)?,row.get::(1)?,row.get::(2)?))).await?.unwrap(); assert_eq!(value, (rows+writes+jobs,rows+writes+jobs,0), "tenant {id}"); // 总量与唯一性之外核对完整键集合,拒绝回滚记录替换成功记录的假通过。 let titles = executor.query(scope, Sql::same("SELECT title FROM demo_service"), vec![], |row| row.get::(0)).await?; for title in titles { let value = title.strip_prefix(&format!("tenant/{id}/")).unwrap(); if let Some(seed) = value.strip_prefix("seed/") { assert!((1..=rows).contains(&seed.parse::().unwrap())); } else { let (client, sequence) = value.strip_prefix("客户端/").unwrap().split_once('/').unwrap(); let client = client.parse::().unwrap(); let sequence = sequence.parse::().unwrap(); assert_eq!(headers[samples[client].tenant].0, *id); assert!(sequence < samples[client].latency.len() && sequence % 10 <= 1, "unexpected persisted request: {title}"); } } let queue = executor.query_one(scope, Sql::same("SELECT COUNT(*),SUM(CASE WHEN state='completed' THEN 1 ELSE 0 END) FROM _dever_job"), vec![], |row| Ok((row.get::(0)?,row.get::>(1)?))).await?.unwrap(); assert_eq!(queue, (*jobs, Some(*jobs)), "tenant {id} queue"); } Ok::<_, Error>(()) }).unwrap().unwrap(); } pub(super) fn run( config: Config, root: &Path, binary: &Path, settings: &Path, port: u16, issue: impl Fn(&str) -> String, command: impl Fn(&str, Option<&str>) -> std::process::Output, ) { assert!( !config.evaluate_slo || std::env::var_os("DEVER_TEST_HEAPTRACK_PRELOAD").is_none(), "allocation profiling cannot be used for one-hour performance acceptance" ); let setting: serde_json::Value = serde_json::from_slice(&fs::read(settings).unwrap()).unwrap(); let database: DatabaseConfig = serde_json::from_value(setting["database"]["default"].clone()).unwrap(); let tenants = prepare(config, root, &database, command); let headers: Vec<_> = tenants .into_iter() .map(|(id, slug)| (id, issue(&slug))) .collect(); let server = Server::mode(binary, settings, port, "all"); let replica = config .replica .then(|| replicas::start_second(root, binary, settings, setting)); let mut resources = metrics::ProcessSamples::new(config.replica); if config.fixed_resources { metrics::pin_cpus(&server, replica.as_ref()); } let barrier = Barrier::new(config.clients + 1); let begin = Instant::now(); let stop = AtomicBool::new(false); let samples = std::thread::scope(|scope| { let handles: Vec<_> = (0..config.clients) .map(|index| { // 相同租户的四个客户端均分两端口,每端口执行完整的十步请求序列。 let server = match &replica { Some(replica) if (index / config.tenants) % 2 == 1 => replica, _ => &server, }; let (headers, barrier, stop) = (&headers, &barrier, &stop); scope.spawn(move || client(config, index, headers, server, barrier, begin, stop)) }) .collect(); barrier.wait(); let mut minute = 0; loop { let finished = handles.iter().filter(|handle| handle.is_finished()).count(); // 定时客户端提前退出表示测试失败;其余客户端结束当前请求后停止。 if finished == config.clients || (config.seconds != 0 && finished != 0) { stop.store(true, Ordering::Relaxed); break; } let resource = resources.sample(&server, replica.as_ref(), begin); if config.seconds != 0 && begin.elapsed().as_secs() / 60 > minute { minute = begin.elapsed().as_secs() / 60; println!( "Large workload: {}/{} seconds; rss={} KiB; fd={}; threads={}", begin.elapsed().as_secs(), config.warmup_seconds + config.seconds, resource["rss_kib"], resource["descriptors"], resource["threads"] ); } std::thread::sleep(Duration::from_millis(250)); } handles .into_iter() .map(|handle| handle.join().unwrap()) .collect::>() }); let duration = begin.elapsed(); let until = Instant::now() + Duration::from_secs(60); let mut counts = vec![(0, 0); config.tenants]; for sample in &samples { counts[sample.tenant].0 += sample.writes; counts[sample.tenant].1 += sample.jobs; } let mut observations = Vec::new(); let mut failure = None; 'drain: for ((id, headers), (writes, jobs)) in headers.iter().zip(&counts) { let mut first = true; loop { let (status, count) = server.call("GET", COUNT, "", headers); assert_eq!(status, 200, "{count}"); if first { observations.push(serde_json::json!({ "tenant":id,"after_load_ms":(begin.elapsed()-duration).as_millis(), "completed_jobs":count["data"].as_i64().unwrap()-config.rows-writes, "submitted_jobs":jobs})); first = false; } if Instant::now() >= until { failure = Some(serde_json::json!({"stage":"job_drain","tenant":id, "expected_rows":config.rows+writes+jobs,"actual":count, "after_load_ms":(begin.elapsed()-duration).as_millis()})); break 'drain; } if count["data"] == config.rows + writes + jobs { break; } std::thread::sleep(Duration::from_millis(10)); } } // 先固定 60 秒内的排空结果,再统计和写出大样本;写出不挤占或延长排空期限。 // 已知失败也先保存测量再断言,不能丢掉一小时的原始请求。 let drain_seconds = (begin.elapsed() - duration).as_secs_f64(); let mut report = metrics::finish(config, root, binary, duration, resources, &samples); report["drain_first_observations"] = serde_json::json!(observations); report["drain_seconds"] = drain_seconds.into(); report["failure"] = serde_json::json!(failure); metrics::save(root, &report); assert!( failure.is_none(), "accepted Job did not complete: {failure:?}" ); for instance in [Some(server), replica].into_iter().flatten() { let pid = instance.child.id(); instance.stop(); assert!(!Path::new(&format!("/proc/{pid}")).exists()); } verify(root, &database, &headers, &counts, config.rows, &samples); report["post_load_verification_seconds"] = (begin.elapsed() - duration).as_secs_f64().into(); report["functional_verified"] = true.into(); report["slo_passed"] = report["performance_slo_passed"].clone(); metrics::save(root, &report); if config.evaluate_slo { assert!( report["slo_passed"] == true, "large workload SLOs failed; raw results saved at {}", root.join("load-results.json").display() ); } }