Dever v0.0.2
This commit is contained in:
commit
e6e175ebcf
816 files changed
+120349
No files matched your search
@@ -0,0 +1,106 @@
|
||||
//! 运维 CMD 直接运行真实产物,核对其选择的物理库以及 System Job 归属。
|
||||
use super::*;
|
||||
use std::io::Write;
|
||||
|
||||
pub(super) fn add(domain: &Path) {
|
||||
let mut app = fs::OpenOptions::new()
|
||||
.append(true)
|
||||
.open(domain.join("app/main.dever"))
|
||||
.unwrap();
|
||||
app.write_all(
|
||||
br#"
|
||||
flow queueReport(title:Text) (out:Id)
|
||||
| step | kind | do |
|
||||
| out | calc | enqueue(job.report,Payload {title=title},title) |
|
||||
flow globalCount() (out:Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.user.count() |
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(domain.join("api.dever"), "cmd write = app.create\ncmd list = app.page\ncmd queueReport = app.queueReport\ncmd globalCount = app.globalCount\njob report(input:app.Payload) retry(1) timeout(1000) = app.save\n").unwrap();
|
||||
}
|
||||
|
||||
pub(super) fn exercise(root: &Path, binary: &Path, settings: &Path, port: u16) {
|
||||
let command = |arguments: &[&str]| {
|
||||
Command::new(binary)
|
||||
.arg("--config")
|
||||
.arg(settings)
|
||||
.args(arguments)
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
let list = "demo.service.list";
|
||||
let write = "demo.service.write";
|
||||
let first = r#"{"title":"cmd-one","accept":true}"#;
|
||||
let second = r#"{"title":"cmd-two","accept":true}"#;
|
||||
let output = command(&[write, first]);
|
||||
assert!(!output.status.success());
|
||||
assert!(String::from_utf8_lossy(&output.stderr).contains("requires --tenant"));
|
||||
assert!(!command(&["--tenant", "0", write, first]).status.success());
|
||||
assert!(!command(&["--tenant", "99", write, first]).status.success());
|
||||
assert_eq!(data(command(&["demo.service.globalCount", "{}"])), 1);
|
||||
|
||||
success(command(&["--tenant", "1", write, first]));
|
||||
success(cli(&[
|
||||
"run",
|
||||
root.to_str().unwrap(),
|
||||
"--",
|
||||
"--tenant",
|
||||
"2",
|
||||
write,
|
||||
second,
|
||||
]));
|
||||
let contains = |tenant: &str, title: &str| {
|
||||
data(command(&["--tenant", tenant, list, "{}"]))["items"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|row| row["title"] == title)
|
||||
};
|
||||
assert!(contains("1", "cmd-one"));
|
||||
assert!(!contains("1", "cmd-two"));
|
||||
assert!(contains("2", "cmd-two"));
|
||||
assert!(!contains("2", "cmd-one"));
|
||||
|
||||
success(command(&[
|
||||
"dever.tenant.component",
|
||||
r#"{"tenant":1,"component":"demo","enabled":false}"#,
|
||||
]));
|
||||
let output = command(&[
|
||||
"--tenant",
|
||||
"1",
|
||||
write,
|
||||
r#"{"title":"cmd-disabled","accept":true}"#,
|
||||
]);
|
||||
assert!(!output.status.success());
|
||||
assert!(String::from_utf8_lossy(&output.stderr).contains("component 'demo' is disabled"));
|
||||
success(command(&[
|
||||
"dever.tenant.component",
|
||||
r#"{"tenant":1,"component":"demo","enabled":true}"#,
|
||||
]));
|
||||
assert!(!contains("1", "cmd-disabled"));
|
||||
|
||||
success(command(&[
|
||||
"--tenant",
|
||||
"2",
|
||||
"demo.service.queueReport",
|
||||
r#"{"title":"cmd-job"}"#,
|
||||
]));
|
||||
let server = Server::mode(binary, settings, port, "all");
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while !contains("2", "cmd-job") {
|
||||
assert!(
|
||||
Instant::now() < deadline,
|
||||
"tenant System Job did not complete"
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
assert!(!contains("1", "cmd-job"));
|
||||
server.stop();
|
||||
}
|
||||
|
||||
fn data(output: Output) -> serde_json::Value {
|
||||
let decoded: serde_json::Value = serde_json::from_str(&success(output)).unwrap();
|
||||
decoded["data"].clone()
|
||||
}
|
||||
@@ -0,0 +1,497 @@
|
||||
//! 同一真实租户项目的并发负载;只在隔离测试目录准备数据,不替换 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::<i64>(0)?, row.get::<String>(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<?2) INSERT INTO demo_service(created_at,title) SELECT 0,?1||n FROM rows",
|
||||
postgres: "INSERT INTO demo_service(created_at,title) SELECT 0,$1||n FROM generate_series(1,$2::bigint) AS rows(n)",
|
||||
},
|
||||
vec![Parameter::Text(format!("tenant/{id}/seed/")), Parameter::Integer(config.rows)]).await?;
|
||||
Ok::<_, Error>(())
|
||||
}).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::<i64>(0)?,row.get::<i64>(1)?,row.get::<i64>(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::<String>(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::<i64>().unwrap()));
|
||||
} else {
|
||||
let (client, sequence) = value.strip_prefix("客户端/").unwrap().split_once('/').unwrap();
|
||||
let client = client.parse::<usize>().unwrap();
|
||||
let sequence = sequence.parse::<usize>().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::<i64>(0)?,row.get::<Option<i64>>(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::<Vec<_>>()
|
||||
});
|
||||
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()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
//! 同一原生缓存预算分别核对起始与增长后的工作集,不更改业务负载或验收门槛。
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
#[ignore = "two-minute SQLite page-cache diagnostic with 1048576 initial Model rows"]
|
||||
fn bounded_small_cache_contention() {
|
||||
small_cache("api-tenant-cache-small", 32768);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "two-minute SQLite page-cache diagnostic with 3200000 initial Model rows"]
|
||||
fn bounded_small_cache_growth() {
|
||||
small_cache("api-tenant-cache-small-grown", 100000);
|
||||
}
|
||||
|
||||
fn small_cache(label: &str, rows: i64) {
|
||||
let config = Config {
|
||||
rows,
|
||||
http_connections: 8,
|
||||
..Config::contention()
|
||||
};
|
||||
super::exercise(
|
||||
label,
|
||||
serde_json::json!({"type":"sqlite","path":"data/control.db","tenant_directory":"data/tenants","max_connections":2,"cache_size_kib":64}),
|
||||
Run::Load(config),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
//! 固定窗口统计和大型负载门槛;失败前也保存原始样本,不混入预热或预期拒绝。
|
||||
use super::*;
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::collections::BTreeMap;
|
||||
mod process;
|
||||
pub(super) use process::ProcessSamples;
|
||||
|
||||
pub(super) fn pin_cpus(server: &Server, replica: Option<&Server>) {
|
||||
assert_eq!(
|
||||
fs::read_to_string("/sys/fs/cgroup/cpu.max").unwrap().trim(),
|
||||
"400000 100000"
|
||||
);
|
||||
assert_eq!(
|
||||
fs::read_to_string("/sys/fs/cgroup/memory.max")
|
||||
.unwrap()
|
||||
.trim(),
|
||||
"8589934592"
|
||||
);
|
||||
let list =
|
||||
std::env::var("DEVER_TEST_LOAD_CPUS").expect("set DEVER_TEST_LOAD_CPUS to four CPU IDs");
|
||||
let cpus: [u32; 4] = list
|
||||
.split(',')
|
||||
.map(str::parse::<u32>)
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.expect("parse DEVER_TEST_LOAD_CPUS")
|
||||
.try_into()
|
||||
.expect("DEVER_TEST_LOAD_CPUS requires four CPU IDs");
|
||||
let mut distinct = cpus;
|
||||
distinct.sort_unstable();
|
||||
assert!(distinct.windows(2).all(|pair| pair[0] != pair[1]));
|
||||
let [first, second, third, driver] = cpus;
|
||||
let service = if replica.is_some() {
|
||||
list
|
||||
} else {
|
||||
format!("{first},{second},{third}")
|
||||
};
|
||||
let driver = driver.to_string();
|
||||
let processes = [Some(server), replica]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|server| (server.child.id(), &service))
|
||||
.chain([(std::process::id(), &driver)]);
|
||||
for (pid, affinity) in processes {
|
||||
success(
|
||||
Command::new("taskset")
|
||||
.args(["-apc", affinity, &pid.to_string()])
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
}
|
||||
println!("Load CPU affinity: server={service}, driver={driver}");
|
||||
}
|
||||
|
||||
pub(super) fn finish(
|
||||
config: Config,
|
||||
root: &Path,
|
||||
binary: &Path,
|
||||
elapsed: Duration,
|
||||
processes: ProcessSamples,
|
||||
samples: &[Samples],
|
||||
) -> serde_json::Value {
|
||||
let ProcessSamples {
|
||||
combined: resources,
|
||||
replicas,
|
||||
postgres,
|
||||
..
|
||||
} = processes;
|
||||
let warmup_ms = config.warmup_seconds * 1000;
|
||||
let measured = |time: u64| {
|
||||
time >= warmup_ms && (config.seconds == 0 || time < warmup_ms + config.seconds * 1000)
|
||||
};
|
||||
let mut windows: BTreeMap<u64, (Vec<u64>, usize)> = BTreeMap::new();
|
||||
let mut successful = Vec::new();
|
||||
let mut rejected = 0;
|
||||
for (time, latency, status) in samples.iter().flat_map(|sample| &sample.latency) {
|
||||
if !measured(*time) {
|
||||
continue;
|
||||
}
|
||||
let (window, conflicts) = windows.entry((time - warmup_ms) / 60000).or_default();
|
||||
if *status == 200 {
|
||||
successful.push(*latency);
|
||||
window.push(*latency);
|
||||
} else {
|
||||
assert_eq!(*status, 409);
|
||||
rejected += 1;
|
||||
*conflicts += 1;
|
||||
}
|
||||
}
|
||||
successful.sort_unstable();
|
||||
let quantile = |values: &[u64], p: usize| values[(values.len() * p).div_ceil(100) - 1];
|
||||
let duration = if config.seconds == 0 {
|
||||
elapsed.as_secs_f64()
|
||||
} else {
|
||||
config.seconds as f64
|
||||
};
|
||||
let windows: Vec<_> = windows
|
||||
.into_iter()
|
||||
.map(|(index, (mut times, conflicts))| {
|
||||
times.sort_unstable();
|
||||
let seconds = (duration - index as f64 * 60.0).min(60.0);
|
||||
serde_json::json!({"index":index,"seconds":seconds,"successes":times.len(),
|
||||
"expected_conflicts":conflicts,"success_throughput":times.len() as f64/seconds,
|
||||
"p50_ns":quantile(×,50),"p95_ns":quantile(×,95),"p99_ns":quantile(×,99)})
|
||||
})
|
||||
.collect();
|
||||
let measured_resources: Vec<_> = resources
|
||||
.iter()
|
||||
.filter(|sample| measured(sample["elapsed_ms"].as_u64().unwrap()))
|
||||
.collect();
|
||||
let peak = |field: &str| {
|
||||
measured_resources
|
||||
.iter()
|
||||
.map(|sample| sample[field].as_u64().unwrap())
|
||||
.max()
|
||||
.unwrap()
|
||||
};
|
||||
let midpoint = warmup_ms + (duration * 500.0) as u64;
|
||||
let (first, second): (Vec<_>, Vec<_>) = measured_resources
|
||||
.iter()
|
||||
.partition(|sample| sample["elapsed_ms"].as_u64().unwrap() < midpoint);
|
||||
let rss_median = |samples: Vec<&&serde_json::Value>| {
|
||||
median(
|
||||
samples
|
||||
.iter()
|
||||
.map(|sample| sample["rss_kib"].as_u64().unwrap())
|
||||
.collect(),
|
||||
)
|
||||
};
|
||||
let first_rss = rss_median(first);
|
||||
let second_rss = rss_median(second);
|
||||
let slope_ok = first_rss
|
||||
.zip(second_rss)
|
||||
.is_some_and(|(first, second)| second <= first * 1.10);
|
||||
let resource_ok =
|
||||
peak("rss_kib") <= 262144 && peak("descriptors") <= 512 && peak("threads") <= 32;
|
||||
let windows_ok = windows.iter().all(|window| {
|
||||
window["success_throughput"].as_f64().unwrap() >= 1000.0
|
||||
&& window["p99_ns"].as_u64().unwrap() <= 200000000
|
||||
});
|
||||
let slo_ok = windows.len() == 60
|
||||
&& measured_resources.len() >= 3600
|
||||
&& resource_ok
|
||||
&& slope_ok
|
||||
&& windows_ok;
|
||||
let digest = |path: &Path| format!("{:x}", Sha256::digest(fs::read(path).unwrap()));
|
||||
let setting: serde_json::Value =
|
||||
serde_json::from_slice(&fs::read(root.join("config/setting.json")).unwrap()).unwrap();
|
||||
// 大量逐请求样本单独写一次,后续更新业务核对状态时只重写小型摘要。
|
||||
let raw = root.join("load-samples.json");
|
||||
let mut output = std::io::BufWriter::new(fs::File::create(&raw).unwrap());
|
||||
serde_json::to_writer(
|
||||
&mut output,
|
||||
&samples
|
||||
.iter()
|
||||
.map(|sample| &sample.latency)
|
||||
.collect::<Vec<_>>(),
|
||||
)
|
||||
.unwrap();
|
||||
output.into_inner().unwrap();
|
||||
let mut report = serde_json::json!({"config":config,"seconds":duration,"total_seconds":elapsed.as_secs_f64(),
|
||||
"allocation_profiler":std::env::var_os("DEVER_TEST_HEAPTRACK_PRELOAD").map(PathBuf::from),
|
||||
"service_configuration":{"backend":setting["database"]["default"]["type"],"http_limits":setting["http"]["limits"],"tenant":setting["tenant"],
|
||||
"job":setting["job"],"connections_per_pool":setting["database"]["default"]["max_connections"],
|
||||
"sqlite_cache_size_kib_per_connection":setting["database"]["default"]["cache_size_kib"]},
|
||||
"contract":"Real release Dever HTTP/Model tenant project using the recorded backend, signed Cookie, live Provider/roles/component checks; deterministic ten-request cycle: seven full-record page reads, one transaction write, one durable user Job and one expected rollback conflict. Each request opens its own connection through the existing Server helper. Preparation, warmup, queue drain and final SQL verification are outside measured time.",
|
||||
"limitations":"Current Dever only; not a four-way performance result, complete PostgreSQL/Worker/cron matrix or universal large-project readiness. Bounded profiles verify functionality and capacity only; they do not evaluate one-hour SLOs.",
|
||||
"binary_sha256":digest(binary),"compiler_sha256":digest(Path::new(env!("CARGO_BIN_EXE_dever"))),
|
||||
"test_binary_sha256":digest(&std::env::current_exe().unwrap()),
|
||||
"fixture_sha256":format!("{:x}",Sha256::digest(include_str!("../../tenant.rs"))),
|
||||
"load_source_sha256":format!("{:x}",Sha256::digest(include_str!("../load.rs"))),
|
||||
"metrics_source_sha256":format!("{:x}",Sha256::digest(include_str!("metrics.rs"))),
|
||||
"requests":successful.len()+rejected,"successful_requests":successful.len(),
|
||||
"submitted_jobs_including_warmup":samples.iter().map(|sample| sample.jobs).sum::<i64>(),
|
||||
"success_throughput":successful.len() as f64/duration,"expected_conflicts":rejected,
|
||||
"p50_ns":quantile(&successful,50),"p95_ns":quantile(&successful,95),"p99_ns":quantile(&successful,99),
|
||||
"windows":windows,"resources":resources,"peak_rss_kib":peak("rss_kib"),
|
||||
"peak_descriptors":peak("descriptors"),"peak_threads":peak("threads"),
|
||||
"rss_trend":{"first_half_median_kib":first_rss,"second_half_median_kib":second_rss,
|
||||
"ratio":first_rss.zip(second_rss).map(|(first,second)|second/first)},
|
||||
"slo_evaluated":config.evaluate_slo,"performance_slo_passed":if config.evaluate_slo {Some(slo_ok)} else {None},
|
||||
"slo_passed":if config.evaluate_slo {Some(false)} else {None},
|
||||
"slo_targets":{"window_seconds":60,"windows":60,"min_success_qps":1000,"max_p99_ns":200000000,
|
||||
"max_rss_kib":262144,"max_descriptors":512,"max_threads":32,"max_rss_half_median_ratio":1.10},
|
||||
"raw_columns":["completion_ms","latency_ns","status"],"raw_samples_file":"load-samples.json",
|
||||
"functional_verified":false});
|
||||
report["service_instances"] = (1 + usize::from(config.replica)).into();
|
||||
if config.replica {
|
||||
report["replica_resource_samples"] = serde_json::json!(replicas);
|
||||
report["postgres_resource_samples"] = serde_json::json!(postgres);
|
||||
}
|
||||
save(root, &report);
|
||||
println!(
|
||||
"Tenant load measured: {} requests; {}",
|
||||
successful.len() + rejected,
|
||||
root.join("load-results.json").display()
|
||||
);
|
||||
report
|
||||
}
|
||||
|
||||
fn median(mut values: Vec<u64>) -> Option<f64> {
|
||||
if values.is_empty() {
|
||||
return None;
|
||||
}
|
||||
values.sort_unstable();
|
||||
let middle = values.len() / 2;
|
||||
Some(if values.len().is_multiple_of(2) {
|
||||
values[middle - 1] as f64 / 2.0 + values[middle] as f64 / 2.0
|
||||
} else {
|
||||
values[middle] as f64
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rss_median_uses_every_sample_and_does_not_treat_missing_measurements_as_zero() {
|
||||
assert_eq!(median(vec![]), None);
|
||||
assert_eq!(median(vec![100, 130, 110]), Some(110.0));
|
||||
assert_eq!(median(vec![120, 100, 110, 130]), Some(115.0));
|
||||
assert_eq!(median(vec![100, 100, 200]), Some(100.0));
|
||||
}
|
||||
|
||||
pub(super) fn save(root: &Path, report: &serde_json::Value) {
|
||||
fs::write(
|
||||
root.join("load-results.json"),
|
||||
serde_json::to_vec(report).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
//! 两个服务进程的份额单列;PostgreSQL 用 PSS 避免将共享页重复计入。
|
||||
use super::*;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub(in crate::api::tenant::load) struct ProcessSamples {
|
||||
database: Option<u32>,
|
||||
pub(super) combined: Vec<Value>,
|
||||
pub(super) replicas: Vec<[Value; 2]>,
|
||||
pub(super) postgres: Vec<Value>,
|
||||
}
|
||||
|
||||
impl ProcessSamples {
|
||||
pub(in crate::api::tenant::load) fn new(replica: bool) -> Self {
|
||||
Self {
|
||||
database: replica.then(|| {
|
||||
std::env::var("DEVER_TEST_POSTGRES_PID")
|
||||
.unwrap()
|
||||
.parse()
|
||||
.unwrap()
|
||||
}),
|
||||
combined: Vec::new(),
|
||||
replicas: Vec::new(),
|
||||
postgres: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::api::tenant::load) fn sample(
|
||||
&mut self,
|
||||
server: &Server,
|
||||
replica: Option<&Server>,
|
||||
begin: Instant,
|
||||
) -> &Value {
|
||||
let mut combined = resources(server.child.id(), begin);
|
||||
if let Some(replica) = replica {
|
||||
let first = combined.clone();
|
||||
let second = resources(replica.child.id(), begin);
|
||||
for field in [
|
||||
"rss_kib",
|
||||
"anonymous_rss_kib",
|
||||
"file_rss_kib",
|
||||
"data_kib",
|
||||
"threads",
|
||||
"descriptors",
|
||||
"cpu_ticks",
|
||||
] {
|
||||
combined[field] =
|
||||
(first[field].as_u64().unwrap() + second[field].as_u64().unwrap()).into();
|
||||
}
|
||||
self.replicas.push([first, second]);
|
||||
}
|
||||
if let Some(pid) = self.database
|
||||
&& self.combined.len().is_multiple_of(20)
|
||||
{
|
||||
self.postgres.push(database_resources(pid, begin));
|
||||
}
|
||||
self.combined.push(combined);
|
||||
self.combined.last().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
fn database_resources(pid: u32, begin: Instant) -> Value {
|
||||
let parent = pid.to_string();
|
||||
let children = fs::read_to_string(format!("/proc/{pid}/task/{pid}/children")).unwrap();
|
||||
let mut pss = 0;
|
||||
let mut rss = 0;
|
||||
let mut ticks = 0;
|
||||
let mut processes = 0;
|
||||
for (index, pid) in std::iter::once(parent.as_str())
|
||||
.chain(children.split_whitespace())
|
||||
.enumerate()
|
||||
{
|
||||
let read = |file| match fs::read_to_string(format!("/proc/{pid}/{file}")) {
|
||||
// 已退出的后端由 postmaster 的子进程 CPU 计数回收;没有可采样的 RSS。
|
||||
Err(error) if index != 0 && matches!(error.raw_os_error(), Some(2 | 3)) => None,
|
||||
result => Some(result.unwrap()),
|
||||
};
|
||||
let Some(stat) = read("stat") else { continue };
|
||||
ticks += cpu_ticks(&stat, index == 0);
|
||||
let Some(memory) = read("smaps_rollup") else {
|
||||
continue;
|
||||
};
|
||||
let kib = |field| {
|
||||
memory
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix(field))
|
||||
.unwrap()
|
||||
.split_whitespace()
|
||||
.next()
|
||||
.unwrap()
|
||||
.parse::<u64>()
|
||||
.unwrap()
|
||||
};
|
||||
pss += kib("Pss:");
|
||||
rss += kib("Rss:");
|
||||
processes += 1;
|
||||
}
|
||||
json!({"elapsed_ms":begin.elapsed().as_millis(),"cpu_ticks":ticks,"pss_kib":pss,
|
||||
"rss_sum_kib":rss,"processes":processes})
|
||||
}
|
||||
|
||||
fn cpu_ticks(stat: &str, include_reaped_children: bool) -> u64 {
|
||||
stat.rsplit_once(')')
|
||||
.unwrap()
|
||||
.1
|
||||
.split_whitespace()
|
||||
.skip(11)
|
||||
.take(if include_reaped_children { 4 } else { 2 })
|
||||
.map(|field| field.parse::<u64>().unwrap())
|
||||
.sum()
|
||||
}
|
||||
|
||||
fn resources(pid: u32, begin: Instant) -> serde_json::Value {
|
||||
let status = fs::read_to_string(format!("/proc/{pid}/status")).unwrap();
|
||||
let field = |name| {
|
||||
status
|
||||
.lines()
|
||||
.find(|line| line.starts_with(name))
|
||||
.unwrap()
|
||||
.split_whitespace()
|
||||
.nth(1)
|
||||
.unwrap()
|
||||
.parse::<u64>()
|
||||
.unwrap()
|
||||
};
|
||||
let descriptors = fs::read_dir(format!("/proc/{pid}/fd")).unwrap().count();
|
||||
let stat = fs::read_to_string(format!("/proc/{pid}/stat")).unwrap();
|
||||
serde_json::json!({"elapsed_ms":begin.elapsed().as_millis(),"rss_kib":field("VmRSS:"),
|
||||
"anonymous_rss_kib":field("RssAnon:"),"file_rss_kib":field("RssFile:"),
|
||||
"data_kib":field("VmData:"),"threads":field("Threads:"),"descriptors":descriptors,
|
||||
"cpu_ticks":cpu_ticks(&stat, false)})
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
//! 已接受任务在执行前撤权;核对真实物理队列和业务行,不用延时猜测执行结果。
|
||||
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::<String>(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::<i64>(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<Database, Error> {
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
//! 两个真实进程共用 PostgreSQL,核对跨实例读写、撤权和租约接手。
|
||||
use super::*;
|
||||
use dever_runtime::{
|
||||
database::{Error, Parameter, Sql, config::Config},
|
||||
task,
|
||||
};
|
||||
|
||||
pub(super) fn start_second(
|
||||
root: &Path,
|
||||
binary: &Path,
|
||||
settings: &Path,
|
||||
mut settings_value: serde_json::Value,
|
||||
) -> Server {
|
||||
let (_, port, _) = config(root);
|
||||
let path = settings.with_file_name("replica.json");
|
||||
settings_value["http"]["port"] = port.into();
|
||||
fs::write(&path, settings_value.to_string()).unwrap();
|
||||
Server::mode(binary, &path, port, "all")
|
||||
}
|
||||
|
||||
pub(super) fn exercise(
|
||||
root: &Path,
|
||||
binary: &Path,
|
||||
settings: &Path,
|
||||
port: u16,
|
||||
[tenant_one, tenant_two]: [&str; 2],
|
||||
command: impl Fn(&str, Option<&str>) -> std::process::Output,
|
||||
) {
|
||||
const COUNT: &str = "/demo/service/front/main/count";
|
||||
const CREATE: &str = "/demo/service/front/main/create";
|
||||
const SUBMIT: &str = "/demo/service/front/main/submit";
|
||||
let settings_value: serde_json::Value =
|
||||
serde_json::from_slice(&fs::read(settings).unwrap()).unwrap();
|
||||
let database: Config =
|
||||
serde_json::from_value(settings_value["database"]["default"].clone()).unwrap();
|
||||
let mut first = Server::mode(binary, settings, port, "all");
|
||||
let second = start_second(root, binary, settings, settings_value);
|
||||
|
||||
for (writer, reader, headers) in [(&first, &second, tenant_one), (&second, &first, tenant_two)]
|
||||
{
|
||||
let (status, body) = writer.call(
|
||||
"POST",
|
||||
CREATE,
|
||||
r#"{"title":"initial","accept":true}"#,
|
||||
headers,
|
||||
);
|
||||
assert_eq!(status, 200, "{body}");
|
||||
assert_eq!(reader.call("GET", COUNT, "", headers).1["data"], 1);
|
||||
}
|
||||
let component = |enabled| {
|
||||
success(command(
|
||||
"dever.tenant.component",
|
||||
Some(&serde_json::json!({"tenant":1,"component":"demo","enabled":enabled}).to_string()),
|
||||
));
|
||||
};
|
||||
component(false);
|
||||
for server in [&first, &second] {
|
||||
assert_eq!(server.call("GET", COUNT, "", tenant_one).0, 403);
|
||||
assert_eq!(server.call("GET", COUNT, "", tenant_two).1["data"], 1);
|
||||
}
|
||||
component(true);
|
||||
|
||||
let submit = |server: &Server, title| {
|
||||
let (status, body) = server.call(
|
||||
"POST",
|
||||
SUBMIT,
|
||||
&serde_json::json!({"title":title}).to_string(),
|
||||
tenant_one,
|
||||
);
|
||||
assert_eq!(status, 200, "{body}");
|
||||
body["data"].as_str().unwrap().to_owned()
|
||||
};
|
||||
task::run(true, 8, async |scope| {
|
||||
let backend = database
|
||||
.tenant_backend(root, scope, false, &[&database])
|
||||
.await?;
|
||||
let database = recovery::physical_database(&backend, 1).await?;
|
||||
let mut gate = database.acquire().await?;
|
||||
let owner = gate.begin(scope).await?;
|
||||
// 在数据库中暂缓业务写入,等两个 worker 都确实领取后再中断其中一个。
|
||||
gate.execute(
|
||||
scope,
|
||||
Sql::same("LOCK TABLE demo_service IN SHARE MODE"),
|
||||
vec![],
|
||||
)
|
||||
.await?;
|
||||
let left = submit(&first, "from-first");
|
||||
let right = submit(&second, "from-second");
|
||||
assert_ne!(left, right);
|
||||
// 幂等键只合并待执行或执行中的任务;两个端口必须返回同一个 ID。
|
||||
assert_eq!(submit(&second, "from-first"), left);
|
||||
assert_eq!(submit(&first, "from-second"), right);
|
||||
let mut probe = database.acquire().await?;
|
||||
let mut ids = [left, right];
|
||||
ids.sort_unstable();
|
||||
for state in ["running", "completed"] {
|
||||
let deadline = Instant::now() + Duration::from_secs(8);
|
||||
loop {
|
||||
let jobs = probe
|
||||
.query(
|
||||
scope,
|
||||
Sql::same("SELECT id, attempt FROM _dever_job WHERE state=$1 ORDER BY id"),
|
||||
vec![Parameter::Text(state.into())],
|
||||
|row| Ok((row.get::<String>(0)?, row.get::<i64>(1)?)),
|
||||
)
|
||||
.await?;
|
||||
if jobs.len() == 2 {
|
||||
assert!(jobs.iter().map(|(id, _)| id).eq(&ids), "{jobs:?}");
|
||||
let mut attempts = [jobs[0].1, jobs[1].1];
|
||||
attempts.sort_unstable();
|
||||
assert_eq!(attempts, if state == "running" { [1, 1] } else { [1, 2] });
|
||||
break;
|
||||
}
|
||||
assert!(
|
||||
Instant::now() < deadline,
|
||||
"replicas did not reach {state}: {jobs:?}"
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
if state == "running" {
|
||||
first.child.kill().unwrap();
|
||||
assert!(!first.child.wait().unwrap().success());
|
||||
assert!(TcpStream::connect(("127.0.0.1", port)).is_err());
|
||||
gate.finish(scope, owner, true).await?;
|
||||
}
|
||||
}
|
||||
let rows = probe
|
||||
.query(
|
||||
scope,
|
||||
Sql::same("SELECT title FROM demo_service ORDER BY title"),
|
||||
vec![],
|
||||
|row| row.get::<String>(0),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(rows, ["from-first", "from-second", "initial"]);
|
||||
Ok::<_, Error>(())
|
||||
})
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(second.call("GET", COUNT, "", tenant_one).1["data"], 3);
|
||||
assert_eq!(second.call("GET", COUNT, "", tenant_two).1["data"], 1);
|
||||
second.stop();
|
||||
}
|
||||
Reference in new issue
Block a user