Dever v0.0.2
This commit is contained in:
commit
e6e175ebcf
816 files changed
+120349
No files matched your search
@@ -0,0 +1,419 @@
|
||||
use super::*;
|
||||
use dever_runtime::{
|
||||
auth::{Claims, Provider},
|
||||
value::{calendar::DateTime, secret::Secret},
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn generated_http_revalidates_accounts_permissions_cookie_origins_and_transactions() {
|
||||
exercise(
|
||||
"api-auth",
|
||||
serde_json::json!({"type":"sqlite","path":"data/api.db","max_connections":2}),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires an isolated PostgreSQL database; run test/postgres.py"]
|
||||
fn postgres_generated_http_identity_permissions_transactions_and_jobs() {
|
||||
let url = std::env::var("DEVER_TEST_POSTGRES").expect("isolated PostgreSQL database");
|
||||
exercise(
|
||||
"api-auth-postgres",
|
||||
serde_json::json!({"type":"postgres","url":url,"tls":"disabled","max_connections":3}),
|
||||
);
|
||||
}
|
||||
fn exercise(name: &str, database: serde_json::Value) {
|
||||
let root = project(
|
||||
name,
|
||||
r#"
|
||||
type Payload {title:Text}
|
||||
type Identity {id:Text,user_id:data.user.id?,tenant_id:data.tenant.id?}
|
||||
flow verify(claims:dever.auth.Claims) (identity:Identity)
|
||||
| step | kind | do |
|
||||
| account | data | data.user.first(subject == claims.subject) |
|
||||
| - | check | account != null else Unauthorized |
|
||||
| - | check | account.enabled else Unauthorized |
|
||||
| identity | calc | Identity {id=claims.subject,user_id=account.id,tenant_id=null} |
|
||||
flow create(title:Text, accept:Bool) (out: data.Service)
|
||||
| step | kind | do |
|
||||
| out | data | data.create({title=title}) |
|
||||
| - | check | accept else Conflict |
|
||||
flow count() (out:Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.count() |
|
||||
flow submit(title:Text) (out:Id)
|
||||
| step | kind | do |
|
||||
| out | calc | enqueue(job.save,Payload {title=title},title) |
|
||||
flow jobStates(owned:Id, scheduled:Id) (owned_state:Text?, scheduled_state:Text?)
|
||||
| step | kind | do |
|
||||
| states | calc | dever.job.states([owned, scheduled, null]) |
|
||||
| owned_state | calc | get(states, owned) |
|
||||
| scheduled_state | calc | get(states, scheduled) |
|
||||
flow systemJobStates(owned:Id, scheduled:Id) (owned_state:Text?, scheduled_state:Text?)
|
||||
| step | kind | do |
|
||||
| states | calc | dever.job.states([owned, scheduled, null], "system") |
|
||||
| owned_state | calc | get(states, owned) |
|
||||
| scheduled_state | calc | get(states, scheduled) |
|
||||
flow save(input:Payload) ()
|
||||
| step | kind | do |
|
||||
| user: data.user.id? | calc | dever.auth.userId() |
|
||||
| - | check | user != null else Unauthorized |
|
||||
| - | data | data.create({title=input.title}) |
|
||||
flow subject() (out:Text)
|
||||
| step | kind | do |
|
||||
| out | calc | dever.auth.id() |
|
||||
flow current() (id:Text,session:Text,user_id:data.user.id?,tenant_id:data.tenant.id?)
|
||||
| step | kind | do |
|
||||
| task | calc | run(app.subject()) |
|
||||
| id | calc | wait(task) |
|
||||
| session | calc | dever.auth.session() |
|
||||
| user_id | calc | dever.auth.userId() |
|
||||
| tenant_id | calc | dever.auth.tenantId() |
|
||||
ready() (out:Bool) {out=true}
|
||||
"#,
|
||||
"job save(input:app.Payload) retry(1) timeout(1000) = app.save\npost submit = app.submit\npost create = app.create\nget count = app.count\nauthenticated get current = app.current\nauthenticated post touch = app.ready\nauthenticated post jobStates = app.jobStates\npublic get health = app.ready",
|
||||
);
|
||||
let domain = root.join("module/demo/service");
|
||||
fs::create_dir_all(domain.join("data")).unwrap();
|
||||
fs::write(
|
||||
domain.join("api.dever"),
|
||||
"cmd submitSystem = app.submit\ncmd systemJobStates = app.systemJobStates",
|
||||
)
|
||||
.unwrap();
|
||||
write_source(domain.join("data/main.dever"), "type Service {title:Text}").unwrap();
|
||||
fs::write(domain.join("data/user.dever"),"global type User {subject:Text unique,enabled:Bool}\nseed { {subject=\"alice\",enabled=true} }").unwrap();
|
||||
fs::write(
|
||||
domain.join("data/tenant.dever"),
|
||||
"global type Tenant {name:Text}",
|
||||
)
|
||||
.unwrap();
|
||||
let (path, port, mut config) = config(&root);
|
||||
config["job"] =
|
||||
serde_json::json!({"workers":1,"poll_ms":5,"lease_ms":10000,"shutdown_ms":5000});
|
||||
config["database"] = serde_json::json!({"default":database});
|
||||
config["sites"]["front"]["auth"] = serde_json::json!("users");
|
||||
config["sites"]["front"]["origin"] = serde_json::json!("http://localhost");
|
||||
config["auth"] = serde_json::json!({"providers":{"users":{"verify":"demo.service.verify","jwtSecret":"01234567890123456789012345678901","ttlSeconds":3600,"cookie":"session"}}});
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
fs::write(&path, config.to_string()).unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
success(
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&path)
|
||||
.arg("migrate")
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
let database_config: dever_runtime::database::config::Config =
|
||||
serde_json::from_value(database).unwrap();
|
||||
let sql = |sql: &'static str| {
|
||||
dever_runtime::task::run(true, 8, async |scope| {
|
||||
let database = database_config.open(&root, false).await.unwrap();
|
||||
database
|
||||
.acquire()
|
||||
.await
|
||||
.unwrap()
|
||||
.execute(
|
||||
scope,
|
||||
dever_runtime::database::Sql {
|
||||
sqlite: sql,
|
||||
postgres: sql,
|
||||
},
|
||||
vec![],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
Ok::<_, String>(())
|
||||
})
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
};
|
||||
// 通过实际角色表赋权;被测入口仍必须读取实时目录和角色状态。
|
||||
sql(
|
||||
"INSERT INTO _dever_role(site,id,name,all_permissions,enabled,protected) VALUES ('front','writer','Writer',FALSE,TRUE,FALSE)",
|
||||
);
|
||||
sql("INSERT INTO _dever_user_role VALUES ('front',1,'writer')");
|
||||
sql(
|
||||
"INSERT INTO _dever_role_permission VALUES ('front','writer','demo.service.front.create'),('front','writer','demo.service.front.count'),('front','writer','demo.service.front.submit')",
|
||||
);
|
||||
let provider = Provider::new(
|
||||
"users".into(),
|
||||
Secret::from_input(b"01234567890123456789012345678901".to_vec()),
|
||||
3600,
|
||||
)
|
||||
.unwrap();
|
||||
let claims = Claims {
|
||||
subject: "alice".into(),
|
||||
session: "session-1".into(),
|
||||
site: "front".into(),
|
||||
tenant: None,
|
||||
};
|
||||
let now = DateTime::now().unwrap().millis() / 1000;
|
||||
let issued = dever_runtime::auth::request::Cookie::new("session".into(), "http://localhost")
|
||||
.unwrap()
|
||||
.issue(&provider, &claims, now)
|
||||
.unwrap();
|
||||
let cookie_value = std::str::from_utf8(&issued.value)
|
||||
.unwrap()
|
||||
.split(';')
|
||||
.next()
|
||||
.unwrap();
|
||||
let authorization = format!("Cookie: {cookie_value}\r\nOrigin: http://localhost\r\n");
|
||||
let server = Server::start(&artifact.binary, &path, port);
|
||||
let create = "/demo/service/front/main/create";
|
||||
let count = "/demo/service/front/main/count";
|
||||
assert_eq!(server.call("GET", count, "", "").0, 401);
|
||||
let json = format!("{authorization}Content-Type: application/json\r\n");
|
||||
assert_eq!(
|
||||
server
|
||||
.call(
|
||||
"POST",
|
||||
create,
|
||||
r#"{"title":"rollback","accept":false}"#,
|
||||
&json
|
||||
)
|
||||
.0,
|
||||
409
|
||||
);
|
||||
assert_eq!(server.call("GET", count, "", &authorization).1["data"], 0);
|
||||
assert_eq!(
|
||||
server
|
||||
.call("POST", create, r#"{"title":"saved","accept":true}"#, &json)
|
||||
.0,
|
||||
200
|
||||
);
|
||||
assert_eq!(server.call("GET", count, "", &authorization).1["data"], 1);
|
||||
let current = server.call(
|
||||
"GET",
|
||||
"/demo/service/front/main/current",
|
||||
"",
|
||||
&authorization,
|
||||
);
|
||||
assert_eq!(current.0, 200);
|
||||
assert_eq!(
|
||||
current.1["data"],
|
||||
serde_json::json!({"id":"alice","session":"session-1","user_id":1,"tenant_id":null})
|
||||
);
|
||||
assert_eq!(
|
||||
server
|
||||
.call(
|
||||
"GET",
|
||||
"/demo/service/front/main/current?user_id=99",
|
||||
"",
|
||||
&authorization
|
||||
)
|
||||
.0,
|
||||
400
|
||||
);
|
||||
sql("DELETE FROM _dever_role_permission WHERE permission_key='demo.service.front.create'");
|
||||
assert_eq!(
|
||||
server
|
||||
.call("POST", create, r#"{"title":"denied","accept":true}"#, &json)
|
||||
.0,
|
||||
403
|
||||
);
|
||||
assert_eq!(
|
||||
server
|
||||
.call(
|
||||
"GET",
|
||||
"/demo/service/front/main/current",
|
||||
"",
|
||||
&authorization
|
||||
)
|
||||
.0,
|
||||
200
|
||||
);
|
||||
let cookie = dever_runtime::auth::request::Cookie::new("session".into(), "http://localhost")
|
||||
.unwrap()
|
||||
.issue(&provider, &claims, now)
|
||||
.unwrap();
|
||||
let cookie = std::str::from_utf8(&cookie.value)
|
||||
.unwrap()
|
||||
.split(';')
|
||||
.next()
|
||||
.unwrap();
|
||||
let headers = format!("Cookie: {cookie}\r\nContent-Type: application/json\r\n");
|
||||
assert_eq!(
|
||||
server
|
||||
.call("POST", "/demo/service/front/main/touch", "{}", &headers)
|
||||
.0,
|
||||
403
|
||||
);
|
||||
assert_eq!(
|
||||
server
|
||||
.call(
|
||||
"POST",
|
||||
"/demo/service/front/main/touch",
|
||||
"{}",
|
||||
&format!("{headers}Origin: http://localhost\r\n")
|
||||
)
|
||||
.0,
|
||||
200
|
||||
);
|
||||
assert_eq!(
|
||||
server
|
||||
.call(
|
||||
"POST",
|
||||
"/demo/service/front/main/touch",
|
||||
"{}",
|
||||
&format!("{headers}Authorization: Bearer invalid\r\nOrigin: http://localhost\r\n")
|
||||
)
|
||||
.0,
|
||||
401
|
||||
);
|
||||
let submit = "/demo/service/front/main/submit";
|
||||
let (status, user_job) = server.call("POST", submit, r#"{"title":"job-ok"}"#, &json);
|
||||
assert_eq!(status, 200, "{user_job}");
|
||||
let user_id = user_job["data"].as_str().unwrap();
|
||||
let mut worker = Server {
|
||||
child: Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&path)
|
||||
.arg("worker")
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap(),
|
||||
port: 0,
|
||||
};
|
||||
let count_jobs = |state: &str| {
|
||||
dever_runtime::task::run(true, 8, async |scope| {
|
||||
let database = database_config.open(&root, false).await.unwrap();
|
||||
let rows = database
|
||||
.acquire()
|
||||
.await
|
||||
.unwrap()
|
||||
.query(
|
||||
scope,
|
||||
dever_runtime::database::Sql::same(
|
||||
"SELECT COUNT(*) FROM _dever_job WHERE state=$1",
|
||||
),
|
||||
vec![dever_runtime::database::Parameter::Text(state.into())],
|
||||
|row| row.get::<i64>(0),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
Ok::<_, String>(rows[0])
|
||||
})
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
};
|
||||
let until = Instant::now() + Duration::from_secs(5);
|
||||
while server.call("GET", count, "", &authorization).1["data"] != 2 {
|
||||
assert!(
|
||||
worker.child.try_wait().unwrap().is_none(),
|
||||
"worker exited early"
|
||||
);
|
||||
assert!(Instant::now() < until, "user Job did not complete");
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
worker.stop();
|
||||
assert_eq!(
|
||||
server
|
||||
.call("POST", submit, r#"{"title":"job-revoked"}"#, &json)
|
||||
.0,
|
||||
200
|
||||
);
|
||||
sql("UPDATE demo_service_user SET enabled=FALSE WHERE id=1");
|
||||
let worker = Server {
|
||||
child: Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&path)
|
||||
.arg("worker")
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap(),
|
||||
port: 0,
|
||||
};
|
||||
let until = Instant::now() + Duration::from_secs(5);
|
||||
while count_jobs("blocked") != 1 {
|
||||
assert!(
|
||||
Instant::now() < until,
|
||||
"revoked identity Job was not blocked"
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
worker.stop();
|
||||
assert_eq!(server.call("GET", count, "", &authorization).0, 401);
|
||||
assert_eq!(
|
||||
server
|
||||
.call("GET", "/demo/service/front/main/health", "", "")
|
||||
.0,
|
||||
200
|
||||
);
|
||||
server.stop();
|
||||
sql("UPDATE demo_service_user SET enabled=TRUE WHERE id=1");
|
||||
let server = Server::mode(&artifact.binary, &path, port, "all");
|
||||
assert_eq!(
|
||||
server
|
||||
.call("POST", submit, r#"{"title":"job-all-mode"}"#, &json)
|
||||
.0,
|
||||
200
|
||||
);
|
||||
let until = Instant::now() + Duration::from_secs(5);
|
||||
while server.call("GET", count, "", &authorization).1["data"] != 3 {
|
||||
assert!(
|
||||
Instant::now() < until,
|
||||
"joint API/worker mode did not execute the Job"
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
server.stop();
|
||||
let owner = |input: &str| {
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&path)
|
||||
.args(["dever.auth.owner", input])
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
for input in [
|
||||
"[]",
|
||||
r#"{"site":"front","user_id":0}"#,
|
||||
r#"{"site":"missing","user_id":1}"#,
|
||||
r#"{"site":"front","site":"front","user_id":1}"#,
|
||||
] {
|
||||
assert!(!owner(input).status.success());
|
||||
}
|
||||
success(owner(r#"{"site":"front","user_id":1}"#));
|
||||
success(owner(r#"{"site":"front","user_id":1}"#));
|
||||
let server = Server::start(&artifact.binary, &path, port);
|
||||
assert_eq!(
|
||||
server
|
||||
.call("POST", create, r#"{"title":"owner","accept":true}"#, &json)
|
||||
.0,
|
||||
200
|
||||
);
|
||||
|
||||
let command = |name: &str, input: serde_json::Value| {
|
||||
let output = success(
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&path)
|
||||
.args([name, &input.to_string()])
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
serde_json::from_str::<serde_json::Value>(&output).unwrap()["data"].clone()
|
||||
};
|
||||
let system_job = command(
|
||||
"demo.service.submitSystem",
|
||||
serde_json::json!({"title":"job-system"}),
|
||||
);
|
||||
let system_id = system_job.as_str().unwrap();
|
||||
let ids = serde_json::json!({"owned":user_id,"scheduled":system_id});
|
||||
let endpoint = "/demo/service/front/main/jobStates";
|
||||
let (status, user_states) = server.call("POST", endpoint, &ids.to_string(), &json);
|
||||
assert_eq!(status, 200, "{user_states}");
|
||||
assert_eq!(
|
||||
user_states["data"],
|
||||
serde_json::json!({"owned_state":"completed","scheduled_state":null})
|
||||
);
|
||||
assert_eq!(
|
||||
command("demo.service.systemJobStates", ids),
|
||||
serde_json::json!({"owned_state":null,"scheduled_state":"pending"})
|
||||
);
|
||||
server.stop();
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
//! 从真实 HTTP 调用授权原语,验证实时生效、事务回滚和 Owner 保护。
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn generated_authorization_uses_real_roles_and_transaction_boundaries() {
|
||||
exercise(
|
||||
"authorization",
|
||||
serde_json::json!({"type":"sqlite","path":"data/main.db","max_connections":1}),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires an isolated PostgreSQL database; run test/postgres.py"]
|
||||
fn postgres_generated_authorization_uses_real_roles_and_transaction_boundaries() {
|
||||
exercise(
|
||||
"authorization-postgres",
|
||||
serde_json::json!({"type":"postgres","url":std::env::var("DEVER_TEST_POSTGRES").unwrap(),"tls":"disabled","max_connections":2}),
|
||||
);
|
||||
}
|
||||
|
||||
fn exercise(name: &str, database: serde_json::Value) {
|
||||
let root = project(
|
||||
name,
|
||||
r#"
|
||||
type Identity {id:Text,user_id:data.user.id?,tenant_id:data.tenant.id?}
|
||||
flow verify(claims:dever.auth.Claims) (identity:Identity)
|
||||
| step | kind | do |
|
||||
| user | data | data.user.first(name == claims.subject) |
|
||||
| - | check | user != null else Unauthorized |
|
||||
| identity | calc | Identity {id=claims.subject,user_id=user.id,tenant_id=null} |
|
||||
flow save(id:Text,accept:Bool) ()
|
||||
| step | kind | do |
|
||||
| - | calc | dever.auth.saveRole(id,"Reader",false,["demo.service.front.read"]) |
|
||||
| - | calc | dever.auth.grantRole(2,id) |
|
||||
| - | check | accept else Conflict |
|
||||
flow roles() (out:List<dever.auth.Role>)
|
||||
| step | kind | do |
|
||||
| out | calc | dever.auth.roles() |
|
||||
flow role(id:Text) (out:dever.auth.Role?)
|
||||
| step | kind | do |
|
||||
| out | calc | dever.auth.role(id) |
|
||||
flow revoke(id:Text) ()
|
||||
| step | kind | do |
|
||||
| - | calc | dever.auth.revokeRole(2,id) |
|
||||
flow disable(id:Text) ()
|
||||
| step | kind | do |
|
||||
| - | calc | dever.auth.disableRole(id) |
|
||||
flow remove(id:Text) ()
|
||||
| step | kind | do |
|
||||
| - | calc | dever.auth.deleteRole(id) |
|
||||
flow permissions() (out:List<dever.auth.Permission>)
|
||||
| step | kind | do |
|
||||
| out | calc | dever.auth.permissions() |
|
||||
flow currentPermissions() (out:List<dever.auth.Permission>)
|
||||
| step | kind | do |
|
||||
| out | calc | dever.auth.currentPermissions() |
|
||||
flow userRoles(user:data.user.id) (out:List<dever.auth.Role>)
|
||||
| step | kind | do |
|
||||
| out | calc | dever.auth.userRoles(user) |
|
||||
flow owner(user:Int) (out:Bool)
|
||||
| step | kind | do |
|
||||
| out | calc | dever.auth.hasProtectedRoles(user) |
|
||||
read() (out:Text) {out="read"}
|
||||
"#,
|
||||
"post save = app.save\nget roles = app.roles\nget role = app.role\npost revoke = app.revoke\npost disable = app.disable\ndelete remove = app.remove\nget permissions = app.permissions\nauthenticated get currentPermissions = app.currentPermissions\nget userRoles = app.userRoles\nget owner = app.owner\nget read = app.read",
|
||||
);
|
||||
let models = root.join("module/demo/service/data");
|
||||
fs::create_dir_all(&models).unwrap();
|
||||
fs::write(
|
||||
models.join("user.dever"),
|
||||
"global type User {name:Text unique}\nseed {{name=\"admin\"},{name=\"reader\"}}",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
models.join("tenant.dever"),
|
||||
"global type Tenant {name:Text}",
|
||||
)
|
||||
.unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
let (path, port, mut config) = config(&root);
|
||||
config["database"] = serde_json::json!({"default":database});
|
||||
config["sites"]["front"]["auth"] = serde_json::json!("users");
|
||||
config["sites"]["front"]["origin"] = serde_json::json!("http://localhost");
|
||||
config["auth"] = serde_json::json!({"providers":{"users":{"verify":"demo.service.verify","jwtSecret":"01234567890123456789012345678901","ttlSeconds":3600,"cookie":"session"}}});
|
||||
fs::write(&path, config.to_string()).unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
for args in [
|
||||
vec!["migrate"],
|
||||
vec![
|
||||
"dever.auth.owner",
|
||||
r#"{"site":"front","user_id":1,"tenant":null}"#,
|
||||
],
|
||||
] {
|
||||
success(
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&path)
|
||||
.args(args)
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
}
|
||||
let provider = dever_runtime::auth::Provider::new(
|
||||
"users".into(),
|
||||
dever_runtime::value::secret::Secret::from_input(
|
||||
b"01234567890123456789012345678901".to_vec(),
|
||||
),
|
||||
3600,
|
||||
)
|
||||
.unwrap();
|
||||
let headers = |subject: &str| {
|
||||
let header =
|
||||
dever_runtime::auth::request::Cookie::new("session".into(), "http://localhost")
|
||||
.unwrap()
|
||||
.issue(
|
||||
&provider,
|
||||
&dever_runtime::auth::Claims {
|
||||
subject: subject.into(),
|
||||
session: "test-session".into(),
|
||||
tenant: None,
|
||||
site: "front".into(),
|
||||
},
|
||||
dever_runtime::value::calendar::DateTime::now()
|
||||
.unwrap()
|
||||
.millis()
|
||||
/ 1000,
|
||||
)
|
||||
.unwrap();
|
||||
format!(
|
||||
"Cookie: {}\r\nOrigin: http://localhost\r\nContent-Type: application/json\r\n",
|
||||
std::str::from_utf8(&header.value)
|
||||
.unwrap()
|
||||
.split(';')
|
||||
.next()
|
||||
.unwrap()
|
||||
)
|
||||
};
|
||||
let admin = headers("admin");
|
||||
let reader = headers("reader");
|
||||
let server = Server::start(&artifact.binary, &path, port);
|
||||
let call = |method: &str, action: &str, body: &str, headers: &str| {
|
||||
server.call(
|
||||
method,
|
||||
&format!("/demo/service/front/main/{action}"),
|
||||
body,
|
||||
headers,
|
||||
)
|
||||
};
|
||||
assert_eq!(call("GET", "read", "", &reader).0, 403);
|
||||
assert_eq!(
|
||||
call(
|
||||
"POST",
|
||||
"save",
|
||||
r#"{"id":"rollback","accept":false}"#,
|
||||
&admin
|
||||
)
|
||||
.0,
|
||||
409
|
||||
);
|
||||
assert!(call("GET", "role?id=rollback", "", &admin).1["data"].is_null());
|
||||
assert_eq!(call("GET", "read", "", &reader).0, 403);
|
||||
assert_eq!(
|
||||
call("POST", "save", r#"{"id":"reader","accept":true}"#, &admin).0,
|
||||
200
|
||||
);
|
||||
assert_eq!(call("GET", "read", "", &reader).0, 200);
|
||||
let permissions = call("GET", "currentPermissions", "", &reader);
|
||||
assert_eq!(permissions.0, 200);
|
||||
assert_eq!(
|
||||
permissions.1["data"],
|
||||
serde_json::json!([{"key":"demo.service.front.read","component":"demo","domain":"service","site":"front","action":"read","method":"GET","kind":"http"}])
|
||||
);
|
||||
assert_eq!(
|
||||
call("GET", "userRoles?user=2", "", &admin).1["data"][0]["id"],
|
||||
"reader"
|
||||
);
|
||||
assert_eq!(call("GET", "owner?user=1", "", &admin).1["data"], true);
|
||||
assert_eq!(call("GET", "owner?user=2", "", &admin).1["data"], false);
|
||||
for action in ["disable", "remove", "save"] {
|
||||
let (method, action, body) = if action == "remove" {
|
||||
("DELETE", "remove?id=owner", "")
|
||||
} else {
|
||||
(
|
||||
"POST",
|
||||
action,
|
||||
if action == "save" {
|
||||
r#"{"id":"owner","accept":true}"#
|
||||
} else {
|
||||
r#"{"id":"owner"}"#
|
||||
},
|
||||
)
|
||||
};
|
||||
assert_eq!(call(method, action, body, &admin).0, 403);
|
||||
}
|
||||
for _ in 0..2 {
|
||||
assert_eq!(call("POST", "revoke", r#"{"id":"reader"}"#, &admin).0, 200);
|
||||
}
|
||||
assert_eq!(call("GET", "read", "", &reader).0, 403);
|
||||
assert_eq!(
|
||||
call("POST", "save", r#"{"id":"reader","accept":true}"#, &admin).0,
|
||||
200
|
||||
);
|
||||
assert_eq!(call("POST", "disable", r#"{"id":"reader"}"#, &admin).0, 200);
|
||||
assert_eq!(call("GET", "read", "", &reader).0, 403);
|
||||
assert_eq!(call("DELETE", "remove?id=reader", "", &admin).0, 200);
|
||||
assert_eq!(call("POST", "revoke", r#"{"id":"reader"}"#, &admin).0, 404);
|
||||
assert_eq!(
|
||||
call("GET", "roles", "", &admin).1["data"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.len(),
|
||||
1
|
||||
);
|
||||
assert!(
|
||||
!call("GET", "permissions", "", &admin).1["data"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
server.stop();
|
||||
}
|
||||
@@ -0,0 +1,461 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn unused_model_sources_are_checked_without_generating_rest_routes() {
|
||||
let root = project(
|
||||
"unused-rest-bindings",
|
||||
"text() (out:Text) {out=\"value\"}",
|
||||
"",
|
||||
);
|
||||
let model = root.join("module/demo/service/data/main.dever");
|
||||
for source in [
|
||||
"title:Text create = missing",
|
||||
"title:Text replace = 1",
|
||||
"title:Text create = app.text()",
|
||||
"title:Text index search = input + 1",
|
||||
"private title:Text create = input",
|
||||
] {
|
||||
write_source(&model, format!("type Service {{{source}}}")).unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(loaded.diagnostics.is_empty());
|
||||
assert!(
|
||||
program::check(&loaded.declarations, &loaded.modules).is_err(),
|
||||
"{source}"
|
||||
);
|
||||
}
|
||||
write_source(&model, "type Service {private internal:Text,title:Text create = text.trim(input) replace = text.lower(input)}").unwrap();
|
||||
let (_, program) = analyze(&root);
|
||||
assert!(program.http.is_empty());
|
||||
assert!(
|
||||
!program
|
||||
.functions
|
||||
.iter()
|
||||
.any(|f| f.signature.name.contains("Rest"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rest_rejects_unsafe_sources_and_ambiguous_routes() {
|
||||
for (model, api) in [
|
||||
("private title:Text", "rest data.article"),
|
||||
("private title:Text create = input", "rest data.article"),
|
||||
("uid:Uuid generated create = input", "rest data.article"),
|
||||
(
|
||||
"owner user_id:data.user.id? = dever.auth.userId()",
|
||||
"rest data.article",
|
||||
),
|
||||
(
|
||||
"owner first_id:data.user.id = dever.auth.userId()\nowner second_id:data.tenant.id = dever.auth.tenantId()",
|
||||
"rest data.article",
|
||||
),
|
||||
("title:Text search = input", "rest data.article"),
|
||||
("title:Text index search = \"fixed\"", "rest data.article"),
|
||||
(
|
||||
"title:Text index search = input\nother_title:Text index search = input",
|
||||
"rest data.article",
|
||||
),
|
||||
("page:Int index search = input", "rest data.article"),
|
||||
("title:Text create = app.text()", "rest data.article"),
|
||||
("title:Text create = missing", "rest data.article"),
|
||||
("title:Text create = 1", "rest data.article"),
|
||||
("title:Text", "rest data.article\nget read = app.text"),
|
||||
] {
|
||||
let root = project(
|
||||
"rest-invalid",
|
||||
"type Identity {id:Text,user_id:data.user.id?,tenant_id:data.tenant.id?}\nverify(claims:dever.auth.Claims) (out:Identity) {out=Identity{id=claims.subject,user_id=null,tenant_id=null}}\ntext() (out:Text) {out=\"value\"}",
|
||||
api,
|
||||
);
|
||||
let directory = root.join("module/demo/service/data");
|
||||
fs::create_dir_all(&directory).unwrap();
|
||||
fs::write(directory.join("user.dever"), "global type User {name:Text}").unwrap();
|
||||
fs::write(
|
||||
directory.join("tenant.dever"),
|
||||
"global type Tenant {name:Text}",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
directory.join("article.dever"),
|
||||
format!("type Article {{{model}}}"),
|
||||
)
|
||||
.unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(
|
||||
loaded.diagnostics.is_empty(),
|
||||
"{model}: {:?}",
|
||||
loaded.diagnostics
|
||||
);
|
||||
assert!(
|
||||
program::check(&loaded.declarations, &loaded.modules).is_err(),
|
||||
"accepted {model} / {api}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_operations_require_http_write_context() {
|
||||
for api in [
|
||||
"public get clear = app.clear",
|
||||
"cmd clear = app.clear",
|
||||
"job clear() retry(1) timeout(1000) = app.clear",
|
||||
] {
|
||||
let root = project(
|
||||
"session-contracts",
|
||||
"flow clear() ()\n| step | kind | do |\n| - | calc | dever.auth.clearCookie() |",
|
||||
api,
|
||||
);
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(loaded.diagnostics.is_empty());
|
||||
let error = program::check(&loaded.declarations, &loaded.modules)
|
||||
.err()
|
||||
.expect("session context required");
|
||||
assert!(
|
||||
error.message.contains("HTTP write entry")
|
||||
|| error.message.contains("CMD cannot")
|
||||
|| error.message.contains("Job cannot"),
|
||||
"{api}: {error:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn authorization_changes_cannot_escape_protected_write_entries() {
|
||||
for api in [
|
||||
"public post change = app.change",
|
||||
"authenticated post change = app.change",
|
||||
"get change = app.change",
|
||||
"long post change = app.change",
|
||||
"job change() retry(1) timeout(1000) = app.change",
|
||||
"cmd change = app.change",
|
||||
] {
|
||||
let root = project(
|
||||
"authorization-contracts",
|
||||
"flow change() ()\n| step | kind | do |\n| - | flow | app.save() |\nflow save() ()\n| step | kind | do |\n| - | calc | dever.auth.saveRole(\"reader\",\"Reader\",false,[]) |",
|
||||
api,
|
||||
);
|
||||
let project = Project::load(&root).unwrap();
|
||||
assert!(project.diagnostics.is_empty());
|
||||
let error = program::check(&project.declarations, &project.modules)
|
||||
.err()
|
||||
.expect("invalid authorization entry");
|
||||
assert!(
|
||||
error.message.contains("protected HTTP write entry")
|
||||
|| error.message.contains("CMD cannot"),
|
||||
"{api}: {error:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn http_bindings_share_wire_and_transaction_contracts_and_keep_source_navigation() {
|
||||
let root = project(
|
||||
"api-contracts",
|
||||
r#"
|
||||
type Payload {value:Text}
|
||||
flow write(value:Text) ()
|
||||
| step | kind | do |
|
||||
| - | data | data.create({value=value}) |
|
||||
flow queue(value:Text) ()
|
||||
| step | kind | do |
|
||||
| - | calc | enqueue(job.save,Payload {value=value},value) |
|
||||
flow save(input:Payload) ()
|
||||
| step | kind | do |
|
||||
| - | data | data.create({value=input.value}) |
|
||||
record(value:Payload) (out:Payload) {out=value}
|
||||
flow print(value:Text) ()
|
||||
| step | kind | do |
|
||||
| - | flow | dever.io.println(value) |
|
||||
scalar(value:Text) (out:Text) {out=value}
|
||||
"#,
|
||||
"public get scalar = app.scalar",
|
||||
);
|
||||
let domain = root.join("module/demo/service");
|
||||
write_source(domain.join("data/main.dever"), "type Service {value:Text}").unwrap();
|
||||
let path = domain.join("api/front/main.dever");
|
||||
for (api, message) in [
|
||||
("get bad = app.write", "GET cannot"),
|
||||
("public post bad = app.print", "cannot block"),
|
||||
("long get bad = app.scalar", "GET cannot"),
|
||||
("public get bad = app.record", "must be scalar"),
|
||||
("public delete bad = app.record", "must be scalar"),
|
||||
(
|
||||
"public post bad = app.queue",
|
||||
"cannot access this Job queue with its declared identity",
|
||||
),
|
||||
(
|
||||
"authenticated post bad = app.queue",
|
||||
"cannot access this Job queue with its declared identity",
|
||||
),
|
||||
(
|
||||
"public get same = app.scalar\npublic get same = app.scalar",
|
||||
"duplicate HTTP",
|
||||
),
|
||||
] {
|
||||
fs::write(
|
||||
&path,
|
||||
format!("job save(input:app.Payload) retry(1) timeout(1000) = app.save\n{api}"),
|
||||
)
|
||||
.unwrap();
|
||||
let project = Project::load(&root).unwrap();
|
||||
assert!(project.diagnostics.is_empty(), "{:?}", project.diagnostics);
|
||||
let error = program::check(&project.declarations, &project.modules)
|
||||
.err()
|
||||
.expect("invalid API rejected");
|
||||
assert!(error.message.contains(message), "{api}: {error:?}");
|
||||
}
|
||||
fs::write(&path,"job save(input:app.Payload) retry(1) timeout(1000) = app.save\npublic get scalar = app.scalar").unwrap();
|
||||
let (project, program) = analyze(&root);
|
||||
let formatted = dever::compiler::format::format(&project.declarations);
|
||||
assert!(formatted.contains("public get scalar = app.scalar"));
|
||||
assert_eq!(program.http.len(), 1);
|
||||
let index = dever::compiler::inspect::analyze(&project, None, 1, true).unwrap();
|
||||
let http = index.symbols.iter().find(|s| s.kind == "http").unwrap();
|
||||
let graph = index.flows.iter().find(|f| f.symbol == http.id).unwrap();
|
||||
assert!(
|
||||
graph
|
||||
.nodes
|
||||
.iter()
|
||||
.any(|n| n.target.as_deref() == Some("demo.service.app.scalar"))
|
||||
);
|
||||
assert!(!graph.nodes.iter().any(|n| n.label.contains("verify")));
|
||||
assert!(graph.edges.iter().any(|e| e.label == "失败"));
|
||||
assert!(
|
||||
index
|
||||
.calls
|
||||
.iter()
|
||||
.any(|c| c.caller == http.id && c.kind == "entry")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tenant_http_rejects_indirect_public_reads_before_listening() {
|
||||
use serde_json::json;
|
||||
let root = project(
|
||||
"tenant-public-contract",
|
||||
r#"
|
||||
flow localCount() (out: Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.count() |
|
||||
flow indirect() (out: Int)
|
||||
| step | kind | do |
|
||||
| out | flow | localCount() |
|
||||
flow globalCount() (out: Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.banner.count() |
|
||||
"#,
|
||||
"public get local = app.indirect\npublic get summary = app.globalCount",
|
||||
);
|
||||
let domain = root.join("module/demo/service");
|
||||
fs::create_dir(domain.join("data")).unwrap();
|
||||
write_source(domain.join("data/main.dever"), "type Service {title: Text}").unwrap();
|
||||
fs::write(
|
||||
domain.join("data/banner.dever"),
|
||||
"global type Banner {title: Text}",
|
||||
)
|
||||
.unwrap();
|
||||
fs::create_dir(root.join("data")).unwrap();
|
||||
success(cli(&["fmt", root.to_str().unwrap()]));
|
||||
let (path, port, mut settings) = config(&root);
|
||||
settings["database"] = json!({"create":true,"default":{"type":"sqlite","path":"data/control.db","tenant_directory":"data/tenants"}});
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
fs::write(&path, settings.to_string()).unwrap();
|
||||
success(cli(&["check", root.to_str().unwrap()]));
|
||||
let server = Server::start(&artifact.binary, &path, port);
|
||||
assert_eq!(
|
||||
server
|
||||
.call("GET", "/demo/service/front/main/local", "", "")
|
||||
.1["data"],
|
||||
0
|
||||
);
|
||||
server.stop();
|
||||
|
||||
settings["tenant"] = json!({"database":"default"});
|
||||
fs::write(&path, settings.to_string()).unwrap();
|
||||
let error = cli(&["check", root.to_str().unwrap()]);
|
||||
let reason = String::from_utf8_lossy(&error.stderr);
|
||||
assert!(!error.status.success());
|
||||
assert!(reason.contains("app/main.dever:"), "{reason}");
|
||||
assert!(
|
||||
reason.contains("GET /demo/service/front/main/local requires authentication"),
|
||||
"{reason}"
|
||||
);
|
||||
let child = Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&path)
|
||||
.arg("api")
|
||||
.stderr(std::process::Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let mut server = Server { child, port };
|
||||
assert!(!server.wait_for_exit().success());
|
||||
let mut reason = String::new();
|
||||
server
|
||||
.child
|
||||
.stderr
|
||||
.take()
|
||||
.unwrap()
|
||||
.read_to_string(&mut reason)
|
||||
.unwrap();
|
||||
assert!(
|
||||
reason.contains("GET /demo/service/front/main/local requires authentication"),
|
||||
"{reason}"
|
||||
);
|
||||
assert!(TcpStream::connect(("127.0.0.1", port)).is_err());
|
||||
drop(artifact);
|
||||
|
||||
fs::write(
|
||||
domain.join("api/front/main.dever"),
|
||||
"public get summary = app.globalCount",
|
||||
)
|
||||
.unwrap();
|
||||
success(cli(&["fmt", root.to_str().unwrap()]));
|
||||
success(cli(&["check", root.to_str().unwrap()]));
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
let server = Server::start(&artifact.binary, &path, port);
|
||||
assert_eq!(
|
||||
server
|
||||
.call("GET", "/demo/service/front/main/summary", "", "")
|
||||
.1["data"],
|
||||
0
|
||||
);
|
||||
server.stop();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn http_shutdown_drains_or_cancels_an_accepted_request() {
|
||||
let root = project(
|
||||
"http-drain-deadline",
|
||||
"echo(value: Text) (out: Text) {out = value}",
|
||||
"public post echo = app.echo",
|
||||
);
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
for (deadline, finish) in [(1500, true), (200, false)] {
|
||||
let (path, port, mut settings) = config(&root);
|
||||
settings["http"]["shutdown_ms"] = deadline.into();
|
||||
fs::write(&path, settings.to_string()).unwrap();
|
||||
let mut server = Server::start(&artifact.binary, &path, port);
|
||||
let body = r#"{"value":"drained"}"#;
|
||||
let mut stream = pending_echo(port, body.len());
|
||||
server.terminate();
|
||||
let mut output = String::new();
|
||||
if finish {
|
||||
let until = Instant::now() + Duration::from_secs(1);
|
||||
while TcpStream::connect(("127.0.0.1", port)).is_ok() {
|
||||
assert!(
|
||||
Instant::now() < until,
|
||||
"listener still accepting after SIGTERM"
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
stream.get_mut().write_all(body.as_bytes()).unwrap();
|
||||
stream.read_to_string(&mut output).unwrap();
|
||||
assert!(output.starts_with("HTTP/1.1 200 "), "{output}");
|
||||
assert!(output.contains("\"data\":\"drained\""), "{output}");
|
||||
} else {
|
||||
stream.read_to_string(&mut output).unwrap();
|
||||
assert!(output.is_empty(), "{output}");
|
||||
}
|
||||
assert_eq!(server.wait_for_exit().success(), finish);
|
||||
if !finish {
|
||||
assert!(
|
||||
fs::read_to_string(path.with_extension("server.log"))
|
||||
.unwrap()
|
||||
.contains("HTTP shutdown deadline expired")
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn pending_echo(port: u16, bytes: usize) -> std::io::BufReader<TcpStream> {
|
||||
use std::io::{BufRead, BufReader};
|
||||
let stream = TcpStream::connect(("127.0.0.1", port)).unwrap();
|
||||
stream
|
||||
.set_read_timeout(Some(Duration::from_secs(5)))
|
||||
.unwrap();
|
||||
let mut stream = BufReader::new(stream);
|
||||
write!(stream.get_mut(), "POST /demo/service/front/main/echo HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\nContent-Type: application/json\r\nExpect: 100-continue\r\nContent-Length: {bytes}\r\n\r\n").unwrap();
|
||||
let mut line = String::new();
|
||||
stream.read_line(&mut line).unwrap();
|
||||
assert!(line.starts_with("HTTP/1.1 100 "), "{line}");
|
||||
line.clear();
|
||||
stream.read_line(&mut line).unwrap();
|
||||
assert_eq!(line, "\r\n");
|
||||
stream
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn http_shutdown_in_all_mode_leaves_the_worker_its_own_deadline() {
|
||||
use serde_json::json;
|
||||
let root = project(
|
||||
"drain-api-and-job",
|
||||
r#"
|
||||
type Input { label: Text }
|
||||
echo(value: Text) (out: Text) {out = value}
|
||||
flow submit(input: Input) (out: Id)
|
||||
| step | kind | do |
|
||||
| out | calc | enqueue(job.record, input, input.label) |
|
||||
transaction flow stage(label: Text) ()
|
||||
| step | kind | do |
|
||||
| - | data | data.create({title = label}) |
|
||||
flow handle(input: Input) ()
|
||||
| step | kind | do |
|
||||
| - | flow | stage(input.label) |
|
||||
| - | flow | dever.time.sleep(900) |
|
||||
| - | flow | stage("finished") |
|
||||
flow count() (out: Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.count() |
|
||||
"#,
|
||||
"public post echo = app.echo\npublic get count = app.count",
|
||||
);
|
||||
let domain = root.join("module/demo/service");
|
||||
write_source(domain.join("data/main.dever"), "type Service {title: Text}").unwrap();
|
||||
fs::write(domain.join("api.dever"), "long job record(input: app.Input) retry(1) timeout(4000) = app.handle\ncmd submit = app.submit\ncmd count = app.count").unwrap();
|
||||
fs::create_dir(root.join("data")).unwrap();
|
||||
let (path, port, mut settings) = config(&root);
|
||||
settings["http"]["shutdown_ms"] = json!(150);
|
||||
settings["job"] = json!({"workers":1,"poll_ms":10,"shutdown_ms":2500});
|
||||
settings["database"] = json!({"create":true,"default":{"type":"sqlite","path":"data/jobs.db","max_connections":4}});
|
||||
fs::write(&path, settings.to_string()).unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
let mut server = Server::mode(&artifact.binary, &path, port, "all");
|
||||
let mut request = pending_echo(port, 16);
|
||||
let call = |name: &str, input: &str| {
|
||||
success(
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&path)
|
||||
.args([name, input])
|
||||
.output()
|
||||
.unwrap(),
|
||||
)
|
||||
};
|
||||
call("demo.service.submit", r#"{"input":{"label":"started"}}"#);
|
||||
let until = Instant::now() + Duration::from_secs(3);
|
||||
loop {
|
||||
let (status, body) = server.call("GET", "/demo/service/front/main/count", "", "");
|
||||
assert_eq!(status, 200, "{body}");
|
||||
match body["data"].as_i64().unwrap() {
|
||||
0 => {
|
||||
assert!(Instant::now() < until, "Job did not start");
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
1 => break,
|
||||
_ => panic!("Job finished before the stop signal"),
|
||||
}
|
||||
}
|
||||
server.terminate();
|
||||
let mut response = String::new();
|
||||
request.read_to_string(&mut response).unwrap();
|
||||
assert!(response.is_empty(), "{response}");
|
||||
assert!(!server.wait_for_exit().success());
|
||||
let error = fs::read_to_string(path.with_extension("server.log")).unwrap();
|
||||
assert!(error.contains("HTTP shutdown deadline expired"), "{error}");
|
||||
let done: serde_json::Value = serde_json::from_str(&call("demo.service.count", "{}")).unwrap();
|
||||
assert_eq!(
|
||||
done["data"], 2,
|
||||
"the worker must finish after HTTP is cancelled"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
//! 身份沿调用图与任务传递,入口权限由编译器约束,Provider 名义类型由配置绑定核对。
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn identity_reads_reject_untrusted_entries_and_pure_functions() {
|
||||
for (name, app, api, message) in [
|
||||
(
|
||||
"anonymous",
|
||||
"flow current() (out:Text)\n| step | kind | do |\n| out | calc | dever.auth.id() |",
|
||||
"public get current = app.current",
|
||||
"public HTTP",
|
||||
),
|
||||
(
|
||||
"command",
|
||||
"flow current() (out:Text)\n| step | kind | do |\n| out | calc | dever.auth.id() |",
|
||||
"cmd current = app.current",
|
||||
"CMD cannot",
|
||||
),
|
||||
(
|
||||
"pure",
|
||||
"current() (out:Text) {out=dever.auth.id()}",
|
||||
"authenticated get current = app.current",
|
||||
"pure",
|
||||
),
|
||||
(
|
||||
"argument",
|
||||
"flow current() (out:Text)\n| step | kind | do |\n| out | calc | dever.auth.id(\"forged\") |",
|
||||
"authenticated get current = app.current",
|
||||
"no arguments",
|
||||
),
|
||||
(
|
||||
"nominal",
|
||||
"flow current() (out:Int?)\n| step | kind | do |\n| out | calc | dever.auth.userId() |",
|
||||
"authenticated get current = app.current",
|
||||
"nominal Model ID",
|
||||
),
|
||||
(
|
||||
"transitive",
|
||||
"flow current() (out:Text)\n| step | kind | do |\n| out | flow | app.readIdentity() |\nflow readIdentity() (out:Text)\n| step | kind | do |\n| out | calc | dever.auth.id() |",
|
||||
"public get current = app.current",
|
||||
"public HTTP",
|
||||
),
|
||||
(
|
||||
"scheduled",
|
||||
"flow current() ()\n| step | kind | do |\n| - | calc | dever.auth.id() |",
|
||||
"job current() retry(1) timeout(1000) = app.current\nschedule every = \"* * * * *\" = app.current",
|
||||
"System Job",
|
||||
),
|
||||
] {
|
||||
let root = project(&format!("identity-{name}"), app, api);
|
||||
let project = Project::load(&root).unwrap();
|
||||
assert!(
|
||||
project.diagnostics.is_empty(),
|
||||
"{name}: {:?}",
|
||||
project.diagnostics
|
||||
);
|
||||
let error = program::check(&project.declarations, &project.modules)
|
||||
.err()
|
||||
.expect("invalid identity use");
|
||||
assert!(error.message.contains(message), "{name}: {error:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identity_provider_types_are_checked_before_starting_http() {
|
||||
let root = project(
|
||||
"identity-provider",
|
||||
r#"
|
||||
type Identity {id:Text,user_id:data.user.id?,tenant_id:data.tenant.id?}
|
||||
flow verify(claims:dever.auth.Claims) (identity:Identity)
|
||||
| step | kind | do |
|
||||
| identity | calc | Identity {id=claims.subject,user_id=null,tenant_id=null} |
|
||||
flow current() (out:data.tenant.id?)
|
||||
| step | kind | do |
|
||||
| out | calc | dever.auth.userId() |
|
||||
"#,
|
||||
"authenticated get current = app.current",
|
||||
);
|
||||
let domain = root.join("module/demo/service/data");
|
||||
fs::create_dir_all(&domain).unwrap();
|
||||
fs::write(domain.join("user.dever"), "global type User {name:Text}").unwrap();
|
||||
fs::write(
|
||||
domain.join("tenant.dever"),
|
||||
"global type Tenant {name:Text}",
|
||||
)
|
||||
.unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
let (path, _, mut config) = config(&root);
|
||||
config["database"] = serde_json::json!({"default":{"type":"sqlite","path":"missing.db"}});
|
||||
config["sites"]["front"]["auth"] = serde_json::json!("users");
|
||||
config["auth"] = serde_json::json!({"providers":{"users":{"verify":"demo.service.verify","jwtSecret":"01234567890123456789012345678901","ttlSeconds":3600}}});
|
||||
fs::write(&path, config.to_string()).unwrap();
|
||||
let result = Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&path)
|
||||
.arg("api")
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(!result.status.success());
|
||||
assert!(
|
||||
String::from_utf8_lossy(&result.stderr).contains("Provider identity types do not match"),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&result.stderr)
|
||||
);
|
||||
assert!(!root.join("missing.db").exists());
|
||||
}
|
||||
@@ -0,0 +1,465 @@
|
||||
mod auth;
|
||||
mod authorization;
|
||||
mod checks;
|
||||
mod identity;
|
||||
mod rest;
|
||||
mod session;
|
||||
mod tenant;
|
||||
mod tls;
|
||||
use super::*;
|
||||
use std::{
|
||||
io::{Read, Write},
|
||||
net::TcpStream,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
fn project(name: &str, app: &str, api: &str) -> PathBuf {
|
||||
let root = directory(name);
|
||||
let domain = root.join("module/demo/service");
|
||||
fs::create_dir_all(domain.join("api/front")).unwrap();
|
||||
write_source(domain.join("app/main.dever"), app).unwrap();
|
||||
fs::write(domain.join("api/front/main.dever"), api).unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
root
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_typescript_client_calls_http_without_losing_integer_or_json_precision() {
|
||||
let root = project(
|
||||
"typescript-client",
|
||||
r#"
|
||||
type Value { count: Int, ratio: Float, price: Decimal, raw: Json, label: Text? }
|
||||
echo(value: Value) (out: Value) { out = value }
|
||||
hello(name: Text) (out: Text) { out = name }
|
||||
flow reject(accepted: Bool) ()
|
||||
| step | kind | do |
|
||||
| - | check | accepted else Conflict |
|
||||
"#,
|
||||
"public post echo = app.echo\npublic get hello = app.hello\npublic post reject = app.reject",
|
||||
);
|
||||
success(cli(&["fmt", root.to_str().unwrap()]));
|
||||
let client = root.join("client.ts");
|
||||
success(cli(&[
|
||||
"client",
|
||||
root.to_str().unwrap(),
|
||||
"--output",
|
||||
client.to_str().unwrap(),
|
||||
]));
|
||||
assert!(
|
||||
!cli(&[
|
||||
"client",
|
||||
root.to_str().unwrap(),
|
||||
"--output",
|
||||
client.to_str().unwrap()
|
||||
])
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
let (path, port, mut value) = config(&root);
|
||||
value["sites"]["front"]["hosts"] = serde_json::json!(["127.0.0.1"]);
|
||||
fs::write(&path, value.to_string()).unwrap();
|
||||
let server = Server::start(&artifact.binary, &path, port);
|
||||
fs::write(root.join("call.mjs"), r#"
|
||||
import assert from 'node:assert/strict';
|
||||
import {createClient,rawJson,ApiError} from './client.ts';
|
||||
const client=createClient(process.argv[2]);
|
||||
const value={count:9223372036854775807n,ratio:1.25,price:'12345678901234567890.12',raw:{number:rawJson('12345678901234567890.123456789')},label:null};
|
||||
assert.deepEqual(await client['POST /demo/service/front/main/echo']({value}),value);
|
||||
const query="中文 + & = / ?";
|
||||
assert.equal(await client['GET /demo/service/front/main/hello']({name:query}),query);
|
||||
await assert.rejects(client['POST /demo/service/front/main/reject']({accepted:false}),e=>e instanceof ApiError&&e.status===409&&e.code===409);
|
||||
await assert.rejects(client['GET /demo/service/front/main/hello']({name:'stop'},{signal:AbortSignal.abort()}),e=>e.name==='AbortError');
|
||||
console.log('client HTTP precision, query, error and abort passed');
|
||||
"#).unwrap();
|
||||
let output = success(
|
||||
Command::new("node")
|
||||
.arg(root.join("call.mjs"))
|
||||
.arg(format!("http://127.0.0.1:{port}"))
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
assert!(output.contains("passed"));
|
||||
server.stop();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_game_example_executes_real_http_and_rejects_unknown_actions() {
|
||||
let example = Path::new(env!("CARGO_MANIFEST_DIR")).join("../examples/next/text_game");
|
||||
let (loaded, program) = analyze(&example);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
let root = directory("text-game-http");
|
||||
fs::create_dir(root.join("config")).unwrap();
|
||||
let (path, port, mut settings) = config(&root);
|
||||
settings["sites"] = serde_json::json!({"web":{"path":"web","hosts":["localhost"]}});
|
||||
fs::write(&path, settings.to_string()).unwrap();
|
||||
let server = Server::start(&artifact.binary, &path, port);
|
||||
for (actions, expected) in [
|
||||
(serde_json::json!([]), "Locked"),
|
||||
(serde_json::json!(["Open"]), "Locked"),
|
||||
(serde_json::json!(["Search", "Search"]), "KeyFound"),
|
||||
(serde_json::json!(["Look", "Search", "Open", "Quit"]), "Won"),
|
||||
(serde_json::json!(["Quit", "Search", "Open"]), "GaveUp"),
|
||||
] {
|
||||
let (status, response) = server.call(
|
||||
"POST",
|
||||
"/game/escape/web/game/play",
|
||||
&serde_json::json!({"actions":actions}).to_string(),
|
||||
"Content-Type: application/json\r\n",
|
||||
);
|
||||
assert_eq!(status, 200, "{response}");
|
||||
assert_eq!(response["data"]["stage"], expected);
|
||||
}
|
||||
let (status, response) = server.call(
|
||||
"POST",
|
||||
"/game/escape/web/game/step",
|
||||
r#"{"stage":"Won","action":"Quit"}"#,
|
||||
"Content-Type: application/json\r\n",
|
||||
);
|
||||
assert_eq!(status, 200, "{response}");
|
||||
assert_eq!(response["data"]["stage"], "Won");
|
||||
let (status, _) = server.call(
|
||||
"POST",
|
||||
"/game/escape/web/game/play",
|
||||
r#"{"actions":["Unknown"]}"#,
|
||||
"Content-Type: application/json\r\n",
|
||||
);
|
||||
assert_eq!(status, 400);
|
||||
server.stop();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn component_front_is_embedded_with_or_without_api_and_keeps_host_and_route_boundaries() {
|
||||
for with_api in [false, true] {
|
||||
let root = if with_api {
|
||||
project(
|
||||
"web-with-api",
|
||||
"hello() (out: Text) { out = \"api\" }",
|
||||
"public get hello = app.hello",
|
||||
)
|
||||
} else {
|
||||
let root = directory("web-only");
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
root
|
||||
};
|
||||
let front = root.join("module/demo/front");
|
||||
let source = front.join("src");
|
||||
fs::create_dir_all(source.join("nested")).unwrap();
|
||||
fs::write(source.join("index.html"), "<h1>Dever 页面</h1>").unwrap();
|
||||
fs::write(source.join("nested/index.html"), "nested page").unwrap();
|
||||
fs::write(source.join("app.js"), "console.log('embedded');").unwrap();
|
||||
fs::create_dir(front.join("dist")).unwrap();
|
||||
fs::write(front.join("dist/stale.txt"), "old build").unwrap();
|
||||
let (path, port, mut value) = config(&root);
|
||||
value["sites"]["front"]["front"] = serde_json::json!({"component":"demo","path":"/"});
|
||||
fs::write(&path, value.to_string()).unwrap();
|
||||
success(cli(&["fmt", root.to_str().unwrap()]));
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
assert!(!front.join("dist/stale.txt").exists());
|
||||
fs::rename(&front, root.join("removed-front")).unwrap();
|
||||
let server = Server::start(&artifact.binary, &path, port);
|
||||
let request = |method: &str, target: &str, host: &str| {
|
||||
let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap();
|
||||
stream
|
||||
.set_read_timeout(Some(Duration::from_secs(5)))
|
||||
.unwrap();
|
||||
write!(stream,"{method} {target} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n").unwrap();
|
||||
let mut reply = String::new();
|
||||
stream.read_to_string(&mut reply).unwrap();
|
||||
reply
|
||||
};
|
||||
let reply = request("GET", "/", "localhost");
|
||||
assert!(reply.starts_with("HTTP/1.1 200"), "{reply}");
|
||||
assert!(reply.ends_with("<h1>Dever 页面</h1>"));
|
||||
assert!(reply.contains("text/html; charset=utf-8"));
|
||||
let head = request("HEAD", "/", "localhost");
|
||||
assert_eq!(head.split_once("\r\n\r\n").unwrap().1, "");
|
||||
assert!(
|
||||
head.contains(&format!("content-length: {}", "<h1>Dever 页面</h1>".len())),
|
||||
"{head}"
|
||||
);
|
||||
assert!(request("GET", "/nested/", "localhost").ends_with("nested page"));
|
||||
assert!(request("GET", "/app.js?v=1", "localhost").contains("text/javascript"));
|
||||
for target in [
|
||||
"/missing",
|
||||
"/../config/setting.json",
|
||||
"/%2e%2e/config/setting.json",
|
||||
] {
|
||||
assert!(request("GET", target, "localhost").starts_with("HTTP/1.1 404"));
|
||||
}
|
||||
assert!(request("GET", "/", "unknown.example").starts_with("HTTP/1.1 404"));
|
||||
assert!(request("POST", "/", "localhost").starts_with("HTTP/1.1 405"));
|
||||
if with_api {
|
||||
assert!(
|
||||
request("GET", "/demo/service/front/main/hello", "localhost")
|
||||
.contains("\"data\":\"api\"")
|
||||
);
|
||||
}
|
||||
server.stop();
|
||||
if with_api {
|
||||
drop(artifact);
|
||||
fs::rename(root.join("removed-front"), &front).unwrap();
|
||||
let conflict = source.join("demo/service/front/main");
|
||||
fs::create_dir_all(&conflict).unwrap();
|
||||
fs::write(conflict.join("hello"), "not an API").unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
let output = Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&path)
|
||||
.arg("api")
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(!output.status.success());
|
||||
assert!(String::from_utf8_lossy(&output.stderr).contains("conflicts with API route"));
|
||||
drop(artifact);
|
||||
fs::write(source.join(".env"), "private").unwrap();
|
||||
assert!(build::build(&loaded, &program, "main", Profile::Dev, None).is_err());
|
||||
fs::remove_file(source.join(".env")).unwrap();
|
||||
std::os::unix::fs::symlink(root.join("config/setting.json"), source.join("link.json"))
|
||||
.unwrap();
|
||||
assert!(build::build(&loaded, &program, "main", Profile::Dev, None).is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(super) struct Server {
|
||||
child: std::process::Child,
|
||||
port: u16,
|
||||
}
|
||||
impl Server {
|
||||
pub(super) fn start(binary: &Path, config: &Path, port: u16) -> Self {
|
||||
Self::mode(binary, config, port, "api")
|
||||
}
|
||||
fn mode(binary: &Path, config: &Path, port: u16, mode: &str) -> Self {
|
||||
// 持续负载的预期 409 也会记录;未读取的 stderr 管道会填满并阻塞服务。
|
||||
let log = config.with_extension("server.log");
|
||||
let errors = fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(&log)
|
||||
.unwrap();
|
||||
let mut command = Command::new(binary);
|
||||
// 只追踪综合负载的服务进程,保持 PID、退出信号和资源采样指向真实应用。
|
||||
if mode == "all"
|
||||
&& let Some(preload) = std::env::var_os("DEVER_TEST_HEAPTRACK_PRELOAD")
|
||||
{
|
||||
command.env("LD_PRELOAD", preload).env(
|
||||
"DUMP_HEAPTRACK_OUTPUT",
|
||||
config.with_extension("heaptrack.raw"),
|
||||
);
|
||||
}
|
||||
command.arg("--config").arg(config);
|
||||
if !mode.is_empty() {
|
||||
command.arg(mode);
|
||||
}
|
||||
let child = command
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(errors)
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let mut server = Self { child, port };
|
||||
let until = Instant::now() + Duration::from_secs(10);
|
||||
loop {
|
||||
if let Some(status) = server.child.try_wait().unwrap() {
|
||||
let reason = fs::read_to_string(&log).unwrap();
|
||||
panic!("API exited {status}: {reason}");
|
||||
}
|
||||
if TcpStream::connect(("127.0.0.1", port)).is_ok() {
|
||||
break;
|
||||
}
|
||||
assert!(Instant::now() < until, "API did not start");
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
server
|
||||
}
|
||||
pub(super) fn call(
|
||||
&self,
|
||||
method: &str,
|
||||
path: &str,
|
||||
body: &str,
|
||||
headers: &str,
|
||||
) -> (u16, serde_json::Value) {
|
||||
let (status, body, _) = self.response(method, path, body, headers);
|
||||
(status, body)
|
||||
}
|
||||
fn response(
|
||||
&self,
|
||||
method: &str,
|
||||
path: &str,
|
||||
body: &str,
|
||||
headers: &str,
|
||||
) -> (u16, serde_json::Value, String) {
|
||||
let (status, body, head) = self.raw_response(method, path, body, headers);
|
||||
(
|
||||
status,
|
||||
serde_json::from_str(&body).expect("API response JSON"),
|
||||
head,
|
||||
)
|
||||
}
|
||||
pub(super) fn raw_response(
|
||||
&self,
|
||||
method: &str,
|
||||
path: &str,
|
||||
body: &str,
|
||||
headers: &str,
|
||||
) -> (u16, String, String) {
|
||||
let mut stream = TcpStream::connect(("127.0.0.1", self.port)).unwrap();
|
||||
stream
|
||||
.set_read_timeout(Some(Duration::from_secs(5)))
|
||||
.unwrap();
|
||||
write!(stream,"{method} {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\nContent-Length: {}\r\n{headers}\r\n{body}",body.len()).unwrap();
|
||||
let mut output = String::new();
|
||||
stream.read_to_string(&mut output).unwrap();
|
||||
let (head, body) = output.split_once("\r\n\r\n").expect("HTTP response");
|
||||
(
|
||||
head.split_whitespace().nth(1).unwrap().parse().unwrap(),
|
||||
body.to_owned(),
|
||||
head.to_owned(),
|
||||
)
|
||||
}
|
||||
fn terminate(&self) {
|
||||
assert!(
|
||||
Command::new("sh")
|
||||
.args(["-c", &format!("kill -TERM {}", self.child.id())])
|
||||
.status()
|
||||
.unwrap()
|
||||
.success()
|
||||
);
|
||||
}
|
||||
fn wait_for_exit(&mut self) -> std::process::ExitStatus {
|
||||
let until = Instant::now() + Duration::from_secs(5);
|
||||
loop {
|
||||
if let Some(status) = self.child.try_wait().unwrap() {
|
||||
return status;
|
||||
}
|
||||
assert!(Instant::now() < until, "API failed to drain");
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
}
|
||||
pub(super) fn stop(mut self) {
|
||||
self.terminate();
|
||||
assert!(self.wait_for_exit().success());
|
||||
}
|
||||
}
|
||||
impl Drop for Server {
|
||||
fn drop(&mut self) {
|
||||
if self.child.try_wait().unwrap().is_none() {
|
||||
let _ = self.child.kill();
|
||||
let _ = self.child.wait();
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(super) fn config(root: &Path) -> (PathBuf, u16, serde_json::Value) {
|
||||
let port = std::net::TcpListener::bind("127.0.0.1:0")
|
||||
.unwrap()
|
||||
.local_addr()
|
||||
.unwrap()
|
||||
.port();
|
||||
let value = serde_json::json!({"http":{"host":"127.0.0.1","port":port},"sites":{"front":{"path":"front","hosts":["localhost"]}}});
|
||||
(root.join("config/setting.json"), port, value)
|
||||
}
|
||||
#[test]
|
||||
fn generated_public_http_uses_typed_query_json_errors_and_graceful_shutdown() {
|
||||
let root = project(
|
||||
"api-public",
|
||||
r#"
|
||||
type Pair { text: Text, count: Int }
|
||||
hello(name: Text, count: Int >= 1 and <= 3, optional: Text?) (out: Text) {
|
||||
out = name
|
||||
}
|
||||
flow reject(accept: Bool) ()
|
||||
| step | kind | do |
|
||||
| - | check | accept else Conflict |
|
||||
pair(value: Pair) (out: Pair) {out = value}
|
||||
"#,
|
||||
"public get hello = app.hello\npublic post pair = app.pair\npublic post reject = app.reject",
|
||||
);
|
||||
let (loaded, program) = analyze(&root);
|
||||
assert_eq!(program.http[0].path, "/demo/service/front/main/hello");
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
let (path, port, value) = config(&root);
|
||||
fs::write(&path, value.to_string()).unwrap();
|
||||
let server = Server::mode(&artifact.binary, &path, port, "");
|
||||
let (status, body) = server.call(
|
||||
"GET",
|
||||
"/demo/service/front/main/hello?name=%E4%B8%AD%E6%96%87+ok&count=2",
|
||||
"",
|
||||
"",
|
||||
);
|
||||
assert_eq!(status, 200);
|
||||
assert_eq!(body["data"], "中文 ok");
|
||||
for query in [
|
||||
"name=a&count=0",
|
||||
"name=a&name=b&count=1",
|
||||
"name=a&count=1&extra=2",
|
||||
"name=a",
|
||||
"name=a&count=no",
|
||||
] {
|
||||
assert_eq!(
|
||||
server
|
||||
.call(
|
||||
"GET",
|
||||
&format!("/demo/service/front/main/hello?{query}"),
|
||||
"",
|
||||
""
|
||||
)
|
||||
.0,
|
||||
400
|
||||
);
|
||||
}
|
||||
let json = "Content-Type: application/json\r\n";
|
||||
assert_eq!(
|
||||
server
|
||||
.call(
|
||||
"POST",
|
||||
"/demo/service/front/main/pair",
|
||||
r#"{"value":{"text":"中文","count":3}}"#,
|
||||
json
|
||||
)
|
||||
.1["data"]["text"],
|
||||
"中文"
|
||||
);
|
||||
for body in [
|
||||
r#"{"value":{"text":"a","count":1,"count":2}}"#,
|
||||
r#"{"value":{"text":"a","count":1,"extra":2}}"#,
|
||||
"[]",
|
||||
] {
|
||||
assert_eq!(
|
||||
server
|
||||
.call("POST", "/demo/service/front/main/pair", body, json)
|
||||
.0,
|
||||
400
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
server
|
||||
.call(
|
||||
"POST",
|
||||
"/demo/service/front/main/reject",
|
||||
r#"{"accept":false}"#,
|
||||
json
|
||||
)
|
||||
.0,
|
||||
409
|
||||
);
|
||||
assert!(
|
||||
server
|
||||
.call(
|
||||
"POST",
|
||||
"/demo/service/front/main/reject",
|
||||
r#"{"accept":true}"#,
|
||||
json
|
||||
)
|
||||
.1["data"]
|
||||
.is_null()
|
||||
);
|
||||
assert_eq!(
|
||||
server
|
||||
.call("GET", "/demo/service/front/main/missing", "", "")
|
||||
.0,
|
||||
404
|
||||
);
|
||||
server.stop();
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
//! 真实 REST 请求验证声明式 CRUD、字段边界和不可绕过的对象归属。
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn generated_rest_uses_model_contracts_and_sql_owner_filters() {
|
||||
exercise(
|
||||
"rest",
|
||||
serde_json::json!({"type":"sqlite","path":"data/main.db","max_connections":1,"max_page_size":5}),
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
#[ignore = "requires an isolated PostgreSQL database; run test/postgres.py"]
|
||||
fn postgres_generated_rest_uses_model_contracts_and_sql_owner_filters() {
|
||||
exercise(
|
||||
"rest-postgres",
|
||||
serde_json::json!({"type":"postgres","url":std::env::var("DEVER_TEST_POSTGRES").unwrap(),"tls":"disabled","max_connections":1,"max_page_size":5}),
|
||||
);
|
||||
}
|
||||
fn exercise(name: &str, database: serde_json::Value) {
|
||||
let root = project(
|
||||
name,
|
||||
r#"
|
||||
type Identity {id:Text,user_id:data.user.id?,tenant_id:data.tenant.id?}
|
||||
apply(callback:handler(value:Text) (out:Text),input:Text) (output:Text) {output=callback(input)}
|
||||
flow verify(claims:dever.auth.Claims) (identity:Identity)
|
||||
| step | kind | do |
|
||||
| user | data | data.user.first(name == claims.subject) |
|
||||
| - | check | user != null else Unauthorized |
|
||||
| identity | calc | Identity {id=claims.subject,user_id=user.id,tenant_id=null} |
|
||||
"#,
|
||||
"rest data.article",
|
||||
);
|
||||
let models = root.join("module/demo/service/data");
|
||||
fs::create_dir_all(&models).unwrap();
|
||||
fs::write(
|
||||
models.join("user.dever"),
|
||||
"global type User {name:Text unique}\nseed {{name=\"alice\"},{name=\"bob\"}}",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
models.join("tenant.dever"),
|
||||
"global type Tenant {name:Text}",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
models.join("article.dever"),
|
||||
r#"
|
||||
type State {Draft,Published}
|
||||
type Article {
|
||||
private owner user_id: data.user.id = dever.auth.userId()
|
||||
title:Text(1,80) unique create = domain.normalize(input) replace = text.lower(input) search = domain.normalize(input)
|
||||
body:Json? default "{\"source\":\"default\"}"
|
||||
score:Int >= 0 default 7
|
||||
state:State default Draft
|
||||
tag:Text? default "automatic"
|
||||
uid:Uuid generated
|
||||
private secret:Text create = "hidden" replace = "changed"
|
||||
private creation_key:Text unique create = dever.auth.id()
|
||||
source:Text create = "created" replace = "replaced"
|
||||
request_method:Text create = dever.api.request.method() replace = dever.api.request.method()
|
||||
request_path:Text create = dever.api.request.path() replace = dever.api.request.path()
|
||||
request_label:Text? create = dever.api.request.header("x-label") replace = dever.api.request.header("x-label")
|
||||
}
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("module/demo/service/domain.dever"),
|
||||
"normalize(input:Text) (value:Text) {value=text.trim(input)}",
|
||||
)
|
||||
.unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
let (path, port, mut config) = config(&root);
|
||||
config["database"] = serde_json::json!({"default":database});
|
||||
config["sites"]["front"]["auth"] = serde_json::json!("users");
|
||||
config["sites"]["front"]["origin"] = serde_json::json!("http://localhost");
|
||||
config["auth"] = serde_json::json!({"providers":{"users":{"verify":"demo.service.verify","jwtSecret":"01234567890123456789012345678901","ttlSeconds":3600,"cookie":"session"}}});
|
||||
fs::write(&path, config.to_string()).unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let index = dever::compiler::inspect::analyze(&loaded, None, 2, true).unwrap();
|
||||
assert!(index.diagnostics.is_empty());
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
success(
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&path)
|
||||
.arg("migrate")
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
for user in [1, 2] {
|
||||
success(
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&path)
|
||||
.arg("dever.auth.owner")
|
||||
.arg(serde_json::json!({"site":"front","user_id":user,"tenant":null}).to_string())
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
}
|
||||
let provider = dever_runtime::auth::Provider::new(
|
||||
"users".into(),
|
||||
dever_runtime::value::secret::Secret::from_input(
|
||||
b"01234567890123456789012345678901".to_vec(),
|
||||
),
|
||||
3600,
|
||||
)
|
||||
.unwrap();
|
||||
let headers = |subject: &str| {
|
||||
let header =
|
||||
dever_runtime::auth::request::Cookie::new("session".into(), "http://localhost")
|
||||
.unwrap()
|
||||
.issue(
|
||||
&provider,
|
||||
&dever_runtime::auth::Claims {
|
||||
subject: subject.into(),
|
||||
session: "session".into(),
|
||||
tenant: None,
|
||||
site: "front".into(),
|
||||
},
|
||||
dever_runtime::value::calendar::DateTime::now()
|
||||
.unwrap()
|
||||
.millis()
|
||||
/ 1000,
|
||||
)
|
||||
.unwrap();
|
||||
format!(
|
||||
"Cookie: {}\r\nOrigin: http://localhost\r\nContent-Type: application/json\r\n",
|
||||
std::str::from_utf8(&header.value)
|
||||
.unwrap()
|
||||
.split(';')
|
||||
.next()
|
||||
.unwrap()
|
||||
)
|
||||
};
|
||||
let alice = headers("alice");
|
||||
let bob = headers("bob");
|
||||
let server = Server::start(&artifact.binary, &path, port);
|
||||
let route = "/demo/service/front/main";
|
||||
assert_eq!(server.call("GET", route, "", "").0, 401);
|
||||
let (status, body) = server.call("POST", route, r#"{"title":" 中文 "}"#, &alice);
|
||||
assert_eq!(status, 200, "{body}");
|
||||
let created = &body["data"];
|
||||
assert_eq!(created["title"], "中文");
|
||||
assert_eq!(created["score"], 7);
|
||||
assert_eq!(created["body"], serde_json::json!({"source":"default"}));
|
||||
assert_eq!(created["state"], "Draft");
|
||||
assert_eq!(created["tag"], "automatic");
|
||||
assert_eq!(created["source"], "created");
|
||||
assert_eq!(created["request_method"], "POST");
|
||||
assert_eq!(created["request_path"], route);
|
||||
assert!(created["request_label"].is_null());
|
||||
assert!(created.get("secret").is_none());
|
||||
assert!(created.get("user_id").is_none());
|
||||
assert_eq!(created["uid"].as_str().unwrap().len(), 36);
|
||||
let detail = format!("{route}/{}", created["id"]);
|
||||
assert_eq!(server.call("GET", &detail, "", &alice).1["data"], *created);
|
||||
for (method, body) in [
|
||||
("GET", ""),
|
||||
("PUT", r#"{"title":"stolen"}"#),
|
||||
("DELETE", ""),
|
||||
] {
|
||||
assert_eq!(server.call(method, &detail, body, &bob).0, 404);
|
||||
}
|
||||
assert_eq!(server.call("GET", route, "", &bob).1["data"]["total"], 0);
|
||||
let page = server.call("GET", route, "", &alice).1;
|
||||
assert_eq!(page["data"]["size"], 5);
|
||||
assert_eq!(page["data"]["total"], 1);
|
||||
assert_eq!(
|
||||
server
|
||||
.call(
|
||||
"GET",
|
||||
&format!("{route}?title=%20%E4%B8%AD%E6%96%87%20"),
|
||||
"",
|
||||
&alice
|
||||
)
|
||||
.1["data"]["total"],
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
server
|
||||
.call("GET", &format!("{route}?title=absent"), "", &alice)
|
||||
.1["data"]["total"],
|
||||
0
|
||||
);
|
||||
assert_eq!(
|
||||
server
|
||||
.call(
|
||||
"GET",
|
||||
&format!("{route}?title=%E4%B8%AD%E6%96%87"),
|
||||
"",
|
||||
&bob
|
||||
)
|
||||
.1["data"]["total"],
|
||||
0
|
||||
);
|
||||
for body in [
|
||||
r#"{"title":" "}"#,
|
||||
r#"{"title":"one","title":"two"}"#,
|
||||
r#"{"title":"bad","score":null}"#,
|
||||
r#"{"title":"bad","score":-1}"#,
|
||||
r#"{"title":"bad","user_id":2}"#,
|
||||
r#"{"title":"bad","secret":"forged"}"#,
|
||||
r#"{"title":"bad","request_method":"forged"}"#,
|
||||
r#"{"title":"bad","uid":"forged"}"#,
|
||||
r#"{"title":"bad","state":"Missing"}"#,
|
||||
] {
|
||||
assert_eq!(server.call("POST", route, body, &alice).0, 400, "{body}");
|
||||
}
|
||||
assert_eq!(
|
||||
server.call("POST", route, r#"{"title":"中文"}"#, &alice).0,
|
||||
409
|
||||
);
|
||||
for suffix in ["?extra=1", "?page=0", "?size=6", "?page=1&page=2"] {
|
||||
assert_eq!(
|
||||
server
|
||||
.call("GET", &format!("{route}{suffix}"), "", &alice)
|
||||
.0,
|
||||
400
|
||||
);
|
||||
}
|
||||
let (status, _, head) = server.response("PUT", route, "{}", &alice);
|
||||
assert_eq!(status, 405);
|
||||
assert!(head.to_ascii_lowercase().contains("allow: get, post"));
|
||||
assert_eq!(
|
||||
server
|
||||
.call("POST", &format!("{route}/invalid"), "{}", &alice)
|
||||
.0,
|
||||
404
|
||||
);
|
||||
assert_eq!(
|
||||
server
|
||||
.call("GET", &format!("{detail}?extra=1"), "", &alice)
|
||||
.0,
|
||||
400
|
||||
);
|
||||
let (status, replaced) = server.call(
|
||||
"PUT",
|
||||
&detail,
|
||||
r#"{"title":"new","tag":null,"body":{"value":0.12345678901234567890123456789}}"#,
|
||||
&alice,
|
||||
);
|
||||
assert_eq!(status, 200, "{replaced}");
|
||||
assert_eq!(replaced["data"]["source"], "replaced");
|
||||
assert_eq!(
|
||||
server
|
||||
.call("POST", route, r#"{"title":"different"}"#, &alice)
|
||||
.0,
|
||||
409
|
||||
);
|
||||
assert!(replaced["data"]["tag"].is_null());
|
||||
assert_eq!(replaced["data"]["uid"], created["uid"]);
|
||||
assert_eq!(server.call("GET", &detail, "", &alice).1, replaced);
|
||||
assert_eq!(server.call("DELETE", &detail, "", &alice).0, 200);
|
||||
assert_eq!(server.call("DELETE", &detail, "", &alice).0, 404);
|
||||
assert_eq!(server.call("GET", route, "", &alice).1["data"]["total"], 0);
|
||||
server.stop();
|
||||
}
|
||||
@@ -0,0 +1,378 @@
|
||||
//! 登录走真实 Argon2、Model 会话和 Cookie;退出必须同时撤销业务会话。
|
||||
use super::*;
|
||||
mod cookie;
|
||||
|
||||
#[test]
|
||||
fn generated_login_and_logout_keep_cookies_with_the_committed_business_result() {
|
||||
let root = project(
|
||||
"api-session",
|
||||
r#"
|
||||
setting password_hash:Text
|
||||
type Identity {id:Text,user_id:data.user.id?,tenant_id:data.tenant.id?}
|
||||
flow verify(claims:dever.auth.Claims) (identity:Identity)
|
||||
| step | kind | do |
|
||||
| user | data | data.user.first(name==claims.subject) |
|
||||
| - | check | user!=null else Unauthorized |
|
||||
| token | calc | uuid.parse(claims.session) |
|
||||
| - | check | token!=null else Unauthorized |
|
||||
| session | data | data.session.first(token==token) |
|
||||
| - | check | session!=null else Unauthorized |
|
||||
| - | check | session.subject==claims.subject else Unauthorized |
|
||||
| identity | calc | Identity {id=claims.subject,user_id=user.id,tenant_id=null} |
|
||||
flow login(name:Text,password:Secret,accept:Bool) ()
|
||||
| step | kind | do |
|
||||
| valid | calc | blocking(dever.crypto.passwordVerify(password,password_hash)) |
|
||||
| - | check | valid else Unauthorized |
|
||||
| - | flow | app.openSession(name,accept) |
|
||||
transaction flow openSession(subject:Text,accept:Bool) ()
|
||||
| step | kind | do |
|
||||
| row | data | data.session.create({subject=subject}) |
|
||||
| - | calc | dever.auth.issueCookie(subject,uuid.toText(row.token),null) |
|
||||
| - | check | accept else Conflict |
|
||||
flow current() (out:Text)
|
||||
| step | kind | do |
|
||||
| out | calc | dever.auth.id() |
|
||||
flow clear() ()
|
||||
| step | kind | do |
|
||||
| - | calc | dever.auth.clearCookie() |
|
||||
flow issueToken() (out:Secret)
|
||||
| step | kind | do |
|
||||
| out | calc | dever.auth.issue("alice","probe",null) |
|
||||
flow probe() (out:Int)
|
||||
| step | kind | do |
|
||||
| task | calc | run(app.issueToken()) |
|
||||
| token | calc | wait(task) |
|
||||
| out | calc | length(dever.crypto.hmacSha256(token,dever.bytes.fromText("probe"))) |
|
||||
flow logout() ()
|
||||
| step | kind | do |
|
||||
| session | calc | dever.auth.session() |
|
||||
| token | calc | uuid.parse(session) |
|
||||
| - | check | token!=null else Unauthorized |
|
||||
| - | data | data.session.delete({where=token==token}) |
|
||||
| - | calc | dever.auth.clearCookie() |
|
||||
flow count() (out:Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.session.count() |
|
||||
flow cookieRead() (out:Text?)
|
||||
| step | kind | do |
|
||||
| out | calc | dever.api.cookie("session") |
|
||||
flow cookieWrite() ()
|
||||
| step | kind | do |
|
||||
| - | calc | dever.api.setCookie("session","forged",dever.api.secureCookieOptions()) |
|
||||
"#,
|
||||
"public long post login = app.login\nauthenticated get current = app.current\nauthenticated post clear = app.clear\nauthenticated post probe = app.probe\nauthenticated post logout = app.logout\ncmd count = app.count\npublic get cookieRead=app.cookieRead\npublic post cookieWrite=app.cookieWrite",
|
||||
);
|
||||
let models = root.join("module/demo/service/data");
|
||||
fs::create_dir_all(&models).unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
fs::write(
|
||||
models.join("user.dever"),
|
||||
"global type User {name:Text unique}\nseed {{name=\"alice\"}}",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
models.join("tenant.dever"),
|
||||
"global type Tenant {name:Text}",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
models.join("session.dever"),
|
||||
"global type Session {token:Uuid generated unique,subject:Text}",
|
||||
)
|
||||
.unwrap();
|
||||
let (path, port, mut config) = config(&root);
|
||||
config["database"] =
|
||||
serde_json::json!({"default":{"type":"sqlite","path":"data/main.db","max_connections":1}});
|
||||
config["sites"]["front"]["auth"] = serde_json::json!("users");
|
||||
config["sites"]["front"]["origin"] = serde_json::json!("http://localhost");
|
||||
config["auth"] = serde_json::json!({"providers":{"users":{"verify":"demo.service.verify","jwtSecret":"01234567890123456789012345678901","ttlSeconds":3600,"cookie":"session"}}});
|
||||
let password =
|
||||
dever_runtime::value::secret::Secret::from_input(b"session-test-password".to_vec());
|
||||
config["module"] = serde_json::json!({"demo":{"service":{"password_hash":dever_runtime::crypto::password_hash(&password).unwrap()}}});
|
||||
fs::write(&path, config.to_string()).unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
let command = |name: &str| {
|
||||
let mut cmd = Command::new(&artifact.binary);
|
||||
cmd.arg("--config").arg(&path).arg(name);
|
||||
if name != "migrate" {
|
||||
cmd.arg("{}");
|
||||
}
|
||||
success(cmd.output().unwrap())
|
||||
};
|
||||
command("migrate");
|
||||
let server = Server::start(&artifact.binary, &path, port);
|
||||
let json = "Content-Type: application/json\r\nOrigin: http://localhost\r\n";
|
||||
let body = |password: &str, accept| {
|
||||
serde_json::json!({"name":"alice","password":password,"accept":accept}).to_string()
|
||||
};
|
||||
let login = "/demo/service/front/main/login";
|
||||
assert_eq!(
|
||||
server
|
||||
.call("GET", "/demo/service/front/main/cookieRead", "", "")
|
||||
.0,
|
||||
403
|
||||
);
|
||||
assert_eq!(
|
||||
server
|
||||
.call("POST", "/demo/service/front/main/cookieWrite", "{}", json)
|
||||
.0,
|
||||
403
|
||||
);
|
||||
let failed = server.response("POST", login, &body("wrong", true), json);
|
||||
assert_eq!(failed.0, 401);
|
||||
assert!(!failed.2.contains("set-cookie"));
|
||||
let rollback = server.response("POST", login, &body("session-test-password", false), json);
|
||||
assert_eq!(rollback.0, 409);
|
||||
assert!(!rollback.2.contains("set-cookie"));
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(&command("demo.service.count")).unwrap()["data"],
|
||||
0
|
||||
);
|
||||
assert_eq!(
|
||||
server
|
||||
.call(
|
||||
"POST",
|
||||
login,
|
||||
&body("session-test-password", true),
|
||||
"Content-Type: application/json\r\nOrigin: http://attacker.invalid\r\n"
|
||||
)
|
||||
.0,
|
||||
403
|
||||
);
|
||||
let issued = server.response("POST", login, &body("session-test-password", true), json);
|
||||
assert_eq!(issued.0, 200);
|
||||
let cookie = issued
|
||||
.2
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("set-cookie: "))
|
||||
.expect("issued Cookie");
|
||||
assert!(cookie.contains("HttpOnly") && cookie.contains("SameSite=Lax"));
|
||||
let headers = format!("Cookie: {}\r\n{json}", cookie.split(';').next().unwrap());
|
||||
assert_eq!(
|
||||
server
|
||||
.call("POST", "/demo/service/front/main/probe", "{}", &headers)
|
||||
.1["data"],
|
||||
32
|
||||
);
|
||||
assert_eq!(
|
||||
server
|
||||
.call("GET", "/demo/service/front/main/current", "", &headers)
|
||||
.1["data"],
|
||||
"alice"
|
||||
);
|
||||
let cleared = server.response("POST", "/demo/service/front/main/clear", "{}", &headers);
|
||||
assert_eq!(cleared.0, 200);
|
||||
assert!(cleared.2.contains("Max-Age=0"));
|
||||
assert_eq!(
|
||||
server
|
||||
.call("GET", "/demo/service/front/main/current", "", &headers)
|
||||
.0,
|
||||
200,
|
||||
"clearing browser Cookie must not claim server-side revocation"
|
||||
);
|
||||
let logout = server.response("POST", "/demo/service/front/main/logout", "{}", &headers);
|
||||
assert_eq!(logout.0, 200);
|
||||
assert!(logout.2.contains("Max-Age=0"));
|
||||
assert_eq!(
|
||||
server
|
||||
.call("GET", "/demo/service/front/main/current", "", &headers)
|
||||
.0,
|
||||
401
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(&command("demo.service.count")).unwrap()["data"],
|
||||
0
|
||||
);
|
||||
server.stop();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn request_metadata_and_response_headers_follow_the_real_http_request() {
|
||||
let root = project(
|
||||
"api-request-context",
|
||||
r#"
|
||||
flow child() (out:Text)
|
||||
| step | kind | do |
|
||||
| out | calc | dever.api.request.requestId() |
|
||||
flow metadata(name:Text) (id:Text, nested_id:Text, method:Text, path:Text, peer:Text, header:Text?, site:Text)
|
||||
| step | kind | do |
|
||||
| id | calc | dever.api.request.requestId() |
|
||||
| task | calc | run(child()) |
|
||||
| nested_id | calc | wait(task) |
|
||||
| method | calc | dever.api.request.method() |
|
||||
| path | calc | dever.api.request.path() |
|
||||
| peer | calc | dever.api.request.clientAddress() |
|
||||
| header | calc | dever.api.request.header(name) |
|
||||
| site | calc | dever.site.key() |
|
||||
flow reply(accept:Bool, name:Text, value:Text) ()
|
||||
| step | kind | do |
|
||||
| - | calc | dever.api.request.setHeader(name,value) |
|
||||
| - | check | accept else Conflict |
|
||||
"#,
|
||||
"public get metadata=app.metadata\npublic post reply=app.reply",
|
||||
);
|
||||
let (path, port, mut config) = config(&root);
|
||||
let site = config["sites"]
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("front")
|
||||
.unwrap();
|
||||
config["sites"]["trusted_front"] = site;
|
||||
fs::write(&path, config.to_string()).unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
let server = Server::start(&artifact.binary, &path, port);
|
||||
let route = "/demo/service/front/main/metadata";
|
||||
let (status, value) = server.call(
|
||||
"GET",
|
||||
&format!("{route}?name=x-label"),
|
||||
"",
|
||||
"X-Label: value\r\nX-Forwarded-For: 203.0.113.1\r\n",
|
||||
);
|
||||
assert_eq!(status, 200, "{value}");
|
||||
let data = &value["data"];
|
||||
assert_eq!(data["id"], data["nested_id"]);
|
||||
let first_id = data["id"].as_str().unwrap();
|
||||
// UUID 形式也排除了即使在本测试 PID 不同的情况下仍会通过的旧格式。
|
||||
assert!(dever_runtime::value::uuid::Uuid::parse(first_id).is_some());
|
||||
assert_eq!(first_id.as_bytes()[14], b'4');
|
||||
assert_eq!(data["method"], "GET");
|
||||
assert_eq!(data["path"], route);
|
||||
assert_eq!(data["peer"], "127.0.0.1");
|
||||
assert_eq!(data["header"], "value");
|
||||
assert_eq!(data["site"], "trusted_front");
|
||||
let (status, next) = server.call("GET", &format!("{route}?name=x-label"), "", "");
|
||||
assert_eq!(status, 200);
|
||||
assert_ne!(next["data"]["id"], data["id"]);
|
||||
assert!(next["data"]["header"].is_null());
|
||||
|
||||
let (_, replica_port, _) = super::config(&root);
|
||||
config["http"]["port"] = serde_json::json!(replica_port);
|
||||
let replica_path = path.with_file_name("replica.json");
|
||||
fs::write(&replica_path, config.to_string()).unwrap();
|
||||
let replica = Server::start(&artifact.binary, &replica_path, replica_port);
|
||||
let (status, response) = replica.call("GET", &format!("{route}?name=x-label"), "", "");
|
||||
assert_eq!(status, 200, "{response}");
|
||||
let replica_data = &response["data"];
|
||||
assert_eq!(replica_data["id"], replica_data["nested_id"]);
|
||||
let replica_id = replica_data["id"].as_str().unwrap();
|
||||
assert!(dever_runtime::value::uuid::Uuid::parse(replica_id).is_some());
|
||||
assert_eq!(replica_id.as_bytes()[14], b'4');
|
||||
assert_ne!(replica_id, first_id);
|
||||
assert_ne!(replica_data["id"], next["data"]["id"]);
|
||||
replica.stop();
|
||||
for name in [
|
||||
"authorization",
|
||||
"proxy-authorization",
|
||||
"cookie",
|
||||
"set-cookie",
|
||||
"x-api-key",
|
||||
] {
|
||||
assert_eq!(
|
||||
server
|
||||
.call("GET", &format!("{route}?name={name}"), "", "")
|
||||
.0,
|
||||
403
|
||||
);
|
||||
}
|
||||
let reply = "/demo/service/front/main/reply";
|
||||
let call = |accept, name: &str, value: &str| {
|
||||
server.response(
|
||||
"POST",
|
||||
reply,
|
||||
&serde_json::json!({"accept":accept,"name":name,"value":value}).to_string(),
|
||||
"Content-Type: application/json\r\n",
|
||||
)
|
||||
};
|
||||
let (status, _, headers) = call(true, "X-Result", "saved");
|
||||
assert_eq!(status, 200);
|
||||
assert!(headers.to_ascii_lowercase().contains("x-result: saved"));
|
||||
let (status, _, headers) = call(false, "X-Result", "discarded");
|
||||
assert_eq!(status, 409);
|
||||
assert!(!headers.to_ascii_lowercase().contains("x-result:"));
|
||||
for name in [
|
||||
"Content-Type",
|
||||
"Set-Cookie",
|
||||
"Content-Length",
|
||||
"Connection",
|
||||
"Transfer-Encoding",
|
||||
"Upgrade",
|
||||
"Host",
|
||||
"TE",
|
||||
] {
|
||||
assert_eq!(call(true, name, "x").0, 403, "{name}");
|
||||
}
|
||||
assert_eq!(call(true, "X-Result", "bad\r\nInjected: value").0, 400);
|
||||
assert_eq!(call(true, "X-Result", &"x".repeat(70000)).0, 400);
|
||||
server.stop();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn request_context_cannot_escape_to_commands_jobs_or_model_writes() {
|
||||
let root = project(
|
||||
"api-request-boundary",
|
||||
"flow read() (out:Text)\n| step | kind | do |\n| out | calc | dever.api.request.path() |",
|
||||
"cmd read=app.read",
|
||||
);
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(
|
||||
program::check(&loaded.declarations, &loaded.modules)
|
||||
.err()
|
||||
.unwrap()
|
||||
.message
|
||||
.contains("request context")
|
||||
);
|
||||
fs::write(
|
||||
root.join("module/demo/service/api/front/main.dever"),
|
||||
"job read() retry(1) timeout(1000)=app.read",
|
||||
)
|
||||
.unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(loaded.diagnostics.is_empty(), "{:?}", loaded.diagnostics);
|
||||
assert!(
|
||||
program::check(&loaded.declarations, &loaded.modules)
|
||||
.err()
|
||||
.unwrap()
|
||||
.message
|
||||
.contains("request context")
|
||||
);
|
||||
fs::write(root.join("module/demo/service/api/front/main.dever"), "").unwrap();
|
||||
write_source(
|
||||
root.join("module/demo/service/app/main.dever"),
|
||||
"flow read() (out:Text)\n| step | kind | do |\n| out | calc | dever.site.key() |",
|
||||
)
|
||||
.unwrap();
|
||||
for binding in [
|
||||
"cmd read=app.read",
|
||||
"job read() retry(1) timeout(1000)=app.read",
|
||||
] {
|
||||
fs::write(
|
||||
root.join("module/demo/service/api/front/main.dever"),
|
||||
binding,
|
||||
)
|
||||
.unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(
|
||||
program::check(&loaded.declarations, &loaded.modules)
|
||||
.err()
|
||||
.unwrap()
|
||||
.message
|
||||
.contains("request context")
|
||||
);
|
||||
}
|
||||
fs::write(root.join("module/demo/service/api/front/main.dever"), "").unwrap();
|
||||
write_source(
|
||||
root.join("module/demo/service/data/main.dever"),
|
||||
"type Service {private origin:Text create = dever.api.request.path()}",
|
||||
)
|
||||
.unwrap();
|
||||
analyze(&root);
|
||||
write_source(
|
||||
root.join("module/demo/service/data/main.dever"),
|
||||
"type Service {private origin:Text create = dever.api.request.setHeader(\"x\",\"y\")}",
|
||||
)
|
||||
.unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(program::check(&loaded.declarations, &loaded.modules).is_err());
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn cookies_use_real_http_preserve_secrets_and_only_send_after_success() {
|
||||
let root = project(
|
||||
"api-general-cookie",
|
||||
r#"
|
||||
flow read(name:Text) (out:Text?)
|
||||
| step | kind | do |
|
||||
| out | calc | dever.api.cookie(name) |
|
||||
flow readSecret(name:Text) (present:Bool)
|
||||
| step | kind | do |
|
||||
| value | calc | dever.api.secretCookie(name) |
|
||||
| present | calc | value!=null |
|
||||
flow write(name:Text,value:Text,options:dever.api.CookieOptions,accept:Bool) ()
|
||||
| step | kind | do |
|
||||
| - | calc | dever.api.setCookie(name,value,options) |
|
||||
| - | check | accept else Conflict |
|
||||
flow writeSecret(value:Secret,options:dever.api.CookieOptions) ()
|
||||
| step | kind | do |
|
||||
| - | calc | dever.api.setSecretCookie("private",value,options) |
|
||||
flow defaults() ()
|
||||
| step | kind | do |
|
||||
| - | calc | dever.api.setCookie("defaults","yes",dever.api.secureCookieOptions()) |
|
||||
"#,
|
||||
"public get read=app.read
|
||||
public get secret=app.readSecret
|
||||
public post write=app.write
|
||||
public post private=app.writeSecret
|
||||
public post defaults=app.defaults",
|
||||
);
|
||||
let (path, port, mut settings) = config(&root);
|
||||
settings["sites"]["front"]["origin"] = serde_json::json!("http://localhost");
|
||||
fs::write(&path, settings.to_string()).unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
let server = Server::start(&artifact.binary, &path, port);
|
||||
let route = "/demo/service/front/main";
|
||||
let headers = "Content-Type: application/json\r\nOrigin: http://localhost\r\n";
|
||||
let options = serde_json::json!({"path":"/","domain":null,"same_site":"Lax","secure":true,"http_only":true,"max_age":60});
|
||||
let write =
|
||||
|name: &str, value: &str, options: &serde_json::Value, accept: bool, headers: &str| {
|
||||
server.response(
|
||||
"POST",
|
||||
&format!("{route}/write"),
|
||||
&serde_json::json!({"name":name,"value":value,"options":options,"accept":accept})
|
||||
.to_string(),
|
||||
headers,
|
||||
)
|
||||
};
|
||||
let (status, _, head) = write("label", "中文; + %", &options, true, headers);
|
||||
assert_eq!(status, 200, "{head}");
|
||||
let cookie = head
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("set-cookie: "))
|
||||
.unwrap();
|
||||
assert!(
|
||||
cookie.contains("HttpOnly")
|
||||
&& cookie.contains("SameSite=Lax")
|
||||
&& cookie.contains("Max-Age=60")
|
||||
);
|
||||
let sent = format!("Cookie: {}\r\n", cookie.split(';').next().unwrap());
|
||||
let read = server.call("GET", &format!("{route}/read?name=label"), "", &sent);
|
||||
assert_eq!(read.0, 200);
|
||||
assert_eq!(read.1["data"], "中文; + %");
|
||||
assert!(
|
||||
server
|
||||
.call("GET", &format!("{route}/read?name=missing"), "", &sent)
|
||||
.1["data"]
|
||||
.is_null()
|
||||
);
|
||||
let failed = write("label", "discarded", &options, false, headers);
|
||||
assert_eq!(failed.0, 409);
|
||||
assert!(!failed.2.contains("set-cookie"));
|
||||
for header in [
|
||||
"Content-Type: application/json\r\n",
|
||||
"Content-Type: application/json\r\nOrigin: http://attacker.invalid\r\n",
|
||||
] {
|
||||
assert_eq!(write("label", "x", &options, true, header).0, 403);
|
||||
}
|
||||
assert_eq!(write("label", "v1.secret", &options, true, headers).0, 403);
|
||||
assert_eq!(write("bad=name", "x", &options, true, headers).0, 400);
|
||||
assert_eq!(
|
||||
write("label", &"x".repeat(17000), &options, true, headers).0,
|
||||
400
|
||||
);
|
||||
for (field, value) in [
|
||||
("path", serde_json::json!("/;Secure")),
|
||||
("domain", serde_json::json!("example.test:8080")),
|
||||
("max_age", serde_json::json!(-1)),
|
||||
] {
|
||||
let mut changed = options.clone();
|
||||
changed[field] = value;
|
||||
assert_eq!(write("label", "x", &changed, true, headers).0, 400);
|
||||
}
|
||||
let mut insecure = options.clone();
|
||||
insecure["secure"] = serde_json::json!(false);
|
||||
assert_eq!(write("__Secure-name", "x", &insecure, true, headers).0, 403);
|
||||
insecure["same_site"] = serde_json::json!("None");
|
||||
assert_eq!(write("label", "x", &insecure, true, headers).0, 403);
|
||||
let mut domain = options.clone();
|
||||
domain["domain"] = serde_json::json!("localhost");
|
||||
assert_eq!(write("__Host-name", "x", &domain, true, headers).0, 403);
|
||||
let private = |options: &serde_json::Value| {
|
||||
server.response(
|
||||
"POST",
|
||||
&format!("{route}/private"),
|
||||
&serde_json::json!({"value":"secret-value","options":options}).to_string(),
|
||||
headers,
|
||||
)
|
||||
};
|
||||
assert_eq!(private(&insecure).0, 403);
|
||||
let secret = private(&options);
|
||||
assert_eq!(secret.0, 200, "{}", secret.2);
|
||||
let secret_header = secret
|
||||
.2
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("set-cookie: "))
|
||||
.unwrap();
|
||||
assert!(!secret_header.contains("secret-value"));
|
||||
let sent = format!("Cookie: {}\r\n", secret_header.split(';').next().unwrap());
|
||||
assert_eq!(
|
||||
server
|
||||
.call("GET", &format!("{route}/secret?name=private"), "", &sent)
|
||||
.1["data"],
|
||||
true
|
||||
);
|
||||
assert_eq!(
|
||||
server
|
||||
.call("GET", &format!("{route}/read?name=private"), "", &sent)
|
||||
.0,
|
||||
403
|
||||
);
|
||||
for value in [
|
||||
"private=plain",
|
||||
"private=v1.%%%",
|
||||
"private=v1.eA;private=v1.eQ",
|
||||
] {
|
||||
assert_eq!(
|
||||
server
|
||||
.call(
|
||||
"GET",
|
||||
&format!("{route}/secret?name=private"),
|
||||
"",
|
||||
&format!("Cookie: {value}\r\n")
|
||||
)
|
||||
.0,
|
||||
400
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
server
|
||||
.response("POST", &format!("{route}/defaults"), "{}", headers)
|
||||
.0,
|
||||
200
|
||||
);
|
||||
server.stop();
|
||||
}
|
||||
@@ -0,0 +1,548 @@
|
||||
use super::*;
|
||||
use dever_runtime::{
|
||||
auth::{Claims, Provider},
|
||||
value::{calendar::DateTime, secret::Secret},
|
||||
};
|
||||
mod cmd;
|
||||
mod load;
|
||||
mod recovery;
|
||||
mod replicas;
|
||||
|
||||
enum Run {
|
||||
Standard,
|
||||
Named,
|
||||
Load(load::Config),
|
||||
Replicas,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_tenant_http_and_jobs_keep_physical_storage_and_live_permissions() {
|
||||
exercise(
|
||||
"api-tenant",
|
||||
serde_json::json!({"type":"sqlite","path":"data/control.db","tenant_directory":"data/tenants","max_connections":2}),
|
||||
Run::Standard,
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
#[ignore = "requires an isolated PostgreSQL database; run test/postgres.py"]
|
||||
fn postgres_generated_tenant_http_and_jobs() {
|
||||
exercise(
|
||||
"api-tenant-postgres",
|
||||
serde_json::json!({"type":"postgres","url":std::env::var("DEVER_TEST_POSTGRES").unwrap(),"tls":"disabled","tenant_database_prefix":"dever_tenant_api","max_connections":3}),
|
||||
Run::Standard,
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn generated_named_tenant_job_authorizes_without_cross_database_transaction() {
|
||||
exercise(
|
||||
"api-tenant-named",
|
||||
serde_json::json!({"type":"sqlite","path":"data/control.db","tenant_directory":"data/tenants","max_connections":2}),
|
||||
Run::Named,
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
#[ignore = "requires an isolated PostgreSQL database; run test/postgres.py"]
|
||||
fn postgres_generated_named_tenant_http_and_jobs() {
|
||||
exercise(
|
||||
"api-tenant-named-postgres",
|
||||
serde_json::json!({"type":"postgres","url":std::env::var("DEVER_TEST_POSTGRES").unwrap(),"tls":"disabled","tenant_database_prefix":"dever_tenant_api","max_connections":3}),
|
||||
Run::Named,
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn generated_concurrent_tenant_http_and_jobs_keep_complete_data_isolated() {
|
||||
exercise(
|
||||
"api-tenant-concurrent",
|
||||
serde_json::json!({"type":"sqlite","path":"data/control.db","tenant_directory":"data/tenants","max_connections":2}),
|
||||
Run::Load(load::Config::smoke()),
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
#[ignore = "requires an isolated PostgreSQL database; run test/postgres.py"]
|
||||
fn postgres_generated_concurrent_tenant_http_and_jobs_keep_complete_data_isolated() {
|
||||
exercise(
|
||||
"api-tenant-postgres-concurrent",
|
||||
serde_json::json!({"type":"postgres","url":std::env::var("DEVER_TEST_POSTGRES").unwrap(),"tls":"disabled","max_connections":3}),
|
||||
Run::Load(load::Config::smoke()),
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
#[ignore = "release capacity workload with 32 tenants and 1048576 stored records"]
|
||||
fn large_project_tenant_capacity() {
|
||||
exercise(
|
||||
"api-tenant-capacity",
|
||||
serde_json::json!({"type":"sqlite","path":"data/control.db","tenant_directory":"data/tenants","max_connections":2}),
|
||||
Run::Load(load::Config::capacity()),
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
#[ignore = "bounded backlog reproduction with the same 32-tenant release workload"]
|
||||
fn large_project_tenant_burst() {
|
||||
exercise(
|
||||
"api-tenant-burst",
|
||||
serde_json::json!({"type":"sqlite","path":"data/control.db","tenant_directory":"data/tenants","max_connections":2}),
|
||||
Run::Load(load::Config::burst()),
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
#[ignore = "two-minute contention diagnostic under the one-hour CPU and memory budget"]
|
||||
fn large_project_tenant_contention() {
|
||||
exercise(
|
||||
"api-tenant-contention",
|
||||
serde_json::json!({"type":"sqlite","path":"data/control.db","tenant_directory":"data/tenants","max_connections":2}),
|
||||
Run::Load(load::Config::contention()),
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
#[ignore = "one-hour release workload with 32 tenants and 1048576 stored records"]
|
||||
fn large_project_tenant_http_and_jobs() {
|
||||
exercise(
|
||||
"api-tenant-large",
|
||||
serde_json::json!({"type":"sqlite","path":"data/control.db","tenant_directory":"data/tenants","max_connections":2,"cache_size_kib":64}),
|
||||
Run::Load(load::Config::large()),
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
#[ignore = "requires an isolated PostgreSQL database; run test/postgres.py"]
|
||||
fn postgres_generated_replicas_share_tenants_and_recover_an_abandoned_job() {
|
||||
exercise(
|
||||
"api-tenant-postgres-replicas",
|
||||
serde_json::json!({"type":"postgres","url":std::env::var("DEVER_TEST_POSTGRES").unwrap(),"tls":"disabled","max_connections":3}),
|
||||
Run::Replicas,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "two-minute probe of the million-row PostgreSQL replica workload"]
|
||||
fn large_project_pg_replica_probe() {
|
||||
postgres_replica_load(
|
||||
"api-tenant-postgres-replica-probe",
|
||||
load::Config::replica_probe(),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "one-hour release workload using two isolated PostgreSQL-backed replicas"]
|
||||
fn large_project_pg_replica_soak() {
|
||||
postgres_replica_load(
|
||||
"api-tenant-postgres-replica-soak",
|
||||
load::Config::replica_soak(),
|
||||
);
|
||||
}
|
||||
|
||||
fn postgres_replica_load(name: &str, config: load::Config) {
|
||||
exercise(
|
||||
name,
|
||||
serde_json::json!({"type":"postgres","url":std::env::var("DEVER_TEST_POSTGRES").unwrap(),"tls":"disabled","max_connections":3}),
|
||||
Run::Load(config),
|
||||
);
|
||||
}
|
||||
|
||||
fn exercise(name: &str, mut database: serde_json::Value, run: Run) {
|
||||
let named = matches!(run, Run::Named);
|
||||
let (attempts, timeout) = if matches!(run, Run::Replicas) {
|
||||
(2, 10_000)
|
||||
} else {
|
||||
(1, 1_000)
|
||||
};
|
||||
// PostgreSQL 用例共用临时实例,控制库隔离之外,物理租户库也必须独立。
|
||||
if database["type"] == "postgres" {
|
||||
database["tenant_database_prefix"] =
|
||||
serde_json::json!(format!("{}_tenant", name.replace('-', "_")));
|
||||
}
|
||||
let root = project(
|
||||
name,
|
||||
r#"
|
||||
type Payload {title:Text}
|
||||
type Identity {id:Text,user_id:data.user.id?,tenant_id:data.tenant.id?}
|
||||
flow verify(claims:dever.auth.Claims) (identity:Identity)
|
||||
| step | kind | do |
|
||||
| account | data | data.user.first(subject==claims.subject) |
|
||||
| - | check | account!=null else Unauthorized |
|
||||
| - | check | account.enabled else Unauthorized |
|
||||
| tenant_slug | calc | claims.tenant |
|
||||
| - | check | tenant_slug!=null else Unauthorized |
|
||||
| tenant | data | data.tenant.first(slug==tenant_slug) |
|
||||
| - | check | tenant!=null else Forbidden |
|
||||
| identity | calc | Identity {id=claims.subject,user_id=account.id,tenant_id=tenant.id} |
|
||||
flow create(title:Text,accept:Bool) (out:data.Service)
|
||||
| step | kind | do |
|
||||
| out | data | data.create({title=title}) |
|
||||
| - | check | accept else Conflict |
|
||||
flow count() (out:Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.count() |
|
||||
flow page() (out:data.Page)
|
||||
| step | kind | do |
|
||||
| out | data | data.page(order = id.asc, size = 10) |
|
||||
flow submit(title:Text) (out:Id)
|
||||
| step | kind | do |
|
||||
| out | calc | enqueue(job.save,Payload {title=title},title) |
|
||||
flow save(input:Payload) ()
|
||||
| step | kind | do |
|
||||
| - | data | data.create({title=input.title}) |
|
||||
flow register(id:Uuid,accept:Bool) (key:Text)
|
||||
| step | kind | do |
|
||||
| key | flow | shared.access.register(id) |
|
||||
| - | check | accept else Conflict |
|
||||
flow remove(id:Uuid) ()
|
||||
| step | kind | do |
|
||||
| - | calc | dever.auth.removeCapability(id) |
|
||||
flow grant(key:Text) ()
|
||||
| step | kind | do |
|
||||
| - | calc | dever.auth.saveRole("resource","Resource",false,[key]) |
|
||||
flow role() (out:dever.auth.Role?)
|
||||
| step | kind | do |
|
||||
| out | calc | dever.auth.role("resource") |
|
||||
flow permissions() (out:List<dever.auth.Permission>)
|
||||
| step | kind | do |
|
||||
| out | calc | dever.auth.currentPermissions() |
|
||||
"#,
|
||||
&format!(
|
||||
"job save(input:app.Payload) retry({attempts}) timeout({timeout}) = app.save\npost create = app.create\nget count = app.count\nget page = app.page\npost submit = app.submit\npost register = app.register\npost remove = app.remove\npost grant = app.grant\nget role = app.role\nget permissions = app.permissions"
|
||||
),
|
||||
);
|
||||
let domain = root.join("module/demo/service");
|
||||
if matches!(run, Run::Standard) {
|
||||
cmd::add(&domain);
|
||||
}
|
||||
let shared = root.join("module/shared/access");
|
||||
fs::create_dir_all(&shared).unwrap();
|
||||
write_source(shared.join("app/main.dever"), "flow register(id:Uuid) (key:Text)\n| step | kind | do |\n| key | calc | dever.auth.registerCapability(id) |").unwrap();
|
||||
fs::create_dir_all(domain.join("data")).unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
// 大分页的精确总数使用窄索引,避免反复读取包含正文的宽记录页。
|
||||
write_source(
|
||||
domain.join("data/main.dever"),
|
||||
"type Service {title:Text}\nindex(id)",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(domain.join("data/user.dever"),"global type User {subject:Text unique,enabled:Bool}\nseed {{subject=\"alice\",enabled=true}}").unwrap();
|
||||
fs::write(domain.join("data/tenant.dever"),"global type Tenant {slug:Text unique}\nseed {{slug=\"one\"},{slug=\"two\"},{slug=\"three\"}}").unwrap();
|
||||
fs::write(
|
||||
domain.join("data/owned.dever"),
|
||||
"type Owned {owner tenant_id:data.tenant.id = dever.auth.tenantId()\ntitle:Text}",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(domain.join("api/front/owned.dever"), "rest data.owned").unwrap();
|
||||
if named {
|
||||
write_source(
|
||||
domain.join("data/main.dever"),
|
||||
"database audit\ntype Service {title:Text}\nindex(id)",
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
if named {
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
let error = program::check(&loaded.declarations, &loaded.modules)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert!(error.message.contains("queue database"), "{error}");
|
||||
let api = domain.join("api/front/main.dever");
|
||||
fs::write(
|
||||
&api,
|
||||
format!("database audit\n{}", fs::read_to_string(&api).unwrap()),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
super::super::upload::tenant_setup(&root);
|
||||
let (path, port, mut config) = config(&root);
|
||||
config["http"]["upload"] = serde_json::json!({"directory":"../upload-store"});
|
||||
config["database"] = serde_json::json!({"default":database});
|
||||
if named {
|
||||
let mut audit = database.clone();
|
||||
if audit["type"] == "sqlite" {
|
||||
audit["path"] = serde_json::json!("data/audit.db");
|
||||
audit["tenant_directory"] = serde_json::json!("data/audit_tenants");
|
||||
} else {
|
||||
// 使用本用例已有控制数据库作为 global 连接;租户数据仍有独立命名空间。
|
||||
audit["tenant_database_prefix"] =
|
||||
serde_json::json!(format!("{}_audit", name.replace('-', "_")));
|
||||
}
|
||||
config["database"]["audit"] = audit;
|
||||
}
|
||||
// HTTP 与 Worker 并发访问两个租户;小池顺序切换由独立 Worker 用例验证。
|
||||
config["tenant"] =
|
||||
serde_json::json!({"database":"default","max_pools":2,"idle_timeout_ms":1000});
|
||||
if named {
|
||||
config["tenant"]["max_pools"] = serde_json::json!(4);
|
||||
}
|
||||
if let Run::Load(load) = &run {
|
||||
config["tenant"]["max_pools"] = serde_json::json!(load.tenants);
|
||||
config["http"]["limits"] = serde_json::json!({"header_bytes":16384,"body_bytes":16777216,"timeout_ms":30000,"connections":load.http_connections,"http2":null});
|
||||
}
|
||||
// PostgreSQL 双实例各用两个 worker,三连接的租户池为前台或续租留一条。
|
||||
let workers = if matches!(run, Run::Load(load) if load.replica) {
|
||||
2
|
||||
} else {
|
||||
1
|
||||
};
|
||||
config["job"] =
|
||||
serde_json::json!({"workers":workers,"poll_ms":5,"lease_ms":10000,"shutdown_ms":5000});
|
||||
config["sites"]["front"]["auth"] = serde_json::json!("users");
|
||||
config["sites"]["front"]["origin"] = serde_json::json!("http://localhost");
|
||||
if matches!(run, Run::Replicas) {
|
||||
config["job"]["lease_ms"] = serde_json::json!(2000);
|
||||
}
|
||||
let ttl = if let Run::Load(load) = &run {
|
||||
(load.warmup_seconds + load.seconds) as i64 + 3600
|
||||
} else {
|
||||
3600
|
||||
};
|
||||
config["auth"] = serde_json::json!({"providers":{"users":{"verify":"demo.service.verify","jwtSecret":"01234567890123456789012345678901","ttlSeconds":ttl,"cookie":"session"}}});
|
||||
fs::write(&path, config.to_string()).unwrap();
|
||||
success(cli(&["fmt", root.to_str().unwrap()]));
|
||||
let (loaded, program) = analyze(&root);
|
||||
let profile = if matches!(run, Run::Load(_)) {
|
||||
Profile::Release
|
||||
} else {
|
||||
Profile::Dev
|
||||
};
|
||||
let artifact = build::build(&loaded, &program, "main", profile, None).unwrap();
|
||||
let binary = artifact.binary.clone();
|
||||
drop(artifact);
|
||||
let command = |name: &str, input: Option<&str>| {
|
||||
let mut command = Command::new(&binary);
|
||||
command.arg("--config").arg(&path).arg(name);
|
||||
if let Some(input) = input {
|
||||
command.arg(input);
|
||||
}
|
||||
command.output().unwrap()
|
||||
};
|
||||
success(command("migrate", None));
|
||||
let provider = Provider::new(
|
||||
"users".into(),
|
||||
Secret::from_input(b"01234567890123456789012345678901".to_vec()),
|
||||
ttl,
|
||||
)
|
||||
.unwrap();
|
||||
let headers = |tenant: &str| {
|
||||
let claims = Claims {
|
||||
subject: "alice".into(),
|
||||
session: "session".into(),
|
||||
site: "front".into(),
|
||||
tenant: Some(tenant.into()),
|
||||
};
|
||||
let cookie =
|
||||
dever_runtime::auth::request::Cookie::new("session".into(), "http://localhost")
|
||||
.unwrap()
|
||||
.issue(&provider, &claims, DateTime::now().unwrap().millis() / 1000)
|
||||
.unwrap();
|
||||
format!(
|
||||
"Cookie: {}\r\nOrigin: http://localhost\r\nContent-Type: application/json\r\n",
|
||||
std::str::from_utf8(&cookie.value)
|
||||
.unwrap()
|
||||
.split(';')
|
||||
.next()
|
||||
.unwrap()
|
||||
)
|
||||
};
|
||||
let first = headers("one");
|
||||
let second = headers("two");
|
||||
let third = headers("three");
|
||||
let count = "/demo/service/front/main/count";
|
||||
let create = "/demo/service/front/main/create";
|
||||
let server = Server::start(&binary, &path, port);
|
||||
super::super::upload::unauthorized(port, &root);
|
||||
assert_eq!(
|
||||
server.call("GET", count, "", &first).0,
|
||||
403,
|
||||
"unprepared tenant was accepted"
|
||||
);
|
||||
assert!(!root.join("data/tenants/1.sqlite").exists());
|
||||
for tenant in [1, 2] {
|
||||
let id = tenant.to_string();
|
||||
success(cli(&["tenant", "migrate", root.to_str().unwrap(), &id]));
|
||||
success(cli(&[
|
||||
"tenant",
|
||||
"owner",
|
||||
root.to_str().unwrap(),
|
||||
&id,
|
||||
"front",
|
||||
"1",
|
||||
]));
|
||||
assert_eq!(
|
||||
server
|
||||
.call("GET", count, "", if tenant == 1 { &first } else { &second })
|
||||
.0,
|
||||
403,
|
||||
"Owner bypassed disabled component"
|
||||
);
|
||||
success(cli(&[
|
||||
"tenant",
|
||||
"component",
|
||||
"enable",
|
||||
root.to_str().unwrap(),
|
||||
&id,
|
||||
"demo",
|
||||
]));
|
||||
}
|
||||
match run {
|
||||
Run::Load(load) => {
|
||||
server.stop();
|
||||
load::run(load, &root, &binary, &path, port, headers, command);
|
||||
return;
|
||||
}
|
||||
Run::Replicas => {
|
||||
server.stop();
|
||||
replicas::exercise(&root, &binary, &path, port, [&first, &second], command);
|
||||
return;
|
||||
}
|
||||
Run::Standard | Run::Named => {}
|
||||
}
|
||||
assert_eq!(
|
||||
server
|
||||
.call(
|
||||
"POST",
|
||||
create,
|
||||
r#"{"title":"rolled back","accept":false}"#,
|
||||
&first
|
||||
)
|
||||
.0,
|
||||
409
|
||||
);
|
||||
super::super::upload::tenant_isolation(&server, &root, &first, &second);
|
||||
let resource = "018f040a-785e-7000-8000-000000000001";
|
||||
let rest = "/demo/service/front/owned";
|
||||
let (status, created) = server.call("POST", rest, r#"{"title":"one only"}"#, &first);
|
||||
assert_eq!(status, 200, "{created}");
|
||||
assert_eq!(created["data"]["tenant_id"], 1);
|
||||
assert_eq!(server.call("GET", rest, "", &second).1["data"]["total"], 0);
|
||||
assert_eq!(
|
||||
server
|
||||
.call("POST", rest, r#"{"title":"forged","tenant_id":2}"#, &first)
|
||||
.0,
|
||||
400
|
||||
);
|
||||
let (status, created) = server.call("POST", rest, r#"{"title":"two only"}"#, &second);
|
||||
assert_eq!(status, 200, "{created}");
|
||||
assert_eq!(created["data"]["tenant_id"], 2);
|
||||
assert_eq!(
|
||||
server.call("GET", rest, "", &first).1["data"]["items"][0]["title"],
|
||||
"one only"
|
||||
);
|
||||
let key = format!("capability:demo.service.front.{resource}");
|
||||
let register = |accept| serde_json::json!({"id":resource,"accept":accept}).to_string();
|
||||
let permissions = |headers: &str| {
|
||||
server
|
||||
.call("GET", "/demo/service/front/main/permissions", "", headers)
|
||||
.1["data"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|entry| entry["key"].as_str().unwrap().to_owned())
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
assert_eq!(
|
||||
server
|
||||
.call(
|
||||
"POST",
|
||||
"/demo/service/front/main/register",
|
||||
®ister(false),
|
||||
&first
|
||||
)
|
||||
.0,
|
||||
409
|
||||
);
|
||||
assert!(!permissions(&first).contains(&key));
|
||||
let registered = server.call(
|
||||
"POST",
|
||||
"/demo/service/front/main/register",
|
||||
®ister(true),
|
||||
&first,
|
||||
);
|
||||
assert_eq!(registered.0, 200);
|
||||
assert_eq!(registered.1["data"], key);
|
||||
assert!(permissions(&first).contains(&key));
|
||||
assert!(!permissions(&second).contains(&key));
|
||||
let grant = serde_json::json!({"key":key}).to_string();
|
||||
assert_eq!(
|
||||
server
|
||||
.call("POST", "/demo/service/front/main/grant", &grant, &second)
|
||||
.0,
|
||||
403
|
||||
);
|
||||
assert_eq!(
|
||||
server
|
||||
.call("POST", "/demo/service/front/main/grant", &grant, &first)
|
||||
.0,
|
||||
200
|
||||
);
|
||||
assert_eq!(
|
||||
server
|
||||
.call("GET", "/demo/service/front/main/role", "", &first)
|
||||
.1["data"]["permission_keys"],
|
||||
serde_json::json!([key])
|
||||
);
|
||||
assert_eq!(
|
||||
server
|
||||
.call(
|
||||
"POST",
|
||||
"/demo/service/front/main/remove",
|
||||
&serde_json::json!({"id":resource}).to_string(),
|
||||
&first
|
||||
)
|
||||
.0,
|
||||
200
|
||||
);
|
||||
assert!(!permissions(&first).contains(&key));
|
||||
assert_eq!(
|
||||
server
|
||||
.call(
|
||||
"POST",
|
||||
"/demo/service/front/main/register",
|
||||
®ister(true),
|
||||
&first
|
||||
)
|
||||
.0,
|
||||
200
|
||||
);
|
||||
assert_eq!(
|
||||
server
|
||||
.call("GET", "/demo/service/front/main/role", "", &first)
|
||||
.1["data"]["permission_keys"],
|
||||
serde_json::json!([])
|
||||
);
|
||||
assert_eq!(server.call("GET", count, "", &first).1["data"], 0);
|
||||
assert_eq!(
|
||||
server
|
||||
.call("POST", create, r#"{"title":"one","accept":true}"#, &first)
|
||||
.0,
|
||||
200
|
||||
);
|
||||
assert_eq!(server.call("GET", count, "", &first).1["data"], 1);
|
||||
assert_eq!(server.call("GET", count, "", &second).1["data"], 0);
|
||||
assert_eq!(
|
||||
server
|
||||
.call(
|
||||
"POST",
|
||||
create,
|
||||
r#"{"title":"forged","accept":true,"tenant":2}"#,
|
||||
&first
|
||||
)
|
||||
.0,
|
||||
400
|
||||
);
|
||||
success(command(
|
||||
"dever.tenant.component",
|
||||
Some(r#"{"tenant":1,"component":"demo","enabled":false}"#),
|
||||
));
|
||||
assert_eq!(server.call("GET", count, "", &first).0, 403);
|
||||
success(command(
|
||||
"dever.tenant.component",
|
||||
Some(r#"{"tenant":1,"component":"demo","enabled":true}"#),
|
||||
));
|
||||
server.stop();
|
||||
recovery::exercise(
|
||||
&root,
|
||||
&binary,
|
||||
&path,
|
||||
port,
|
||||
[&first, &second, &third],
|
||||
if named { "audit" } else { "default" },
|
||||
command,
|
||||
);
|
||||
if matches!(run, Run::Standard) {
|
||||
cmd::exercise(&root, &binary, &path, port);
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
use super::*;
|
||||
use dever_runtime::{
|
||||
http::{self, Http2Limits, Limits, PoolLimits, Request},
|
||||
task, tls,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn generated_api_uses_configured_rustls_and_both_http_protocols() {
|
||||
let root = project(
|
||||
"api-tls",
|
||||
"ready() (out:Bool) {out=true}",
|
||||
"public get ready = app.ready",
|
||||
);
|
||||
for name in ["server.pem", "server-key.pem"] {
|
||||
fs::copy(
|
||||
Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../test/fixtures/tls")
|
||||
.join(name),
|
||||
root.join("config").join(name),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
let (project, program) = analyze(&root);
|
||||
let artifact = build::build(&project, &program, "main", Profile::Dev, None).unwrap();
|
||||
for h2 in [false, true] {
|
||||
let (path, port, mut config) = config(&root);
|
||||
config["http"]["tls"] =
|
||||
serde_json::json!({"certificate":"server.pem","key":"server-key.pem"});
|
||||
config["http"]["limits"] = serde_json::json!({"header_bytes":16384,"body_bytes":4096,"timeout_ms":3000,"connections":8,"http2":if h2{serde_json::json!({"streams":8,"stream_window_bytes":65535,"connection_window_bytes":65535})}else{serde_json::Value::Null}});
|
||||
fs::write(&path, config.to_string()).unwrap();
|
||||
let server = Server::start(&artifact.binary, &path, port);
|
||||
task::run(true, 16, async |scope| {
|
||||
let tls = tls::client(include_bytes!("../../../fixtures/tls/root.pem")).unwrap();
|
||||
let limits = Limits {
|
||||
header_bytes: 16384,
|
||||
body_bytes: 4096,
|
||||
timeout_ms: 3000,
|
||||
connections: 8,
|
||||
http2: h2.then_some(Http2Limits {
|
||||
streams: 8,
|
||||
stream_window_bytes: 65535,
|
||||
connection_window_bytes: 65535,
|
||||
}),
|
||||
};
|
||||
let client = http::client(
|
||||
&format!("https://localhost:{port}"),
|
||||
&tls,
|
||||
&limits,
|
||||
&PoolLimits {
|
||||
idle_ms: 1000,
|
||||
chunk_bytes: 1024,
|
||||
read_ms: 3000,
|
||||
},
|
||||
scope,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let response = client
|
||||
.request(Request {
|
||||
method: "GET".into(),
|
||||
target: "/demo/service/front/main/ready".into(),
|
||||
headers: vec![],
|
||||
body: Default::default(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status, 200);
|
||||
assert_eq!(
|
||||
serde_json::from_slice::<serde_json::Value>(&response.body).unwrap()["data"],
|
||||
true
|
||||
);
|
||||
drop(client);
|
||||
Ok::<_, String>(())
|
||||
})
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
server.stop();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user