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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn bundled_bytes_keep_normal_calls_navigation_and_project_only_writes() {
|
||||
let root = directory("bytes-library");
|
||||
let domain = root.join("module/demo/binary");
|
||||
fs::create_dir_all(&domain).unwrap();
|
||||
let app = domain.join("app/main.dever");
|
||||
write_source(
|
||||
&app,
|
||||
"echo(text: Text) (out: Text) { out = domain.roundtrip(text) }",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(domain.join("domain.dever"), "roundtrip(text: Text) (out: Text) { out = dever.bytes.toText(dever.bytes.fromText(text)) }").unwrap();
|
||||
fs::write(domain.join("api.dever"), "cmd echo = app.echo").unwrap();
|
||||
let library = Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../lib/dever/bytes.dv")
|
||||
.canonicalize()
|
||||
.unwrap();
|
||||
let before = fs::read(&library).unwrap();
|
||||
let path = root.to_str().unwrap();
|
||||
success(cli(&["fmt", path]));
|
||||
success(cli(&["check", path]));
|
||||
let (project, _) = analyze(&root);
|
||||
assert_eq!(
|
||||
project
|
||||
.sources
|
||||
.iter()
|
||||
.filter(|source| source.path == library)
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
let index: serde_json::Value =
|
||||
serde_json::from_str(&success(cli(&["inspect", path, "--json"]))).unwrap();
|
||||
assert!(index["diagnostics"].as_array().unwrap().is_empty());
|
||||
let target = index["symbols"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|symbol| symbol["name"] == "dever.bytes.app.toText")
|
||||
.unwrap();
|
||||
let file = target["declarations"][0][0].as_u64().unwrap() as usize;
|
||||
assert_eq!(index["files"][file]["path"], library.to_str().unwrap());
|
||||
success(cli(&["inspect", path, "--links"]));
|
||||
success(cli(&["inspect", path, "--links", "--check"]));
|
||||
assert!(domain.join("link.md").is_file());
|
||||
assert!(!root.join("module/dever").exists());
|
||||
assert_eq!(fs::read(&library).unwrap(), before);
|
||||
let output = cli(&["run", path, "--", "demo.binary.echo", r#"{"text":"中文"}"#]);
|
||||
let value: serde_json::Value = serde_json::from_str(&success(output)).unwrap();
|
||||
assert_eq!(value["data"], "中文");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bytes_boundaries_reject_hidden_errors_wire_values_and_reserved_modules() {
|
||||
let root = directory("bytes-invalid");
|
||||
let source = root.join("main.dever");
|
||||
for (text, code) in [
|
||||
(
|
||||
"f(values: List<Int>) (out: Int) { pending: dever.bytes.BufferResult = result(dever.bytes.fromInts(values))\nout = 1 }",
|
||||
"C012",
|
||||
),
|
||||
(
|
||||
"f(data: Bytes) (out: Bytes) { out = data }\ncmd f = app.f",
|
||||
"C005",
|
||||
),
|
||||
(
|
||||
"f(text: Text) (out: Bytes) { out = dever.system.bytesFromText(text) }",
|
||||
"C003",
|
||||
),
|
||||
(
|
||||
"f(text: Text) (out: Bytes) { out = dever.bytes.fromInts(text) }",
|
||||
"C005",
|
||||
),
|
||||
(
|
||||
"f(data: Bytes) (out: Int) { out = length(data) }\nloop g(data: Bytes) (out: List<Int>)\n| each value in data | result |\n| out | list f(value) |\n",
|
||||
"C005",
|
||||
),
|
||||
] {
|
||||
fs::write(&source, text).unwrap();
|
||||
let project = Project::load(&source).unwrap();
|
||||
assert!(project.diagnostics.is_empty(), "{:?}", project.diagnostics);
|
||||
let error = program::check(&project.declarations, &project.modules)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(error.code, code, "{error}");
|
||||
}
|
||||
let forged = root.join("module/dever/bytes");
|
||||
fs::create_dir_all(&forged).unwrap();
|
||||
write_source(forged.join("app/main.dever"), "f() (out: Int) { out = 1 }").unwrap();
|
||||
let error = Project::load(&root).err().unwrap();
|
||||
assert!(error.to_string().contains("reserved"));
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn constants_resolve_across_files_keep_navigation_and_invalidate_builds() {
|
||||
let root = directory("constants");
|
||||
let domain = root.join("module/demo/pricing");
|
||||
fs::create_dir_all(domain.join("app")).unwrap();
|
||||
let values = domain.join("app/values.dever");
|
||||
fs::write(&values, "const amount = 42").unwrap();
|
||||
write_source(
|
||||
domain.join("app/main.dever"),
|
||||
"const price = amount\nquote() (out: Int) { out = price }",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(domain.join("api.dever"), "cmd quote = app.quote").unwrap();
|
||||
let path = root.to_str().unwrap();
|
||||
success(cli(&["fmt", path]));
|
||||
success(cli(&["fmt", path, "--check"]));
|
||||
success(cli(&["check", path]));
|
||||
let load = || -> serde_json::Value {
|
||||
serde_json::from_str(&success(cli(&["inspect", path, "--json"]))).unwrap()
|
||||
};
|
||||
let index = load();
|
||||
assert_eq!(
|
||||
index["symbols"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|s| s["kind"] == "constant")
|
||||
.count(),
|
||||
2
|
||||
);
|
||||
assert_eq!(
|
||||
index["calls"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|e| e["kind"] == "reference")
|
||||
.count(),
|
||||
2
|
||||
);
|
||||
let selected: serde_json::Value = serde_json::from_str(&success(cli(&[
|
||||
"inspect",
|
||||
path,
|
||||
"--json",
|
||||
"--symbol",
|
||||
"demo.pricing.app.price",
|
||||
"--depth",
|
||||
"1",
|
||||
])))
|
||||
.unwrap();
|
||||
assert_eq!(selected["symbols"].as_array().unwrap().len(), 3);
|
||||
for (name, expected) in [("before", 42), ("after", 43)] {
|
||||
fs::write(&values, format!("const amount = {expected}\n")).unwrap();
|
||||
let binary = root.join(name);
|
||||
success(cli(&[
|
||||
"build",
|
||||
path,
|
||||
"--profile",
|
||||
"dev",
|
||||
"--output",
|
||||
binary.to_str().unwrap(),
|
||||
]));
|
||||
let output: serde_json::Value = serde_json::from_str(&success(
|
||||
Command::new(binary)
|
||||
.args(["demo.pricing.quote", "{}"])
|
||||
.output()
|
||||
.unwrap(),
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(output["data"], expected);
|
||||
}
|
||||
assert_ne!(index["files"], load()["files"]);
|
||||
fs::write(&values, "const amount: Int = true\n").unwrap();
|
||||
let broken = load();
|
||||
assert!(broken["symbols"].as_array().unwrap().is_empty(), "{broken}");
|
||||
assert!(!broken["diagnostics"].as_array().unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_references_obey_roles_and_participate_in_domain_cycles() {
|
||||
let root = directory("constant-access");
|
||||
let first = root.join("module/demo/first");
|
||||
let second = root.join("module/demo/second");
|
||||
for path in [&first, &second] {
|
||||
fs::create_dir_all(path).unwrap();
|
||||
}
|
||||
fs::write(first.join("domain.dever"), "const private_price = 8").unwrap();
|
||||
write_source(
|
||||
first.join("app/main.dever"),
|
||||
"const price = domain.private_price",
|
||||
)
|
||||
.unwrap();
|
||||
write_source(
|
||||
second.join("app/main.dever"),
|
||||
"const count = 2\nquote() (out: Int) { out = first.price }",
|
||||
)
|
||||
.unwrap();
|
||||
analyze(&root);
|
||||
write_source(
|
||||
first.join("app/main.dever"),
|
||||
"const price = domain.private_price\nconst quantity = second.count",
|
||||
)
|
||||
.unwrap();
|
||||
let project = Project::load(&root).unwrap();
|
||||
let error = program::check(&project.declarations, &project.modules)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(error.code, "C010");
|
||||
write_source(
|
||||
first.join("app/main.dever"),
|
||||
"const price = domain.private_price",
|
||||
)
|
||||
.unwrap();
|
||||
write_source(
|
||||
second.join("app/main.dever"),
|
||||
"quote() (out: Int) { out = demo.first.domain.private_price }",
|
||||
)
|
||||
.unwrap();
|
||||
let project = Project::load(&root).unwrap();
|
||||
let error = program::check(&project.declarations, &project.modules)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(error.code, "C003");
|
||||
write_source(second.join("app/main.dever"), "const price = first.price").unwrap();
|
||||
write_source(first.join("app/main.dever"), "const price = second.price").unwrap();
|
||||
let project = Project::load(&root).unwrap();
|
||||
assert_eq!(
|
||||
program::check(&project.declarations, &project.modules)
|
||||
.err()
|
||||
.unwrap()
|
||||
.code,
|
||||
"C010"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn secret_settings_and_command_inputs_validate_without_exposing_values() {
|
||||
let root = directory("secret");
|
||||
fs::write(root.join("app.dever"), r#"
|
||||
setting key: Secret
|
||||
setting count: Int
|
||||
sign(value: Text) (out: Int) { out = length(dever.crypto.hmacSha256(key, dever.bytes.fromText(value))) }
|
||||
input(key: Secret, count: Int) (out: Int) { out = length(dever.crypto.hmacSha256(key, dever.bytes.fromText(int.toText(count)))) }
|
||||
cmd sign = app.sign
|
||||
cmd input = app.input
|
||||
"#).unwrap();
|
||||
let path = root.to_str().unwrap();
|
||||
success(cli(&["fmt", path]));
|
||||
let (project, program) = analyze(&root);
|
||||
let artifact = build::build(&project, &program, "main", Profile::Dev, None).unwrap();
|
||||
let binary = root.join("application");
|
||||
artifact.publish(&binary).unwrap();
|
||||
drop(artifact);
|
||||
fs::create_dir(root.join("config")).unwrap();
|
||||
let config = root.join("config/setting.json");
|
||||
fs::write(
|
||||
&config,
|
||||
r#"{"module":{"main":{"main":{"key":"test-config-secret","count":1}}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let run = |name, input| Command::new(&binary).args([name, input]).output().unwrap();
|
||||
let output = success(run("main.main.sign", r#"{"value":"abc"}"#));
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(&output).unwrap()["data"],
|
||||
32
|
||||
);
|
||||
success(run(
|
||||
"main.main.input",
|
||||
r#"{"key":"test-input-secret","count":2}"#,
|
||||
));
|
||||
for input in [
|
||||
r#"{"key":"test-input-secret","count":"not-to-be-echoed"}"#,
|
||||
r#"{"key":123456789,"count":2}"#,
|
||||
] {
|
||||
let output = run("main.main.input", input);
|
||||
assert!(!output.status.success() && output.stdout.is_empty());
|
||||
let error = String::from_utf8(output.stderr).unwrap();
|
||||
assert!(
|
||||
error.contains("line") && error.contains("column"),
|
||||
"{error}"
|
||||
);
|
||||
for value in ["test-input-secret", "not-to-be-echoed", "123456789"] {
|
||||
assert!(!error.contains(value));
|
||||
}
|
||||
}
|
||||
fs::write(
|
||||
&config,
|
||||
r#"{"module":{"main":{"main":{"key":"test-config-secret","count":"not-to-be-echoed"}}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let output = run("main.main.sign", r#"{"value":"abc"}"#);
|
||||
assert!(!output.status.success() && output.stdout.is_empty());
|
||||
let error = String::from_utf8(output.stderr).unwrap();
|
||||
assert!(error.contains("line") && error.contains("column"));
|
||||
assert!(!error.contains("test-config-secret") && !error.contains("not-to-be-echoed"));
|
||||
for source in [
|
||||
"setting key: Secret\nmain() (out: Secret) { out = key }",
|
||||
"type Box { key: Secret }\nencode(value: Box) (out: Json) { out = dever.json.encode(value) }",
|
||||
] {
|
||||
fs::write(root.join("app.dever"), source).unwrap();
|
||||
success(cli(&["fmt", path]));
|
||||
let output = cli(&[
|
||||
"build",
|
||||
path,
|
||||
"--output",
|
||||
root.join("rejected").to_str().unwrap(),
|
||||
]);
|
||||
assert!(!output.status.success());
|
||||
assert!(String::from_utf8_lossy(&output.stderr).contains("Secret cannot"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn provider_verify_restricts_the_entire_call_graph_to_global_reads() {
|
||||
let root = project(
|
||||
"verify-global-contract",
|
||||
r#"
|
||||
type Identity { id: Text, user_id: demo.user.data.id?, tenant_id: data.id? }
|
||||
flow lookup(session: Text) (out: data.Article?)
|
||||
| step | kind | do |
|
||||
| out | data | data.first(title == session) |
|
||||
flow verify(claims: dever.auth.Claims) (identity: Identity)
|
||||
| step | kind | do |
|
||||
| session | flow | lookup(claims.session) |
|
||||
| - | check | session != null else Unauthorized |
|
||||
| identity | calc | Identity {id = claims.subject, user_id = null, tenant_id = null} |
|
||||
"#,
|
||||
);
|
||||
let model = root.join("module/demo/article/data/main.dever");
|
||||
write_source(&model, "global type Article {title:Text}").unwrap();
|
||||
analyze(&root);
|
||||
write_source(&model, "type Article {title:Text}").unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
let error = program::check(&loaded.declarations, &loaded.modules)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert!(error.message.contains("tenant Model"), "{error:?}");
|
||||
write_source(&model, "global type Article {title:Text}").unwrap();
|
||||
for operation in [
|
||||
"| - | data | data.create({title = claims.subject}) |",
|
||||
"| - | flow | dever.time.sleep(1) |",
|
||||
"| - | flow | dever.io.println(claims.subject) |",
|
||||
] {
|
||||
let app = format!(
|
||||
"type Identity {{ id: Text, user_id: demo.user.data.id?, tenant_id: data.id? }}\nflow verify(claims: dever.auth.Claims) (identity: Identity)\n| step | kind | do |\n{operation}\n| identity | calc | Identity {{id=claims.subject,user_id=null,tenant_id=null}} |\n"
|
||||
);
|
||||
write_source(root.join("module/demo/article/app/main.dever"), app).unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
let error = program::check(&loaded.declarations, &loaded.modules)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(error.code, "C014", "{operation}: {error:?}");
|
||||
assert!(error.message.contains("Provider verify"), "{error:?}");
|
||||
}
|
||||
for identity in [
|
||||
"type Identity {id:Text,user_id:Int?,tenant_id:Int?}",
|
||||
"type Identity {id:Text,user_id:demo.user.data.id?,tenant_id:data.id?,extra:Text?}",
|
||||
"type Identity {private id:Text,user_id:demo.user.data.id?,tenant_id:data.id?}",
|
||||
] {
|
||||
let app = format!(
|
||||
"{identity}\nflow verify(claims: dever.auth.Claims) (identity: Identity)\n| step | kind | do |\n| identity | calc | Identity {{id=claims.subject,user_id=null,tenant_id=null{} }} |\n",
|
||||
if identity.contains("extra") {
|
||||
",extra=null"
|
||||
} else {
|
||||
""
|
||||
}
|
||||
);
|
||||
write_source(root.join("module/demo/article/app/main.dever"), app).unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(
|
||||
program::check(&loaded.declarations, &loaded.modules).is_err(),
|
||||
"{identity}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn named_databases_keep_schemas_separate_and_reject_cross_database_transactions() {
|
||||
let root = project(
|
||||
"model-bindings-native",
|
||||
r#"
|
||||
flow save(title: Text) ()
|
||||
| step | kind | do |
|
||||
| - | data | data.create({title = title}) |
|
||||
transaction flow article(title: Text) ()
|
||||
| step | kind | do |
|
||||
| - | flow | save(title) |
|
||||
flow both(title: Text) ()
|
||||
| step | kind | do |
|
||||
| - | flow | save(title) |
|
||||
| - | flow | demo.user.app.save(title) |
|
||||
flow stages(title: Text) ()
|
||||
| step | kind | do |
|
||||
| - | flow | article(title) |
|
||||
| - | flow | demo.user.app.transactional(title) |
|
||||
flow link(user_id: demo.user.data.id) (out: data.Article) {
|
||||
out = data.create({title = "linked", author_id = user_id})
|
||||
}
|
||||
flow linked(user_id: demo.user.data.id) (out: data.Article) {
|
||||
out = data.get(author_id == user_id)
|
||||
}
|
||||
flow counts() (articles: Int, users: Int)
|
||||
| step | kind | do |
|
||||
| articles | data | data.count() |
|
||||
| users | flow | demo.user.app.count() |
|
||||
"#,
|
||||
);
|
||||
write_source(
|
||||
root.join("module/demo/article/data/main.dever"),
|
||||
"type Article { title: Text, author_id: demo.user.data.id? external }",
|
||||
)
|
||||
.unwrap();
|
||||
write_source(
|
||||
root.join("module/demo/user/data/main.dever"),
|
||||
"database archive\nglobal type User { name: Text }",
|
||||
)
|
||||
.unwrap();
|
||||
write_source(
|
||||
root.join("module/demo/user/app/main.dever"),
|
||||
r#"
|
||||
flow save(name: Text) ()
|
||||
| step | kind | do |
|
||||
| - | data | data.create({name = name}) |
|
||||
transaction flow transactional(name: Text) ()
|
||||
| step | kind | do |
|
||||
| - | flow | save(name) |
|
||||
flow count() (out: Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.count() |
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("module/demo/article/api.dever"),
|
||||
"cmd both = app.both\nlong cmd stages = app.stages\ncmd counts = app.counts\ncmd link = app.link\ncmd linked = app.linked",
|
||||
)
|
||||
.unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
let config = root.join("config/setting.json");
|
||||
fs::write(&config,r#"{"database":{"default":{"type":"sqlite","path":"data/main.db"},"archive":{"type":"sqlite","path":"data/archive.db"}}}"#).unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let user = program
|
||||
.definitions
|
||||
.iter()
|
||||
.find(|d| d.name == "demo.user.data.User")
|
||||
.unwrap();
|
||||
assert!(user.model.as_ref().unwrap().global);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
let call = |name: &str, input: &str| {
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.args([&format!("demo.article.{name}"), input])
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
success(
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.arg("migrate")
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
assert!(
|
||||
!call("both", r#"{"title":"must roll back"}"#)
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
let counts: serde_json::Value = serde_json::from_str(&success(call("counts", "{}"))).unwrap();
|
||||
assert_eq!(counts["data"], serde_json::json!({"articles":0,"users":0}));
|
||||
success(call("stages", r#"{"title":"committed stages"}"#));
|
||||
let counts: serde_json::Value = serde_json::from_str(&success(call("counts", "{}"))).unwrap();
|
||||
assert_eq!(counts["data"], serde_json::json!({"articles":1,"users":1}));
|
||||
let user = r#"{"user_id":1}"#;
|
||||
let saved: serde_json::Value = serde_json::from_str(&success(call("link", user))).unwrap();
|
||||
let found: serde_json::Value = serde_json::from_str(&success(call("linked", user))).unwrap();
|
||||
assert_eq!(saved["data"]["author_id"], 1);
|
||||
assert_eq!(found["data"], saved["data"]);
|
||||
// 读取本测试生成的两个真实文件,确认各库没有另一库的业务表。
|
||||
for (file, expected, absent) in [
|
||||
("main.db", "demo_article", "demo_user"),
|
||||
("archive.db", "demo_user", "demo_article"),
|
||||
] {
|
||||
let path = root.join("data").join(file);
|
||||
let db = dever_runtime::database::Database::sqlite(
|
||||
&path,
|
||||
false,
|
||||
dever_runtime::database::Options {
|
||||
max_page_size: 100,
|
||||
max_connections: 1,
|
||||
wait_timeout: std::time::Duration::from_secs(5),
|
||||
io_timeout: std::time::Duration::from_secs(30),
|
||||
},
|
||||
None,
|
||||
);
|
||||
let path_check = dever_runtime::task::run(true, 8, async |scope| {
|
||||
let mut executor = db.await.unwrap().acquire().await.unwrap();
|
||||
executor
|
||||
.query(
|
||||
scope,
|
||||
"SELECT name FROM sqlite_schema WHERE type='table'".into(),
|
||||
vec![],
|
||||
|row| row.get::<String>(0),
|
||||
)
|
||||
.await
|
||||
})
|
||||
.unwrap();
|
||||
let names = path_check.unwrap();
|
||||
assert!(names.iter().any(|n| n == expected));
|
||||
assert!(!names.iter().any(|n| n == absent));
|
||||
}
|
||||
fs::rename(
|
||||
root.join("data/archive.db"),
|
||||
root.join("data/archive.saved.db"),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!call("counts", "{}").status.success());
|
||||
assert!(!root.join("data/archive.db").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn physical_table_names_are_unique_per_database_binding() {
|
||||
let root = directory("physical-table-collision");
|
||||
let first = "module/sales/item_log/data/item_log.dv";
|
||||
let second = "module/sales_item/log/data/log.dv";
|
||||
write_source(root.join(first), "type ItemLog { title: Text }").unwrap();
|
||||
write_source(root.join(second), "type Log { title: Text }").unwrap();
|
||||
let check = || cli(&["check", root.to_str().unwrap()]);
|
||||
success(cli(&["fmt", root.to_str().unwrap()]));
|
||||
let output = check();
|
||||
let error = String::from_utf8_lossy(&output.stderr);
|
||||
assert!(
|
||||
!output.status.success()
|
||||
&& error.contains("duplicate physical table sales_item_log in database default"),
|
||||
"{error}"
|
||||
);
|
||||
assert!(error.contains(first) && error.contains(second), "{error}");
|
||||
write_source(
|
||||
root.join(second),
|
||||
"database archive\ntype Log { title: Text }",
|
||||
)
|
||||
.unwrap();
|
||||
success(cli(&["fmt", root.to_str().unwrap()]));
|
||||
success(check());
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn migration_data_steps_bind_parameters_and_rollback_with_schema_changes() {
|
||||
let root = project(
|
||||
"model-data-migration",
|
||||
"flow get(article_id: data.id) (out: data.Article)\n| step | kind | do |\n| out | data | data.get(article_id) |\n",
|
||||
);
|
||||
let model = root.join("module/demo/article/data/main.dever");
|
||||
write_source(&model, "type Article { title: Text unique, obsolete: Text default \"old\" }\nseed { {title = \"initial\"} }").unwrap();
|
||||
fs::write(
|
||||
root.join("module/demo/article/api.dever"),
|
||||
"cmd get = app.get",
|
||||
)
|
||||
.unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
let config = root.join("config/setting.json");
|
||||
fs::write(
|
||||
&config,
|
||||
r#"{"database":{"default":{"type":"sqlite","path":"data/model.db"}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let build = || {
|
||||
let (loaded, program) = analyze(&root);
|
||||
build::build(&loaded, &program, "main", Profile::Dev, None).unwrap()
|
||||
};
|
||||
let migrate = |binary: &Path| {
|
||||
Command::new(binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.arg("migrate")
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
let read = |binary: &Path| {
|
||||
let out = success(
|
||||
Command::new(binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.args(["demo.article.get", r#"{"article_id":1}"#])
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
serde_json::from_str::<serde_json::Value>(&out).unwrap()["data"].clone()
|
||||
};
|
||||
let original = build();
|
||||
success(migrate(&original.binary));
|
||||
let initial = read(&original.binary);
|
||||
let old_binary = root.join("original");
|
||||
fs::copy(&original.binary, &old_binary).unwrap();
|
||||
drop(original);
|
||||
let migration = r#"
|
||||
type Article { title: Text unique, copies: Int default 0 }
|
||||
migrate rewrite {
|
||||
before {
|
||||
sqlite = "UPDATE demo_article SET title = title || ?1 WHERE obsolete = ?2"
|
||||
postgres = "UPDATE demo_article SET title = title || $1 WHERE obsolete = $2"
|
||||
parameters = ["'; -- _dever_history", "old"]
|
||||
}
|
||||
drop obsolete
|
||||
after {
|
||||
sqlite = "UPDATE demo_article SET copies = copies + ?1"
|
||||
postgres = "UPDATE demo_article SET copies = copies + $1"
|
||||
parameters = [2]
|
||||
}
|
||||
}
|
||||
"#;
|
||||
// after 失败时,before 的数据改写和删列都必须回滚。
|
||||
write_source(
|
||||
&model,
|
||||
migration.replace("copies = copies + ?1", "missing = ?1"),
|
||||
)
|
||||
.unwrap();
|
||||
let failed = build();
|
||||
assert!(!migrate(&failed.binary).status.success());
|
||||
assert_eq!(read(&old_binary), initial);
|
||||
drop(failed);
|
||||
write_source(&model, migration).unwrap();
|
||||
let valid = build();
|
||||
success(migrate(&valid.binary));
|
||||
success(migrate(&valid.binary));
|
||||
let updated = read(&valid.binary);
|
||||
assert_eq!(updated["title"], "initial'; -- _dever_history");
|
||||
assert_eq!(updated["copies"], 2);
|
||||
assert!(updated.get("obsolete").is_none());
|
||||
assert_eq!(updated["id"], initial["id"]);
|
||||
assert_eq!(updated["created_at"], initial["created_at"]);
|
||||
let valid_binary = root.join("valid");
|
||||
fs::copy(&valid.binary, &valid_binary).unwrap();
|
||||
drop(valid);
|
||||
// 已执行参数也是历史内容;改写必须失败,不能重跑迁移。
|
||||
write_source(
|
||||
&model,
|
||||
migration.replace("parameters = [2]", "parameters = [3]"),
|
||||
)
|
||||
.unwrap();
|
||||
let changed = build();
|
||||
let failed = migrate(&changed.binary);
|
||||
assert!(!failed.status.success());
|
||||
assert!(
|
||||
String::from_utf8_lossy(&failed.stderr)
|
||||
.contains("applied migration content or order changed")
|
||||
);
|
||||
assert_eq!(read(&valid_binary), updated);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn migration_sql_uses_library_parsing_and_rejects_invalid_boundaries() {
|
||||
let root = project("model-data-sql-check", "");
|
||||
let path = root.join("module/demo/article/data/main.dever");
|
||||
let source = |sqlite: &str, postgres: &str, parameters: &str| {
|
||||
format!(
|
||||
"type Article {{ title: Text }}\nmigrate rewrite {{ after {{ sqlite = {}, postgres = {}, parameters = {parameters} }} }}",
|
||||
serde_json::to_string(sqlite).unwrap(),
|
||||
serde_json::to_string(postgres).unwrap()
|
||||
)
|
||||
};
|
||||
for (sqlite, postgres, parameters) in [
|
||||
(
|
||||
"UPDATE demo_article SET title=?1 /* ; ?2 */",
|
||||
"UPDATE demo_article SET title=$1",
|
||||
"[\"ok\"]",
|
||||
),
|
||||
(
|
||||
"INSERT INTO demo_article (created_at,title) VALUES (?1,?2)",
|
||||
"INSERT INTO demo_article (created_at,title) VALUES ($1,$2)",
|
||||
"[-1,\"text\"]",
|
||||
),
|
||||
(
|
||||
"DELETE FROM demo_article WHERE title='?1'",
|
||||
"DELETE FROM demo_article WHERE title=$$$_dever_history$$",
|
||||
"[]",
|
||||
),
|
||||
] {
|
||||
write_source(&path, source(sqlite, postgres, parameters)).unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(loaded.diagnostics.is_empty(), "{:?}", loaded.diagnostics);
|
||||
program::check(&loaded.declarations, &loaded.modules).unwrap();
|
||||
let formatted = dever::compiler::format::definitions(
|
||||
loaded
|
||||
.declarations
|
||||
.iter()
|
||||
.filter(|d| loaded.modules[d.span().source].domain == "article"),
|
||||
);
|
||||
write_source(&path, &formatted).unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(loaded.diagnostics.is_empty());
|
||||
assert_eq!(
|
||||
formatted,
|
||||
dever::compiler::format::definitions(
|
||||
loaded
|
||||
.declarations
|
||||
.iter()
|
||||
.filter(|d| loaded.modules[d.span().source].domain == "article")
|
||||
)
|
||||
);
|
||||
}
|
||||
for (sqlite, postgres, parameters) in [
|
||||
(
|
||||
"UPDATE demo_article SET title=?2",
|
||||
"UPDATE demo_article SET title=$1",
|
||||
"[\"x\"]",
|
||||
),
|
||||
(
|
||||
"UPDATE demo_article SET title=?1",
|
||||
"UPDATE demo_article SET title=$2",
|
||||
"[\"x\"]",
|
||||
),
|
||||
(
|
||||
"UPDATE demo_article SET title=?1",
|
||||
"UPDATE demo_article SET title=$1",
|
||||
"[\"x\",2]",
|
||||
),
|
||||
(
|
||||
"UPDATE demo_article SET title=?",
|
||||
"UPDATE demo_article SET title=$1",
|
||||
"[\"x\"]",
|
||||
),
|
||||
(
|
||||
"UPDATE demo_article SET title=$1",
|
||||
"UPDATE demo_article SET title=$1",
|
||||
"[\"x\"]",
|
||||
),
|
||||
(
|
||||
"UPDATE demo_article SET title=:name",
|
||||
"UPDATE demo_article SET title=$1",
|
||||
"[\"x\"]",
|
||||
),
|
||||
(
|
||||
"UPDATE demo_article SET title='x'; DELETE FROM demo_article",
|
||||
"DELETE FROM demo_article",
|
||||
"[]",
|
||||
),
|
||||
("UPDATE demo_article SET", "DELETE FROM demo_article", "[]"),
|
||||
("DROP TABLE demo_article", "DELETE FROM demo_article", "[]"),
|
||||
(
|
||||
"UPDATE \"_dever_history\" SET name='x'",
|
||||
"DELETE FROM demo_article",
|
||||
"[]",
|
||||
),
|
||||
(
|
||||
"UPDATE demo_article SET title=(SELECT name FROM sqlite_schema LIMIT 1)",
|
||||
"DELETE FROM demo_article",
|
||||
"[]",
|
||||
),
|
||||
(
|
||||
"DELETE FROM demo_article",
|
||||
"DELETE FROM pg_catalog.pg_class",
|
||||
"[]",
|
||||
),
|
||||
(
|
||||
"DELETE FROM demo_article",
|
||||
"UPDATE demo_article SET title=$1",
|
||||
"[1.2]",
|
||||
),
|
||||
(
|
||||
"DELETE FROM demo_article",
|
||||
"UPDATE demo_article SET title=$1",
|
||||
"[1e999]",
|
||||
),
|
||||
] {
|
||||
write_source(&path, source(sqlite, postgres, parameters)).unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(loaded.diagnostics.is_empty(), "{:?}", loaded.diagnostics);
|
||||
assert!(
|
||||
program::check(&loaded.declarations, &loaded.modules).is_err(),
|
||||
"{sqlite} / {postgres} / {parameters}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn seeds_insert_missing_keys_without_overwriting_live_records() {
|
||||
let root = project(
|
||||
"model-seed-native",
|
||||
r#"
|
||||
type Entry {code:Text, amount:Decimal, title:Text, token:Uuid}
|
||||
loop entries(rows:List<data.Article>) (out:List<Entry>)
|
||||
| each row in rows | result |
|
||||
| out | list Entry {code=row.code,amount=row.amount,title=row.title,token=row.token} |
|
||||
flow all() (total:Int, items:List<Entry>)
|
||||
| step | kind | do |
|
||||
| page | data | data.page(order = id.asc) |
|
||||
| total | calc | page.total |
|
||||
| items | loop | entries(page.items) |
|
||||
flow change(article_id: data.id, title: Text) ()
|
||||
| step | kind | do |
|
||||
| - | data | data.update(article_id, {title = title}) |
|
||||
"#,
|
||||
);
|
||||
write_source(
|
||||
root.join("module/demo/user/data/main.dever"),
|
||||
"type User { name: Text unique }\nseed { {name = \"作者\"} }",
|
||||
)
|
||||
.unwrap();
|
||||
let model = root.join("module/demo/article/data/main.dever");
|
||||
let base = "type Article { user_id: demo.user.data.id, code: Text lower, title: Text(1,30), token: Uuid generated, amount: Decimal(8,2) default 0.50 }\nunique(user_id,code)\n";
|
||||
write_source(
|
||||
&model,
|
||||
format!("{base}seed {{ {{user_id = 1, code = \" FIRST \", title = \"first\"}} }}"),
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("module/demo/article/api.dever"),
|
||||
"cmd all = app.all\ncmd change = app.change",
|
||||
)
|
||||
.unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
let config = root.join("config/setting.json");
|
||||
fs::write(
|
||||
&config,
|
||||
r#"{"database":{"default":{"type":"sqlite","path":"data/model.db"}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let build = || {
|
||||
let (loaded, program) = analyze(&root);
|
||||
build::build(&loaded, &program, "main", Profile::Dev, None).unwrap()
|
||||
};
|
||||
let migrate = |binary: &Path| {
|
||||
success(
|
||||
Command::new(binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.arg("migrate")
|
||||
.output()
|
||||
.unwrap(),
|
||||
)
|
||||
};
|
||||
let call = |binary: &Path, name: &str, input: &str| {
|
||||
success(
|
||||
Command::new(binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.args([name, input])
|
||||
.output()
|
||||
.unwrap(),
|
||||
)
|
||||
};
|
||||
let page = |binary: &Path| {
|
||||
serde_json::from_str::<serde_json::Value>(&call(binary, "demo.article.all", "{}")).unwrap()
|
||||
["data"]
|
||||
.clone()
|
||||
};
|
||||
let artifact = build();
|
||||
migrate(&artifact.binary);
|
||||
let first = page(&artifact.binary);
|
||||
assert_eq!(first["total"], 1);
|
||||
assert_eq!(first["items"][0]["code"], "first");
|
||||
assert_eq!(first["items"][0]["amount"], "0.5");
|
||||
call(
|
||||
&artifact.binary,
|
||||
"demo.article.change",
|
||||
r#"{"article_id":1,"title":"edited"}"#,
|
||||
);
|
||||
migrate(&artifact.binary);
|
||||
assert_eq!(page(&artifact.binary)["items"][0]["title"], "edited");
|
||||
drop(artifact);
|
||||
write_source(&model, format!("{base}seed {{ {{user_id = 1, code = \"FIRST\", title = \"must not replace\"}}\n{{user_id = 1,code = \"second\",title = \"new\",amount = 12.50}} }}")).unwrap();
|
||||
let artifact = build();
|
||||
migrate(&artifact.binary);
|
||||
migrate(&artifact.binary);
|
||||
let after = page(&artifact.binary);
|
||||
assert_eq!(after["total"], 2);
|
||||
assert_eq!(after["items"][0]["title"], "edited");
|
||||
assert_eq!(after["items"][0]["token"], first["items"][0]["token"]);
|
||||
assert_eq!(after["items"][1]["amount"], "12.5");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_rename_addition_and_failed_migration_preserve_real_data() {
|
||||
let root = project(
|
||||
"model-migration-native",
|
||||
r#"
|
||||
flow create(title: Text) (out: data.Article)
|
||||
| step | kind | do |
|
||||
| out | data | data.create({title = title}) |
|
||||
flow get(article_id: data.id) (out: data.Article)
|
||||
| step | kind | do |
|
||||
| out | data | data.get(article_id) |
|
||||
"#,
|
||||
);
|
||||
let model = root.join("module/demo/article/data/main.dever");
|
||||
write_source(&model, "type Article { title: Text(2,20) }").unwrap();
|
||||
fs::write(
|
||||
root.join("module/demo/article/api.dever"),
|
||||
"cmd create = app.create\ncmd get = app.get",
|
||||
)
|
||||
.unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
let config = root.join("config/setting.json");
|
||||
fs::write(
|
||||
&config,
|
||||
r#"{"database":{"default":{"type":"sqlite","path":"data/model.db"}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let build = || {
|
||||
let (loaded, program) = analyze(&root);
|
||||
build::build(&loaded, &program, "main", Profile::Dev, None).unwrap()
|
||||
};
|
||||
let migrate = |binary: &Path| {
|
||||
Command::new(binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.arg("migrate")
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
let call = |binary: &Path, name: &str, input: &str| {
|
||||
Command::new(binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.args([name, input])
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
let artifact = build();
|
||||
success(migrate(&artifact.binary));
|
||||
// NUL 也按 Unicode 码点计算,不能使用 SQLite 内建 length 的截断语义。
|
||||
let original: serde_json::Value = serde_json::from_str(&success(call(
|
||||
&artifact.binary,
|
||||
"demo.article.create",
|
||||
r#"{"title":"文\u0000章"}"#,
|
||||
)))
|
||||
.unwrap();
|
||||
drop(artifact);
|
||||
write_source(root.join("module/demo/article/app/main.dever"), "flow get(article_id: data.id) (out: data.Article)\n| step | kind | do |\n| out | data | data.get(article_id) |").unwrap();
|
||||
fs::write(
|
||||
root.join("module/demo/article/api.dever"),
|
||||
"cmd get = app.get",
|
||||
)
|
||||
.unwrap();
|
||||
let renamed = "type Article { heading: Text(2,20) from title, token: Uuid generated unique, amount: Decimal(8,2) default 12.50, label: Text lower default \" NEWS \", note: Text(1,10)? }";
|
||||
write_source(&model, renamed).unwrap();
|
||||
let artifact = build();
|
||||
assert!(
|
||||
!call(&artifact.binary, "demo.article.get", r#"{"article_id":1}"#)
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
success(migrate(&artifact.binary));
|
||||
success(migrate(&artifact.binary));
|
||||
let read = |binary: &Path| {
|
||||
serde_json::from_str::<serde_json::Value>(&success(call(
|
||||
binary,
|
||||
"demo.article.get",
|
||||
r#"{"article_id":1}"#,
|
||||
)))
|
||||
.unwrap()["data"]
|
||||
.clone()
|
||||
};
|
||||
let after = read(&artifact.binary);
|
||||
assert_eq!(after["id"], original["data"]["id"]);
|
||||
assert_eq!(after["created_at"], original["data"]["created_at"]);
|
||||
assert_eq!(after["heading"], original["data"]["title"]);
|
||||
assert_eq!(after["label"], "news");
|
||||
assert_eq!(after["amount"], "12.5");
|
||||
assert!(after["note"].is_null());
|
||||
assert_eq!(after["token"].as_str().unwrap().chars().nth(14), Some('7'));
|
||||
let valid_binary = root.join("renamed");
|
||||
fs::copy(&artifact.binary, &valid_binary).unwrap();
|
||||
drop(artifact);
|
||||
for invalid in [
|
||||
renamed.replace("Text(2,20)", "Text(1,2)"),
|
||||
renamed.replace("heading: Text(2,20) from title, ", ""),
|
||||
renamed.replace(
|
||||
"Decimal(8,2) default 12.50",
|
||||
"Decimal(8,2) <= 10 default 1.00",
|
||||
),
|
||||
] {
|
||||
write_source(&model, invalid).unwrap();
|
||||
let artifact = build();
|
||||
assert!(!migrate(&artifact.binary).status.success());
|
||||
assert_eq!(read(&valid_binary), after);
|
||||
}
|
||||
write_source(
|
||||
&model,
|
||||
renamed.replace(
|
||||
"Decimal(8,2) default 12.50",
|
||||
"Decimal(8,2) > 12.491 and < 12.509 default 12.50",
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
let artifact = build();
|
||||
success(migrate(&artifact.binary));
|
||||
assert_eq!(read(&artifact.binary), after);
|
||||
drop(artifact);
|
||||
let dropped = format!(
|
||||
"{}\nmigrate remove_heading {{ drop heading }}",
|
||||
renamed.replace("heading: Text(2,20) from title, ", "")
|
||||
);
|
||||
write_source(&model, &dropped).unwrap();
|
||||
let artifact = build();
|
||||
success(migrate(&artifact.binary));
|
||||
success(migrate(&artifact.binary));
|
||||
let mut expected = after.clone();
|
||||
expected.as_object_mut().unwrap().remove("heading");
|
||||
assert_eq!(read(&artifact.binary), expected);
|
||||
drop(artifact);
|
||||
write_source(
|
||||
&model,
|
||||
dropped.replace("drop heading", "drop different_column"),
|
||||
)
|
||||
.unwrap();
|
||||
let artifact = build();
|
||||
let failure = migrate(&artifact.binary);
|
||||
assert!(!failure.status.success());
|
||||
assert!(
|
||||
String::from_utf8_lossy(&failure.stderr)
|
||||
.contains("applied migration content or order changed")
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
use super::*;
|
||||
mod data_migration;
|
||||
mod migration;
|
||||
|
||||
#[test]
|
||||
fn composite_upsert_and_foreign_keys_execute_in_the_database() {
|
||||
let root = project(
|
||||
"model-index-native",
|
||||
r#"
|
||||
flow save(user_id: demo.user.data.id, category: Text?, title: Text) (id: data.id, author: demo.user.data.id, saved_title: Text)
|
||||
| step | kind | do |
|
||||
| row | data | data.upsert({category = category, user_id = user_id}, {title = title}, {title = title}) |
|
||||
| id | calc | row.id |
|
||||
| author | calc | row.user_id |
|
||||
| saved_title | calc | row.title |
|
||||
flow create(user_id: demo.user.data.id, category: Text?, title: Text) (id: data.id)
|
||||
| step | kind | do |
|
||||
| row | data | data.create({user_id = user_id, category = category, title = title}) |
|
||||
| id | calc | row.id |
|
||||
flow remove(article_id: data.id) (out: Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.delete(article_id) |
|
||||
flow defaultUser() (id: data.id, user_id: demo.user.data.id)
|
||||
| step | kind | do |
|
||||
| row | data | data.create({title = "default user"}) |
|
||||
| id | calc | row.id |
|
||||
| user_id | calc | row.user_id |
|
||||
"#,
|
||||
);
|
||||
write_source(root.join("module/demo/article/data/main.dever"), "type Article { user_id: demo.user.data.id default 1, category: Text?, title: Text, parent_id: data.id? }\nunique(user_id, category)\nindex(title, created_at)").unwrap();
|
||||
fs::write(
|
||||
root.join("module/demo/article/api.dever"),
|
||||
"cmd save = app.save\ncmd create = app.create\ncmd remove = app.remove\ncmd defaultUser = app.defaultUser",
|
||||
)
|
||||
.unwrap();
|
||||
write_source(
|
||||
root.join("module/demo/user/app/main.dever"),
|
||||
r#"
|
||||
flow create(name: Text) (out: data.User)
|
||||
| step | kind | do |
|
||||
| out | data | data.create({name = name}) |
|
||||
flow remove(user_id: data.id) (out: Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.delete(user_id) |
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("module/demo/user/api.dever"),
|
||||
"cmd create = app.create\ncmd remove = app.remove",
|
||||
)
|
||||
.unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
let config = root.join("config/setting.json");
|
||||
fs::write(
|
||||
&config,
|
||||
r#"{"database":{"default":{"type":"sqlite","path":"data/model.db"}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let formatted = dever::compiler::format::format(
|
||||
&loaded
|
||||
.declarations
|
||||
.iter()
|
||||
.filter(|d| matches!(d, dever::syntax::ast::Declaration::Index { .. }))
|
||||
.cloned()
|
||||
.collect::<Vec<_>>(),
|
||||
);
|
||||
assert!(formatted.contains("unique(user_id, category)"));
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
let call = |name: &str, input: serde_json::Value| {
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.args([name, &input.to_string()])
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
success(
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.arg("migrate")
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
let data = |name: &str, input| {
|
||||
serde_json::from_str::<serde_json::Value>(&success(call(name, input))).unwrap()["data"]
|
||||
.clone()
|
||||
};
|
||||
let user = data("demo.user.create", serde_json::json!({"name":"author"}));
|
||||
let default = data("demo.article.defaultUser", serde_json::json!({}));
|
||||
assert_eq!(default["user_id"], user["id"]);
|
||||
assert_eq!(
|
||||
data(
|
||||
"demo.article.remove",
|
||||
serde_json::json!({"article_id":default["id"]})
|
||||
),
|
||||
1
|
||||
);
|
||||
let key = serde_json::json!({"user_id":user["id"],"category":" news ","title":"first"});
|
||||
let first = data("demo.article.save", key.clone());
|
||||
let mut updated = key.clone();
|
||||
updated["title"] = "updated".into();
|
||||
let second = data("demo.article.save", updated);
|
||||
assert_eq!(first["id"], second["id"]);
|
||||
assert_eq!(second["saved_title"], "updated");
|
||||
assert_eq!(second["author"], user["id"]);
|
||||
for input in [
|
||||
key,
|
||||
serde_json::json!({"user_id":999,"category":"bad","title":"missing parent"}),
|
||||
] {
|
||||
let output = call("demo.article.create", input);
|
||||
assert!(!output.status.success());
|
||||
assert!(String::from_utf8_lossy(&output.stderr).contains("Constraint"));
|
||||
}
|
||||
let output = call(
|
||||
"demo.article.save",
|
||||
serde_json::json!({"user_id":user["id"],"category":null,"title":"null key"}),
|
||||
);
|
||||
assert!(!output.status.success());
|
||||
assert!(String::from_utf8_lossy(&output.stderr).contains("InvalidData"));
|
||||
assert!(
|
||||
!call(
|
||||
"demo.user.remove",
|
||||
serde_json::json!({"user_id":user["id"]})
|
||||
)
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
assert_eq!(
|
||||
data(
|
||||
"demo.article.remove",
|
||||
serde_json::json!({"article_id":first["id"]})
|
||||
),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
data(
|
||||
"demo.user.remove",
|
||||
serde_json::json!({"user_id":user["id"]})
|
||||
),
|
||||
1
|
||||
);
|
||||
// 真实 catalog 验证外键默认索引与复合前缀去重。
|
||||
dever_runtime::task::run(true, 8, async |scope| {
|
||||
let database = dever_runtime::database::Database::sqlite(
|
||||
&root.join("data/model.db"),
|
||||
false,
|
||||
dever_runtime::database::Options {
|
||||
max_page_size: 100,
|
||||
max_connections: 1,
|
||||
wait_timeout: std::time::Duration::from_secs(5),
|
||||
io_timeout: std::time::Duration::from_secs(30),
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut executor = database.acquire().await.unwrap();
|
||||
let indexes = executor
|
||||
.query(
|
||||
scope,
|
||||
"SELECT name FROM pragma_index_list('demo_article') ORDER BY name".into(),
|
||||
vec![],
|
||||
|row| row.get::<String>(0),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
indexes,
|
||||
[
|
||||
"demo_article__compound_0",
|
||||
"demo_article__compound_1",
|
||||
"demo_article_parent_id_idx"
|
||||
]
|
||||
);
|
||||
Ok::<_, std::convert::Infallible>(())
|
||||
})
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_indexes_and_cross_database_references_are_rejected() {
|
||||
let root = project(
|
||||
"model-index-errors",
|
||||
"copy(value: data.Article) (out: data.Article) { out = value }",
|
||||
);
|
||||
for model in [
|
||||
"type Article { title: Text }\nindex(missing)",
|
||||
"type Article { title: Text }\nunique(title, title)",
|
||||
"type Article { title: Text }\nindex(title)\nunique(title)",
|
||||
"database archive\ntype Article { user_id: demo.user.data.id }",
|
||||
"global type Article { user_id: demo.user.data.id }",
|
||||
"type Article { title: Text external }",
|
||||
"type Article { user_id: demo.user.data.id external }",
|
||||
"global type Article { user_id: demo.user.data.id external }",
|
||||
"type Article { title: Text from title }",
|
||||
"type Article { title: Text, heading: Text from title }",
|
||||
"type Article { title: Text from old_title, heading: Text from old_title }",
|
||||
"type Article { title: Text }\nseed {{title = \"x\"}}",
|
||||
"type Article { title: Text unique }\nseed {{id = 1,title = \"x\"}}",
|
||||
"type Article { title: Text(3,10) unique }\nseed {{title = \"x\"}}",
|
||||
"type Article { title: Text? unique }\nseed {{title = null}}",
|
||||
] {
|
||||
write_source(root.join("module/demo/article/data/main.dever"), model).unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(loaded.diagnostics.is_empty(), "{model}");
|
||||
let error = program::check(&loaded.declarations, &loaded.modules)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(error.code, "C005", "{error:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_wire_checks_stored_fields_without_traversing_virtual_relations() {
|
||||
let root = project(
|
||||
"model-relation-wire",
|
||||
"flow read(article_id: data.id) (out: data.Article?)\n| step | kind | do |\n| out | data | data.first(id == article_id) |",
|
||||
);
|
||||
write_source(
|
||||
root.join("module/demo/article/data/main.dever"),
|
||||
"type Article { title: Text, category_id: data.category.id? }",
|
||||
)
|
||||
.unwrap();
|
||||
fs::create_dir_all(root.join("module/demo/article/data")).unwrap();
|
||||
fs::write(
|
||||
root.join("module/demo/article/data/category.dever"),
|
||||
"type Category { name: Text }",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("module/demo/article/api.dever"),
|
||||
"cmd read = app.read",
|
||||
)
|
||||
.unwrap();
|
||||
// 关联目标的私有字段不在 Article 的协议里。自身存储字段的限制仍须保留。
|
||||
fs::write(
|
||||
root.join("module/demo/article/data/category.dever"),
|
||||
"type Category { private name: Text }",
|
||||
)
|
||||
.unwrap();
|
||||
analyze(&root);
|
||||
write_source(
|
||||
root.join("module/demo/article/data/main.dever"),
|
||||
"type Article { private title: Text, category_id: data.category.id? }",
|
||||
)
|
||||
.unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
let error = program::check(&loaded.declarations, &loaded.modules)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(error.code, "C006", "{error:?}");
|
||||
write_source(
|
||||
root.join("module/demo/article/data/main.dever"),
|
||||
"type Article { title: Text, category_id: data.category.id? }",
|
||||
)
|
||||
.unwrap();
|
||||
write_source(root.join("module/demo/article/app/main.dever"), "type Envelope { article:data.Article, key:Secret }\necho(value:Envelope) (out:Envelope) {out=value}").unwrap();
|
||||
fs::write(
|
||||
root.join("module/demo/article/api.dever"),
|
||||
"cmd echo=app.echo",
|
||||
)
|
||||
.unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
let error = program::check(&loaded.declarations, &loaded.modules)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(error.code, "C005", "{error:?}");
|
||||
assert!(error.message.contains("Secret"), "{error:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postgres_constraint_indexes_are_unique_across_model_tables() {
|
||||
let root = project(
|
||||
"model-pg-names",
|
||||
"flow read() (out: data.Article?)\n| step | kind | do |\n| out | data | data.first() |",
|
||||
);
|
||||
for (domain, model) in [("article", "Article"), ("user", "User")] {
|
||||
fs::write(
|
||||
root.join(format!("module/demo/{domain}/data/main.dever")),
|
||||
format!("type {model} {{ slug: Text unique }}"),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
let (loaded, program) = analyze(&root);
|
||||
let generated = emit::emit(&program, &ownership::analyze(&program), &loaded.sources);
|
||||
let text = generated
|
||||
.values()
|
||||
.map(|file| file.text.as_str())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
for table in ["demo_article", "demo_user"] {
|
||||
assert!(text.contains(&format!("{table}_pkey")));
|
||||
assert!(text.contains(&format!("_dever_unique_{table}_2")));
|
||||
}
|
||||
assert!(!text.contains("_dever_pk"));
|
||||
assert!(!text.contains("_dever_unique_2"));
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn model_crud_and_transaction_use_real_database() {
|
||||
let root = project(
|
||||
"model-crud-native",
|
||||
r#"
|
||||
flow create(title: Text) (out: data.Article)
|
||||
| step | kind | do |
|
||||
| out | data | data.create({ title = title, with = title }) |
|
||||
|
||||
flow read(article_id: data.id) (out: data.Article)
|
||||
| step | kind | do |
|
||||
| out | data | data.get(article_id) |
|
||||
|
||||
transaction flow rename(article_id: data.id, title: Text) (changed: Int)
|
||||
| step | kind | do |
|
||||
| changed | data | data.update({ where = id == article_id }, { title = title }) |
|
||||
|
||||
flow reject(title: Text, accepted: Bool) ()
|
||||
| step | kind | do |
|
||||
| saved | data | data.create({ title = title }) |
|
||||
| - | check | accepted else Conflict |
|
||||
|
||||
flow list(page: Int, size: Int) (out: data.Page)
|
||||
| step | kind | do |
|
||||
| out | data | data.page(page = page, size = size, order = id.asc) |
|
||||
|
||||
flow items(page: Int, size: Int) (out: List<data.Article>) {
|
||||
out = data.page(title.contains("标题"), page = page, size = size, order = id.asc).items
|
||||
}
|
||||
|
||||
flow count() (out: Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.count() |
|
||||
|
||||
flow remove(article_id: data.id) (out: Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.delete(article_id) |
|
||||
"#,
|
||||
);
|
||||
write_source(root.join("module/demo/article/data/main.dever"), "type Status { Draft, Published }\ntype Article { title: Text(1, 120) unique, status: Status default Draft index, body: Text? raw, with: Text? }").unwrap();
|
||||
fs::write(root.join("module/demo/article/api.dever"),"cmd create = app.create\ncmd read = app.read\ncmd rename = app.rename\ncmd reject = app.reject\ncmd count = app.count\ncmd list = app.list\ncmd items = app.items\ncmd remove = app.remove").unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
let config = root.join("config/setting.json");
|
||||
fs::write(
|
||||
&config,
|
||||
r#"{"database":{"default":{"type":"sqlite","path":"data/model.db"}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
let call = |name: &str, input: &str| {
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.args([name, input])
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
assert!(!call("demo.article.count", "{}").status.success());
|
||||
assert!(!root.join("data/model.db").exists());
|
||||
success(
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.arg("migrate")
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
let output = success(call("demo.article.create", r#"{"title":"' OR 1=1 --"}"#));
|
||||
let saved: serde_json::Value = serde_json::from_str(&output).unwrap();
|
||||
let id = saved["data"]["id"].as_i64().unwrap();
|
||||
assert_eq!(saved["data"]["title"], "' OR 1=1 --");
|
||||
assert_eq!(saved["data"]["with"], saved["data"]["title"]);
|
||||
assert_eq!(saved["data"]["status"], "Draft");
|
||||
assert_eq!(saved["data"]["body"], serde_json::Value::Null);
|
||||
let duplicate = call("demo.article.create", r#"{"title":"' OR 1=1 --"}"#);
|
||||
assert!(!duplicate.status.success());
|
||||
assert!(String::from_utf8_lossy(&duplicate.stderr).contains("Constraint"));
|
||||
assert!(
|
||||
!call("demo.article.create", r#"{"title":" "}"#)
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
let input = serde_json::json!({"article_id":id}).to_string();
|
||||
let read: serde_json::Value =
|
||||
serde_json::from_str(&success(call("demo.article.read", &input))).unwrap();
|
||||
assert_eq!(read["data"], saved["data"]);
|
||||
success(call(
|
||||
"demo.article.rename",
|
||||
&serde_json::json!({"article_id":id,"title":" 新标题 "}).to_string(),
|
||||
));
|
||||
let output = call(
|
||||
"demo.article.reject",
|
||||
r#"{"title":"必须回滚","accepted":false}"#,
|
||||
);
|
||||
assert!(!output.status.success());
|
||||
let count: serde_json::Value =
|
||||
serde_json::from_str(&success(call("demo.article.count", "{}"))).unwrap();
|
||||
assert_eq!(count["data"], 1);
|
||||
let page: serde_json::Value = serde_json::from_str(&success(call(
|
||||
"demo.article.list",
|
||||
r#"{"page":1,"size":2}"#,
|
||||
)))
|
||||
.unwrap();
|
||||
assert_eq!(page["data"]["total"], 1);
|
||||
assert_eq!(page["data"]["pages"], 1);
|
||||
let items = |p: i64, size: i64| {
|
||||
call(
|
||||
"demo.article.items",
|
||||
&serde_json::json!({"page":p,"size":size}).to_string(),
|
||||
)
|
||||
};
|
||||
let first: serde_json::Value = serde_json::from_str(&success(items(1, 2))).unwrap();
|
||||
assert_eq!(first["data"], page["data"]["items"]);
|
||||
let past: serde_json::Value = serde_json::from_str(&success(items(2, 2))).unwrap();
|
||||
assert_eq!(past["data"], serde_json::json!([]));
|
||||
assert!(!items(0, 2).status.success());
|
||||
assert!(!items(i64::MAX, 2).status.success());
|
||||
assert_eq!(page["data"]["items"][0]["title"], "新标题");
|
||||
let page: serde_json::Value = serde_json::from_str(&success(call(
|
||||
"demo.article.list",
|
||||
r#"{"page":2,"size":2}"#,
|
||||
)))
|
||||
.unwrap();
|
||||
assert_eq!(page["data"]["total"], 1);
|
||||
assert_eq!(page["data"]["items"], serde_json::json!([]));
|
||||
assert!(
|
||||
!call("demo.article.list", r#"{"page":0,"size":2}"#)
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
assert!(
|
||||
!call("demo.article.list", r#"{"page":1,"size":101}"#)
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
success(call("demo.article.remove", &input));
|
||||
let output = call("demo.article.read", &input);
|
||||
assert!(!output.status.success());
|
||||
assert!(String::from_utf8_lossy(&output.stderr).contains("NotFound"));
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
use super::*;
|
||||
|
||||
fn executable(name: &str, app: &str, api: &str) -> (PathBuf, PathBuf) {
|
||||
let root = project(name, app);
|
||||
fs::write(root.join("module/demo/article/api.dever"), api).unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
let config = root.join("config/setting.json");
|
||||
fs::write(
|
||||
&config,
|
||||
r#"{"database":{"default":{"type":"sqlite","path":"data/model.db","max_connections":4}}}"#,
|
||||
)
|
||||
.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(&config)
|
||||
.arg("migrate")
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
(artifact.binary, config)
|
||||
}
|
||||
fn call(binary: &std::path::Path, config: &std::path::Path, name: &str, input: &str) -> Output {
|
||||
Command::new(binary)
|
||||
.arg("--config")
|
||||
.arg(config)
|
||||
.args([name, input])
|
||||
.output()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_failure_cannot_be_captured_and_committed() {
|
||||
let (binary, config) = executable(
|
||||
"model-nested-rollback",
|
||||
r#"
|
||||
type Problem { error Denied }
|
||||
type Attempt { Saved, error Rejected(value: Problem), error Storage(value: dever.database.Error) }
|
||||
transaction flow inner(title: Text, allowed: Bool) ()
|
||||
| step | kind | do |
|
||||
| saved | data | data.create({title = title}) |
|
||||
| - | check | allowed else Problem.Denied |
|
||||
rule handled(value: Attempt) (out: Bool) recover("报告被拒绝的请求")
|
||||
| value | out |
|
||||
| Saved | true |
|
||||
| Rejected(error) | false |
|
||||
| Storage(error) | fail(error) |
|
||||
transaction flow outer(title: Text, allowed: Bool) (out: Bool)
|
||||
| step | kind | do |
|
||||
| attempt: Attempt | flow | result(inner(title, allowed)) |
|
||||
| out | rule | handled(attempt) |
|
||||
flow count() (out: Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.count() |
|
||||
"#,
|
||||
"cmd outer = app.outer\ncmd count = app.count",
|
||||
);
|
||||
let output = call(
|
||||
&binary,
|
||||
&config,
|
||||
"demo.article.outer",
|
||||
r#"{"title":"不得提交","allowed":false}"#,
|
||||
);
|
||||
assert!(!output.status.success());
|
||||
assert!(String::from_utf8_lossy(&output.stderr).contains("Database"));
|
||||
let output: serde_json::Value =
|
||||
serde_json::from_str(&success(call(&binary, &config, "demo.article.count", "{}"))).unwrap();
|
||||
assert_eq!(output["data"], 0);
|
||||
success(call(
|
||||
&binary,
|
||||
&config,
|
||||
"demo.article.outer",
|
||||
r#"{"title":"正常提交","allowed":true}"#,
|
||||
));
|
||||
let output: serde_json::Value =
|
||||
serde_json::from_str(&success(call(&binary, &config, "demo.article.count", "{}"))).unwrap();
|
||||
assert_eq!(output["data"], 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_entry_commits_explicit_stages_and_tasks_use_separate_contexts() {
|
||||
let (binary, config) = executable(
|
||||
"model-long-stages",
|
||||
r#"
|
||||
transaction flow save(title: Text) ()
|
||||
| step | kind | do |
|
||||
| saved | data | data.create({title = title}) |
|
||||
flow stages(title: Text, allowed: Bool) ()
|
||||
| step | kind | do |
|
||||
| - | flow | save(title) |
|
||||
| - | flow | dever.time.sleep(1) |
|
||||
| - | check | allowed else Conflict |
|
||||
flow count() (out: Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.count() |
|
||||
flow concurrent() (out: Int)
|
||||
| step | kind | do |
|
||||
| task | calc | run(count()) |
|
||||
| out | calc | wait(task) |
|
||||
flow counts() (left: Int, right: Int)
|
||||
| step | kind | parallel | do |
|
||||
| left | data | reads | data.count() |
|
||||
| right | flow | reads | count() |
|
||||
"#,
|
||||
"long cmd stages = app.stages\ncmd count = app.concurrent\ncmd counts = app.counts",
|
||||
);
|
||||
assert!(
|
||||
!call(
|
||||
&binary,
|
||||
&config,
|
||||
"demo.article.stages",
|
||||
r#"{"title":"已提交阶段","allowed":false}"#
|
||||
)
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
let output: serde_json::Value =
|
||||
serde_json::from_str(&success(call(&binary, &config, "demo.article.count", "{}"))).unwrap();
|
||||
assert_eq!(output["data"], 1);
|
||||
let output: serde_json::Value = serde_json::from_str(&success(call(
|
||||
&binary,
|
||||
&config,
|
||||
"demo.article.counts",
|
||||
"{}",
|
||||
)))
|
||||
.unwrap();
|
||||
assert_eq!(output["data"], serde_json::json!({"left":1,"right":1}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_transaction_and_model_access_constraints_are_static() {
|
||||
let root = project(
|
||||
"model-entry-constraints",
|
||||
r#"
|
||||
flow create(title: Text) ()
|
||||
| step | kind | do |
|
||||
| saved | data | data.create({title = title}) |
|
||||
"#,
|
||||
);
|
||||
fs::write(
|
||||
root.join("module/demo/article/api.dever"),
|
||||
"long cmd create = app.create",
|
||||
)
|
||||
.unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
let error = program::check(&loaded.declarations, &loaded.modules)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert!(error.message.contains("transaction flow"), "{error:?}");
|
||||
fs::write(
|
||||
root.join("module/demo/article/api.dever"),
|
||||
"cmd create = app.create",
|
||||
)
|
||||
.unwrap();
|
||||
for app in [
|
||||
"flow create(title: Text) ()\n| step | kind | do |\n| saved | data | data.create({title = title}) |\n| - | flow | dever.time.sleep(1) |",
|
||||
"flow create(title: Text) ()\n| step | kind | do |\n| changed | data | data.update({}, {title = title}) |",
|
||||
"flow create(title: Text) ()\n| step | kind | do |\n| saved | data | demo.user.data.create({name = title}) |",
|
||||
"transaction flow create(title: Text) ()\n| step | kind | parallel | do |\n| left | data | reads | data.count() |\n| right | data | reads | data.count() |",
|
||||
] {
|
||||
write_source(root.join("module/demo/article/app/main.dever"), app).unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(loaded.diagnostics.is_empty(), "{:?}", loaded.diagnostics);
|
||||
assert!(
|
||||
program::check(&loaded.declarations, &loaded.modules).is_err(),
|
||||
"{app}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sqlite_services_migrate_when_configured() {
|
||||
services_migrate_when_configured(
|
||||
"sqlite-startup-migration",
|
||||
serde_json::json!({"type":"sqlite","path":"data/model.db"}),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires an isolated PostgreSQL database; run test/postgres.py"]
|
||||
fn postgres_services_migrate_when_configured() {
|
||||
let url = std::env::var("DEVER_TEST_POSTGRES").expect("isolated PostgreSQL test connection");
|
||||
services_migrate_when_configured(
|
||||
"postgres-startup-migration",
|
||||
serde_json::json!({"type":"postgres","url":url,"tls":"disabled"}),
|
||||
);
|
||||
}
|
||||
|
||||
fn services_migrate_when_configured(name: &str, database: serde_json::Value) {
|
||||
use crate::api::{Server, config};
|
||||
let root = project(
|
||||
name,
|
||||
r#"
|
||||
flow create(title: Text) (out: data.Article)
|
||||
| step | kind | do |
|
||||
| out | data | data.create({title = title}) |
|
||||
flow get(article_id: data.id) (out: data.Article)
|
||||
| step | kind | do |
|
||||
| out | data | data.get(article_id) |
|
||||
"#,
|
||||
);
|
||||
let model = root.join("module/demo/article/data/main.dever");
|
||||
let api = root.join("module/demo/article/api/front");
|
||||
fs::create_dir_all(&api).unwrap();
|
||||
fs::write(
|
||||
api.join("main.dever"),
|
||||
"public post create = app.create\npublic get get = app.get",
|
||||
)
|
||||
.unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
let (path, port, mut settings) = config(&root);
|
||||
settings["database"] = serde_json::json!({"create":true,"default":database});
|
||||
fs::write(&path, settings.to_string()).unwrap();
|
||||
let build = || {
|
||||
let (loaded, program) = analyze(&root);
|
||||
build::build(&loaded, &program, "main", Profile::Dev, None).unwrap()
|
||||
};
|
||||
let artifact = build();
|
||||
let first = Server::start(&artifact.binary, &path, port);
|
||||
let (status, original) = first.call(
|
||||
"POST",
|
||||
"/demo/article/front/main/create",
|
||||
r#"{"title":"original"}"#,
|
||||
"Content-Type: application/json\r\n",
|
||||
);
|
||||
assert_eq!(status, 200, "{original}");
|
||||
let (_, second_port, mut second_settings) = config(&root);
|
||||
let second_path = path.with_file_name("second.json");
|
||||
second_settings["database"] = settings["database"].clone();
|
||||
fs::write(&second_path, second_settings.to_string()).unwrap();
|
||||
first.stop();
|
||||
drop(artifact);
|
||||
|
||||
write_source(
|
||||
&model,
|
||||
"type Article { title: Text, state: Text default \"draft\" }",
|
||||
)
|
||||
.unwrap();
|
||||
let artifact = build();
|
||||
settings["database"]["create"] = false.into();
|
||||
fs::write(&path, settings.to_string()).unwrap();
|
||||
let reserved = std::net::TcpListener::bind(("127.0.0.1", port)).unwrap();
|
||||
let rejected = Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&path)
|
||||
.arg("api")
|
||||
.output()
|
||||
.unwrap();
|
||||
drop(reserved);
|
||||
assert!(!rejected.status.success());
|
||||
let error = String::from_utf8_lossy(&rejected.stderr);
|
||||
assert!(error.contains("schema is outdated or changed"), "{error}");
|
||||
|
||||
settings["database"]["create"] = true.into();
|
||||
fs::write(&path, settings.to_string()).unwrap();
|
||||
let (first, second) = std::thread::scope(|scope| {
|
||||
let first = scope.spawn(|| Server::start(&artifact.binary, &path, port));
|
||||
let second = scope.spawn(|| Server::start(&artifact.binary, &second_path, second_port));
|
||||
(first.join().unwrap(), second.join().unwrap())
|
||||
});
|
||||
for server in [first, second] {
|
||||
let (status, updated) =
|
||||
server.call("GET", "/demo/article/front/main/get?article_id=1", "", "");
|
||||
assert_eq!(status, 200, "{updated}");
|
||||
assert_eq!(updated["data"]["id"], original["data"]["id"]);
|
||||
assert_eq!(
|
||||
updated["data"]["created_at"],
|
||||
original["data"]["created_at"]
|
||||
);
|
||||
assert_eq!(updated["data"]["title"], "original");
|
||||
assert_eq!(updated["data"]["state"], "draft");
|
||||
server.stop();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn http_startup_prepares_declared_models_without_database_calls() {
|
||||
use crate::api::{Server, config};
|
||||
let root = project("declared-model-startup", "hello() (out: Int) { out = 42 }");
|
||||
let api = root.join("module/demo/article/api/front");
|
||||
fs::create_dir_all(&api).unwrap();
|
||||
fs::write(api.join("main.dever"), "public get hello = app.hello").unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
let (path, port, mut settings) = config(&root);
|
||||
settings["database"] =
|
||||
serde_json::json!({"create":true,"default":{"type":"sqlite","path":"data/model.db"}});
|
||||
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);
|
||||
assert!(root.join("data/model.db").is_file());
|
||||
let (status, value) = server.call("GET", "/demo/article/front/main/hello", "", "");
|
||||
assert_eq!(status, 200, "{value}");
|
||||
assert_eq!(value["data"], 42);
|
||||
server.stop();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn front_startup_prepares_declared_models() {
|
||||
use crate::api::{Server, config};
|
||||
let root = project("front-model-startup", "hello() (out: Int) { out = 42 }");
|
||||
let front = root.join("module/demo/front/src");
|
||||
for directory in [&front, &root.join("config"), &root.join("data")] {
|
||||
fs::create_dir_all(directory).unwrap();
|
||||
}
|
||||
fs::write(front.join("index.html"), "<h1>Dever</h1>").unwrap();
|
||||
let (path, port, mut settings) = config(&root);
|
||||
settings["sites"]["front"]["front"] = serde_json::json!({"component":"demo","path":"/"});
|
||||
settings["database"] =
|
||||
serde_json::json!({"create":true,"default":{"type":"sqlite","path":"data/model.db"}});
|
||||
fs::write(&path, settings.to_string()).unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
Server::start(&artifact.binary, &path, port).stop();
|
||||
|
||||
settings["database"]["create"] = false.into();
|
||||
fs::write(&path, settings.to_string()).unwrap();
|
||||
let server = Server::start(&artifact.binary, &path, port);
|
||||
let (status, body, _) = server.raw_response("GET", "/", "", "");
|
||||
assert_eq!(status, 200, "{body}");
|
||||
assert_eq!(body, "<h1>Dever</h1>");
|
||||
server.stop();
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
use super::*;
|
||||
use dever::compiler::model::{Shape, Type};
|
||||
mod auth;
|
||||
mod bindings;
|
||||
mod constraints;
|
||||
mod crud;
|
||||
mod lifecycle;
|
||||
mod query;
|
||||
mod scalars;
|
||||
mod transaction;
|
||||
mod writes;
|
||||
|
||||
fn project(name: &str, app: &str) -> PathBuf {
|
||||
let root = directory(name);
|
||||
for (domain, model) in [
|
||||
("article", "type Article { title: Text }"),
|
||||
("user", "type User { name: Text }"),
|
||||
] {
|
||||
let path = root.join(format!("module/demo/{domain}"));
|
||||
fs::create_dir_all(&path).unwrap();
|
||||
write_source(path.join("data/main.dever"), model).unwrap();
|
||||
}
|
||||
write_source(root.join("module/demo/article/app/main.dever"), app).unwrap();
|
||||
root
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_ids_and_generated_fields_execute_through_the_real_wire_boundary() {
|
||||
let root = project(
|
||||
"model-id-native",
|
||||
"echo(article: data.Article) (out: data.Article) { out = article }\nkey(article_id: data.id) (out: Text) { out = dever.id.toText(article_id) }\nflow taskKey(article_id: data.id) (out: Text) { out = parallel(dever.id.toText(article_id)) }",
|
||||
);
|
||||
fs::write(
|
||||
root.join("module/demo/article/api.dever"),
|
||||
"cmd echo = app.echo\ncmd key = app.key\ncmd taskKey = app.taskKey",
|
||||
)
|
||||
.unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let article = program
|
||||
.definitions
|
||||
.iter()
|
||||
.find(|definition| definition.name == "demo.article.data.Article")
|
||||
.unwrap();
|
||||
let Shape::Record(fields) = &article.shape else {
|
||||
panic!("Model record")
|
||||
};
|
||||
assert_eq!(
|
||||
fields
|
||||
.iter()
|
||||
.map(|field| field.name.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
["id", "created_at", "title"]
|
||||
);
|
||||
assert!(matches!(fields[0].kind, Type::ModelId(_)));
|
||||
let files = emit::emit(&program, &ownership::analyze(&program), &loaded.sources);
|
||||
let app = &files["module/d_4_demo_7_article_3_app.rs"].text;
|
||||
assert!(!app.contains("clone"), "{app}");
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
for (cmd, id) in [
|
||||
("demo.article.key", 1),
|
||||
("demo.article.key", i64::MAX),
|
||||
("demo.article.taskKey", i64::MAX),
|
||||
] {
|
||||
let output = success(
|
||||
Command::new(&artifact.binary)
|
||||
.args([cmd, &serde_json::json!({"article_id":id}).to_string()])
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(&output).unwrap()["data"],
|
||||
id.to_string()
|
||||
);
|
||||
}
|
||||
let input =
|
||||
serde_json::json!({"article":{"id":7,"created_at":"2026-11-12T12:00:00Z","title":"文章"}});
|
||||
let output = success(
|
||||
Command::new(&artifact.binary)
|
||||
.args(["demo.article.echo", &input.to_string()])
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
let output: serde_json::Value = serde_json::from_str(&output).unwrap();
|
||||
assert_eq!(output["data"], input["article"]);
|
||||
for id in [
|
||||
serde_json::json!(0),
|
||||
serde_json::json!(-1),
|
||||
serde_json::json!("7"),
|
||||
serde_json::json!(7.5),
|
||||
] {
|
||||
let mut input = input.clone();
|
||||
input["article"]["id"] = id;
|
||||
let output = Command::new(&artifact.binary)
|
||||
.args(["demo.article.echo", &input.to_string()])
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(!output.status.success(), "invalid Model ID accepted");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_ids_are_nominal_and_model_topics_keep_separate_identity() {
|
||||
let root = project(
|
||||
"model-id-check",
|
||||
"same(left: data.id, right: data.id) (out: Bool) { out = left == right }",
|
||||
);
|
||||
let topic = root.join("module/demo/article/data");
|
||||
fs::create_dir_all(&topic).unwrap();
|
||||
fs::write(
|
||||
topic.join("revision.dever"),
|
||||
"type Revision { article_id: data.id }",
|
||||
)
|
||||
.unwrap();
|
||||
write_source(root.join("module/demo/article/app/main.dever"), "same(left: data.id, right: data.id) (out: Bool) { out = left == right }\ncopy(value: data.revision.id) (out: data.revision.id) { out = value }\npage(value: data.Page) (out: data.Page) { out = value }").unwrap();
|
||||
analyze(&root);
|
||||
for app in [
|
||||
"wrong(value: data.id) (out: demo.user.data.id) { out = value }",
|
||||
"wrong(value: data.id) (out: data.revision.id) { out = value }",
|
||||
"wrong(value: Int) (out: data.id) { out = value }",
|
||||
"wrong() (out: data.id) { out = 1 }",
|
||||
"wrong(value: data.id?) (out: Text) { out = dever.id.toText(value) }",
|
||||
"wrong(value: Int) (out: Text) { out = dever.id.toText(value) }",
|
||||
] {
|
||||
write_source(root.join("module/demo/article/app/main.dever"), app).unwrap();
|
||||
let project = Project::load(&root).unwrap();
|
||||
assert!(
|
||||
program::check(&project.declarations, &project.modules).is_err(),
|
||||
"{app}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_generated_fields_and_role_boundaries_cannot_be_overridden() {
|
||||
let root = project(
|
||||
"model-generated-check",
|
||||
"read(value: data.Article) (out: Text) { out = value.title }",
|
||||
);
|
||||
for model in [
|
||||
"type Article { id: Int }",
|
||||
"type Article { created_at: DateTime }",
|
||||
"type Article { title: Text }\ntype Page { total: Int }",
|
||||
] {
|
||||
write_source(root.join("module/demo/article/data/main.dever"), model).unwrap();
|
||||
let project = Project::load(&root).unwrap();
|
||||
assert!(
|
||||
program::check(&project.declarations, &project.modules).is_err(),
|
||||
"{model}"
|
||||
);
|
||||
}
|
||||
write_source(
|
||||
root.join("module/demo/article/data/main.dever"),
|
||||
"type Article { title: Text }",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("module/demo/article/domain.dever"),
|
||||
"copy(value: data.id) (out: data.id) { out = value }",
|
||||
)
|
||||
.unwrap();
|
||||
let project = Project::load(&root).unwrap();
|
||||
assert!(program::check(&project.declarations, &project.modules).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nominal_id_references_participate_in_domain_cycle_checks() {
|
||||
let root = project(
|
||||
"model-id-domain-cycle",
|
||||
"copy(value: demo.user.data.id) (out: demo.user.data.id) { out = value }",
|
||||
);
|
||||
write_source(
|
||||
root.join("module/demo/user/app/main.dever"),
|
||||
"copy(value: demo.article.data.id) (out: demo.article.data.id) { out = value }",
|
||||
)
|
||||
.unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
let error = program::check(&loaded.declarations, &loaded.modules)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert!(error.message.contains("cyclic domain"), "{error:?}");
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
use super::*;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
#[test]
|
||||
fn sqlite_model_filters_apply_to_pages_cursors_and_writes() {
|
||||
filters(
|
||||
"sqlite-model-filters",
|
||||
json!({"type":"sqlite","path":"data/article.db"}),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires an isolated PostgreSQL database; run test/postgres.py"]
|
||||
fn postgres_model_filters_apply_to_pages_cursors_and_writes() {
|
||||
let url = std::env::var("DEVER_TEST_POSTGRES").unwrap();
|
||||
filters(
|
||||
"postgres-model-filters",
|
||||
json!({"type":"postgres","url":url,"tls":"disabled"}),
|
||||
);
|
||||
}
|
||||
|
||||
fn filters(name: &str, database: Value) {
|
||||
let sqlite = database["type"] == "sqlite";
|
||||
let root = directory(name);
|
||||
let domain = root.join("module/demo/article");
|
||||
write_source(domain.join("flow/article.dv"), r#"
|
||||
flow add(title: Text, rank: Int, cost: Decimal) (out: data.Article) {
|
||||
out = data.create({title = title, rank = rank, cost = cost})
|
||||
}
|
||||
flow required(rank_value: Int) (out: data.Article) {
|
||||
out = data.get(rank == rank_value)
|
||||
}
|
||||
flow earliest(rank_value: Int) (out: data.Article) {
|
||||
out = data.get(rank == rank_value, order = id.asc)
|
||||
}
|
||||
flow page(prefix: Text, suffix: Text, minimum: Decimal, maximum: Decimal) (out: data.Page) {
|
||||
out = data.page(in(rank, [1, 2]) and between(cost, minimum, maximum) and startsWith(title, prefix) and endsWith(title, suffix) and not (title.contains("跳过") or note != null), order = cost.asc, size = 1)
|
||||
}
|
||||
flow scoped(store: Int, sku: Text, name: Text, take: Int) (out: List<data.Article>) {
|
||||
out = data.list(rank == store and (title == sku or title == name), order = id.asc, limit = take)
|
||||
}
|
||||
flow optional(term: Text?, rank_value: Int?, note_value: Text?) (out: Int) {
|
||||
out = data.count(ifSet(title.contains(term)) and ifSet(rank == rank_value) and ifSet(note == note_value))
|
||||
}
|
||||
flow grouped(term: Text?, n: Int?) (disj: Int, nested: Int, neg: Int, root: Int, neq: Int, plain: Int) {
|
||||
disj = data.count(rank == 3 or ifSet(title == term))
|
||||
nested = data.count(rank == 3 or (ifSet(rank == n) and ifSet(title == term)))
|
||||
neg = data.count(not (ifSet(title == term)))
|
||||
root = data.count(ifSet(rank == n) or ifSet(title == term))
|
||||
neq = data.count(ifSet(note != term))
|
||||
plain = data.count(note != term)
|
||||
}
|
||||
flow change(term: Text?) (out: Int) {
|
||||
out = data.update({where = rank == 3 or ifSet(title == term)}, {note = "selected"})
|
||||
}
|
||||
flow optionalChange(term: Text?, n: Int?) (out: Int) {
|
||||
out = data.update({where = ifSet(rank == n) or ifSet(title == term)}, {note = "optional"})
|
||||
}
|
||||
flow optionalDelete(n: Int?) (out: Int) {
|
||||
out = data.delete({where = not (ifSet(rank != n))})
|
||||
}
|
||||
flow scan(after: data.Article?, prefix: Text, suffix: Text) (out: data.Cursor) {
|
||||
out = data.cursor(startsWith(title, prefix) and endsWith(title, suffix) and not (rank == 3), after = after, order = cost.asc, size = 1)
|
||||
}
|
||||
flow mark(prefix: Text, suffix: Text, cost: Decimal) (out: Int) {
|
||||
out = data.update({where = in(cost, [cost]) and startsWith(title, prefix) and endsWith(title, suffix)}, {note = "marked"})
|
||||
}
|
||||
flow count(suffix: Text) (out: Int) {
|
||||
out = data.count(endsWith(title, suffix))
|
||||
}
|
||||
"#).unwrap();
|
||||
write_source(
|
||||
domain.join("data/article.dv"),
|
||||
"type Article {title: Text raw,rank: Int,cost: Decimal(20,2),note: Text?}",
|
||||
)
|
||||
.unwrap();
|
||||
write_source(domain.join("api/article.dv"), "cmd add = app.add\ncmd required = app.required\ncmd earliest = app.earliest\ncmd page = app.page\ncmd scan = app.scan\ncmd mark = app.mark\ncmd count = app.count\ncmd optional = app.optional\ncmd scoped = app.scoped\ncmd grouped = app.grouped\ncmd change = app.change\ncmd optionalChange = app.optionalChange\ncmd optionalDelete = app.optionalDelete").unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
fs::create_dir(root.join("data")).unwrap();
|
||||
let config = root.join("config/setting.json");
|
||||
fs::write(
|
||||
&config,
|
||||
json!({"database":{"default":database}}).to_string(),
|
||||
)
|
||||
.unwrap();
|
||||
let (project, program) = analyze(&root);
|
||||
let artifact = build::build(&project, &program, "main", Profile::Dev, None).unwrap();
|
||||
let command = || {
|
||||
let mut command = Command::new(&artifact.binary);
|
||||
command.arg("--config").arg(&config);
|
||||
command
|
||||
};
|
||||
success(command().arg("migrate").output().unwrap());
|
||||
let call = |name: &str, args: Value| -> Value {
|
||||
let text = success(
|
||||
command()
|
||||
.args([&format!("demo.article.{name}"), &args.to_string()])
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
serde_json::from_str::<Value>(&text).unwrap()["data"].clone()
|
||||
};
|
||||
let prefix = "边%a_";
|
||||
let suffix = "_尾%";
|
||||
let low = "9007199254740992.01";
|
||||
let high = "9007199254740992.02";
|
||||
for (title, rank, cost) in [
|
||||
("边%a_x_尾%", 1, low),
|
||||
("边%a_y_尾%", 2, high),
|
||||
("边%a_跳过_尾%", 2, high),
|
||||
("边%a_z_尾%", 3, high),
|
||||
("边%a_z_尾%", 2, "9007199254740992.03"),
|
||||
("边%a_wrong尾%", 1, low),
|
||||
("边%Ax_尾%", 1, low),
|
||||
] {
|
||||
call("add", json!({"title":title,"rank":rank,"cost":cost}));
|
||||
}
|
||||
assert_eq!(
|
||||
call("required", json!({"rank_value": 2}))["title"],
|
||||
"边%a_z_尾%"
|
||||
);
|
||||
assert_eq!(
|
||||
call("earliest", json!({"rank_value": 2}))["title"],
|
||||
"边%a_y_尾%"
|
||||
);
|
||||
let scoped =
|
||||
|store, take| json!({"store":store,"sku":"边%a_y_尾%","name":"边%a_z_尾%","take":take});
|
||||
let found = call("scoped", scoped(2, 10));
|
||||
let found = found.as_array().unwrap();
|
||||
assert_eq!(found.len(), 2);
|
||||
assert!(found.iter().all(|row| row["rank"] == 2));
|
||||
assert_eq!(call("scoped", scoped(2, 1)), json!([found[0]]));
|
||||
assert_eq!(call("scoped", scoped(99, 10)), json!([]));
|
||||
for take in [0, -1, i64::MAX] {
|
||||
let invalid = command()
|
||||
.args(["demo.article.scoped", &scoped(2, take).to_string()])
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(!invalid.status.success());
|
||||
assert!(String::from_utf8_lossy(&invalid.stderr).contains("InvalidData"));
|
||||
}
|
||||
let miss = command()
|
||||
.args(["demo.article.required", r#"{"rank_value":99}"#])
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(!miss.status.success());
|
||||
assert!(String::from_utf8_lossy(&miss.stderr).contains("NotFound"));
|
||||
let args = json!({"prefix":prefix,"suffix":suffix,"minimum":low,"maximum":high});
|
||||
assert_eq!(call("optional", json!({})), 7);
|
||||
assert_eq!(call("optional", json!({"term":"%a_", "rank_value":2})), 3);
|
||||
assert_eq!(call("optional", json!({"note_value":"absent"})), 0);
|
||||
let page = call("page", args.clone());
|
||||
assert_eq!(page["total"], 2);
|
||||
assert_eq!(page["items"][0]["title"], "边%a_x_尾%");
|
||||
let first = call(
|
||||
"scan",
|
||||
json!({"after":null,"prefix":prefix,"suffix":suffix}),
|
||||
);
|
||||
assert_eq!(first["items"][0]["title"], "边%a_x_尾%");
|
||||
assert_eq!(first["has_more"], true);
|
||||
let second = call(
|
||||
"scan",
|
||||
json!({"after":first["next"],"prefix":prefix,"suffix":suffix}),
|
||||
);
|
||||
assert_eq!(second["items"][0]["cost"], high);
|
||||
assert_eq!(
|
||||
call("mark", json!({"prefix":prefix,"suffix":suffix,"cost":low})),
|
||||
1
|
||||
);
|
||||
assert_eq!(call("page", args)["total"], 1);
|
||||
assert_eq!(call("count", json!({"suffix":""})), 7);
|
||||
assert_eq!(call("count", json!({"suffix":"' OR 1=1 --"})), 0);
|
||||
if sqlite {
|
||||
for title in ["边%a_z_尾%\0后续", "边%a_z\0_尾%"] {
|
||||
call("add", json!({"title":title,"rank":1,"cost":low}));
|
||||
}
|
||||
assert_eq!(call("count", json!({"suffix":suffix})), 7);
|
||||
assert_eq!(call("count", json!({"suffix":"\0_尾%"})), 1);
|
||||
}
|
||||
let total = if sqlite { 9 } else { 7 };
|
||||
for cmd in ["optionalChange", "optionalDelete"] {
|
||||
let invalid = command()
|
||||
.args([&format!("demo.article.{cmd}"), "{}"])
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(!invalid.status.success());
|
||||
assert!(String::from_utf8_lossy(&invalid.stderr).contains("InvalidData"));
|
||||
}
|
||||
assert_eq!(call("optional", json!({"note_value":"optional"})), 0);
|
||||
let empty = call("grouped", json!({}));
|
||||
assert_eq!(empty["disj"], 1);
|
||||
assert_eq!(empty["nested"], 1);
|
||||
assert_eq!(empty["neg"], total);
|
||||
assert_eq!(empty["root"], total);
|
||||
assert_eq!(call("change", json!({})), 1);
|
||||
let selected = call("grouped", json!({"term":"selected"}));
|
||||
assert_eq!(selected["neq"], total - 1);
|
||||
assert_eq!(selected["neq"], selected["plain"]);
|
||||
assert_eq!(call("grouped", json!({"n":2}))["nested"], 4);
|
||||
assert_eq!(call("optionalChange", json!({"n":3})), 1);
|
||||
assert_eq!(call("optionalDelete", json!({"n":3})), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_filters_reject_invalid_fields_types_and_lists() {
|
||||
let root = directory("invalid-model-filters");
|
||||
let domain = root.join("module/demo/article");
|
||||
write_source(
|
||||
domain.join("data/article.dv"),
|
||||
"type Article { title: Text, rank: Int }",
|
||||
)
|
||||
.unwrap();
|
||||
let path = domain.join("flow/article.dv");
|
||||
for condition in [
|
||||
"in(title, [])",
|
||||
"in(title, [1])",
|
||||
"in(rank, values)",
|
||||
"between(title, 1, 2)",
|
||||
"startsWith(id, \"a\")",
|
||||
"endsWith(title, null)",
|
||||
"not (missing == \"a\")",
|
||||
] {
|
||||
write_source(
|
||||
&path,
|
||||
format!(
|
||||
"flow scan(values: List<Text>) (out: Int) {{\n out = data.count({condition})\n}}"
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
let project = Project::load(&root).unwrap();
|
||||
assert!(project.diagnostics.is_empty(), "{condition}");
|
||||
assert_eq!(
|
||||
program::check(&project.declarations, &project.modules)
|
||||
.err()
|
||||
.unwrap()
|
||||
.code,
|
||||
"C005",
|
||||
"{condition}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
use super::*;
|
||||
mod filters;
|
||||
mod native;
|
||||
mod postgres;
|
||||
mod relation;
|
||||
mod stream;
|
||||
|
||||
#[test]
|
||||
fn cursor_reads_stable_pages_without_count_and_preserves_exact_decimal_order() {
|
||||
let root = project(
|
||||
"model-cursor-native",
|
||||
r#"
|
||||
flow create(title: Text, rank: Int, cost: Decimal) (out: data.Article)
|
||||
| step | kind | do |
|
||||
| out | data | data.create({title = title, rank = rank, cost = cost}) |
|
||||
flow page(after: data.Article?, size: Int, keyword: Text) (out: data.Cursor)
|
||||
| step | kind | do |
|
||||
| out | data | data.cursor(title.contains(keyword), order = [rank.asc, cost.desc], after = after, size = size) |
|
||||
flow newest(after: data.Article?, size: Int) (out: data.Cursor)
|
||||
| step | kind | do |
|
||||
| out | data | data.cursor(after = after, size = size) |
|
||||
flow remove(article_id: data.id) (out: Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.delete(article_id) |
|
||||
"#,
|
||||
);
|
||||
write_source(
|
||||
root.join("module/demo/article/data/main.dever"),
|
||||
"type Article { title: Text, rank: Int, cost: Decimal(20,2), note: Text? }",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(root.join("module/demo/article/api.dever"), "cmd create = app.create\ncmd page = app.page\ncmd newest = app.newest\ncmd remove = app.remove").unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
let config = root.join("config/setting.json");
|
||||
fs::write(
|
||||
&config,
|
||||
r#"{"database":{"default":{"type":"sqlite","path":"data/cursor.db"}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let generated = emit::emit(&program, &ownership::analyze(&program), &loaded.sources);
|
||||
let app = &generated["module/d_4_demo_7_article_3_app.rs"].text;
|
||||
assert!(!app.contains("COUNT("));
|
||||
assert!(!app.contains("OFFSET"));
|
||||
assert!(
|
||||
!app.contains("(NOT "),
|
||||
"cursor SQL must seek without an optional-cursor OR flag"
|
||||
);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
let call = |name: &str, input: serde_json::Value| {
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.args([name, &input.to_string()])
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
success(
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.arg("migrate")
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
let data = |name: &str, input| {
|
||||
serde_json::from_str::<serde_json::Value>(&success(call(name, input))).unwrap()["data"]
|
||||
.clone()
|
||||
};
|
||||
let empty = data(
|
||||
"demo.article.page",
|
||||
serde_json::json!({"after":null,"size":2,"keyword":"keep"}),
|
||||
);
|
||||
assert_eq!(
|
||||
empty,
|
||||
serde_json::json!({"items":[],"next":null,"has_more":false})
|
||||
);
|
||||
let mut rows = Vec::new();
|
||||
for (title, rank, cost) in [
|
||||
("keep A", 1, "9007199254740992.01"),
|
||||
("keep B", 1, "9007199254740992.02"),
|
||||
("keep C", 1, "9007199254740992.02"),
|
||||
("keep D", 2, "1.00"),
|
||||
("skip", 0, "2.00"),
|
||||
] {
|
||||
rows.push(data(
|
||||
"demo.article.create",
|
||||
serde_json::json!({"title":title,"rank":rank,"cost":cost}),
|
||||
));
|
||||
}
|
||||
let first = data(
|
||||
"demo.article.page",
|
||||
serde_json::json!({"after":null,"size":2,"keyword":"keep"}),
|
||||
);
|
||||
assert_eq!(first["items"], serde_json::json!([rows[2], rows[1]]));
|
||||
assert_eq!(first["has_more"], true);
|
||||
assert_eq!(first["next"], rows[1]);
|
||||
// 游标值携带排序键,上一页末记录删除后仍能继续,不重新查询该记录。
|
||||
data(
|
||||
"demo.article.remove",
|
||||
serde_json::json!({"article_id":rows[1]["id"]}),
|
||||
);
|
||||
let second = data(
|
||||
"demo.article.page",
|
||||
serde_json::json!({"after":first["next"],"size":2,"keyword":"keep"}),
|
||||
);
|
||||
assert_eq!(second["items"], serde_json::json!([rows[0], rows[3]]));
|
||||
assert_eq!(second["has_more"], false);
|
||||
assert!(second["next"].is_null());
|
||||
let newest = data(
|
||||
"demo.article.newest",
|
||||
serde_json::json!({"after":null,"size":1}),
|
||||
);
|
||||
assert_eq!(newest["items"], serde_json::json!([rows[4]]));
|
||||
for size in [0, -1, i64::MAX] {
|
||||
let output = call(
|
||||
"demo.article.newest",
|
||||
serde_json::json!({"after":null,"size":size}),
|
||||
);
|
||||
assert!(!output.status.success());
|
||||
assert!(String::from_utf8_lossy(&output.stderr).contains("InvalidData"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cursor_rejects_nullable_keys_wrong_identity_and_unknown_options() {
|
||||
let root = project("model-cursor-errors", "");
|
||||
write_source(
|
||||
root.join("module/demo/article/data/main.dever"),
|
||||
"type Article { title: Text?, rank: Int }",
|
||||
)
|
||||
.unwrap();
|
||||
for query in [
|
||||
"order = [title.asc]",
|
||||
"order = [rank.asc, rank.desc]",
|
||||
"order = []",
|
||||
"order = [missing.asc]",
|
||||
"page = 1",
|
||||
"after = 1",
|
||||
"size = null",
|
||||
] {
|
||||
write_source(root.join("module/demo/article/app/main.dever"), format!("flow read() (out: data.Cursor)\n| step | kind | do |\n| out | data | data.cursor({query}) |\n")).unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(loaded.diagnostics.is_empty(), "{query}");
|
||||
assert!(
|
||||
program::check(&loaded.declarations, &loaded.modules).is_err(),
|
||||
"{query}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn named_sql_runs_typed_queries_and_keeps_real_result_failures() {
|
||||
let root = project(
|
||||
"named-sql-native",
|
||||
r#"
|
||||
type Title { title: Text }
|
||||
flow lookup(title: Text) (out: Title?)
|
||||
| step | kind | do |
|
||||
| out | data | data.lookup(title) |
|
||||
flow titles(limit: Int >= 1 and <= 10) (out: List<Title>)
|
||||
| step | kind | do |
|
||||
| out | data | data.titles(limit) |
|
||||
flow full() (out: data.Article)
|
||||
| step | kind | do |
|
||||
| out | data | data.full() |
|
||||
flow invalid() (out: Title)
|
||||
| step | kind | do |
|
||||
| out | data | data.invalid() |
|
||||
flow duplicate() (out: Title?)
|
||||
| step | kind | do |
|
||||
| out | data | data.duplicate() |
|
||||
flow invalidId() (out: data.Article)
|
||||
| step | kind | do |
|
||||
| out | data | data.invalidId() |
|
||||
"#,
|
||||
);
|
||||
write_source(
|
||||
root.join("module/demo/article/data/main.dever"),
|
||||
r#"
|
||||
type Article { title: Text(2,80) unique }
|
||||
seed { {title = "hello"}, {title = "雪' OR 1=1 --"} }
|
||||
sql lookup(title: Text) (row: app.Title?) {
|
||||
sqlite = "SELECT title FROM demo_article WHERE title=?1"
|
||||
postgres = "SELECT title FROM demo_article WHERE title=$1"
|
||||
}
|
||||
sql titles(limit: Int >= 1 and <= 10) (rows: List<app.Title>) {
|
||||
sqlite = "SELECT title FROM demo_article ORDER BY id LIMIT ?1"
|
||||
postgres = "SELECT title FROM demo_article ORDER BY id LIMIT $1"
|
||||
}
|
||||
sql full() (row: Article) {
|
||||
sqlite = "SELECT id,created_at,title FROM demo_article WHERE id=1"
|
||||
postgres = "SELECT id,created_at,title FROM demo_article WHERE id=1"
|
||||
}
|
||||
sql invalid() (row: app.Title) {
|
||||
sqlite = "SELECT 3 AS title"
|
||||
postgres = "SELECT 3::BIGINT AS title"
|
||||
}
|
||||
sql duplicate() (row: app.Title?) {
|
||||
sqlite = "SELECT title FROM demo_article"
|
||||
postgres = "SELECT title FROM demo_article"
|
||||
}
|
||||
sql invalidId() (row: Article) {
|
||||
sqlite = "SELECT 0 AS id, created_at, title FROM demo_article WHERE id=1"
|
||||
postgres = "SELECT 0::BIGINT AS id, created_at, title FROM demo_article WHERE id=1"
|
||||
}
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(root.join("module/demo/article/api.dever"), "cmd lookup = app.lookup\ncmd titles = app.titles\ncmd full = app.full\ncmd invalid = app.invalid\ncmd duplicate = app.duplicate\ncmd invalidId = app.invalidId").unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
let config = root.join("config/setting.json");
|
||||
fs::write(
|
||||
&config,
|
||||
r#"{"database":{"default":{"type":"sqlite","path":"data/model.db","max_page_size":2}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let index = dever::compiler::inspect::analyze(&loaded, None, 0, true).unwrap();
|
||||
let query = index
|
||||
.symbols
|
||||
.iter()
|
||||
.find(|s| s.name == "demo.article.data.lookup")
|
||||
.unwrap();
|
||||
assert_eq!(query.kind, "sql");
|
||||
assert!(
|
||||
index
|
||||
.calls
|
||||
.iter()
|
||||
.any(|edge| edge.callee == query.id && edge.kind == "sql")
|
||||
);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
let call = |name: &str, input: serde_json::Value| {
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.args([name, &input.to_string()])
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
success(
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.arg("migrate")
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
let value = |name: &str, input: serde_json::Value| {
|
||||
serde_json::from_str::<serde_json::Value>(&success(call(name, input))).unwrap()["data"]
|
||||
.clone()
|
||||
};
|
||||
assert_eq!(
|
||||
value(
|
||||
"demo.article.lookup",
|
||||
serde_json::json!({"title":"雪' OR 1=1 --"})
|
||||
)["title"],
|
||||
"雪' OR 1=1 --"
|
||||
);
|
||||
assert!(value("demo.article.lookup", serde_json::json!({"title":"absent"})).is_null());
|
||||
assert_eq!(
|
||||
value("demo.article.titles", serde_json::json!({"limit":2}))
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.len(),
|
||||
2
|
||||
);
|
||||
assert_eq!(value("demo.article.full", serde_json::json!({}))["id"], 1);
|
||||
for name in [
|
||||
"demo.article.invalid",
|
||||
"demo.article.duplicate",
|
||||
"demo.article.invalidId",
|
||||
] {
|
||||
assert!(
|
||||
!call(name, serde_json::json!({})).status.success(),
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn named_sql_checks_contracts_and_only_proves_direct_reads() {
|
||||
let root = project(
|
||||
"named-sql-contract",
|
||||
"type Title { title: Text }\nflow find() (out: List<Title>)\n| step | kind | do |\n| out | data | data.find() |\n",
|
||||
);
|
||||
let path = root.join("module/demo/article/data/main.dever");
|
||||
let source = |sql: &str| {
|
||||
format!(
|
||||
"type Article {{ title: Text }}\nsql find() (rows: List<app.Title>) {{ sqlite = {}, postgres = {} }}",
|
||||
serde_json::to_string(sql).unwrap(),
|
||||
serde_json::to_string(sql).unwrap()
|
||||
)
|
||||
};
|
||||
for name in ["notifyChange", "waitChange"] {
|
||||
write_source(
|
||||
&path,
|
||||
source("SELECT title FROM demo_article").replace("sql find", &format!("sql {name}")),
|
||||
)
|
||||
.unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
let error = program::check(&loaded.declarations, &loaded.modules)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert!(
|
||||
error.message.contains("reserved Model SQL operation"),
|
||||
"{error:?}"
|
||||
);
|
||||
}
|
||||
for (sql, readonly) in [
|
||||
("SELECT title FROM demo_article WHERE title='?1'", true),
|
||||
("SELECT upper(title) AS title FROM demo_article", false),
|
||||
(
|
||||
"SELECT a.title FROM demo_article AS a JOIN demo_user AS u ON u.id=a.id",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"WITH titles AS (SELECT title FROM demo_article) SELECT title FROM titles",
|
||||
false,
|
||||
),
|
||||
] {
|
||||
write_source(&path, source(sql)).unwrap();
|
||||
let (_, program) = analyze(&root);
|
||||
let function = program
|
||||
.functions
|
||||
.iter()
|
||||
.find(|f| f.signature.name == "demo.article.app.find")
|
||||
.unwrap();
|
||||
assert_eq!(!function.effects.database_write, readonly, "{sql}");
|
||||
}
|
||||
for sql in [
|
||||
"SELECT * FROM _dever_history",
|
||||
"SELECT title FROM demo_article; SELECT 1",
|
||||
"DELETE FROM demo_article",
|
||||
] {
|
||||
write_source(&path, source(sql)).unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(
|
||||
program::check(&loaded.declarations, &loaded.modules).is_err(),
|
||||
"{sql}"
|
||||
);
|
||||
}
|
||||
write_source(
|
||||
root.join("module/demo/user/data/main.dever"),
|
||||
"database archive\ntype User { name: Text }",
|
||||
)
|
||||
.unwrap();
|
||||
write_source(
|
||||
&path,
|
||||
source("SELECT a.title FROM demo_article AS a JOIN demo_user AS u ON a.id=u.id"),
|
||||
)
|
||||
.unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(
|
||||
program::check(&loaded.declarations, &loaded.modules)
|
||||
.err()
|
||||
.unwrap()
|
||||
.message
|
||||
.contains("database bindings")
|
||||
);
|
||||
write_source(
|
||||
&path,
|
||||
source("SELECT title FROM demo_article").replace("List<app.Title>", "Text"),
|
||||
)
|
||||
.unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(program::check(&loaded.declarations, &loaded.modules).is_err());
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
use super::*;
|
||||
use dever_runtime::{
|
||||
database::{Sql, config::Config},
|
||||
task,
|
||||
};
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires an isolated PostgreSQL database; run test/postgres.py"]
|
||||
fn postgres_generated_models_queries_transactions_and_migrations() {
|
||||
let url = std::env::var("DEVER_TEST_POSTGRES").expect("isolated PostgreSQL test connection");
|
||||
let root = project(
|
||||
"postgres-model-native",
|
||||
r#"
|
||||
type Title { title: Text }
|
||||
flow save(code: Text, title: Text, cost: Decimal) (out: data.Article)
|
||||
| step | kind | do |
|
||||
| out | data | data.upsert({code = code}, {title = title, cost = cost}, {title = title, cost = cost}) |
|
||||
flow page(after: data.Article?) (out: data.Cursor)
|
||||
| step | kind | do |
|
||||
| out | data | data.cursor(after = after, size = 1, order = cost.asc) |
|
||||
flow filtered(after: data.Article?, minimum: Decimal) (out: data.Cursor)
|
||||
| step | kind | do |
|
||||
| out | data | data.cursor(cost >= minimum, after = after, size = 1, order = cost.asc) |
|
||||
flow total() (out: Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.count() |
|
||||
flow exactPage(page: Int) (out: data.Page)
|
||||
| step | kind | do |
|
||||
| out | data | data.page(page = page, size = 1) |
|
||||
flow filteredTotal() (out: Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.count(code == "two") |
|
||||
flow remove(id: data.id) (out: Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.delete(id) |
|
||||
flow titles() (out: List<Title>)
|
||||
| step | kind | do |
|
||||
| out | data | data.titles() |
|
||||
flow rejected(accept: Bool) ()
|
||||
| step | kind | do |
|
||||
| - | data | data.create({code = "rollback", title = "new", cost = 2.50}) |
|
||||
| - | check | accept else Invalid |
|
||||
"#,
|
||||
);
|
||||
let model = root.join("module/demo/article/data/main.dever");
|
||||
let original = r#"
|
||||
type Article { code: Text unique, title: Text(2,50), cost: Decimal(20,2), live: Bool default true, obsolete: Text default "old" }
|
||||
sql titles() (rows: List<app.Title>) {
|
||||
sqlite = "SELECT title FROM demo_article ORDER BY id"
|
||||
postgres = "SELECT title FROM demo_article ORDER BY id"
|
||||
}
|
||||
"#;
|
||||
write_source(&model, original).unwrap();
|
||||
write_source(
|
||||
root.join("module/demo/user/data/main.dever"),
|
||||
"type User { name: Text unique }",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(root.join("module/demo/article/api.dever"),"cmd save = app.save\ncmd page = app.page\ncmd filtered = app.filtered\ncmd titles = app.titles\ncmd rejected = app.rejected\ncmd total = app.total\ncmd exactPage = app.exactPage\ncmd filteredTotal = app.filteredTotal\ncmd remove = app.remove").unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
let config = root.join("config/setting.json");
|
||||
let connection = |url: &str| serde_json::json!({"type":"postgres","url":url,"tls":"disabled","max_connections":2});
|
||||
let setting =
|
||||
|url: &str| serde_json::json!({"database":{"default":connection(url)}}).to_string();
|
||||
fs::write(&config, setting(&url)).unwrap();
|
||||
let build = || {
|
||||
let (loaded, program) = analyze(&root);
|
||||
build::build(&loaded, &program, "main", Profile::Dev, None).unwrap()
|
||||
};
|
||||
let migrate = |binary: &Path| {
|
||||
Command::new(binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.arg("migrate")
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
let call = |binary: &Path, name: &str, input: serde_json::Value| {
|
||||
Command::new(binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.args([name, &input.to_string()])
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
let value = |binary: &Path, name: &str, input: serde_json::Value| {
|
||||
serde_json::from_str::<serde_json::Value>(&success(call(binary,name,input))).unwrap()["data"].clone()
|
||||
};
|
||||
let artifact = build();
|
||||
success(migrate(&artifact.binary));
|
||||
success(migrate(&artifact.binary));
|
||||
let first = value(
|
||||
&artifact.binary,
|
||||
"demo.article.save",
|
||||
serde_json::json!({"code":"one","title":"first","cost":"9007199254740993.01"}),
|
||||
);
|
||||
assert_eq!(first["cost"], "9007199254740993.01");
|
||||
assert_eq!(first["live"], true);
|
||||
let updated = value(
|
||||
&artifact.binary,
|
||||
"demo.article.save",
|
||||
serde_json::json!({"code":"one","title":"updated","cost":"9007199254740993.01"}),
|
||||
);
|
||||
assert_eq!(updated["id"], first["id"]);
|
||||
value(
|
||||
&artifact.binary,
|
||||
"demo.article.save",
|
||||
serde_json::json!({"code":"two","title":"second","cost":"9007199254740993.02"}),
|
||||
);
|
||||
let page = value(
|
||||
&artifact.binary,
|
||||
"demo.article.page",
|
||||
serde_json::json!({"after":null}),
|
||||
);
|
||||
assert_eq!(page["items"][0]["title"], "updated");
|
||||
assert_eq!(page["has_more"], true);
|
||||
let last = value(
|
||||
&artifact.binary,
|
||||
"demo.article.page",
|
||||
serde_json::json!({"after":page["next"]}),
|
||||
);
|
||||
assert_eq!(last["items"][0]["title"], "second");
|
||||
assert_eq!(last["has_more"], false);
|
||||
for (after, minimum, expected) in [
|
||||
(serde_json::Value::Null, "9007199254740993.01", page.clone()),
|
||||
(page["next"].clone(), "9007199254740993.01", last.clone()),
|
||||
(serde_json::Value::Null, "9007199254740993.02", last.clone()),
|
||||
] {
|
||||
assert_eq!(
|
||||
value(
|
||||
&artifact.binary,
|
||||
"demo.article.filtered",
|
||||
serde_json::json!({"after":after,"minimum":minimum})
|
||||
),
|
||||
expected
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
!call(
|
||||
&artifact.binary,
|
||||
"demo.article.rejected",
|
||||
serde_json::json!({"accept":false})
|
||||
)
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
assert_eq!(
|
||||
value(
|
||||
&artifact.binary,
|
||||
"demo.article.titles",
|
||||
serde_json::json!({})
|
||||
)
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.len(),
|
||||
2
|
||||
);
|
||||
let total = |binary: &Path| value(binary, "demo.article.total", serde_json::json!({}));
|
||||
assert_eq!(total(&artifact.binary), 2);
|
||||
assert_eq!(
|
||||
value(
|
||||
&artifact.binary,
|
||||
"demo.article.filteredTotal",
|
||||
serde_json::json!({})
|
||||
),
|
||||
1
|
||||
);
|
||||
let beyond = value(
|
||||
&artifact.binary,
|
||||
"demo.article.exactPage",
|
||||
serde_json::json!({"page":3}),
|
||||
);
|
||||
assert_eq!(
|
||||
beyond,
|
||||
serde_json::json!({"items":[],"page":3,"size":1,"total":2,"pages":2})
|
||||
);
|
||||
drop(artifact);
|
||||
let changed = format!(
|
||||
"{}\n{}",
|
||||
original.replace(", obsolete: Text default \"old\"", ""),
|
||||
r#"
|
||||
migrate revise {
|
||||
before { sqlite = "UPDATE demo_article SET title = title || ?1", postgres = "UPDATE demo_article SET title = title || $1", parameters = ["!"] }
|
||||
drop obsolete
|
||||
after { sqlite = "UPDATE demo_article SET live=?1", postgres = "UPDATE demo_article SET live=$1", parameters = [false] }
|
||||
}
|
||||
"#
|
||||
);
|
||||
write_source(&model, &changed).unwrap();
|
||||
let artifact = build();
|
||||
success(migrate(&artifact.binary));
|
||||
success(migrate(&artifact.binary));
|
||||
let page = value(
|
||||
&artifact.binary,
|
||||
"demo.article.page",
|
||||
serde_json::json!({"after":null}),
|
||||
);
|
||||
assert_eq!(page["items"][0]["title"], "updated!");
|
||||
assert_eq!(page["items"][0]["live"], false);
|
||||
assert!(page["items"][0].get("obsolete").is_none());
|
||||
assert_eq!(total(&artifact.binary), 2);
|
||||
assert_eq!(
|
||||
value(
|
||||
&artifact.binary,
|
||||
"demo.article.remove",
|
||||
serde_json::json!({"id":first["id"]})
|
||||
),
|
||||
1
|
||||
);
|
||||
assert_eq!(total(&artifact.binary), 1);
|
||||
let database: Config = serde_json::from_value(connection(&url)).unwrap();
|
||||
task::run(true, 16, async |scope| {
|
||||
let database = database.open(&root, false).await?;
|
||||
let mut executor = database.acquire().await?;
|
||||
for sql in [
|
||||
"CREATE ROLE dever_page_viewer",
|
||||
"GRANT SELECT ON demo_article, _dever_model_count, _dever_history TO dever_page_viewer",
|
||||
"ALTER TABLE demo_article ENABLE ROW LEVEL SECURITY",
|
||||
"CREATE POLICY published_article ON demo_article FOR SELECT TO dever_page_viewer USING (code='one')",
|
||||
] {
|
||||
executor.execute(scope, Sql::same(sql), vec![]).await?;
|
||||
}
|
||||
Ok::<_, dever_runtime::database::Error>(())
|
||||
}).unwrap().unwrap();
|
||||
fs::write(
|
||||
&config,
|
||||
setting(&format!("{url} options='-c role=dever_page_viewer'")),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(total(&artifact.binary), 0);
|
||||
assert_eq!(
|
||||
value(
|
||||
&artifact.binary,
|
||||
"demo.article.exactPage",
|
||||
serde_json::json!({"page":1})
|
||||
)["total"],
|
||||
0
|
||||
);
|
||||
fs::write(&config, setting(&url)).unwrap();
|
||||
drop(artifact);
|
||||
write_source(
|
||||
&model,
|
||||
changed.replace("parameters = [false]", "parameters = [true]"),
|
||||
)
|
||||
.unwrap();
|
||||
let artifact = build();
|
||||
assert!(!migrate(&artifact.binary).status.success());
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn related_records_load_in_batches_on_one_sqlite_connection() {
|
||||
exercise(
|
||||
"model-relations",
|
||||
serde_json::json!({"type":"sqlite","path":"data/main.db","max_connections":1,"max_page_size":2}),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires an isolated PostgreSQL database; run test/postgres.py"]
|
||||
fn postgres_related_records_load_in_batches() {
|
||||
exercise(
|
||||
"model-relations-postgres",
|
||||
serde_json::json!({"type":"postgres","url":std::env::var("DEVER_TEST_POSTGRES").unwrap(),"tls":"disabled","max_connections":1,"max_page_size":2}),
|
||||
);
|
||||
}
|
||||
|
||||
fn exercise(name: &str, mut database: serde_json::Value) {
|
||||
let root = directory(name);
|
||||
let domain = root.join("module/demo/people");
|
||||
fs::create_dir_all(domain.join("data")).unwrap();
|
||||
for (name, source) in [
|
||||
(
|
||||
"organization",
|
||||
"type Organization {name:Text unique}\nseed {{name=\"Team\"}}",
|
||||
),
|
||||
(
|
||||
"user",
|
||||
"type User {name:Text unique,organization_id:data.organization.id?,manager_id:data.user.id?,extra:Json default \"{\\\"x\\\":1}\"}\nrelation posts = data.post.author_id\nseed {{name=\"Ada\",organization_id=1,manager_id=null},{name=\"Ben\",organization_id=null,manager_id=1}}",
|
||||
),
|
||||
(
|
||||
"post",
|
||||
"type Post {title:Text unique,author_id:data.user.id}\nseed {{title=\"first\",author_id=1},{title=\"second\",author_id=1},{title=\"third\",author_id=2}}",
|
||||
),
|
||||
] {
|
||||
fs::write(domain.join(format!("data/{name}.dever")), source).unwrap();
|
||||
}
|
||||
write_source(domain.join("app/main.dever"), r#"
|
||||
rule orgName(value:data.organization.Organization?) (out:Text)
|
||||
| value | out |
|
||||
| null | "none" |
|
||||
| other | value.name |
|
||||
rule organization(value:Related<data.organization.Organization?>) (out:Text)
|
||||
| value | out |
|
||||
| Unloaded | "unloaded" |
|
||||
| Loaded(row) | orgName(row) |
|
||||
rule posts(value:Related<List<data.post.Post>>) (out:Int)
|
||||
| value | out |
|
||||
| Unloaded | -1 |
|
||||
| Loaded(rows) | length(rows) |
|
||||
rule takePosts(value:Related<List<data.post.Post>>) (out:List<data.post.Post>)
|
||||
| value | out |
|
||||
| Unloaded | [] |
|
||||
| Loaded(rows) | rows |
|
||||
loop titles(rows:List<data.post.Post>) (out:List<Text>)
|
||||
| each row in rows | result |
|
||||
| out | list row.title |
|
||||
rule managerName(value:Related<data.user.User?>) (out:Text)
|
||||
| value | out |
|
||||
| Unloaded | "unloaded" |
|
||||
| Loaded(row) | optionalUser(row) |
|
||||
rule optionalUser(value:data.user.User?) (out:Text)
|
||||
| value | out |
|
||||
| null | "none" |
|
||||
| other | value.name+":"+organization(value.organization) |
|
||||
flow owned() (names:List<Text>, copies:List<Text>, manager:Text)
|
||||
| step | kind | do |
|
||||
| first | data | data.user.get(name=="Ada", with = [posts]) |
|
||||
| last | data | data.user.first(name=="Ben", with = [manager]) |
|
||||
| - | check | last != null else NotFound |
|
||||
| names | loop | titles(takePosts(first.posts)) |
|
||||
| copies | loop | titles(takePosts(first.posts)) |
|
||||
| manager | rule | managerName(last.manager) |
|
||||
show(value:data.user.User) (out:Text) {out=value.name+":"+organization(value.organization)+":"+int.toText(posts(value.posts))}
|
||||
loop labels(rows:List<data.user.User>) (out:List<Text>)
|
||||
| each row in rows | result |
|
||||
| out | list show(row) |
|
||||
flow plain() (out:List<Text>)
|
||||
| step | kind | do |
|
||||
| page | data | data.user.page(order = id.asc, size = 2) |
|
||||
| out | loop | labels(page.items) |
|
||||
flow users() (out:List<Text>)
|
||||
| step | kind | do |
|
||||
| rows | data | data.user.page(order = id.asc, size = 2, with = [organization,manager,posts]).items |
|
||||
| out | loop | labels(rows) |
|
||||
flow first() (out:Text)
|
||||
| step | kind | do |
|
||||
| user | data | data.user.first(order = id.asc, with = [organization,posts]) |
|
||||
| - | check | user != null else NotFound |
|
||||
| out | calc | show(user) |
|
||||
flow cursor() (out:List<Text>)
|
||||
| step | kind | do |
|
||||
| first | data | data.user.cursor(order = id.asc, size = 1, with = [organization,posts]) |
|
||||
| next | data | data.user.cursor(order = id.asc, size = 1, after = first.next, with = [organization,posts]) |
|
||||
| out | loop | labels(next.items) |
|
||||
flow empty() (out:List<Text>)
|
||||
| step | kind | do |
|
||||
| page | data | data.user.page(name=="missing", size = 2, with = [organization,posts]) |
|
||||
| out | loop | labels(page.items) |
|
||||
echo(value:data.user.User) (out:data.user.User) {out=value}
|
||||
decoded(value:data.user.User) (out:Text) {out=show(value)}
|
||||
flow plainRows() (out:data.user.Page)
|
||||
| step | kind | do |
|
||||
| out | data | data.user.page(order = id.asc, size = 2) |
|
||||
flow loadedRows() (out:data.user.Page)
|
||||
| step | kind | do |
|
||||
| out | data | data.user.page(order = id.asc, size = 2, with = [organization,manager,posts]) |
|
||||
flow post() (out:data.post.Post?)
|
||||
| step | kind | do |
|
||||
| out | data | data.post.first(title=="first", with = [author]) |
|
||||
"#).unwrap();
|
||||
fs::write(domain.join("api.dever"), "cmd plain=app.plain\ncmd users=app.users\ncmd first=app.first\ncmd cursor=app.cursor\ncmd empty=app.empty\ncmd owned=app.owned\ncmd echo=app.echo\ncmd decoded=app.decoded\ncmd plainRows=app.plainRows\ncmd loadedRows=app.loadedRows\ncmd post=app.post").unwrap();
|
||||
fs::create_dir_all(domain.join("api/front")).unwrap();
|
||||
fs::write(domain.join("api/front/wire.dever"), "public post echo=app.echo\npublic get plainRows=app.plainRows\npublic get loadedRows=app.loadedRows\npublic get post=app.post").unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
let (config, port, mut settings) = crate::api::config(&root);
|
||||
settings["database"] = serde_json::json!({"default":database});
|
||||
fs::write(&config, settings.to_string()).unwrap();
|
||||
let (project, program) = analyze(&root);
|
||||
let binary = build::build(&project, &program, "main", Profile::Dev, None).unwrap();
|
||||
success(
|
||||
Command::new(&binary.binary)
|
||||
.args(["--config", config.to_str().unwrap(), "migrate"])
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
let call = |name: &str| {
|
||||
Command::new(&binary.binary)
|
||||
.args([
|
||||
"--config",
|
||||
config.to_str().unwrap(),
|
||||
&format!("demo.people.{name}"),
|
||||
"{}",
|
||||
])
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
let data = |name: &str| {
|
||||
serde_json::from_str::<serde_json::Value>(&success(call(name))).unwrap()["data"].clone()
|
||||
};
|
||||
assert_eq!(
|
||||
data("plain"),
|
||||
serde_json::json!(["Ada:unloaded:-1", "Ben:unloaded:-1"])
|
||||
);
|
||||
assert_eq!(
|
||||
data("users"),
|
||||
serde_json::json!(["Ada:Team:2", "Ben:none:1"])
|
||||
);
|
||||
assert_eq!(data("first"), "Ada:Team:2");
|
||||
assert_eq!(data("cursor"), serde_json::json!(["Ben:none:1"]));
|
||||
assert_eq!(data("empty"), serde_json::json!([]));
|
||||
assert_eq!(
|
||||
data("owned"),
|
||||
serde_json::json!({"names":["second","first"],"copies":["second","first"],"manager":"Ada:unloaded"})
|
||||
);
|
||||
wire_contract(&binary.binary, &config, port, data);
|
||||
database["max_page_size"] = 1.into();
|
||||
fs::write(
|
||||
&config,
|
||||
serde_json::json!({"database":{"default":database}}).to_string(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!call("first").status.success());
|
||||
}
|
||||
|
||||
fn wire_contract(
|
||||
binary: &Path,
|
||||
config: &Path,
|
||||
port: u16,
|
||||
data: impl Fn(&str) -> serde_json::Value,
|
||||
) {
|
||||
let page = data("plainRows");
|
||||
assert_eq!(page, data("loadedRows"));
|
||||
let user = &page["items"][0];
|
||||
let keys = user
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.keys()
|
||||
.map(String::as_str)
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
keys,
|
||||
[
|
||||
"created_at",
|
||||
"extra",
|
||||
"id",
|
||||
"manager_id",
|
||||
"name",
|
||||
"organization_id"
|
||||
]
|
||||
);
|
||||
assert_eq!(user["extra"], serde_json::json!({"x":1}));
|
||||
assert!(page["items"][1]["organization_id"].is_null());
|
||||
let input = serde_json::json!({"value":user});
|
||||
let echo = |name: &str, value: &serde_json::Value| {
|
||||
Command::new(binary)
|
||||
.args([
|
||||
"--config",
|
||||
config.to_str().unwrap(),
|
||||
&format!("demo.people.{name}"),
|
||||
&value.to_string(),
|
||||
])
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(&success(echo("echo", &input))).unwrap()["data"],
|
||||
*user
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(&success(echo("decoded", &input))).unwrap()["data"],
|
||||
"Ada:unloaded:-1"
|
||||
);
|
||||
let server = crate::api::Server::start(binary, config, port);
|
||||
for name in ["plainRows", "loadedRows", "post"] {
|
||||
let (status, reply) =
|
||||
server.call("GET", &format!("/demo/people/front/wire/{name}"), "", "");
|
||||
assert_eq!(status, 200, "{reply}");
|
||||
assert_eq!(reply["data"], data(name));
|
||||
}
|
||||
let (status, reply) = server.call(
|
||||
"POST",
|
||||
"/demo/people/front/wire/echo",
|
||||
&input.to_string(),
|
||||
"Content-Type: application/json\r\n",
|
||||
);
|
||||
assert_eq!(status, 200, "{reply}");
|
||||
assert_eq!(reply["data"], *user);
|
||||
for relation in ["organization", "manager", "posts"] {
|
||||
for state in [
|
||||
serde_json::json!("Unloaded"),
|
||||
serde_json::json!({"Loaded":null}),
|
||||
] {
|
||||
let mut input = input.clone();
|
||||
input["value"][relation] = state;
|
||||
assert!(!echo("echo", &input).status.success());
|
||||
assert_eq!(
|
||||
server
|
||||
.call(
|
||||
"POST",
|
||||
"/demo/people/front/wire/echo",
|
||||
&input.to_string(),
|
||||
"Content-Type: application/json\r\n"
|
||||
)
|
||||
.0,
|
||||
400
|
||||
);
|
||||
}
|
||||
}
|
||||
server.stop();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relation_contract_rejects_invalid_declarations_queries_and_explicit_wire_relations() {
|
||||
let root = project(
|
||||
"model-relation-contract",
|
||||
"flow read() (out:Int)\n| step | kind | do |\n| out | data | data.count() |",
|
||||
);
|
||||
let article = root.join("module/demo/article/data/main.dever");
|
||||
let user = root.join("module/demo/user/data/main.dever");
|
||||
let app = root.join("module/demo/article/app/main.dever");
|
||||
let base = "type Article {title:Text, author_id:demo.user.data.id}";
|
||||
write_source(&article, base).unwrap();
|
||||
for query in [
|
||||
"data.page(with = [unknown])",
|
||||
"data.page(with = [author,author])",
|
||||
"data.page(with = [author.name])",
|
||||
"data.page(with = author)",
|
||||
"data.count(with = [author])",
|
||||
"data.list(page = 1)",
|
||||
"data.page(limit = 3)",
|
||||
"data.list(limit = 1, limit = 2)",
|
||||
"data.get()",
|
||||
"data.get(order = id.asc)",
|
||||
"data.get(with = [author])",
|
||||
"data.create({title=\"x\",author_id=1,author=Unloaded})",
|
||||
] {
|
||||
write_source(
|
||||
&app,
|
||||
format!("flow read() ()\n| step | kind | do |\n| - | data | {query} |"),
|
||||
)
|
||||
.unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(loaded.diagnostics.is_empty(), "{:?}", loaded.diagnostics);
|
||||
assert!(
|
||||
program::check(&loaded.declarations, &loaded.modules).is_err(),
|
||||
"accepted {query}"
|
||||
);
|
||||
}
|
||||
write_source(
|
||||
&app,
|
||||
"flow read() (out:data.Article?)\n| step | kind | do |\n| out | data | data.first() |",
|
||||
)
|
||||
.unwrap();
|
||||
for model in [
|
||||
"type Article {title:Text,author:Text,author_id:demo.user.data.id}",
|
||||
"type Article {title:Text}\nrelation users = demo.user.data.name",
|
||||
"type Article {title:Text}\nrelation users = demo.user.data.missing",
|
||||
] {
|
||||
write_source(&article, model).unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(loaded.diagnostics.is_empty());
|
||||
assert!(
|
||||
program::check(&loaded.declarations, &loaded.modules).is_err(),
|
||||
"accepted {model}"
|
||||
);
|
||||
}
|
||||
write_source(&article, base).unwrap();
|
||||
write_source(&user, "database archive\ntype User {name:Text}").unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(program::check(&loaded.declarations, &loaded.modules).is_err());
|
||||
write_source(&user, "type User {name:Text}").unwrap();
|
||||
write_source(
|
||||
&app,
|
||||
"echo(value:Related<demo.user.data.User>) (out:Related<demo.user.data.User>) {out=value}",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("module/demo/article/api.dever"),
|
||||
"cmd echo=app.echo",
|
||||
)
|
||||
.unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
let error = program::check(&loaded.declarations, &loaded.modules)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert!(error.message.contains("relation"), "{error:?}");
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn model_streams_propagate_driver_errors_and_consume_rows_in_loops() {
|
||||
exercise(
|
||||
"model-stream",
|
||||
serde_json::json!({"type":"sqlite","path":"data/model.db","max_connections":1}),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires an isolated PostgreSQL database; run test/postgres.py"]
|
||||
fn postgres_model_streams() {
|
||||
exercise(
|
||||
"model-stream-postgres",
|
||||
serde_json::json!({"type":"postgres","url":std::env::var("DEVER_TEST_POSTGRES").unwrap(),"tls":"disabled","max_connections":1}),
|
||||
);
|
||||
}
|
||||
|
||||
fn exercise(name: &str, database: serde_json::Value) {
|
||||
let app = r#"
|
||||
flow rows(keyword: Text) (out: AsyncStream<data.Article>)
|
||||
| step | kind | do |
|
||||
| out | data | data.stream(title.contains(keyword), order = id.asc) |
|
||||
loop titles(rows: AsyncStream<data.Article>) (out: List<Text>)
|
||||
| each row in rows | result |
|
||||
| out | list row.title |
|
||||
loop first(rows: AsyncStream<data.Article>) (out: Text?)
|
||||
| each row in rows | result |
|
||||
| out | first row.title |
|
||||
loop parallelTitles(rows: AsyncStream<data.Article>) (out: List<Text>)
|
||||
| each row in rows parallel(2) | result |
|
||||
| out | list row.title |
|
||||
flow list(keyword: Text) (out: List<Text>)
|
||||
| step | kind | do |
|
||||
| rows | flow | rows(keyword) |
|
||||
| out | loop | titles(rows) |
|
||||
flow parallelList(keyword: Text) (out: List<Text>)
|
||||
| step | kind | do |
|
||||
| rows | flow | rows(keyword) |
|
||||
| out | loop | parallelTitles(rows) |
|
||||
flow firstThenCount(keyword: Text) (first: Text?, count: Int)
|
||||
| step | kind | do |
|
||||
| rows | flow | rows(keyword) |
|
||||
| first | loop | first(rows) |
|
||||
| count | data | data.count() |
|
||||
flow fromList(value: data.Article) (out: List<Text>)
|
||||
| step | kind | do |
|
||||
| rows | calc | stream([value]) |
|
||||
| out | loop | titles(rows) |
|
||||
"#;
|
||||
let root = project(name, app);
|
||||
write_source(
|
||||
root.join("module/demo/article/data/main.dever"),
|
||||
"type Article {title:Text unique}\nseed {{title=\"first\"},{title=\"second\"},{title=\"third\"}}",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(root.join("module/demo/article/api.dever"), "cmd list = app.list\ncmd parallelList = app.parallelList\ncmd firstThenCount = app.firstThenCount\ncmd fromList = app.fromList").unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
let config = root.join("config/setting.json");
|
||||
fs::write(
|
||||
&config,
|
||||
serde_json::json!({"database":{"default":database}}).to_string(),
|
||||
)
|
||||
.unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
let call = |name: &str, input: &str| {
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.args([name, input])
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
success(
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.arg("migrate")
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
for entry in ["list", "parallelList"] {
|
||||
let response: serde_json::Value = serde_json::from_str(&success(call(
|
||||
&format!("demo.article.{entry}"),
|
||||
r#"{"keyword":""}"#,
|
||||
)))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
response["data"],
|
||||
serde_json::json!(["first", "second", "third"])
|
||||
);
|
||||
}
|
||||
let response: serde_json::Value = serde_json::from_str(&success(call(
|
||||
"demo.article.firstThenCount",
|
||||
r#"{"keyword":""}"#,
|
||||
)))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
response["data"],
|
||||
serde_json::json!({"first":"first","count":3})
|
||||
);
|
||||
let response: serde_json::Value = serde_json::from_str(&success(call(
|
||||
"demo.article.list",
|
||||
r#"{"keyword":"missing"}"#,
|
||||
)))
|
||||
.unwrap();
|
||||
assert_eq!(response["data"], serde_json::json!([]));
|
||||
let response: serde_json::Value = serde_json::from_str(&success(call(
|
||||
"demo.article.fromList",
|
||||
r#"{"value":{"id":1,"created_at":"2026-11-12T00:00:00Z","title":"local"}}"#,
|
||||
)))
|
||||
.unwrap();
|
||||
assert_eq!(response["data"], serde_json::json!(["local"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stream_creation_and_consumption_are_rejected_in_transaction_flows() {
|
||||
let root = project(
|
||||
"model-stream-transaction",
|
||||
"transaction flow rows() (out: AsyncStream<data.Article>)\n| step | kind | do |\n| out | data | data.stream() |",
|
||||
);
|
||||
let project = Project::load(&root).unwrap();
|
||||
let error = program::check(&project.declarations, &project.modules)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(error.code, "C013");
|
||||
}
|
||||
@@ -0,0 +1,416 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn data_methods_apply_text_rules_by_column() {
|
||||
let root = directory("data-text-conditions");
|
||||
let domain = root.join("module/demo/article");
|
||||
write_source(domain.join("data/article.dv"), "type Article {title: Text(2,12) lower, code: Text? upper, label: Text, signature: Text raw}").unwrap();
|
||||
write_source(domain.join("flow/article.dv"), r#"
|
||||
flow probe(term: Text, code: Text?, missing: Text?) (stored: Text, hit: Bool, kept: Bool, optional: Bool, skipped: Bool, fragment: Bool, short: Bool, updated: Int, removed: Int) {
|
||||
row = data.create({title = term, code = code, label = " Label ", signature = " Raw "})
|
||||
stored = row.title
|
||||
hit = data.exists(title == term and code == code and label == " Label ")
|
||||
kept = data.exists(signature == " Raw " and signature != "Raw")
|
||||
optional = data.exists(ifSet(title == code))
|
||||
skipped = data.exists(ifSet(title == missing))
|
||||
fragment = data.exists(title.contains(" É "))
|
||||
short = data.exists(title == " ")
|
||||
terms = [term, "Other"]
|
||||
updated = data.update({where = in(title, terms)}, {code = missing})
|
||||
removed = data.delete({where = title == term and code == missing})
|
||||
}
|
||||
"#).unwrap();
|
||||
write_source(domain.join("api/article.dv"), "cmd probe = app.probe").unwrap();
|
||||
let config = root.join("config/setting.json");
|
||||
write_source(
|
||||
&config,
|
||||
r#"{"database":{"default":{"type":"sqlite","path":"data/probe.db"}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let binary = build::build(&loaded, &program, "main", Profile::Dev, None)
|
||||
.unwrap()
|
||||
.binary;
|
||||
let run = |args: &[&str]| {
|
||||
success(
|
||||
Command::new(&binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.args(args)
|
||||
.output()
|
||||
.unwrap(),
|
||||
)
|
||||
};
|
||||
run(&["migrate"]);
|
||||
let out: serde_json::Value = serde_json::from_str(&run(&[
|
||||
"demo.article.probe",
|
||||
r#"{"term":" Écho ","code":" éCHO ","missing":null}"#,
|
||||
]))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
out["data"],
|
||||
serde_json::json!({"stored":"écho","hit":true,"kept":true,"optional":true,"skipped":true,"fragment":false,"short":false,"updated":1,"removed":1})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn data_text_input_normalizes_before_the_function_body() {
|
||||
let root = project(
|
||||
"data-text-input",
|
||||
"flow checkName(account:data.title, password:Text) (name:Text, original:Text) { name = account\noriginal = password }",
|
||||
);
|
||||
write_source(
|
||||
root.join("module/demo/article/data/main.dever"),
|
||||
"type Article {title:Text(1,4) lower unique}",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("module/demo/article/api.dever"),
|
||||
"cmd account = app.checkName",
|
||||
)
|
||||
.unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
let call = |name: &str| {
|
||||
Command::new(&artifact.binary)
|
||||
.args([
|
||||
"demo.article.account",
|
||||
&serde_json::json!({"account":name,"password":" XyZ "}).to_string(),
|
||||
])
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
let value: serde_json::Value = serde_json::from_str(&success(call(" É雪 "))).unwrap();
|
||||
assert_eq!(
|
||||
value["data"],
|
||||
serde_json::json!({"name":"é雪","original":" XyZ "})
|
||||
);
|
||||
for invalid in [" ", "12345"] {
|
||||
let error = call(invalid);
|
||||
assert!(!error.status.success());
|
||||
assert!(
|
||||
String::from_utf8_lossy(&error.stdout).contains("Invalid")
|
||||
|| String::from_utf8_lossy(&error.stderr).contains("Invalid"),
|
||||
"{:?}",
|
||||
error
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_bytes_move_owned_buffers_and_preserve_shared_inputs() {
|
||||
bytes_storage(serde_json::json!({"type":"sqlite","path":"data/model.db"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires an isolated PostgreSQL database; run test/postgres.py"]
|
||||
fn postgres_model_bytes_preserve_owned_shared_and_optional_values() {
|
||||
bytes_storage(serde_json::json!({
|
||||
"type":"postgres","url":std::env::var("DEVER_TEST_POSTGRES").unwrap(),
|
||||
"tls":"disabled","max_connections":1
|
||||
}));
|
||||
}
|
||||
|
||||
fn bytes_storage(database: serde_json::Value) {
|
||||
let root = project(
|
||||
"model-bytes-storage",
|
||||
r#"
|
||||
flow save(text: Text) (out: Text)
|
||||
| step | kind | do |
|
||||
| content | calc | dever.bytes.fromText(text) |
|
||||
| row | data | data.create({content = content, optional = null}) |
|
||||
| out | calc | dever.bytes.toText(row.content) |
|
||||
flow copy(article_id: data.id) (out: Text, original: Text, optional: Text)
|
||||
| step | kind | do |
|
||||
| source | data | data.get(article_id) |
|
||||
| row | data | data.create({content = source.content, optional = source.content}) |
|
||||
| optional_content | calc | row.optional |
|
||||
| - | check | optional_content != null else NotFound |
|
||||
| out | calc | dever.bytes.toText(row.content) |
|
||||
| original | calc | dever.bytes.toText(source.content) |
|
||||
| optional | calc | dever.bytes.toText(optional_content) |
|
||||
"#,
|
||||
);
|
||||
write_source(
|
||||
root.join("module/demo/article/data/main.dever"),
|
||||
"type Article {content:Bytes(0,65536),optional:Bytes?}",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("module/demo/article/api.dever"),
|
||||
"cmd save = app.save\ncmd copy = app.copy",
|
||||
)
|
||||
.unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
let config = root.join("config/setting.json");
|
||||
fs::write(
|
||||
&config,
|
||||
serde_json::json!({"database":{"default":database}}).to_string(),
|
||||
)
|
||||
.unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let generated = emit::emit(&program, &ownership::analyze(&program), &loaded.sources);
|
||||
assert!(
|
||||
generated
|
||||
.values()
|
||||
.all(|file| !file.text.contains("value.to_vec()"))
|
||||
);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
let call = |arguments: &[&str]| {
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.args(arguments)
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
success(call(&["migrate"]));
|
||||
for text in ["".to_owned(), "雪🙂\0".repeat(4096)] {
|
||||
let input = serde_json::json!({"text":text}).to_string();
|
||||
let out: serde_json::Value =
|
||||
serde_json::from_str(&success(call(&["demo.article.save", &input]))).unwrap();
|
||||
assert_eq!(out["data"], text);
|
||||
}
|
||||
let copied: serde_json::Value = serde_json::from_str(&success(call(&[
|
||||
"demo.article.copy",
|
||||
r#"{"article_id":2}"#,
|
||||
])))
|
||||
.unwrap();
|
||||
for field in ["out", "original", "optional"] {
|
||||
assert_eq!(copied["data"][field], "雪🙂\0".repeat(4096));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_writes_use_proven_ranges_and_still_reject_unknown_invalid_values() {
|
||||
let root = project(
|
||||
"model-proven-ranges",
|
||||
r#"
|
||||
flow known(amount: Int >= 0 and <= 10, flag: Bool?, note: Text?) (out: data.Article)
|
||||
| step | kind | do |
|
||||
| out | data | data.create({amount = amount, flag = flag, note = note}) |
|
||||
flow copy(article_id: data.id) (out: data.Article)
|
||||
| step | kind | do |
|
||||
| row | data | data.get(article_id) |
|
||||
| out | data | data.create({amount = row.amount, flag = row.flag, note = row.note}) |
|
||||
flow unknown(amount: Int) (out: data.Article)
|
||||
| step | kind | do |
|
||||
| out | data | data.create({amount = amount}) |
|
||||
flow defaultAmount() (out: data.Article)
|
||||
| step | kind | do |
|
||||
| out | data | data.create({}) |
|
||||
flow count() (out: Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.count() |
|
||||
"#,
|
||||
);
|
||||
write_source(
|
||||
root.join("module/demo/article/data/main.dever"),
|
||||
"type Article { amount: Int >= 0 and <= 10 default 7, flag: Bool?, note: Text? raw }",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("module/demo/article/api.dever"),
|
||||
"cmd known = app.known\ncmd copy = app.copy\ncmd unknown = app.unknown\ncmd defaultAmount = app.defaultAmount\ncmd count = app.count",
|
||||
)
|
||||
.unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
let config = root.join("config/setting.json");
|
||||
fs::write(
|
||||
&config,
|
||||
r#"{"database":{"default":{"type":"sqlite","path":"data/model.db"}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let generated = emit::emit(&program, &ownership::analyze(&program), &loaded.sources);
|
||||
assert_eq!(
|
||||
generated
|
||||
.values()
|
||||
.map(|file| file
|
||||
.text
|
||||
.matches("Model field amount is out of range")
|
||||
.count())
|
||||
.sum::<usize>(),
|
||||
1,
|
||||
"only the unconstrained input needs a Model range check"
|
||||
);
|
||||
assert!(generated.values().all(|file| {
|
||||
!file
|
||||
.text
|
||||
.contains("value.map(|value| -> Result<_,dever_runtime::database::Error>")
|
||||
}));
|
||||
assert!(
|
||||
generated
|
||||
.values()
|
||||
.all(|file| !file.text.contains("text::TextMode::Raw"))
|
||||
);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
success(
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.arg("migrate")
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
let call = |name: &str, input: &str| {
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.args([&format!("demo.article.{name}"), input])
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
for (amount, flag, note) in [(0, None, None), (10, Some(true), Some(" 原文 "))] {
|
||||
let input = serde_json::json!({"amount":amount,"flag":flag,"note":note});
|
||||
let output: serde_json::Value =
|
||||
serde_json::from_str(&success(call("known", &input.to_string()))).unwrap();
|
||||
assert_eq!(output["data"]["amount"], amount);
|
||||
assert_eq!(output["data"]["flag"], input["flag"]);
|
||||
assert_eq!(output["data"]["note"], input["note"]);
|
||||
}
|
||||
let copied: serde_json::Value =
|
||||
serde_json::from_str(&success(call("copy", r#"{"article_id":2}"#))).unwrap();
|
||||
assert_eq!(copied["data"]["amount"], 10);
|
||||
assert_eq!(copied["data"]["flag"], true);
|
||||
assert_eq!(copied["data"]["note"], " 原文 ");
|
||||
assert!(success(call("defaultAmount", "{}")).contains(r#""amount":7"#));
|
||||
for name in ["known", "unknown"] {
|
||||
for amount in [-1, 11] {
|
||||
let output = call(name, &format!(r#"{{"amount":{amount}}}"#));
|
||||
assert!(!output.status.success(), "{name} accepted {amount}");
|
||||
assert!(!output.stderr.is_empty());
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
!call("known", r#"{"amount":1,"flag":"true"}"#)
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
assert!(success(call("count", "{}")).contains(r#""data":4"#));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_defaults_share_the_runtime_validation_contract() {
|
||||
let root = project("invalid-json-defaults", "");
|
||||
for raw in [
|
||||
"{".to_owned(),
|
||||
r#"{"a":1,"\u0061":2}"#.to_owned(),
|
||||
format!("{}0{}", "[".repeat(65), "]".repeat(65)),
|
||||
format!("[{}0]", "0,".repeat(65_536)),
|
||||
] {
|
||||
let literal = serde_json::to_string(&raw).unwrap();
|
||||
write_source(
|
||||
root.join("module/demo/article/data/main.dever"),
|
||||
format!("type Article {{content:Json default {literal}}}"),
|
||||
)
|
||||
.unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(loaded.diagnostics.is_empty());
|
||||
let error = program::check(&loaded.declarations, &loaded.modules)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert!(error.message.contains("JSON"), "{}", error.message);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decimal_storage_preserves_precision_order_and_json_original_text() {
|
||||
let root = project(
|
||||
"model-scalars-native",
|
||||
r#"
|
||||
flow create(amount: Decimal, discount: Decimal?, content: Json) (out: data.Article)
|
||||
| step | kind | do |
|
||||
| out | data | data.create({amount = amount, discount = discount, content = content}) |
|
||||
flow list(minimum: Decimal) (out: data.Page)
|
||||
| step | kind | do |
|
||||
| out | data | data.page(amount >= minimum, order = amount.asc) |
|
||||
flow count(amount: Decimal) (out: Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.count(amount == amount) |
|
||||
flow change(article_id: data.id, discount: Decimal?) (out: data.Article)
|
||||
| step | kind | do |
|
||||
| out | data | data.update(article_id,{discount = discount}) |
|
||||
"#,
|
||||
);
|
||||
write_source(root.join("module/demo/article/data/main.dever"), r#"type Article { amount: Decimal(34,2), discount: Decimal(8,2)?, content: Json, extra: Json? default "{ \"large\":1e9999 }" }"#).unwrap();
|
||||
fs::write(root.join("module/demo/article/api.dever"), "cmd create = app.create\ncmd list = app.list\ncmd count = app.count\ncmd change = app.change").unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
let config = root.join("config/setting.json");
|
||||
fs::write(
|
||||
&config,
|
||||
r#"{"database":{"default":{"type":"sqlite","path":"data/model.db"}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
let call = |name: &str, input: &str| {
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.args([&format!("demo.article.{name}"), input])
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
success(
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.arg("migrate")
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
for amount in [
|
||||
"-10.25",
|
||||
"0.00",
|
||||
"2.01",
|
||||
"99999999999999999999999999999999.99",
|
||||
] {
|
||||
let input = format!(
|
||||
r#"{{"amount":"{amount}","discount":null,"content": {{ "large":1e9999, "text":"原文" }} }}"#
|
||||
);
|
||||
let out = success(call("create", &input));
|
||||
assert!(out.contains(r#"{ "large":1e9999 }"#), "{out}");
|
||||
assert!(
|
||||
out.contains(r#"{ "large":1e9999, "text":"原文" }"#),
|
||||
"{out}"
|
||||
);
|
||||
}
|
||||
for amount in ["1.001", "100000000000000000000000000000000"] {
|
||||
assert!(
|
||||
!call(
|
||||
"create",
|
||||
&format!(r#"{{"amount":"{amount}","discount":null,"content":null}}"#)
|
||||
)
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
}
|
||||
let page = success(call("list", r#"{"minimum":"-100"}"#));
|
||||
// 使用原文检查,避免测试端 JSON 库把高精度内容变成 Float。
|
||||
assert!(page.contains(r#""total":4"#), "{page}");
|
||||
let positions = [
|
||||
"-10.25",
|
||||
"\"0\"",
|
||||
"2.01",
|
||||
"99999999999999999999999999999999.99",
|
||||
]
|
||||
.map(|value| page.find(value).unwrap());
|
||||
assert!(positions.windows(2).all(|pair| pair[0] < pair[1]));
|
||||
assert!(success(call("count", r#"{"amount":"2.01"}"#)).contains(r#""data":1"#));
|
||||
let changed = success(call("change", r#"{"article_id":1,"discount":"3.50"}"#));
|
||||
assert!(changed.contains(r#""discount":"3.5""#), "{changed}");
|
||||
assert!(
|
||||
!call("change", r#"{"article_id":1,"discount":"3.501"}"#)
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
assert!(
|
||||
success(call("change", r#"{"article_id":1,"discount":null}"#))
|
||||
.contains(r#""discount":null"#)
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn transaction_flow_preserves_syntax_and_inspection_and_allows_clock_reads() {
|
||||
let root = project(
|
||||
"transaction-clock",
|
||||
"transaction flow stamp() (out: DateTime)\n| step | kind | do |\n| out | flow | dever.time.now() |\ntransaction flow nested() (out: DateTime)\n| step | kind | do |\n| out | flow | stamp() |",
|
||||
);
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(
|
||||
&loaded,
|
||||
&program,
|
||||
"demo.article.app.nested",
|
||||
Profile::Dev,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(run(&artifact.binary).starts_with("DateTime("));
|
||||
let path = root.to_str().unwrap();
|
||||
success(cli(&["fmt", path]));
|
||||
success(cli(&["fmt", path, "--check"]));
|
||||
assert!(
|
||||
fs::read_to_string(root.join("module/demo/article/app/main.dever"))
|
||||
.unwrap()
|
||||
.contains("transaction flow stamp")
|
||||
);
|
||||
let inspection: serde_json::Value = serde_json::from_str(&success(cli(&[
|
||||
"inspect",
|
||||
path,
|
||||
"--json",
|
||||
"--symbol",
|
||||
"demo.article.app.stamp",
|
||||
"--depth",
|
||||
"0",
|
||||
])))
|
||||
.unwrap();
|
||||
assert!(inspection["flows"].as_array().unwrap().iter().any(|flow| {
|
||||
flow["nodes"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|node| node["kind"] == "transaction")
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transaction_rejects_effects_through_subflows_and_static_handlers() {
|
||||
let root = project("transaction-effects", "");
|
||||
for body in [
|
||||
"transaction flow waitFor() ()\n| step | kind | do |\n| - | flow | dever.time.sleep(1) |",
|
||||
"flow waitFor() ()\n| step | kind | do |\n| - | flow | dever.time.sleep(1) |\ntransaction flow wrapped() ()\n| step | kind | do |\n| - | flow | waitFor() |",
|
||||
"flow waitFor() ()\n| step | kind | do |\n| - | flow | dever.time.sleep(1) |\ntransaction flow wrapped(action: handler() ()) ()\n| step | kind | do |\n| - | calc | action() |\nflow start() ()\n| step | kind | do |\n| - | flow | wrapped(waitFor) |",
|
||||
"transaction flow random() (out: Secret)\n| step | kind | do |\n| out | flow | dever.crypto.token(32) |",
|
||||
"transaction flow hash(password: Secret) (out: Text)\n| step | kind | do |\n| out | flow | dever.crypto.passwordHash(password) |",
|
||||
] {
|
||||
write_source(root.join("module/demo/article/app/main.dever"), body).unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(loaded.diagnostics.is_empty(), "{:?}", loaded.diagnostics);
|
||||
let analysis = program::analyze(&loaded.declarations, &loaded.modules);
|
||||
assert!(
|
||||
analysis
|
||||
.diagnostics
|
||||
.iter()
|
||||
.any(|error| error.message.contains("transaction flow cannot")),
|
||||
"{:?}",
|
||||
analysis.diagnostics
|
||||
);
|
||||
}
|
||||
for body in [
|
||||
"transaction rule wrong(value: Int) (out: Int)",
|
||||
"transaction plain() () {}",
|
||||
] {
|
||||
write_source(root.join("module/demo/article/app/main.dever"), body).unwrap();
|
||||
assert!(!Project::load(&root).unwrap().diagnostics.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn batch_upsert_generated_values_and_captured_database_errors_execute() {
|
||||
let root = project(
|
||||
"model-writes-native",
|
||||
r#"
|
||||
flow seed() (out: Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.createMany([{ title = " First% ", code = "first" }, { code = "second", title = "Second_" }]) |
|
||||
flow empty() (out: Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.createMany([]) |
|
||||
flow batchConflict() (out: Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.createMany([{ title = "must roll back", code = "third" }, { title = "duplicate", code = "first" }]) |
|
||||
flow save(code: Text?, title: Text) (out: data.Article)
|
||||
| step | kind | do |
|
||||
| out | data | data.upsert({code = code}, {title = title}, {title = title}) |
|
||||
flow keep(code: Text?) (out: data.Article)
|
||||
| step | kind | do |
|
||||
| out | data | data.upsert({code = code}, {title = "created"}, {}) |
|
||||
flow find(needle: Text) (out: data.Page)
|
||||
| step | kind | do |
|
||||
| out | data | data.page(title.contains(needle), order = id.asc) |
|
||||
flow count() (out: Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.count() |
|
||||
type Read { Found(value: data.Article), error Storage(value: dever.database.Error) }
|
||||
rule present(value: Read) (out: Bool) recover("记录不存在时报告查询失败")
|
||||
| value | out |
|
||||
| Found(article) | true |
|
||||
| Storage(error) | false |
|
||||
flow captured(article_id: data.id) (out: Bool)
|
||||
| step | kind | do |
|
||||
| read: Read | data | result(data.get(article_id)) |
|
||||
| out | rule | present(read) |
|
||||
checkedTitle(value:Text) (out:Text) {
|
||||
check length(value) > 0 else Invalid
|
||||
out = value
|
||||
}
|
||||
flow caughtTitle(title: Text) (out: Bool)
|
||||
| step | kind | do |
|
||||
| saved: Read | data | result(data.create({title = checkedTitle(title)})) |
|
||||
| out | rule | present(saved) |
|
||||
flow caughtSave(code: Text?, title: Text) (out: Bool)
|
||||
| step | kind | do |
|
||||
| saved: Read | data | result(data.upsert({code = code},{title = title},{})) |
|
||||
| out | rule | present(saved) |
|
||||
flow calendar(code: Text, day: Date, clock: Time, moment: DateTime, tag: Uuid?) (out: data.Article)
|
||||
| step | kind | do |
|
||||
| out | data | data.create({title = code, code = code, day = day, clock = clock, moment = moment, tag = tag}) |
|
||||
"#,
|
||||
);
|
||||
write_source(
|
||||
root.join("module/demo/article/data/main.dever"),
|
||||
r#"
|
||||
type Article {
|
||||
title: Text(1, 120)
|
||||
code: Text? unique
|
||||
token: Uuid generated unique
|
||||
day: Date?
|
||||
clock: Time?
|
||||
moment: DateTime?
|
||||
tag: Uuid?
|
||||
}
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(root.join("module/demo/article/api.dever"), "cmd seed = app.seed\ncmd empty = app.empty\ncmd batchConflict = app.batchConflict\ncmd save = app.save\ncmd keep = app.keep\ncmd find = app.find\ncmd count = app.count\ncmd captured = app.captured\ncmd calendar = app.calendar\ncmd caughtSave = app.caughtSave\ncmd caughtTitle = app.caughtTitle").unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
let config = root.join("config/setting.json");
|
||||
fs::write(
|
||||
&config,
|
||||
r#"{"database":{"default":{"type":"sqlite","path":"data/model.db"}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
let call = |name: &str, input: serde_json::Value| {
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.args([&format!("demo.article.{name}"), &input.to_string()])
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
let data = |name: &str, input: serde_json::Value| {
|
||||
let output = success(call(name, input));
|
||||
serde_json::from_str::<serde_json::Value>(&output).unwrap()["data"].clone()
|
||||
};
|
||||
success(
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.arg("migrate")
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
assert_eq!(data("seed", serde_json::json!({})), 2);
|
||||
assert_eq!(data("empty", serde_json::json!({})), 0);
|
||||
assert!(
|
||||
!call("batchConflict", serde_json::json!({}))
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
assert_eq!(data("count", serde_json::json!({})), 2);
|
||||
let first = data("find", serde_json::json!({"needle":"%"}));
|
||||
assert_eq!(first["total"], 1);
|
||||
assert_eq!(first["items"][0]["title"], "First%");
|
||||
let first = &first["items"][0];
|
||||
assert_eq!(first["token"].as_str().unwrap().chars().nth(14), Some('7'));
|
||||
let updated = data(
|
||||
"save",
|
||||
serde_json::json!({"code":"first","title":" changed "}),
|
||||
);
|
||||
assert_eq!(updated["id"], first["id"]);
|
||||
assert_eq!(updated["token"], first["token"]);
|
||||
assert_eq!(updated["created_at"], first["created_at"]);
|
||||
assert_eq!(updated["title"], "changed");
|
||||
assert_eq!(data("keep", serde_json::json!({"code":"first"})), updated);
|
||||
let created = data("keep", serde_json::json!({"code":"new"}));
|
||||
assert_eq!(created["title"], "created");
|
||||
assert_ne!(created["token"], updated["token"]);
|
||||
assert!(
|
||||
!call("save", serde_json::json!({"code":null,"title":"invalid"}))
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
assert_eq!(data("count", serde_json::json!({})), 3);
|
||||
assert_eq!(
|
||||
data("captured", serde_json::json!({"article_id":9999})),
|
||||
false
|
||||
);
|
||||
assert_eq!(
|
||||
data("captured", serde_json::json!({"article_id":updated["id"]})),
|
||||
true
|
||||
);
|
||||
assert_eq!(
|
||||
data(
|
||||
"caughtSave",
|
||||
serde_json::json!({"code":null,"title":"handled failure"})
|
||||
),
|
||||
false
|
||||
);
|
||||
assert_eq!(
|
||||
data(
|
||||
"caughtSave",
|
||||
serde_json::json!({"code":"first","title":"unchanged"})
|
||||
),
|
||||
true
|
||||
);
|
||||
let invalid = call("caughtTitle", serde_json::json!({"title":""}));
|
||||
assert!(!invalid.status.success());
|
||||
assert!(String::from_utf8_lossy(&invalid.stderr).contains("Invalid"));
|
||||
assert!(!String::from_utf8_lossy(&invalid.stderr).contains("InvalidData"));
|
||||
assert_eq!(
|
||||
data("caughtTitle", serde_json::json!({"title":"正常实参"})),
|
||||
true
|
||||
);
|
||||
let calendar = data(
|
||||
"calendar",
|
||||
serde_json::json!({"code":"calendar","day":"2026-11-12","clock":"12:34:56","moment":"2026-11-12T12:34:56Z","tag":updated["token"]}),
|
||||
);
|
||||
assert_eq!(calendar["day"], "2026-11-12");
|
||||
assert_eq!(calendar["clock"], "12:34:56");
|
||||
assert_eq!(calendar["moment"], "2026-11-12T12:34:56Z");
|
||||
assert_eq!(calendar["tag"], updated["token"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_rejects_invalid_storage_and_defaults_before_native_compilation() {
|
||||
let root = project(
|
||||
"model-invalid-storage",
|
||||
"copy(value: data.Article) (out: data.Article) { out = value }",
|
||||
);
|
||||
for model in [
|
||||
"type Article { title: Text default -1 }",
|
||||
"type Article { title: Text(2,10) default \" x \" }",
|
||||
"type Article { title: Text(2,10) upper default \"ß\" }", // expands to SS and is valid below
|
||||
"type Article { values: List<Int> }",
|
||||
"type Article { key: Uuid? generated }",
|
||||
] {
|
||||
write_source(root.join("module/demo/article/data/main.dever"), model).unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
let result = program::check(&loaded.declarations, &loaded.modules);
|
||||
if model.contains("ß") {
|
||||
assert!(result.is_ok());
|
||||
} else {
|
||||
assert!(result.is_err(), "{model}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn blocking_password_command_preserves_mismatch_error_and_secret_boundaries() {
|
||||
let (project, _) = checked(
|
||||
"flow verify(password: Secret, hash: Text) (valid: Bool)\n| step | kind | do |\n| valid | calc | blocking(dever.crypto.passwordVerify(password, hash)) |\ncmd verify = verify\n",
|
||||
"blocking-command",
|
||||
);
|
||||
let path = project.sources[0].path.to_str().unwrap();
|
||||
let binary = project.sources[0].path.parent().unwrap().join("verify");
|
||||
success(cli(&["fmt", path]));
|
||||
success(cli(&[
|
||||
"build",
|
||||
path,
|
||||
"--profile",
|
||||
"dev",
|
||||
"--output",
|
||||
binary.to_str().unwrap(),
|
||||
]));
|
||||
let password = "public-test-only-password";
|
||||
let secret = dever_runtime::value::secret::Secret::from_input(password.as_bytes().to_vec());
|
||||
let hash = dever_runtime::crypto::password_hash(&secret).unwrap();
|
||||
for (input, valid) in [(password, true), ("different-test-password", false)] {
|
||||
let output = Command::new(&binary)
|
||||
.args([
|
||||
"main.main.verify",
|
||||
&serde_json::json!({"password": input, "hash": hash}).to_string(),
|
||||
])
|
||||
.output()
|
||||
.unwrap();
|
||||
let value: serde_json::Value = serde_json::from_str(&success(output)).unwrap();
|
||||
assert_eq!(value["data"], valid);
|
||||
}
|
||||
let output = Command::new(&binary)
|
||||
.args([
|
||||
"main.main.verify",
|
||||
&serde_json::json!({"password": password, "hash": "invalid"}).to_string(),
|
||||
])
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(!output.status.success() && output.stdout.is_empty());
|
||||
let error = String::from_utf8(output.stderr).unwrap();
|
||||
assert!(error.contains("VerifyResult.Failed"));
|
||||
assert!(!error.contains(password));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocking_requires_a_known_synchronous_target_and_cannot_hide_in_async_code() {
|
||||
let prefix = r#"
|
||||
identity(value: Int) (out: Int) { out = value }
|
||||
flow verify(password: Secret, hash: Text) (out: Bool)
|
||||
| step | kind | do |
|
||||
| out | flow | dever.crypto.passwordVerify(password, hash) |
|
||||
flow offload(password: Secret, hash: Text) (out: Bool)
|
||||
| step | kind | do |
|
||||
| out | calc | blocking(verify(password, hash)) |
|
||||
"#;
|
||||
let cases = [
|
||||
"flow apply(action: handler(value: Int) (out: Int)) (out: Int)\n| step | kind | do |\n| out | calc | blocking(action(1)) |\nflow bad() (out: Int)\n| step | kind | do |\n| out | flow | apply(identity) |",
|
||||
"flow bad() (out: Int)\n| step | kind | do |\n| out | calc | blocking(identity(1)) |",
|
||||
"flow bad() ()\n| step | kind | do |\n| - | calc | blocking(dever.time.sleep(0)) |",
|
||||
"flow bad() (out: DateTime)\n| step | kind | do |\n| out | calc | blocking(dever.time.now()) |",
|
||||
"flow bad(password: Secret, hash: Text) (out: Bool)\n| step | kind | do |\n| out | calc | parallel(verify(password, hash)) |",
|
||||
"flow bad(password: Secret, hash: Text) (out: Bool)\n| step | kind | do |\n| out | calc | blocking(offload(password, hash)) |",
|
||||
"bad(password: Secret, hash: Text) (out: Bool) { out = blocking(verify(password, hash)) }",
|
||||
"flow bad(password: Secret, hash: Text) (out: Bool)\n| step | kind | do |\n| - | flow | dever.time.sleep(0) |\n| out | flow | verify(password, hash) |",
|
||||
"flow bad(password: Secret, hash: Text) (out: Bool)\n| step | kind | parallel | do |\n| - | flow | work | dever.time.sleep(0) |\n| out | flow | work | verify(password, hash) |",
|
||||
"flow bad(password: Secret, hash: Text) (out: Bool)\n| step | kind | do |\n| out | calc | wait(blocking(verify(password, hash))) |",
|
||||
];
|
||||
for (index, source) in cases.iter().enumerate() {
|
||||
let path = directory(&format!("blocking-invalid-{index}")).join("app.dever");
|
||||
fs::write(&path, format!("{prefix}{source}\n")).unwrap();
|
||||
let project = Project::load(&path).unwrap();
|
||||
assert!(project.diagnostics.is_empty(), "{:?}", project.diagnostics);
|
||||
let error = program::check(&project.declarations, &project.modules)
|
||||
.err()
|
||||
.expect(source);
|
||||
assert!(matches!(error.code, "C013" | "C014"), "{index}: {error:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocking_propagates_effects_formats_and_navigates_real_password_operations() {
|
||||
let (project, program) = checked(include_str!("../../native/blocking.dever"), "blocking-docs");
|
||||
let target = program
|
||||
.functions
|
||||
.iter()
|
||||
.find(|f| f.signature.name == "dever.crypto.app.passwordVerify")
|
||||
.unwrap();
|
||||
assert!(target.effects.blocking && !target.effects.suspends);
|
||||
let entry = program
|
||||
.functions
|
||||
.iter()
|
||||
.find(|f| f.signature.name == "main.main.app.verify")
|
||||
.unwrap();
|
||||
assert!(entry.effects.tasks && entry.effects.suspends && !entry.effects.blocking);
|
||||
let path = project.sources[0].path.to_str().unwrap();
|
||||
success(cli(&["fmt", path]));
|
||||
success(cli(&["fmt", path, "--check"]));
|
||||
let index =
|
||||
dever::compiler::inspect::analyze(&project, Some("main.main.app.verify"), 1, true).unwrap();
|
||||
let text = serde_json::to_string(&index).unwrap();
|
||||
assert!(
|
||||
text.contains("线程池执行同步阻塞调用") && text.contains("dever.crypto.app.passwordVerify")
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn channels_reject_hidden_effects_wrong_payloads_and_wire_escape() {
|
||||
let cases = [
|
||||
"bad() (out: Channel<Int>) { out = channel<Int>(1) }",
|
||||
"flow bad() ()\n| step | kind | do |\n| - | calc | send(channel<Int>(1), 1) |",
|
||||
"flow bad(channel: Channel<Int>) ()\n| step | kind | do |\n| - | calc | send(channel, true) |",
|
||||
"flow bad() (out: Int?)\n| step | kind | do |\n| out | calc | receive(1) |",
|
||||
"flow bad() ()\n| step | kind | do |\n| - | calc | close(1) |",
|
||||
"bad(a: Channel<Int>, b: Channel<Int>) (out: Bool) { out = a == b }",
|
||||
"type Box { value: Channel<Int> }\nbad(a: Box, b: Box) (out: Bool) { out = a == b }",
|
||||
"bad(a: List<Channel<Int>>, b: Channel<Int>) (out: Bool) { out = contains(a, b) }",
|
||||
"flow bad() (out: Channel<Int>)\n| step | kind | do |\n| out | calc | channel<Int>(1) |\ncmd bad = bad",
|
||||
"flow bad(channel: Channel<Int>) ()\n| step | kind | do |\n| - | calc | close(channel) |\ncmd bad = bad",
|
||||
"type Outcome { Ok, error Bad }\nflow bad(channel: Channel<Outcome>) ()\n| step | kind | do |\n| error | calc | Outcome.Bad |\n| - | calc | send(channel, error) |",
|
||||
"rule bad(input: Int) (out: Channel<Int>)\n| input | out |\n| - | channel<Int>(1) |",
|
||||
];
|
||||
for (index, source) in cases.iter().enumerate() {
|
||||
let path = directory(&format!("channel-invalid-{index}")).join("app.dever");
|
||||
fs::write(&path, source).unwrap();
|
||||
let project = Project::load(&path).unwrap();
|
||||
assert!(
|
||||
project.diagnostics.is_empty(),
|
||||
"{index}: {:?}",
|
||||
project.diagnostics
|
||||
);
|
||||
let error = program::check(&project.declarations, &project.modules)
|
||||
.err()
|
||||
.expect(source);
|
||||
assert!(
|
||||
matches!(error.code, "C005" | "C012" | "C013" | "C014"),
|
||||
"{index}: {error:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn channels_format_and_show_queue_close_and_cancel_in_workflows() {
|
||||
let (project, program) = checked(include_str!("../../native/channel.dever"), "channel-docs");
|
||||
let entry = program
|
||||
.functions
|
||||
.iter()
|
||||
.find(|f| f.signature.source_name.ends_with(".produce"))
|
||||
.unwrap();
|
||||
assert!(entry.effects.channel && entry.effects.suspends && !entry.effects.tasks);
|
||||
let path = project.sources[0].path.to_str().unwrap();
|
||||
success(cli(&["fmt", path]));
|
||||
success(cli(&["fmt", path, "--check"]));
|
||||
success(cli(&["check", path]));
|
||||
let index = dever::compiler::inspect::analyze(&project, Some("main.main.app.produce"), 1, true)
|
||||
.unwrap();
|
||||
let text = serde_json::to_string(&index).unwrap();
|
||||
assert!(text.contains("等待空位,移交消息") && text.contains("关闭通道并唤醒等待者"));
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn token_random_effects_follow_actual_calls_and_navigate_bundled_source() {
|
||||
let (project, program) = checked(include_str!("../../native/token.dever"), "token-effects");
|
||||
for name in [
|
||||
"dever.crypto.app.token",
|
||||
"main.main.app.generate",
|
||||
"main.main.app.handled",
|
||||
] {
|
||||
let function = program
|
||||
.functions
|
||||
.iter()
|
||||
.find(|f| f.signature.source_name == name)
|
||||
.unwrap();
|
||||
assert!(function.effects.random && !function.effects.pure());
|
||||
assert!(!function.effects.blocking && !function.effects.suspends);
|
||||
}
|
||||
let path = project.sources[0].path.to_str().unwrap();
|
||||
success(cli(&["fmt", path]));
|
||||
success(cli(&["fmt", path, "--check"]));
|
||||
let index =
|
||||
dever::compiler::inspect::analyze(&project, Some("main.main.app.generate"), 2, true)
|
||||
.unwrap();
|
||||
let text = serde_json::to_string(&index).unwrap();
|
||||
assert!(text.contains("效果") && text.contains("dever.crypto.app.token"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tokens_cannot_hide_random_effects_or_escape_secret_and_failure_boundaries() {
|
||||
let cases = [
|
||||
"bad() (out: Secret) { out = dever.crypto.token(32) }",
|
||||
"flow bad() (out: Bytes)\n| step | kind | do |\n| out | calc | dever.crypto.hmacSha256(dever.crypto.token(32), dever.bytes.fromText(\"message\")) |",
|
||||
"flow bad() (out: Secret)\n| step | kind | do |\n| out | calc | parallel(dever.crypto.token(32)) |",
|
||||
"flow bad() (out: Secret)\n| step | kind | do |\n| out | calc | blocking(dever.crypto.token(32)) |",
|
||||
"flow bad() (out: Secret)\n| step | kind | do |\n| out | flow | dever.crypto.token(32) |\ncmd bad = bad",
|
||||
"flow bad() (out: Text)\n| step | kind | do |\n| key | flow | dever.crypto.token(32) |\n| out | calc | dever.json.encode(key) |",
|
||||
"type Attempt { Ready(value: Secret), error Failed(value: dever.crypto.TokenResult) }\nflow bad() (out: Int)\n| step | kind | do |\n| value: Attempt | flow | result(dever.crypto.token(15)) |\n| out | calc | 1 |",
|
||||
"apply(create: handler(bytes: Int) (value: Secret)) (out: Secret) { out = create(32) }\nflow bad() (out: Secret)\n| step | kind | do |\n| out | calc | apply(dever.crypto.token) |",
|
||||
];
|
||||
for (index, source) in cases.iter().enumerate() {
|
||||
let path = directory(&format!("invalid-token-{index}")).join("app.dever");
|
||||
fs::write(&path, source).unwrap();
|
||||
let project = Project::load(&path).unwrap();
|
||||
assert!(project.diagnostics.is_empty(), "{:?}", project.diagnostics);
|
||||
let errors = program::analyze(&project.declarations, &project.modules).diagnostics;
|
||||
assert!(!errors.is_empty(), "{index}: {source}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,382 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn streaming_boundaries_do_not_hide_network_effects_or_discard_failures() {
|
||||
for (index, source) in [
|
||||
"flow bad(client: dever.system.HttpClient, body: AsyncStream<dever.io.ReadEvent>) ()\n| step | kind | do |\n| response | flow | dever.http.openStream(client, dever.http.StreamRequest { method = \"POST\", target = \"/upload\", headers = [], body = body }) |\n| - | calc | close(response.body) |",
|
||||
"bad(socket: dever.system.WebSocket) (state: dever.websocket.ReceiveState) { state = dever.websocket.receive(socket) }",
|
||||
"flow bad(socket: dever.system.WebSocket) ()\n| step | kind | do |\n| ignored | flow | result(dever.websocket.receive(socket)) |",
|
||||
"loop bad(events: AsyncStream<dever.websocket.MessageEvent>) (count: Int)\n| each event in events | result |\n| count | count |",
|
||||
"same(left: dever.system.WebSocket, right: dever.system.WebSocket) (out: Bool) { out = left == right }",
|
||||
].iter().enumerate() {
|
||||
let path = directory(&format!("streaming-boundary-{index}")).join("app.dever");
|
||||
fs::write(&path, source).unwrap();
|
||||
let project = Project::load(&path).unwrap();
|
||||
assert!(project.diagnostics.is_empty(), "{:?}", project.diagnostics);
|
||||
let diagnostics = program::analyze(&project.declarations, &project.modules).diagnostics;
|
||||
assert!(diagnostics.iter().any(|error| matches!(error.code, "C005" | "C012" | "C013")), "{index}: {diagnostics:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn http_pool_is_a_shared_network_resource_with_explicit_effects() {
|
||||
let (project, program) = checked(
|
||||
include_str!("../../native/http_pool.dever"),
|
||||
"http-pool-effects",
|
||||
);
|
||||
assert!(program.uses_http() && program.uses_network());
|
||||
let open = program
|
||||
.functions
|
||||
.iter()
|
||||
.find(|f| f.signature.name == "main.main.app.open")
|
||||
.unwrap();
|
||||
assert!(open.effects.network && open.effects.tasks && open.effects.suspends);
|
||||
let kind = &open.signature.outputs[0].kind;
|
||||
assert_eq!(*kind, dever::compiler::model::Type::HttpClient);
|
||||
assert!(!program.comparable(kind));
|
||||
let fetch = program
|
||||
.functions
|
||||
.iter()
|
||||
.find(|f| f.signature.name == "main.main.app.fetch")
|
||||
.unwrap();
|
||||
assert!(fetch.effects.network && fetch.effects.suspends && !fetch.effects.tasks);
|
||||
let index =
|
||||
dever::compiler::inspect::analyze(&project, Some("main.main.app.fetch"), 1, true).unwrap();
|
||||
let text = serde_json::to_string(&index).unwrap();
|
||||
assert!(text.contains("dever.http.app.request") && text.contains("挂起"));
|
||||
let download = program
|
||||
.functions
|
||||
.iter()
|
||||
.find(|f| f.signature.name == "main.main.app.download")
|
||||
.unwrap();
|
||||
assert!(download.effects.network && download.effects.suspends && download.effects.stream);
|
||||
let index =
|
||||
dever::compiler::inspect::analyze(&project, Some("main.main.app.download"), 1, true)
|
||||
.unwrap();
|
||||
let text = serde_json::to_string(&index).unwrap();
|
||||
assert!(text.contains("dever.http.app.open") && text.contains("挂起"));
|
||||
let path = directory("http-download-unhandled-body").join("app.dever");
|
||||
fs::write(&path, "loop bad(body: AsyncStream<dever.io.ReadEvent>) (count: Int)\n| each event in body | result |\n| count | count |\n").unwrap();
|
||||
let project = Project::load(&path).unwrap();
|
||||
assert!(project.diagnostics.is_empty(), "{:?}", project.diagnostics);
|
||||
let errors = program::analyze(&project.declarations, &project.modules).diagnostics;
|
||||
assert!(errors.iter().any(|e| e.code == "C012"), "{errors:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn http_server_binds_handlers_preserves_effects_and_rejects_unsafe_callbacks() {
|
||||
let source = include_str!("../../native/http_server.dever");
|
||||
let (project, program) = checked(source, "http-server-effects");
|
||||
let start = program
|
||||
.functions
|
||||
.iter()
|
||||
.find(|f| f.signature.name == "main.main.app.startTasks")
|
||||
.unwrap();
|
||||
assert!(
|
||||
start.effects.network
|
||||
&& start.effects.tasks
|
||||
&& start.effects.suspends
|
||||
&& start.effects.clock
|
||||
);
|
||||
assert!(!start.effects.blocking);
|
||||
let (_, streaming) = checked(
|
||||
&format!(
|
||||
"{source}\nloop firstTick(ticks: AsyncStream<Int>) (tick: Int?)\n| each value in ticks | result |\n| tick | first value |\nflow streamRoute(request: dever.http.Request) (response: dever.http.Response)\n| step | kind | do |\n| ticks | flow | dever.task.ticks(1) |\n| tick | loop | firstTick(ticks) |\n| response | calc | echo(request) |\nflow streamServer(listener: dever.system.Listener) ()\n| step | kind | do |\n| - | flow | dever.http.serve(streamRoute, listener, dever.http.defaultLimits()) |"
|
||||
),
|
||||
"http-stream-handler-effects",
|
||||
);
|
||||
assert!(
|
||||
streaming
|
||||
.functions
|
||||
.iter()
|
||||
.find(|f| f.signature.name == "main.main.app.streamServer")
|
||||
.unwrap()
|
||||
.effects
|
||||
.stream
|
||||
);
|
||||
let config = program
|
||||
.functions
|
||||
.iter()
|
||||
.find(|f| f.signature.name == "main.main.app.startConfig")
|
||||
.unwrap();
|
||||
assert!(config.uses_settings);
|
||||
let start_failure = program
|
||||
.functions
|
||||
.iter()
|
||||
.find(|f| f.signature.name == "main.main.app.startFailure")
|
||||
.unwrap();
|
||||
assert!(
|
||||
start_failure
|
||||
.failures
|
||||
.iter()
|
||||
.all(|error| !matches!(error, dever::compiler::model::Failure::Api(_)))
|
||||
);
|
||||
let index =
|
||||
dever::compiler::inspect::analyze(&project, Some("main.main.app.startTasks"), 2, true)
|
||||
.unwrap();
|
||||
let index = serde_json::to_string(&index).unwrap();
|
||||
assert!(
|
||||
index.contains("请求处理")
|
||||
&& index.contains("main.main.app.scheduledRoute")
|
||||
&& index.contains("监听器关闭")
|
||||
);
|
||||
for (index, route) in [
|
||||
"bad(request: dever.http.Request) (out: dever.http.Response) { out = echo(request) }",
|
||||
"bad(request: Text) (response: dever.http.Response) { response = dever.http.Response { status = 200, headers = [], body = dever.bytes.fromText(request) } }",
|
||||
"flow bad(request: dever.http.Request) (response: dever.http.Response)\n| step | kind | do |\n| - | flow | dever.io.println(request.target) |\n| response | calc | echo(request) |",
|
||||
"flow bad(request: dever.http.Request) (response: dever.http.Response)\n| step | kind | do |\n| - | calc | blocking(dever.io.println(request.target)) |\n| response | calc | echo(request) |",
|
||||
"flow bad(request: dever.http.Request) (response: dever.http.Response)\n| step | kind | do |\n| file | flow | dever.io.open(request.target) |
|
||||
| - | flow | dever.io.close(file) |\n| response | calc | echo(request) |",
|
||||
].iter().enumerate() {
|
||||
let path = directory(&format!("http-invalid-handler-{index}")).join("app.dever");
|
||||
fs::write(&path, format!("{source}\n{route}\nflow badServer(listener: dever.system.Listener) ()\n| step | kind | do |\n| - | flow | dever.http.serve(bad, listener, dever.http.defaultLimits()) |\n")).unwrap();
|
||||
let project = Project::load(&path).unwrap();
|
||||
assert!(project.diagnostics.is_empty(), "{:?}", project.diagnostics);
|
||||
let errors = program::analyze(&project.declarations, &project.modules).diagnostics;
|
||||
assert!(errors.iter().any(|e| matches!(e.code, "C005" | "C013")), "{index}: {errors:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn http_send_keeps_network_effects_failures_and_navigation() {
|
||||
let (_, plain) = checked("main() (out: Int) { out = 1 }", "without-http");
|
||||
assert!(!plain.uses_http());
|
||||
let (project, program) = checked(include_str!("../../native/http.dever"), "http-send");
|
||||
assert!(program.uses_http());
|
||||
let fetch = program
|
||||
.functions
|
||||
.iter()
|
||||
.find(|f| f.signature.name == "main.main.app.fetch")
|
||||
.unwrap();
|
||||
assert!(fetch.effects.network && fetch.effects.suspends && !fetch.effects.blocking);
|
||||
let index =
|
||||
dever::compiler::inspect::analyze(&project, Some("main.main.app.fetch"), 1, true).unwrap();
|
||||
assert!(
|
||||
serde_json::to_string(&index)
|
||||
.unwrap()
|
||||
.contains("dever.http.app.send")
|
||||
);
|
||||
for (index, source) in [
|
||||
"bad(request: dever.http.Request) (out: dever.http.Response) { out = dever.http.send(\"127.0.0.1\", 80, request, dever.http.defaultLimits()) }",
|
||||
"flow bad(request: dever.http.Request) ()\n| step | kind | do |\n| ignored | flow | result(dever.http.send(\"127.0.0.1\", 80, request, dever.http.defaultLimits())) |",
|
||||
].iter().enumerate() {
|
||||
let path = directory(&format!("invalid-http-{index}")).join("app.dever");
|
||||
fs::write(&path, source).unwrap();
|
||||
let project = Project::load(&path).unwrap();
|
||||
assert!(project.diagnostics.is_empty(), "{:?}", project.diagnostics);
|
||||
assert!(!program::analyze(&project.declarations, &project.modules).diagnostics.is_empty(), "{source}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tls_configuration_is_pure_shared_opaque_and_navigable() {
|
||||
let (_, plain) = checked("main() (out: Int) { out = 1 }", "without-tls");
|
||||
assert!(!plain.uses_tls());
|
||||
let (_, typed) = checked(
|
||||
"type Config { tls: dever.system.ClientTls? }",
|
||||
"tls-type-only",
|
||||
);
|
||||
assert!(typed.uses_tls());
|
||||
let (project, program) = checked(include_str!("../../native/tls.dever"), "tls-config");
|
||||
assert!(program.uses_tls());
|
||||
for name in ["clientTls", "serverTls", "defaultTls"] {
|
||||
let function = program
|
||||
.functions
|
||||
.iter()
|
||||
.find(|f| f.signature.name == format!("main.main.app.{name}"))
|
||||
.unwrap();
|
||||
assert!(
|
||||
!function.effects.network && !function.effects.suspends && !function.effects.blocking
|
||||
);
|
||||
}
|
||||
let index =
|
||||
dever::compiler::inspect::analyze(&project, Some("main.main.app.clientTls"), 1, true)
|
||||
.unwrap();
|
||||
assert!(
|
||||
serde_json::to_string(&index)
|
||||
.unwrap()
|
||||
.contains("dever.tls.app.client")
|
||||
);
|
||||
for (index, source) in [
|
||||
"same(a: dever.system.ClientTls, b: dever.system.ClientTls) (out: Bool) { out = a == b }",
|
||||
"setting config: dever.system.ClientTls\nmain() (out: Int) { out = 1 }",
|
||||
"type Config { tls: dever.system.ServerTls }\nencode(value: Config) (out: Json) { out = dever.json.encode(value) }",
|
||||
"main() (out: dever.system.ClientTls) { out = dever.tls.system() }\ncmd config = main",
|
||||
"ignore(ca: Bytes) () { ignored = result(dever.tls.client(ca)) }",
|
||||
].iter().enumerate() {
|
||||
let path = directory(&format!("invalid-tls-{index}")).join("app.dever");
|
||||
fs::write(&path, source).unwrap();
|
||||
let project = Project::load(&path).unwrap();
|
||||
assert!(project.diagnostics.is_empty(), "{:?}", project.diagnostics);
|
||||
assert!(!program::analyze(&project.declarations, &project.modules).diagnostics.is_empty(), "{source}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn network_effects_resources_and_source_navigation_follow_calls() {
|
||||
let (_, plain) = checked("main() (out: Int) { out = 1 }", "without-network-driver");
|
||||
assert!(!plain.uses_network());
|
||||
let (_, typed) = checked(
|
||||
"type Holder { socket: dever.system.Socket? }\nmain() (out: Int) { out = 1 }",
|
||||
"network-type-only",
|
||||
);
|
||||
assert!(typed.uses_network());
|
||||
let (_, minimal) = checked(
|
||||
"flow disconnect(socket: dever.system.Socket) ()\n| step | kind | do |\n| - | flow | dever.net.close(socket) |",
|
||||
"network-transitive-library",
|
||||
);
|
||||
assert!(
|
||||
minimal
|
||||
.definitions
|
||||
.iter()
|
||||
.any(|value| value.name == "dever.io.app.CloseResult")
|
||||
);
|
||||
let (project, program) = checked(include_str!("../../native/net.dever"), "network-effects");
|
||||
for name in ["roundTrip", "dialTimed", "readSome", "send"] {
|
||||
let function = program
|
||||
.functions
|
||||
.iter()
|
||||
.find(|f| f.signature.name == format!("main.main.app.{name}"))
|
||||
.unwrap();
|
||||
assert!(
|
||||
function.effects.network && function.effects.suspends && !function.effects.blocking,
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
let path = project.sources[0].path.to_str().unwrap();
|
||||
success(cli(&["fmt", path]));
|
||||
success(cli(&["fmt", path, "--check"]));
|
||||
let index =
|
||||
dever::compiler::inspect::analyze(&project, Some("main.main.app.roundTrip"), 1, true)
|
||||
.unwrap();
|
||||
let index = serde_json::to_string(&index).unwrap();
|
||||
for name in [
|
||||
"listen",
|
||||
"port",
|
||||
"connect",
|
||||
"accept",
|
||||
"chunks",
|
||||
"close",
|
||||
"closeListener",
|
||||
] {
|
||||
assert!(index.contains(&format!("dever.net.app.{name}")), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn network_cannot_escape_effects_wire_or_error_obligations() {
|
||||
for (index, source) in [
|
||||
"bad(socket: dever.system.Socket) () { dever.net.close(socket) }",
|
||||
"flow bad(socket: dever.system.Socket) ()\n| step | kind | do |\n| - | calc | parallel(dever.net.close(socket)) |",
|
||||
"flow bad(host: Text) (out: dever.system.Listener)\n| step | kind | do |\n| out | flow | dever.net.listen(host, 0) |\ncmd bad = bad",
|
||||
"same(a: dever.system.Socket, b: dever.system.Socket) (out: Bool) { out = a == b }",
|
||||
"type Box { value: dever.system.Listener }\nserialize(value: Box) (out: Json) { out = dever.json.encode(value) }",
|
||||
"flow bad(listener: dever.system.Listener) ()\n| step | kind | do |\n| events | flow | dever.net.connections(listener) |",
|
||||
"flow bad(socket: dever.system.Socket) (out: dever.io.ReadState)\n| step | kind | do |\n| out | flow | dever.net.read(socket, length(dever.process.arguments())) |",
|
||||
].iter().enumerate() {
|
||||
let path = directory(&format!("invalid-network-{index}")).join("app.dever");
|
||||
fs::write(&path, source).unwrap();
|
||||
let project = Project::load(&path).unwrap();
|
||||
assert!(project.diagnostics.is_empty(), "{:?}", project.diagnostics);
|
||||
let errors = program::analyze(&project.declarations, &project.modules).diagnostics;
|
||||
assert!(!errors.is_empty(), "{index}: {source}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_arguments_are_explicit_effects_with_bundled_navigation() {
|
||||
let (project, program) = checked(
|
||||
include_str!("../../native/arguments.dever"),
|
||||
"arguments-effects",
|
||||
);
|
||||
let read = program
|
||||
.functions
|
||||
.iter()
|
||||
.find(|f| f.signature.name == "main.main.app.readArgs")
|
||||
.unwrap();
|
||||
assert!(read.effects.process && !read.effects.blocking && !read.effects.suspends);
|
||||
let index =
|
||||
dever::compiler::inspect::analyze(&project, Some("main.main.app.readArgs"), 1, true)
|
||||
.unwrap();
|
||||
assert!(
|
||||
serde_json::to_string(&index)
|
||||
.unwrap()
|
||||
.contains("dever.process.app.arguments")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stdout_has_an_explicit_blocking_output_effect_and_real_navigation() {
|
||||
let (project, program) = checked(include_str!("../../native/stdout.dever"), "stdout-effects");
|
||||
let print = program
|
||||
.functions
|
||||
.iter()
|
||||
.find(|f| f.signature.name == "main.main.app.printLine")
|
||||
.unwrap();
|
||||
assert!(print.effects.output && print.effects.blocking && !print.effects.file);
|
||||
let offload = program
|
||||
.functions
|
||||
.iter()
|
||||
.find(|f| f.signature.name == "main.main.app.offload")
|
||||
.unwrap();
|
||||
assert!(offload.effects.output && offload.effects.suspends && !offload.effects.blocking);
|
||||
let index =
|
||||
dever::compiler::inspect::analyze(&project, Some("main.main.app.printLine"), 1, true)
|
||||
.unwrap();
|
||||
assert!(
|
||||
serde_json::to_string(&index)
|
||||
.unwrap()
|
||||
.contains("dever.io.app.println")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_effects_and_workflow_navigation_follow_the_real_bundled_functions() {
|
||||
let (project, program) = checked(include_str!("../../native/file.dever"), "file-effects");
|
||||
let read = program
|
||||
.functions
|
||||
.iter()
|
||||
.find(|f| f.signature.name == "main.main.app.readSome")
|
||||
.unwrap();
|
||||
assert!(read.effects.file && read.effects.blocking && !read.effects.suspends);
|
||||
let offload = program
|
||||
.functions
|
||||
.iter()
|
||||
.find(|f| f.signature.name == "main.main.app.offload")
|
||||
.unwrap();
|
||||
assert!(offload.effects.tasks && offload.effects.suspends && !offload.effects.blocking);
|
||||
let path = project.sources[0].path.to_str().unwrap();
|
||||
success(cli(&["fmt", path]));
|
||||
success(cli(&["fmt", path, "--check"]));
|
||||
let index = dever::compiler::inspect::analyze(&project, Some("main.main.app.offload"), 2, true)
|
||||
.unwrap();
|
||||
let text = serde_json::to_string(&index).unwrap();
|
||||
assert!(text.contains("线程池执行同步阻塞调用") && text.contains("dever.io.app.read"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_cannot_bypass_effects_resource_comparison_or_wire_boundaries() {
|
||||
let cases = [
|
||||
"bad() (out: List<Text>) { out = dever.process.arguments() }",
|
||||
"flow bad() (out: List<Text>)\n| step | kind | do |\n| out | calc | parallel(dever.process.arguments()) |",
|
||||
"bad(text: Text) () { dever.io.println(text) }",
|
||||
"flow bad(text: Text) ()\n| step | kind | do |\n| - | flow | dever.time.sleep(0) |\n| - | flow | dever.io.println(text) |",
|
||||
"flow bad(text: Text) ()\n| step | kind | do |\n| - | calc | parallel(dever.io.println(text)) |",
|
||||
"bad(path: Text) (out: dever.system.File) { out = dever.io.open(path) }",
|
||||
"flow bad(path: Text) (out: dever.io.ReadState)\n| step | kind | do |\n| out | flow | dever.io.read(dever.io.open(path), 1) |",
|
||||
"flow bad(path: Text) (out: dever.system.File)\n| step | kind | do |\n| - | flow | dever.time.sleep(0) |\n| out | flow | dever.io.open(path) |",
|
||||
"flow bad(path: Text) (out: dever.system.File)\n| step | kind | do |\n| out | calc | parallel(dever.io.open(path)) |",
|
||||
"flow bad(path: Text) (out: dever.system.File)\n| step | kind | do |\n| out | flow | dever.io.open(path) |\ncmd bad = bad",
|
||||
"type Holder { file: dever.system.File }\nflow bad(file: dever.system.File) (out: Text)\n| step | kind | do |\n| out | calc | dever.json.encode(Holder { file = file }) |",
|
||||
"same(left: dever.system.File, right: dever.system.File) (out: Bool) { out = left == right }",
|
||||
"type Holder { file: dever.system.File }\nsame(left: Holder, right: Holder) (out: Bool) { out = left == right }",
|
||||
];
|
||||
for (index, source) in cases.iter().enumerate() {
|
||||
let path = directory(&format!("invalid-file-{index}")).join("app.dever");
|
||||
fs::write(&path, source).unwrap();
|
||||
let project = Project::load(&path).unwrap();
|
||||
assert!(project.diagnostics.is_empty(), "{:?}", project.diagnostics);
|
||||
let errors = program::analyze(&project.declarations, &project.modules).diagnostics;
|
||||
assert!(!errors.is_empty(), "{index}: {source}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
//! 检查真实项目和实际 handler 实例;拒绝隐藏效果,不以库名代替纯度。
|
||||
use super::*;
|
||||
|
||||
fn checked(source: &str, name: &str) -> (Project, dever::compiler::model::Program) {
|
||||
let root = directory(name);
|
||||
let path = root.join("app.dever");
|
||||
fs::write(&path, source).unwrap();
|
||||
analyze(&path)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effects_follow_tables_and_bound_handlers_without_making_pure_calls_async() {
|
||||
let (project, program) = checked(include_str!("../../native/tasks.dever"), "effects");
|
||||
for name in [
|
||||
"delay",
|
||||
"chosen",
|
||||
"eachDelay",
|
||||
"next",
|
||||
"walked",
|
||||
"apply",
|
||||
"handled",
|
||||
"captured",
|
||||
"borrowed",
|
||||
"accumulated",
|
||||
"firstDelay",
|
||||
"walkFrom",
|
||||
] {
|
||||
let function = program
|
||||
.functions
|
||||
.iter()
|
||||
.find(|function| function.signature.source_name == format!("main.main.app.{name}"))
|
||||
.unwrap();
|
||||
assert!(
|
||||
function.effects.clock && function.effects.suspends,
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
for name in ["identity", "advance", "resolve", "measureText"] {
|
||||
let function = program
|
||||
.functions
|
||||
.iter()
|
||||
.find(|function| function.signature.source_name == format!("main.main.app.{name}"))
|
||||
.unwrap();
|
||||
assert!(function.effects.pure(), "{name}");
|
||||
}
|
||||
let now = program
|
||||
.functions
|
||||
.iter()
|
||||
.find(|function| function.signature.name == "dever.time.app.now")
|
||||
.unwrap();
|
||||
assert!(now.effects.clock && !now.effects.suspends);
|
||||
let generated = emit::emit(&program, &ownership::analyze(&program), &project.sources);
|
||||
let text = generated
|
||||
.values()
|
||||
.map(|file| file.text.as_str())
|
||||
.collect::<String>();
|
||||
assert!(text.contains("pub async fn d_4_main_4_main_3_app_5_delay"));
|
||||
assert!(text.contains("pub fn d_4_main_4_main_3_app_8_identity"));
|
||||
assert!(text.contains("pub async fn d_4_main_4_main_3_app_8_borrowed(v0: &str)"));
|
||||
assert!(!text.contains("tokio::spawn") && !text.contains("Box::pin"));
|
||||
let index = dever::compiler::inspect::analyze(&project, Some("main.main.app.handled"), 3, true)
|
||||
.unwrap();
|
||||
let data = serde_json::to_string(&index).unwrap();
|
||||
assert!(data.contains("挂起") && data.contains("transform = main.main.app.delay"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_effects_are_rejected_in_functions_arguments_guards_and_filters() {
|
||||
let prefix = r#"
|
||||
flow tick() (out: Bool)
|
||||
| step | kind | do |
|
||||
| - | flow | dever.time.sleep(0) |
|
||||
| out | calc | true |
|
||||
identity(value: Bool) (out: Bool) { out = value }
|
||||
type Attempt { Done, error Failed(value: dever.time.SleepResult) }
|
||||
rule finish(value: Attempt) (out: Bool) recover("report whether the delay was accepted")
|
||||
| value | out |
|
||||
| Done | true |
|
||||
| Failed(error) | false |
|
||||
flow safeTick() (out: Bool)
|
||||
| step | kind | do |
|
||||
| attempt: Attempt | flow | result(dever.time.sleep(0)) |
|
||||
| out | rule | finish(attempt) |
|
||||
|
||||
"#;
|
||||
let cases = [
|
||||
"bad() (out: Int) { out = dever.time.unixMillis() }",
|
||||
"bad() (out: Int) { out = dever.time.monotonicNanos() }",
|
||||
"bad() (out: Bool) { out = tick() }",
|
||||
"flow bad() (out: Bool)\n| step | kind | do |\n| out | calc | identity(tick()) |",
|
||||
"flow bad() (out: Bool)\n| step | kind | do |\n| out | calc | tick() and true |",
|
||||
"flow bad() ()\n| step | kind | do |\n| - | check | tick() else Invalid |",
|
||||
"flow bad() (out: List<Bool>)\n| step | kind | do |\n| out | calc | [tick()] |",
|
||||
"rule bad(value: Bool) (out: Bool)\n| value | out |\n| - | identity(tick()) |",
|
||||
"loop bad(values: List<Int>) (out: Int)\n| each value in values | safeTick() | result |\n| out | true | count |",
|
||||
"apply(work: handler() (out: Bool)) (out: Bool) { out = work() }\nflow bad() (out: Bool)\n| step | kind | do |\n| out | calc | apply(tick) |",
|
||||
"loop bad(values: List<Int>) (out: Int)\n| each value in values | safeTick() | result |\n| out | - | count |",
|
||||
];
|
||||
let root = directory("hidden-effects");
|
||||
let path = root.join("app.dever");
|
||||
for source in cases {
|
||||
fs::write(&path, format!("{prefix}\n{source}")).unwrap();
|
||||
let project = Project::load(&path).unwrap();
|
||||
assert!(
|
||||
project.diagnostics.is_empty(),
|
||||
"{:?}: {source}",
|
||||
project.diagnostics
|
||||
);
|
||||
let errors = program::analyze(&project.declarations, &project.modules).diagnostics;
|
||||
assert!(
|
||||
errors.iter().any(|error| error.code == "C013"),
|
||||
"{errors:?}: {source}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn domain_cannot_gain_clock_effects_through_standard_library_or_rule() {
|
||||
let root = directory("domain-effects");
|
||||
let domain = root.join("module/demo/time");
|
||||
fs::create_dir_all(&domain).unwrap();
|
||||
fs::write(
|
||||
domain.join("domain.dever"),
|
||||
"rule current(flag: Bool) (out: DateTime)\n| flag | out |\n| - | dever.time.now() |\n",
|
||||
)
|
||||
.unwrap();
|
||||
let project = Project::load(&root).unwrap();
|
||||
assert!(project.diagnostics.is_empty(), "{:?}", project.diagnostics);
|
||||
let errors = program::analyze(&project.declarations, &project.modules).diagnostics;
|
||||
assert!(
|
||||
errors.iter().any(|error| error.code == "C013"),
|
||||
"{errors:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn async_standalone_and_cmd_entries_execute_and_propagate_errors() {
|
||||
let root = directory("async-entries");
|
||||
let path = root.join("app.dever");
|
||||
fs::write(&path, "flow main() (out: Int)\n| step | kind | do |\n| - | flow | dever.time.sleep(1) |\n| out | calc | 42 |\n").unwrap();
|
||||
success(cli(&["fmt", path.to_str().unwrap()]));
|
||||
assert_eq!(success(cli(&["run", path.to_str().unwrap()])).trim(), "42");
|
||||
fs::write(&path, "flow pause(millis: Int) (out: Int)\n| step | kind | do |\n| - | flow | dever.time.sleep(millis) |\n| out | calc | millis |\ncmd pause = app.pause\n").unwrap();
|
||||
let (project, program) = analyze(&path);
|
||||
let artifact = build::build(&project, &program, "main", Profile::Dev, None).unwrap();
|
||||
let invoke = |value| {
|
||||
Command::new(&artifact.binary)
|
||||
.args(["main.main.pause", value])
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
let output = success(invoke(r#"{"millis":1}"#));
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(&output).unwrap()["data"],
|
||||
1
|
||||
);
|
||||
let output = invoke(r#"{"millis":-1}"#);
|
||||
assert!(!output.status.success() && output.stdout.is_empty());
|
||||
assert!(String::from_utf8_lossy(&output.stderr).contains("SleepResult.Failed"));
|
||||
}
|
||||
|
||||
mod blocking;
|
||||
mod channel;
|
||||
mod crypto;
|
||||
mod file;
|
||||
mod parallel;
|
||||
mod stream;
|
||||
mod task;
|
||||
@@ -0,0 +1,207 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn concurrent_loops_round_trip_bound_capacity_and_expose_cleanup() {
|
||||
let (project, _) = checked(
|
||||
include_str!("../../native/concurrent.dever"),
|
||||
"concurrent-loop",
|
||||
);
|
||||
let path = project.sources[0].path.to_str().unwrap();
|
||||
success(cli(&["fmt", path]));
|
||||
success(cli(&["fmt", path, "--check"]));
|
||||
let index = dever::compiler::inspect::analyze(&project, Some("main.main.app.ordered"), 1, true)
|
||||
.unwrap();
|
||||
let text = serde_json::to_string(&index).unwrap();
|
||||
for label in [
|
||||
"并发容量",
|
||||
"在途工作与待交付结果共用容量",
|
||||
"同一元素内逐行执行",
|
||||
"保留首个观察错误",
|
||||
"按输入顺序交付剩余结果",
|
||||
] {
|
||||
assert!(text.contains(label), "{label}");
|
||||
}
|
||||
let cases = [
|
||||
"loop bad(n: Int) (out: List<Int>)\n| each value in range(0, n) parallel n | result |\n| out | list value |",
|
||||
"loop bad() (out: List<Int>)\n| each value in [1] parallel 0 | result |\n| out | list value |",
|
||||
"loop bad() (out: List<Int>)\n| each value in [1] parallel 65537 | result |\n| out | list value |",
|
||||
"loop bad() (out: Int)\n| each value in [1] parallel 2 | result |\n| out | sum value |",
|
||||
"loop bad() (out: List<Int>)\n| each value in [1] parallel 2 | take | result |\n| out | 1 | list value |",
|
||||
"loop bad() (out: List<Int>)\n| each value in [1] parallel 2 | sort | result |\n| out | [value.asc] | list value |",
|
||||
"loop bad() (out: List<Int>)\n| each value in [1] parallel value | result |\n| out | list value |",
|
||||
"loop bad(file: dever.system.File) ()\n| each value in [1] parallel 2 | result |\n| - | do dever.io.close(file) |",
|
||||
"loop bad(values: Stream<Int>) (out: List<Int>)\n| each value in values parallel 2 | result |\n| out | list value |",
|
||||
];
|
||||
for (index, source) in cases.iter().enumerate() {
|
||||
let path = directory(&format!("invalid-concurrent-{index}")).join("app.dever");
|
||||
fs::write(&path, source).unwrap();
|
||||
let project = Project::load(&path).unwrap();
|
||||
assert!(
|
||||
project.diagnostics.is_empty(),
|
||||
"{index}: {:?}",
|
||||
project.diagnostics
|
||||
);
|
||||
assert!(
|
||||
!program::analyze(&project.declarations, &project.modules)
|
||||
.diagnostics
|
||||
.is_empty(),
|
||||
"{index}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catching_concurrent_failure_does_not_erase_cancelled_input_obligations() {
|
||||
let source = r#"
|
||||
type Attempt { Ok, error Bad }
|
||||
type Trouble { error Broken }
|
||||
type Caught { Done(values: List<Int>), error Failed(reason: Trouble) }
|
||||
rule resolve(value: Attempt) (out: Int) recover("report failure as -1")
|
||||
| value | out |
|
||||
| Ok | 1 |
|
||||
| Bad | -1 |
|
||||
flow work(value: Attempt, valid: Bool) (out: Int)
|
||||
| step | kind | do |
|
||||
| - | check | valid else Trouble.Broken |
|
||||
| out | rule | resolve(value) |
|
||||
loop jobs(values: List<Attempt>, valid: Bool) (out: List<Int>)
|
||||
| each value in values parallel 2 | result |
|
||||
| out | list work(value, valid) |
|
||||
flow forwarded(values: List<Attempt>, valid: Bool) (out: List<Int>)
|
||||
| step | kind | do |
|
||||
| out | loop | jobs(values, valid) |
|
||||
rule recoverCaught(value: Caught) (out: List<Int>) recover("report failed batch as empty")
|
||||
| value | out |
|
||||
| Done(values) | values |
|
||||
| Failed(reason) | [] |
|
||||
flow bad(values: List<Attempt>, valid: Bool) (out: List<Int>)
|
||||
| step | kind | do |
|
||||
| attempt: Caught | loop | result(jobs(values, valid)) |
|
||||
| out | rule | recoverCaught(attempt) |
|
||||
"#;
|
||||
for target in ["jobs", "forwarded"] {
|
||||
let source = source
|
||||
.replace(
|
||||
"result(jobs(values, valid))",
|
||||
&format!("result({target}(values, valid))"),
|
||||
)
|
||||
.replace(
|
||||
"| attempt: Caught | loop |",
|
||||
if target == "jobs" {
|
||||
"| attempt: Caught | loop |"
|
||||
} else {
|
||||
"| attempt: Caught | flow |"
|
||||
},
|
||||
);
|
||||
let path = directory(&format!("concurrent-cancelled-input-{target}")).join("app.dever");
|
||||
fs::write(&path, &source).unwrap();
|
||||
let project = Project::load(&path).unwrap();
|
||||
assert!(project.diagnostics.is_empty(), "{:?}", project.diagnostics);
|
||||
let errors = program::analyze(&project.declarations, &project.modules).diagnostics;
|
||||
assert!(
|
||||
errors
|
||||
.iter()
|
||||
.any(|error| error.code == "C012"
|
||||
&& error.message.contains("failure is not handled")),
|
||||
"{errors:?}"
|
||||
);
|
||||
let valid = source
|
||||
.replace("| attempt: Caught |", "| out | ")
|
||||
.split("| out | rule | recoverCaught")
|
||||
.next()
|
||||
.unwrap()
|
||||
.replace("result(jobs(values, valid))", "jobs(values, valid)")
|
||||
.replace(
|
||||
"result(forwarded(values, valid))",
|
||||
"forwarded(values, valid)",
|
||||
);
|
||||
checked(&valid, &format!("concurrent-propagated-input-{target}"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parallel_groups_round_trip_check_dependencies_and_expose_fork_join_cleanup() {
|
||||
let source = include_str!("../../native/parallel.dever").replace(
|
||||
"| left | flow | read | delayed(11, 5) |",
|
||||
"| left | - | read | delayed(11, 5) |",
|
||||
);
|
||||
let (project, program) = checked(&source, "parallel");
|
||||
let source = project.sources[0].path.to_str().unwrap();
|
||||
success(cli(&["fmt", source]));
|
||||
success(cli(&["fmt", source, "--check"]));
|
||||
let formatted = fs::read_to_string(source).unwrap();
|
||||
assert!(formatted.contains("parallel"));
|
||||
let row = formatted
|
||||
.lines()
|
||||
.find(|row| row.contains("delayed(11, 5)"))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
row.split('|').map(str::trim).collect::<Vec<_>>(),
|
||||
["", "left", "flow", "read", "delayed(11, 5)", ""]
|
||||
);
|
||||
let pure = program
|
||||
.functions
|
||||
.iter()
|
||||
.find(|f| f.signature.name.ends_with(".pureGroup"))
|
||||
.unwrap();
|
||||
assert!(pure.effects.pure());
|
||||
let generated = emit::emit(&program, &ownership::analyze(&program), &project.sources);
|
||||
let text = generated
|
||||
.values()
|
||||
.map(|file| file.text.as_str())
|
||||
.collect::<String>();
|
||||
assert!(text.contains("try_join!(biased;"));
|
||||
assert!(!text.contains("tokio::spawn") && !text.contains("Box::pin"));
|
||||
assert!(text.contains("pub fn d_4_main_4_main_3_app_9_pureGroup"));
|
||||
let index =
|
||||
dever::compiler::inspect::analyze(&project, Some("main.main.app.together"), 0, true)
|
||||
.unwrap();
|
||||
let data = serde_json::to_value(index).unwrap();
|
||||
let flow = &data["flows"][0];
|
||||
for label in [
|
||||
"并发组 read",
|
||||
"等待本组全部步骤成功",
|
||||
"取消其余步骤,等待资源释放",
|
||||
] {
|
||||
assert!(
|
||||
flow["nodes"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|node| node["label"] == label),
|
||||
"{label}"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
flow["edges"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|edge| edge["label"] == "并发推进")
|
||||
.count(),
|
||||
2
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parallel_rejects_single_split_guard_dependent_and_hidden_effect_steps() {
|
||||
let root = directory("parallel-errors");
|
||||
let path = root.join("app.dever");
|
||||
let prefix = "identity(value: Int) (out: Int) { out = value }\nflow delayed(value: Int) (out: Int)\n| step | kind | do |\n| - | flow | dever.time.sleep(1) |\n| out | calc | value |\n";
|
||||
for rows in [
|
||||
"| a | calc | group | identity(value) |\n| out | calc | - | a |",
|
||||
"| a | calc | group | identity(value) |\n| b | calc | group | identity(value) |\n| c | calc | - | a |\n| d | calc | group | identity(value) |\n| out | calc | group | identity(value) |",
|
||||
"| - | check | group | value != 0 else Invalid |\n| out | calc | group | identity(value) |",
|
||||
"| a | calc | group | identity(value) |\n| out | calc | group | identity(a) |",
|
||||
"| a | calc | group | identity(delayed(value)) |\n| out | calc | group | identity(value) |",
|
||||
] {
|
||||
fs::write(&path, format!("{prefix}\nflow bad(value: Int) (out: Int)\n| step | kind | parallel | do |\n{rows}\n")).unwrap();
|
||||
let project = Project::load(&path).unwrap();
|
||||
assert!(project.diagnostics.is_empty(), "{:?}", project.diagnostics);
|
||||
let errors = program::analyze(&project.declarations, &project.modules).diagnostics;
|
||||
assert!(
|
||||
errors.iter().any(|error| error.code == "C013"),
|
||||
"{errors:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn synchronous_streams_preserve_lazy_errors_and_show_source_cleanup() {
|
||||
let (project, program) = checked(
|
||||
include_str!("../../native/sync_stream.dever"),
|
||||
"sync-stream-effects",
|
||||
);
|
||||
let first = program
|
||||
.functions
|
||||
.iter()
|
||||
.find(|f| f.signature.name == "main.main.app.first")
|
||||
.unwrap();
|
||||
assert!(
|
||||
first.effects.blocking
|
||||
&& first.effects.file
|
||||
&& first.effects.stream
|
||||
&& !first.effects.suspends
|
||||
);
|
||||
let path = project.sources[0].path.to_str().unwrap();
|
||||
success(cli(&["fmt", path]));
|
||||
success(cli(&["fmt", path, "--check"]));
|
||||
let index =
|
||||
dever::compiler::inspect::analyze(&project, Some("main.main.app.first"), 1, true).unwrap();
|
||||
let text = serde_json::to_string(&index).unwrap();
|
||||
for expected in [
|
||||
"同步拉取文件流的下一元素",
|
||||
"关闭来源流,保留外部文件",
|
||||
"同一次拉取分发给各行",
|
||||
] {
|
||||
assert!(text.contains(expected), "{expected}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn synchronous_streams_cannot_cross_task_or_suspension_boundaries_or_discard_read_errors() {
|
||||
let cases = [
|
||||
"loop bad(values: Stream<dever.io.ReadEvent>) (out: Int)\n| each value in values | result |\n| out | count |",
|
||||
"flow bad(file: dever.system.File) (out: Stream<dever.io.ReadEvent>)\n| step | kind | do |\n| out | calc | blocking(dever.io.chunks(file, 2)) |",
|
||||
"flow consume(values: Stream<dever.io.ReadEvent>) ()\n| step | kind | do |\n| - | calc | close(values) |\nflow bad(values: Stream<dever.io.ReadEvent>) ()\n| step | kind | do |\n| task | calc | run(consume(values)) |\n| - | calc | wait(task) |",
|
||||
"flow bad(values: Stream<dever.io.ReadEvent>) ()\n| step | kind | do |\n| - | flow | dever.time.sleep(1) |\n| - | calc | close(values) |",
|
||||
"type Box { values: Stream<Int> }\nflow bad(box: Box) ()\n| step | kind | do |\n| - | flow | dever.time.sleep(1) |",
|
||||
"type Box { values: Stream<Int> }\nflow bad() (out: Channel<Box>)\n| step | kind | do |\n| out | calc | channel<Box>(2) |",
|
||||
"flow bad(values: List<Stream<Int>>) (out: AsyncStream<Stream<Int>>)\n| step | kind | do |\n| out | calc | stream(values) |",
|
||||
"flow bad(file: dever.system.File) (out: Stream<dever.io.ReadEvent>)\n| step | kind | do |\n| out | flow | dever.io.chunks(file, 2) |\ncmd bad = bad",
|
||||
];
|
||||
for (index, source) in cases.iter().enumerate() {
|
||||
let path = directory(&format!("invalid-sync-stream-{index}")).join("app.dever");
|
||||
fs::write(&path, source).unwrap();
|
||||
let project = Project::load(&path).unwrap();
|
||||
assert!(project.diagnostics.is_empty(), "{:?}", project.diagnostics);
|
||||
let errors = program::analyze(&project.declarations, &project.modules).diagnostics;
|
||||
assert!(!errors.is_empty(), "{index}: {source}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn streams_reject_hidden_operations_error_discard_and_wire_escape() {
|
||||
let cases = [
|
||||
"bad() (out: AsyncStream<Int>) { out = stream([1]) }",
|
||||
"flow bad() (out: AsyncStream<Int>)\n| step | kind | do |\n| out | calc | stream(1) |",
|
||||
"flow bad() (out: AsyncStream<Int>)\n| step | kind | do |\n| out | calc | stream([]) |\ncmd bad = bad",
|
||||
"bad(a: AsyncStream<Int>, b: AsyncStream<Int>) (out: Bool) { out = a == b }",
|
||||
"type Box { values: AsyncStream<Int> }\nbad(a: Box, b: Box) (out: Bool) { out = a == b }",
|
||||
"flow bad() (out: AsyncStream<Int>)\n| step | kind | do |\n| out | calc | dever.system.taskTicks(1) |",
|
||||
"type Attempt { Ok, error Bad }\nflow bad(values: AsyncStream<Attempt>) ()\n| step | kind | do |\n| - | calc | close(values) |",
|
||||
"type Attempt { Ok, error Bad }\nloop bad(values: AsyncStream<Attempt>) (out: Int)\n| each value in values | result |\n| out | count |",
|
||||
"type Attempt { Ok, error Bad }\nloop bad(values: AsyncStream<Attempt>) (out: Attempt?)\n| each value in values | result |\n| out | first value |",
|
||||
"type Attempt { Ok, error Bad }\nflow bad() ()\n| step | kind | do |\n| values | calc | stream([Attempt.Bad]) |\n| - | calc | close(values) |",
|
||||
];
|
||||
for (index, source) in cases.iter().enumerate() {
|
||||
let path = directory(&format!("stream-invalid-{index}")).join("app.dever");
|
||||
fs::write(&path, source).unwrap();
|
||||
let project = Project::load(&path).unwrap();
|
||||
assert!(
|
||||
project.diagnostics.is_empty(),
|
||||
"{index}: {:?}",
|
||||
project.diagnostics
|
||||
);
|
||||
let error = program::check(&project.declarations, &project.modules)
|
||||
.err()
|
||||
.expect(source);
|
||||
assert!(
|
||||
matches!(error.code, "C003" | "C005" | "C012" | "C013" | "C014"),
|
||||
"{index}: {error:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn streams_preserve_one_loop_source_and_show_cleanup_and_tick_navigation() {
|
||||
let (project, program) = checked(include_str!("../../native/stream.dever"), "stream-docs");
|
||||
let entry = program
|
||||
.functions
|
||||
.iter()
|
||||
.find(|f| f.signature.source_name.ends_with(".summary"))
|
||||
.unwrap();
|
||||
assert!(entry.effects.stream && entry.effects.suspends && !entry.effects.tasks);
|
||||
let ticks = program
|
||||
.functions
|
||||
.iter()
|
||||
.find(|f| f.signature.name == "dever.task.app.ticks")
|
||||
.unwrap();
|
||||
assert!(ticks.effects.stream && ticks.effects.clock && !ticks.effects.suspends);
|
||||
let path = project.sources[0].path.to_str().unwrap();
|
||||
success(cli(&["fmt", path]));
|
||||
success(cli(&["fmt", path, "--check"]));
|
||||
success(cli(&["check", path]));
|
||||
let index = dever::compiler::inspect::analyze(&project, Some("main.main.app.summary"), 1, true)
|
||||
.unwrap();
|
||||
let text = serde_json::to_string(&index).unwrap();
|
||||
for expected in [
|
||||
"挂起拉取流的下一元素",
|
||||
"同一次拉取分发给各行",
|
||||
"关闭来源流",
|
||||
"取消或运行故障",
|
||||
] {
|
||||
assert!(text.contains(expected), "{expected}");
|
||||
}
|
||||
let source = "type Attempt { Ok(value: Int), error Bad }\nrule handle(value: Attempt) (out: Int) recover(\"record rejected elements\")\n| value | out |\n| Ok(n) | n |\n| Bad | 0 |\nloop handled(values: AsyncStream<Attempt>) (out: Int)\n| each value in values | result |\n| out | sum handle(value) |\n";
|
||||
checked(source, "stream-recovery");
|
||||
}
|
||||
@@ -0,0 +1,403 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn task_handles_are_affine_and_scheduling_is_explicit() {
|
||||
let prefix = "identity(value: Int) (out: Int) { out = value }\nnoop() () {}\n";
|
||||
let cases = [
|
||||
"flow bad() ()\n| step | kind | do |\n| t | calc | run(noop()) |",
|
||||
"flow bad() ()\n| step | kind | do |\n| t | calc | run(noop()) |\n| - | calc | wait(t) |\n| - | calc | stop(t) |",
|
||||
"flow bad() ()\n| step | kind | do |\n| t | calc | run(noop()) |\n| alias | calc | t |\n| - | calc | wait(t) |",
|
||||
"flow bad() ()\n| step | kind | do |\n| t | calc | run(noop()) |\n| list | calc | [t] |\n| - | calc | wait(t) |",
|
||||
"flow bad() ()\n| step | kind | do |\n| t | calc | run(identity(1)) |\n| - | calc | stop(t) |",
|
||||
"flow bad() (out: Int)\n| step | kind | do |\n| t | calc | run(identity(1)) |\n| out | calc | identity(wait(t)) |",
|
||||
"bad() () { t = run(noop())\nwait(t) }",
|
||||
"rule bad(value: Int) (out: Int)\n| value | out |\n| - | wait(run(identity(value))) |",
|
||||
"flow bad() ()\n| step | kind | parallel | do |\n| t | calc | - | run(noop()) |\n| - | calc | join | wait(t) |\n| - | calc | join | stop(t) |",
|
||||
"flow bad() ()\n| step | kind | do |\n| - | calc | run(noop()) |",
|
||||
"flow bad() ()\n| step | kind | do |\n| t | calc | run(length([1])) |",
|
||||
"flow bad() ()\n| step | kind | do |\n| t | calc | run(noop()) |\n| n | calc | identity(t) |\n| - | calc | wait(t) |",
|
||||
"flow bad() ()\n| step | kind | do |\n| t: Task | calc | run(noop()) |\n| - | calc | wait(t) |",
|
||||
];
|
||||
for (index, source) in cases.iter().enumerate() {
|
||||
let root = directory(&format!("task-invalid-{index}"));
|
||||
let path = root.join("app.dever");
|
||||
fs::write(&path, format!("{prefix}{source}\n")).unwrap();
|
||||
let project = Project::load(&path).unwrap();
|
||||
assert!(
|
||||
project.diagnostics.is_empty(),
|
||||
"{index}: {:?}",
|
||||
project.diagnostics
|
||||
);
|
||||
let error = program::check(&project.declarations, &project.modules)
|
||||
.err()
|
||||
.expect(source);
|
||||
assert!(
|
||||
matches!(error.code, "C004" | "C005" | "C014"),
|
||||
"{index}: {error:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn task_outputs_keep_nominal_error_obligations() {
|
||||
let source = r#"
|
||||
type Outcome { Done, error Failed }
|
||||
rule choose(value: Bool) (out: Outcome)
|
||||
| value | out |
|
||||
| true | Done |
|
||||
| false | Failed |
|
||||
flow bad(value: Bool) (out: Int)
|
||||
| step | kind | do |
|
||||
| t | calc | run(choose(value)) |
|
||||
| received | calc | wait(t) |
|
||||
| out | calc | 1 |
|
||||
"#;
|
||||
let root = directory("task-obligation");
|
||||
let path = root.join("app.dever");
|
||||
fs::write(&path, source).unwrap();
|
||||
let project = Project::load(&path).unwrap();
|
||||
let error = program::check(&project.declarations, &project.modules)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(error.code, "C012", "{error:?}");
|
||||
|
||||
let source = r#"
|
||||
type Outcome { Done, error Failed }
|
||||
noop() () {}
|
||||
rule consume(value: Outcome) () recover("explicitly acknowledge the input failure")
|
||||
| value | do |
|
||||
| Done | noop() |
|
||||
| Failed | noop() |
|
||||
flow cancel(value: Outcome) ()
|
||||
| step | kind | do |
|
||||
| task | calc | run(consume(value)) |
|
||||
| - | calc | stop(task) |
|
||||
"#;
|
||||
fs::write(&path, source).unwrap();
|
||||
let project = Project::load(&path).unwrap();
|
||||
assert!(project.diagnostics.is_empty());
|
||||
let error = program::check(&project.declarations, &project.modules)
|
||||
.err()
|
||||
.expect("stop may cancel before input recovery executes");
|
||||
assert_eq!(error.code, "C012", "{error:?}");
|
||||
fs::write(&path, source.replace("stop(task)", "wait(task)")).unwrap();
|
||||
let project = Project::load(&path).unwrap();
|
||||
program::check(&project.declarations, &project.modules).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn task_program_formats_navigates_and_runs_real_command_entry() {
|
||||
let source = include_str!("../../native/spawn.dever")
|
||||
.lines()
|
||||
.filter(|line| !line.starts_with("cmd "))
|
||||
.collect::<Vec<_>>()
|
||||
.join(
|
||||
"
|
||||
",
|
||||
);
|
||||
let (project, _) = checked(&source, "task-entry");
|
||||
let path = project.sources[0].path.to_str().unwrap();
|
||||
success(cli(&["fmt", path]));
|
||||
success(cli(&["fmt", path, "--check"]));
|
||||
let output = success(cli(&["run", path]));
|
||||
assert_eq!(output.trim(), "42");
|
||||
let index =
|
||||
dever::compiler::inspect::analyze(&project, Some("main.main.app.main"), 1, true).unwrap();
|
||||
let text = serde_json::to_string(&index).unwrap();
|
||||
assert!(text.contains("派生任务") && text.contains("消费任务"));
|
||||
let commands = format!(
|
||||
"{}\n{}",
|
||||
include_str!("../../native/spawn.dever"),
|
||||
r#"
|
||||
type PrivateFailure { error Rejected(detail: Text) }
|
||||
reject(detail: Text) () { fail(PrivateFailure.Rejected(detail)) }
|
||||
flow rejected(detail: Text) ()
|
||||
| step | kind | do |
|
||||
| tasks | calc | group(1) |
|
||||
| - | calc | run(tasks, reject(detail)) |
|
||||
| - | calc | wait(tasks) |
|
||||
cmd rejected = rejected
|
||||
denied(value: Int) () {
|
||||
check value > 0 else Forbidden
|
||||
}
|
||||
cmd denied = denied
|
||||
"#
|
||||
);
|
||||
fs::write(path, commands).unwrap();
|
||||
let (project, program) = analyze(&project.sources[0].path);
|
||||
let decisions = ownership::analyze(&program);
|
||||
let mut generated = emit::emit(&program, &decisions, &project.sources);
|
||||
generated
|
||||
.get_mut("main.rs")
|
||||
.unwrap()
|
||||
.text
|
||||
.push_str(&emit::application::emit(&program, &decisions));
|
||||
let artifact = build::compile(
|
||||
&project.root,
|
||||
&program,
|
||||
&generated,
|
||||
Profile::Dev,
|
||||
&project,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let binary = project.sources[0].path.parent().unwrap().join("commands");
|
||||
artifact.publish(&binary).unwrap();
|
||||
drop(artifact);
|
||||
let output = Command::new(&binary)
|
||||
.args(["main.main.main", "{}"])
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(success(output).contains("42"));
|
||||
let output = Command::new(&binary)
|
||||
.args(["main.main.overflow", r#"{"value":9223372036854775807}"#])
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(!output.status.success() && output.stdout.is_empty());
|
||||
assert!(String::from_utf8_lossy(&output.stderr).contains("arithmetic fault"));
|
||||
let output = Command::new(&binary)
|
||||
.args(["main.main.rejected", r#"{"detail":"private-value"}"#])
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(!output.status.success() && output.stdout.is_empty());
|
||||
assert_eq!(
|
||||
String::from_utf8(output.stderr).unwrap().trim(),
|
||||
"main.main.app.PrivateFailure.Rejected"
|
||||
);
|
||||
let output = Command::new(&binary)
|
||||
.args(["main.main.denied", r#"{"value":0}"#])
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(!output.status.success() && output.stdout.is_empty());
|
||||
assert_eq!(
|
||||
String::from_utf8(output.stderr).unwrap().trim(),
|
||||
"Forbidden"
|
||||
);
|
||||
fs::write(path, "identity(value: Int) (out: Int) { out = value }\nflow main() (out: Int)\n| step | kind | do |\n| t | calc | run(identity(42)) |\n| out | calc | wait(t) |\n").unwrap();
|
||||
success(cli(&["fmt", path]));
|
||||
assert_eq!(success(cli(&["run", path])).trim(), "42");
|
||||
let (project, program) = checked(
|
||||
"setting label: Text\nidentity(value: Int) (out: Int) { out = value }\nflow main() (out: Int)\n| step | kind | do |\n| t | calc | run(identity(42)) |\n| received | calc | wait(t) |\n| out | calc | received + length(label) |\n",
|
||||
"task-local-settings",
|
||||
);
|
||||
let generated = emit::emit(&program, &ownership::analyze(&program), &project.sources);
|
||||
assert!(
|
||||
!generated["wire.rs"].text.contains("Arc<SettingValues>"),
|
||||
"settings used only by the caller need no shared allocation"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn combinations_reject_aliases_contract_mismatches_and_overlapping_groups() {
|
||||
let prefix = "identity(value: Int) (out: Int) { out = value }\nfallback() (out: Int) { out = 1 }\nother() (different: Int) { different = 1 }\nnoop() () {}\n";
|
||||
let cases = [
|
||||
"| t | calc | run(identity(1)) |\n| out | calc | race(t, t) |",
|
||||
"| out | calc | race(run(identity(1))) |",
|
||||
"| out | calc | timeout(run(identity(1)), 1, identity) |",
|
||||
"| out | calc | timeout(run(identity(1)), 1, other) |",
|
||||
"| out | calc | race(run(identity(1)), run(other())) |",
|
||||
"| g | calc | group(1) |\n| - | calc | run(g, identity(1)) |\n| - | calc | wait(g) |\n| out | calc | 1 |",
|
||||
"| g | calc | group(1) |\n| alias | calc | g |\n| - | calc | wait(g) |\n| out | calc | 1 |",
|
||||
"| g | calc | group(1) |\n| - | calc | wait(g) |\n| - | calc | run(g, noop()) |\n| out | calc | 1 |",
|
||||
"| g | calc | group(1) |\n| out | calc | 1 |",
|
||||
];
|
||||
for (index, body) in cases.iter().enumerate() {
|
||||
let root = directory(&format!("combination-invalid-{index}"));
|
||||
let path = root.join("app.dever");
|
||||
fs::write(
|
||||
&path,
|
||||
format!("{prefix}flow bad() (out: Int)\n| step | kind | do |\n{body}\n"),
|
||||
)
|
||||
.unwrap();
|
||||
let project = Project::load(&path).unwrap();
|
||||
assert!(project.diagnostics.is_empty(), "{:?}", project.diagnostics);
|
||||
let error = program::check(&project.declarations, &project.modules)
|
||||
.err()
|
||||
.expect(body);
|
||||
assert_eq!(error.code, "C014", "{index}: {error:?}");
|
||||
}
|
||||
let source = format!(
|
||||
"{prefix}flow bad() ()\n| step | kind | parallel | do |\n| g | calc | - | group(2) |\n| - | calc | both | run(g, noop()) |\n| - | calc | both | run(g, noop()) |\n| - | calc | - | wait(g) |\n"
|
||||
);
|
||||
let path = directory("group-overlap").join("app.dever");
|
||||
fs::write(&path, source).unwrap();
|
||||
let project = Project::load(&path).unwrap();
|
||||
assert_eq!(
|
||||
program::check(&project.declarations, &project.modules)
|
||||
.err()
|
||||
.unwrap()
|
||||
.code,
|
||||
"C014"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn combinations_only_discharge_errors_on_proven_completed_paths() {
|
||||
let prefix = r#"
|
||||
type Outcome { Done, error Failed }
|
||||
noop() () {}
|
||||
rule consume(value: Outcome) () recover("acknowledge an input failure")
|
||||
| value | do |
|
||||
| Done | noop() |
|
||||
| Failed | noop() |
|
||||
"#;
|
||||
let cases = [
|
||||
(
|
||||
"| - | calc | timeout(run(consume(value)), 1, noop) |",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"| - | calc | race(run(consume(value)), run(noop())) |",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"| - | calc | race(run(consume(value)), run(consume(value))) |",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"| g | calc | group(1) |\n| - | calc | run(g, consume(value)) |\n| - | calc | stop(g) |",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"| g | calc | group(1) |\n| - | calc | run(g, consume(value)) |\n| - | calc | wait(g) |",
|
||||
true,
|
||||
),
|
||||
("| - | calc | wait(run(consume(value))) |", true),
|
||||
("| - | calc | parallel(consume(value)) |", true),
|
||||
];
|
||||
for (index, (body, valid)) in cases.iter().enumerate() {
|
||||
let path = directory(&format!("combination-obligation-{index}")).join("app.dever");
|
||||
fs::write(
|
||||
&path,
|
||||
format!("{prefix}flow handle(value: Outcome) ()\n| step | kind | do |\n{body}\n"),
|
||||
)
|
||||
.unwrap();
|
||||
let project = Project::load(&path).unwrap();
|
||||
assert!(project.diagnostics.is_empty(), "{:?}", project.diagnostics);
|
||||
let result = program::check(&project.declarations, &project.modules);
|
||||
if *valid {
|
||||
result.unwrap();
|
||||
} else {
|
||||
assert_eq!(result.err().expect(body).code, "C012");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn combinations_format_and_inspect_checked_task_workflows() {
|
||||
let (project, _) = checked(
|
||||
include_str!("../../native/combinations.dever"),
|
||||
"combination-docs",
|
||||
);
|
||||
let path = project.sources[0].path.to_str().unwrap();
|
||||
success(cli(&["fmt", path]));
|
||||
success(cli(&["fmt", path, "--check"]));
|
||||
let index = dever::compiler::inspect::analyze(&project, None, 1, true).unwrap();
|
||||
let text = serde_json::to_string(&index).unwrap();
|
||||
for label in ["限时等待", "首个就绪结果", "等待组内空位", "消费任务"] {
|
||||
assert!(text.contains(label), "missing {label}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn captured_combination_failure_cannot_erase_cancelled_input_obligations() {
|
||||
let prefix = r#"
|
||||
type Outcome { Done, error Failed }
|
||||
type Problem { error Invalid }
|
||||
type Captured { Done, error Failed(reason: Problem) }
|
||||
noop() () {}
|
||||
failNow() () { fail(Problem.Invalid) }
|
||||
rule consume(value: Outcome) () recover("acknowledge this input")
|
||||
| value | do |
|
||||
| Done | noop() |
|
||||
| Failed | noop() |
|
||||
rule acknowledge(value: Captured) () recover("acknowledge the combination failure only")
|
||||
| value | do |
|
||||
| Done | noop() |
|
||||
| Failed(reason) | noop() |
|
||||
"#;
|
||||
for (index, steps) in [
|
||||
"| result: Captured | calc | result(race(run(consume(value)), run(failNow()))) |",
|
||||
"| result: Captured | calc | result(timeout(run(consume(value)), 1, failNow)) |",
|
||||
"| g | calc | group(2) |\n| - | calc | run(g, consume(value)) |\n| - | calc | run(g, failNow()) |\n| result: Captured | calc | result(wait(g)) |",
|
||||
].iter().enumerate() {
|
||||
let path = directory(&format!("captured-combination-input-{index}")).join("app.dever");
|
||||
fs::write(&path, format!("{prefix}flow bad(value: Outcome) ()\n| step | kind | do |\n{steps}\n| - | rule | acknowledge(result) |\n")).unwrap();
|
||||
let project = Project::load(&path).unwrap();
|
||||
assert!(project.diagnostics.is_empty(), "{:?}", project.diagnostics);
|
||||
assert_eq!(program::check(&project.declarations, &project.modules).err().expect(steps).code, "C012");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cpu_parallel_rejects_effectful_targets_hidden_calls_and_task_consumption() {
|
||||
let prefix = r#"
|
||||
identity(value: Int) (out: Int) { out = value }
|
||||
flow clock() (out: DateTime)
|
||||
| step | kind | do |
|
||||
| out | flow | dever.time.now() |
|
||||
flow waiting() ()
|
||||
| step | kind | do |
|
||||
| - | flow | dever.time.sleep(0) |
|
||||
flow taskWork() (out: Int)
|
||||
| step | kind | do |
|
||||
| t | calc | run(identity(1)) |
|
||||
| out | calc | wait(t) |
|
||||
"#;
|
||||
let cases = [
|
||||
"flow bad() (out: DateTime)\n| step | kind | do |\n| out | calc | parallel(clock()) |",
|
||||
"flow bad() ()\n| step | kind | do |\n| - | calc | parallel(waiting()) |",
|
||||
"flow bad() (out: Int)\n| step | kind | do |\n| out | calc | parallel(taskWork()) |",
|
||||
"bad() (out: Int) { out = parallel(identity(1)) }",
|
||||
"flow bad() (out: Int)\n| step | kind | do |\n| out | calc | identity(parallel(identity(1))) |",
|
||||
"flow bad() (out: Int)\n| step | kind | do |\n| out | calc | wait(parallel(identity(1))) |",
|
||||
"flow apply(action: handler() ()) ()\n| step | kind | do |\n| - | calc | parallel(action()) |\nflow bad() ()\n| step | kind | do |\n| - | flow | apply(waiting) |",
|
||||
];
|
||||
for (index, source) in cases.iter().enumerate() {
|
||||
let path = directory(&format!("worker-invalid-{index}")).join("app.dever");
|
||||
fs::write(&path, format!("{prefix}{source}\n")).unwrap();
|
||||
let project = Project::load(&path).unwrap();
|
||||
assert!(project.diagnostics.is_empty(), "{:?}", project.diagnostics);
|
||||
let error = program::check(&project.declarations, &project.modules)
|
||||
.err()
|
||||
.expect(source);
|
||||
assert!(matches!(error.code, "C013" | "C014"), "{index}: {error:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cpu_parallel_preserves_ranges_and_nominal_error_obligations() {
|
||||
let path = directory("worker-infallible-capture").join("app.dever");
|
||||
fs::write(&path, "type Problem { error Invalid }\ntype Attempt { Done(value: Int), error Failed(reason: Problem) }\nidentity(value: Int) (out: Int) { out = value }\nflow bad() (out: Attempt)\n| step | kind | do |\n| out | calc | result(parallel(identity(1))) |\n").unwrap();
|
||||
let project = Project::load(&path).unwrap();
|
||||
assert!(project.diagnostics.is_empty());
|
||||
let error = program::check(&project.declarations, &project.modules)
|
||||
.err()
|
||||
.expect("infallible call needs no recovery");
|
||||
assert_eq!(error.code, "C012");
|
||||
assert_eq!(error.message, "result on an infallible call is redundant");
|
||||
checked(
|
||||
"positive() (out: Int >= 1) { out = 1 }\nflow main() (out: Int >= 1)\n| step | kind | do |\n| out | calc | parallel(positive()) |\n",
|
||||
"worker-range",
|
||||
);
|
||||
let source = "type Outcome { Done, error Failed }\nrule choose(value: Bool) (out: Outcome)\n| value | out |\n| true | Done |\n| false | Failed |\nflow bad(value: Bool) (out: Int)\n| step | kind | do |\n| received | calc | parallel(choose(value)) |\n| out | calc | 1 |\n";
|
||||
let path = directory("worker-output-obligation").join("app.dever");
|
||||
fs::write(&path, source).unwrap();
|
||||
let project = Project::load(&path).unwrap();
|
||||
assert_eq!(
|
||||
program::check(&project.declarations, &project.modules)
|
||||
.err()
|
||||
.unwrap()
|
||||
.code,
|
||||
"C012"
|
||||
);
|
||||
let (project, _) = checked(include_str!("../../native/worker.dever"), "worker-docs");
|
||||
let path = project.sources[0].path.to_str().unwrap();
|
||||
success(cli(&["fmt", path]));
|
||||
success(cli(&["fmt", path, "--check"]));
|
||||
let index =
|
||||
dever::compiler::inspect::analyze(&project, Some("main.main.app.together"), 1, true)
|
||||
.unwrap();
|
||||
let text = serde_json::to_string(&index).unwrap();
|
||||
assert!(text.contains("线程池执行纯计算") && text.contains("main.main.app.pair"));
|
||||
}
|
||||
@@ -0,0 +1,408 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn flow_formatting_resolves_kinds_and_navigation_uses_the_same_steps() {
|
||||
let root = directory("flow-kinds");
|
||||
let path = root.join("main.dever");
|
||||
let source = "rule fee(remote: Bool) (amount: Int)\n| remote | amount |\n| true | 15 |\n| false | 8 |\nflow quote(remote: Bool, count: Int) (total: Int)\n| step | kind | do |\n| - | - | count > 0 else Invalid |\n| amount | - | fee(remote) |\n| total | - | amount * count |\nflow main() (out: Int)\n| step | kind | do |\n| out | - | quote(false, 2) |\n";
|
||||
fs::write(&path, source).unwrap();
|
||||
let file = path.to_str().unwrap();
|
||||
success(cli(&["fmt", file]));
|
||||
let formatted = fs::read_to_string(&path).unwrap();
|
||||
success(cli(&["fmt", file, "--check"]));
|
||||
assert_eq!(formatted, fs::read_to_string(&path).unwrap());
|
||||
success(cli(&["check", file]));
|
||||
assert_eq!(success(cli(&["run", file])).trim(), "16");
|
||||
let index: serde_json::Value = serde_json::from_str(&success(cli(&[
|
||||
"inspect",
|
||||
file,
|
||||
"--json",
|
||||
"--symbol",
|
||||
"main.main.app.quote",
|
||||
"--depth",
|
||||
"0",
|
||||
])))
|
||||
.unwrap();
|
||||
assert_eq!(index["symbols"][0]["kind"], "flow");
|
||||
let nodes = index["flows"][0]["nodes"].as_array().unwrap();
|
||||
assert!(
|
||||
nodes
|
||||
.iter()
|
||||
.any(|node| node["label"] == "rule · amount = fee(remote)")
|
||||
);
|
||||
assert!(nodes.iter().any(|node| node["label"] == "传播原错误"));
|
||||
assert!(
|
||||
nodes
|
||||
.iter()
|
||||
.any(|node| node["target"] == "main.main.app.fee")
|
||||
);
|
||||
let invalid = source.replace("fee(remote)", "missing(remote)");
|
||||
fs::write(&path, &invalid).unwrap();
|
||||
assert!(!cli(&["fmt", file]).status.success());
|
||||
assert_eq!(
|
||||
fs::read_to_string(&path).unwrap(),
|
||||
invalid,
|
||||
"unknown targets must not be filled as calc"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn workflow_follows_argument_order_rule_branches_and_short_circuiting() {
|
||||
let root = directory("workflow");
|
||||
let path = root.join("app.dever");
|
||||
fs::write(
|
||||
&path,
|
||||
r#"first() (n: Int) { n = 2 }
|
||||
guarded(value: Int) (n: Int) { check value >= 1 else Invalid
|
||||
n = value }
|
||||
nested() (n: Int) { n = guarded(first()) }
|
||||
positive(value: Int) (ok: Bool) { ok = guarded(value) >= 1 }
|
||||
short(flag: Bool, value: Int) (ok: Bool) { ok = flag and positive(value) }
|
||||
rule choose(flag: Bool, value: Int) (out: Int)
|
||||
| flag | value | out |
|
||||
| true | - | guarded(value) |
|
||||
| false | - | 0 |
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
let load = |name: &str| -> serde_json::Value {
|
||||
serde_json::from_str(&success(cli(&[
|
||||
"inspect",
|
||||
path.to_str().unwrap(),
|
||||
"--json",
|
||||
"--symbol",
|
||||
name,
|
||||
"--depth",
|
||||
"0",
|
||||
])))
|
||||
.unwrap()
|
||||
};
|
||||
let nested = load("main.main.app.nested");
|
||||
let targets = nested["flows"][0]["nodes"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter_map(|node| node["target"].as_str())
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(targets, ["main.main.app.first", "main.main.app.guarded"]);
|
||||
let choice = load("main.main.app.choose");
|
||||
let flow = &choice["flows"][0];
|
||||
let nodes = flow["nodes"].as_array().unwrap();
|
||||
let edges = flow["edges"].as_array().unwrap();
|
||||
let branch = nodes
|
||||
.iter()
|
||||
.position(|node| node["kind"] == "branch")
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
edges.iter().filter(|edge| edge["from"] == branch).count(),
|
||||
2
|
||||
);
|
||||
assert!(nodes.iter().any(|node| node["label"] == "flag: true"));
|
||||
assert!(nodes.iter().any(|node| node["label"] == "flag: false"));
|
||||
assert!(nodes.iter().any(|node| node["label"] == "传播原错误"));
|
||||
let short = load("main.main.app.short");
|
||||
let flow = &short["flows"][0];
|
||||
let nodes = flow["nodes"].as_array().unwrap();
|
||||
let branch = nodes
|
||||
.iter()
|
||||
.position(|node| node["kind"] == "branch")
|
||||
.unwrap();
|
||||
let alternatives = flow["edges"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|edge| edge["from"] == branch)
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(alternatives.len(), 2);
|
||||
let skipped = alternatives
|
||||
.iter()
|
||||
.find(|edge| edge["label"] == "不成立,短路")
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
nodes[skipped["to"].as_u64().unwrap() as usize]["label"],
|
||||
"布尔结果"
|
||||
);
|
||||
assert!(
|
||||
nodes
|
||||
.iter()
|
||||
.any(|node| node["target"] == "main.main.app.positive")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inspect_uses_checked_calls_and_utf16_positions_without_cargo() {
|
||||
let root = directory("inspect");
|
||||
let path = root.join("app.dever");
|
||||
let source = "sink(text: Text, value: Int) (n: Int) { n = value }\nhelper() (n: Int) { n = 3 }\nmain() (n: Int) { n = sink(\"😀\", helper()) }";
|
||||
fs::write(&path, source).unwrap();
|
||||
let output = Command::new(env!("CARGO_BIN_EXE_dever"))
|
||||
.args(["inspect", path.to_str().unwrap(), "--json"])
|
||||
.env("PATH", "")
|
||||
.output()
|
||||
.unwrap();
|
||||
let index: serde_json::Value = serde_json::from_str(&success(output)).unwrap();
|
||||
assert_eq!(index["symbols"].as_array().unwrap().len(), 3);
|
||||
assert_eq!(index["calls"].as_array().unwrap().len(), 2);
|
||||
let helper = index["calls"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|call| call["callee"] == 1)
|
||||
.unwrap();
|
||||
assert_eq!(helper["site"][1], 2);
|
||||
let column = source
|
||||
.lines()
|
||||
.nth(2)
|
||||
.unwrap()
|
||||
.split("helper")
|
||||
.next()
|
||||
.unwrap()
|
||||
.encode_utf16()
|
||||
.count();
|
||||
assert_eq!(helper["site"][2], column);
|
||||
let before = index["files"][0]["sha256"].clone();
|
||||
fs::write(&path, source.replace("n = 3", "n = 4")).unwrap();
|
||||
let index: serde_json::Value = serde_json::from_str(&success(cli(&[
|
||||
"inspect",
|
||||
path.to_str().unwrap(),
|
||||
"--json",
|
||||
"--symbol",
|
||||
"main.main.app.helper",
|
||||
"--depth",
|
||||
"1",
|
||||
])))
|
||||
.unwrap();
|
||||
assert_ne!(index["files"][0]["sha256"], before);
|
||||
assert_eq!(index["symbols"].as_array().unwrap().len(), 2);
|
||||
assert_eq!(index["calls"].as_array().unwrap().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inspect_keeps_independent_checked_definitions_after_local_errors() {
|
||||
let root = directory("partial-inspect");
|
||||
let path = root.join("app.dever");
|
||||
fs::write(&path, "broken() (n: Int) { n = true }\ndependent() (n: Int) { n = broken() }\nhelper() (n: Int) { n = 3 }\nvalid() (n: Int) { n = helper() }\nmalformed() (n: Int) { n = }\ncmd good = valid\ncmd bad = broken").unwrap();
|
||||
let index: serde_json::Value = serde_json::from_str(&success(cli(&[
|
||||
"inspect",
|
||||
path.to_str().unwrap(),
|
||||
"--json",
|
||||
])))
|
||||
.unwrap();
|
||||
let names = index["symbols"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|symbol| symbol["name"].as_str().unwrap())
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
names,
|
||||
[
|
||||
"main.main.app.helper",
|
||||
"main.main.app.valid",
|
||||
"main.main.good"
|
||||
]
|
||||
);
|
||||
assert_eq!(index["calls"].as_array().unwrap().len(), 2);
|
||||
assert!(index["diagnostics"].as_array().unwrap().len() >= 4);
|
||||
assert!(!cli(&["check", path.to_str().unwrap()]).status.success());
|
||||
let selected: serde_json::Value = serde_json::from_str(&success(cli(&[
|
||||
"inspect",
|
||||
path.to_str().unwrap(),
|
||||
"--json",
|
||||
"--symbol",
|
||||
"main.main.app.helper",
|
||||
"--depth",
|
||||
"1",
|
||||
])))
|
||||
.unwrap();
|
||||
assert_eq!(selected["symbols"].as_array().unwrap().len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inspect_excludes_invalid_types_cycles_duplicates_and_their_dependents() {
|
||||
let root = directory("invalid-inspect");
|
||||
let path = root.join("app.dever");
|
||||
let cases = [
|
||||
"lexical() (n: Int) { n = @ }",
|
||||
"lexical() (n: Int) { if true }",
|
||||
"lexical() (n: Text) { n = \"bad\\q\" }",
|
||||
"lexical() (n: Text) { n = \"unclosed\n}",
|
||||
"lexical() (n: Text) { n = \"bad\\\n}",
|
||||
"lexical() (n: Text) { n = \"bad\\u{ffff\n}",
|
||||
"type Broken { value: Missing }\nuseBroken(value: Broken) () {}",
|
||||
"type Cycle { next: Cycle? }\nuseCycle(value: Cycle) () {}",
|
||||
"cycle() (n: Int) { n = cycle() }\nuseCycle() (n: Int) { n = cycle() }",
|
||||
"duplicate() (n: Int) { n = 1 }\nduplicate() (n: Int) { n = 2 }\nuseDuplicate() (n: Int) { n = duplicate() }",
|
||||
"type Duplicate { value: Int }\ntype Duplicate { value: Bool }\nuseDuplicate(value: Duplicate) () {}",
|
||||
"cmd duplicate = valid\ncmd duplicate = valid",
|
||||
];
|
||||
for source in cases {
|
||||
fs::write(&path, format!("{source}\nvalid() (n: Int) {{ n = 3 }}")).unwrap();
|
||||
let index: serde_json::Value = serde_json::from_str(&success(cli(&[
|
||||
"inspect",
|
||||
path.to_str().unwrap(),
|
||||
"--json",
|
||||
])))
|
||||
.unwrap();
|
||||
assert_eq!(index["symbols"].as_array().unwrap().len(), 1, "{index}");
|
||||
assert_eq!(index["symbols"][0]["name"], "main.main.app.valid");
|
||||
assert!(index["calls"].as_array().unwrap().is_empty());
|
||||
assert!(!index["diagnostics"].as_array().unwrap().is_empty());
|
||||
}
|
||||
let order = root.join("module/demo/order");
|
||||
let stock = root.join("module/demo/stock");
|
||||
let other = root.join("module/demo/other");
|
||||
for directory in [&order, &stock, &other] {
|
||||
fs::create_dir_all(directory).unwrap();
|
||||
}
|
||||
write_source(
|
||||
order.join("app/main.dever"),
|
||||
"one() (n: Int) { n = stock.two() }\nthree() (n: Int) { n = 3 }",
|
||||
)
|
||||
.unwrap();
|
||||
write_source(
|
||||
stock.join("app/main.dever"),
|
||||
"two() (n: Int) { n = 2 }\nfour() (n: Int) { n = order.three() }",
|
||||
)
|
||||
.unwrap();
|
||||
write_source(other.join("app/main.dever"), "valid() (n: Int) { n = 3 }").unwrap();
|
||||
let index: serde_json::Value = serde_json::from_str(&success(cli(&[
|
||||
"inspect",
|
||||
root.to_str().unwrap(),
|
||||
"--json",
|
||||
])))
|
||||
.unwrap();
|
||||
assert_eq!(index["symbols"].as_array().unwrap().len(), 1, "{index}");
|
||||
assert_eq!(index["symbols"][0]["name"], "demo.other.app.valid");
|
||||
assert!(index["calls"].as_array().unwrap().is_empty());
|
||||
assert!(
|
||||
index["diagnostics"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|error| error["code"] == "C010")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inspect_binds_markdown_to_checked_symbols_and_rejects_ambiguous_descriptions() {
|
||||
let root = directory("documentation");
|
||||
let domain = root.join("module/demo/article");
|
||||
fs::create_dir_all(domain.join("doc")).unwrap();
|
||||
write_source(
|
||||
domain.join("app/main.dever"),
|
||||
"title() (text: Text) { text = \"标题\" }",
|
||||
)
|
||||
.unwrap();
|
||||
let doc = domain.join("doc/article.md");
|
||||
fs::write(&doc, "# 文章\n\n```markdown\n## ignored.example\n```\n\n## `demo.article.app.title`\n\n读取标题。\n\n## demo.article.app.missing\n不存在的能力。").unwrap();
|
||||
let load = || -> serde_json::Value {
|
||||
serde_json::from_str(&success(cli(&[
|
||||
"inspect",
|
||||
root.to_str().unwrap(),
|
||||
"--json",
|
||||
])))
|
||||
.unwrap()
|
||||
};
|
||||
let first = load();
|
||||
assert_eq!(first["documentation"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(
|
||||
first["documentation"][0]["symbol"],
|
||||
"demo.article.app.title"
|
||||
);
|
||||
assert_eq!(first["documentation"][0]["markdown"], "读取标题。");
|
||||
assert_eq!(first["documentation_errors"].as_array().unwrap().len(), 1);
|
||||
fs::write(&doc, "## demo.article.app.title\n新版说明。").unwrap();
|
||||
let second = load();
|
||||
assert_ne!(
|
||||
first["documentation_files"][0]["sha256"],
|
||||
second["documentation_files"][0]["sha256"]
|
||||
);
|
||||
assert_eq!(second["documentation"][0]["markdown"], "新版说明。");
|
||||
fs::write(
|
||||
domain.join("doc/duplicate.md"),
|
||||
"## demo.article.app.title\n重复说明。",
|
||||
)
|
||||
.unwrap();
|
||||
let duplicate = load();
|
||||
assert!(duplicate["documentation"].as_array().unwrap().is_empty());
|
||||
assert_eq!(
|
||||
duplicate["documentation_errors"].as_array().unwrap().len(),
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn links_preserve_user_files_and_track_current_source_and_descriptions() {
|
||||
let root = directory("links");
|
||||
let domain = root.join("module/demo/reader");
|
||||
fs::create_dir_all(domain.join("doc")).unwrap();
|
||||
let source = domain.join("app/main.dever");
|
||||
write_source(
|
||||
&source,
|
||||
"helper() (n: Int) { n = 3 }\nmain() (n: Int) { n = helper() }",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(domain.join("api.dever"), "cmd read = app.main").unwrap();
|
||||
let root = root.to_str().unwrap();
|
||||
let index = domain.join("link.md");
|
||||
let inspect = |check: bool| {
|
||||
if check {
|
||||
cli(&["inspect", root, "--links", "--check"])
|
||||
} else {
|
||||
cli(&["inspect", root, "--links"])
|
||||
}
|
||||
};
|
||||
assert!(!inspect(true).status.success());
|
||||
success(inspect(false));
|
||||
success(inspect(true));
|
||||
let page = fs::read_to_string(&index).unwrap();
|
||||
assert!(page.contains("flowchart TD"));
|
||||
assert!(page.contains("子流程 [demo.reader.app.helper]"));
|
||||
assert!(page.contains("click n"));
|
||||
assert!(
|
||||
page.find("## demo.reader.read").unwrap() < page.find("## demo.reader.app.main").unwrap()
|
||||
);
|
||||
let modified = fs::metadata(&index).unwrap().modified().unwrap();
|
||||
success(inspect(false));
|
||||
assert_eq!(modified, fs::metadata(&index).unwrap().modified().unwrap());
|
||||
fs::write(
|
||||
domain.join("doc/reader.md"),
|
||||
"## demo.reader.app.main\n读取结果。",
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!inspect(true).status.success());
|
||||
success(inspect(false));
|
||||
assert!(fs::read_to_string(&index).unwrap().contains("读取结果。"));
|
||||
write_source(
|
||||
&source,
|
||||
"helper() (n: Int) { n = 4 }\nmain() (n: Int) { n = helper() }",
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!inspect(true).status.success());
|
||||
success(inspect(false));
|
||||
let before = fs::read(&index).unwrap();
|
||||
write_source(&source, "broken() (n: Int) { n = true }").unwrap();
|
||||
assert!(!inspect(false).status.success());
|
||||
assert_eq!(before, fs::read(&index).unwrap());
|
||||
write_source(
|
||||
&source,
|
||||
"helper() (n: Int) { n = 3 }\nmain() (n: Int) { n = helper() }",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(&index, "用户维护的文档").unwrap();
|
||||
assert!(!inspect(false).status.success());
|
||||
assert_eq!(fs::read_to_string(&index).unwrap(), "用户维护的文档");
|
||||
for flags in [
|
||||
vec!["--check"],
|
||||
vec!["--links", "--json"],
|
||||
vec!["--links", "--symbol", "demo.reader.app.main"],
|
||||
] {
|
||||
let mut arguments = vec!["inspect", root];
|
||||
arguments.extend(flags);
|
||||
assert!(!cli(&arguments).status.success());
|
||||
}
|
||||
}
|
||||
|
||||
#[path = "inspect/handler.rs"]
|
||||
mod handler;
|
||||
@@ -0,0 +1,103 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn handler_navigation_keeps_bindings_separate_and_never_exposes_prototype_calls() {
|
||||
let root = directory("handler-inspect");
|
||||
let domain = root.join("module/shop/value");
|
||||
fs::create_dir_all(domain.join("doc")).unwrap();
|
||||
write_source(
|
||||
domain.join("app/main.dever"),
|
||||
r#"
|
||||
identity(value: Int) (out: Int) { out = value }
|
||||
double(value: Int) (out: Int) { out = value * 2 }
|
||||
apply(value: Int, transform: handler(value: Int) (out: Int)) (out: Int) { out = transform(value) }
|
||||
start(value: Int) (out: Int) { out = apply(value, identity) + apply(value, double) }
|
||||
unused(transform: handler(value: Int) (out: Int)) (out: Int) { out = transform(1) }
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(domain.join("doc/app.md"), "## shop.value.app.apply\n\n调用传入的具名计算。\n\n## shop.value.app.unused\n\n未绑定的模板。\n").unwrap();
|
||||
let load = |name: Option<&str>| -> serde_json::Value {
|
||||
let mut args = vec!["inspect", root.to_str().unwrap(), "--json"];
|
||||
if let Some(name) = name {
|
||||
args.extend(["--symbol", name, "--depth", "0"]);
|
||||
}
|
||||
serde_json::from_str(&success(cli(&args))).unwrap()
|
||||
};
|
||||
let index = load(None);
|
||||
assert_eq!(index["diagnostics"], serde_json::json!([]));
|
||||
assert_eq!(index["documentation_errors"], serde_json::json!([]));
|
||||
let symbols = index["symbols"].as_array().unwrap();
|
||||
let template = symbols
|
||||
.iter()
|
||||
.find(|s| s["name"] == "shop.value.app.apply" && s["kind"] == "template")
|
||||
.unwrap();
|
||||
let instances = symbols
|
||||
.iter()
|
||||
.filter(|s| s["template"] == template["id"])
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(instances.len(), 2);
|
||||
assert_ne!(instances[0]["name"], instances[1]["name"]);
|
||||
assert_eq!(
|
||||
index["calls"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|edge| edge["kind"] == "handler")
|
||||
.count(),
|
||||
2
|
||||
);
|
||||
for instance in instances {
|
||||
assert!(instance.get("declarations").is_none());
|
||||
assert!(instance.get("signatures").is_none());
|
||||
let name = instance["name"].as_str().unwrap();
|
||||
assert!(!name.contains("__handler_"));
|
||||
let selected = load(Some(name));
|
||||
assert_eq!(
|
||||
selected["symbols"][0]["source_name"],
|
||||
"shop.value.app.apply"
|
||||
);
|
||||
assert!(selected["symbols"][0].get("template").is_none());
|
||||
assert_eq!(
|
||||
selected["symbols"][0]["declarations"],
|
||||
template["declarations"]
|
||||
);
|
||||
assert_eq!(
|
||||
selected["symbols"][0]["signatures"][0],
|
||||
template["signatures"][0]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.replacen("shop.value.app.apply", name, 1)
|
||||
);
|
||||
let flows = selected["flows"].as_array().unwrap();
|
||||
assert_eq!(flows.len(), 1);
|
||||
let targets = flows[0]["nodes"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter_map(|node| node["target"].as_str())
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(targets.len(), 1);
|
||||
assert!(name.contains(targets[0]));
|
||||
assert_eq!(
|
||||
selected["documentation"][0]["symbol"],
|
||||
"shop.value.app.apply"
|
||||
);
|
||||
}
|
||||
let all = load(Some("shop.value.app.apply"));
|
||||
assert_eq!(all["flows"].as_array().unwrap().len(), 2);
|
||||
let unused = load(Some("shop.value.app.unused"));
|
||||
assert_eq!(unused["symbols"][0]["kind"], "template");
|
||||
assert!(unused.get("flows").is_none());
|
||||
assert_eq!(unused["calls"], serde_json::json!([]));
|
||||
success(cli(&["inspect", root.to_str().unwrap(), "--links"]));
|
||||
success(cli(&[
|
||||
"inspect",
|
||||
root.to_str().unwrap(),
|
||||
"--links",
|
||||
"--check",
|
||||
]));
|
||||
let links = fs::read_to_string(domain.join("link.md")).unwrap();
|
||||
assert!(!links.contains("__handler_"));
|
||||
fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
@@ -0,0 +1,463 @@
|
||||
use super::*;
|
||||
use std::time::{Duration, Instant};
|
||||
mod tenants;
|
||||
|
||||
fn project(name: &str, app: &str, api: &str) -> PathBuf {
|
||||
let root = directory(name);
|
||||
let domain = root.join("module/demo/work");
|
||||
fs::create_dir_all(&domain).unwrap();
|
||||
write_source(domain.join("app/main.dever"), app).unwrap();
|
||||
fs::write(domain.join("api.dever"), api).unwrap();
|
||||
root
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_job_queue_and_worker_commit_or_rollback_the_same_database_transaction() {
|
||||
exercise_queue(
|
||||
"job-native",
|
||||
serde_json::json!({"type":"sqlite","path":"data/job.db","max_connections":2}),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires an isolated PostgreSQL database; run test/postgres.py"]
|
||||
fn postgres_generated_job_queue_and_worker() {
|
||||
let url = std::env::var("DEVER_TEST_POSTGRES").expect("isolated PostgreSQL test connection");
|
||||
exercise_queue(
|
||||
"job-postgres-native",
|
||||
serde_json::json!({"type":"postgres","url":url,"tls":"disabled","max_connections":2}),
|
||||
);
|
||||
}
|
||||
|
||||
fn exercise_queue(name: &str, database_config: serde_json::Value) {
|
||||
let root = project(
|
||||
name,
|
||||
r#"
|
||||
type Payload { label: Text, accept: Bool }
|
||||
type Submission { key: Text, payload: Payload }
|
||||
flow submitMany(inputs: List<Submission>) (out: List<Id>)
|
||||
| step | kind | do |
|
||||
| out | calc | enqueueMany(job.save, inputs) |
|
||||
flow rollbackMany(inputs: List<Submission>, accept: Bool) ()
|
||||
| step | kind | do |
|
||||
| - | calc | enqueueMany(job.save, inputs) |
|
||||
| - | check | accept else Invalid |
|
||||
flow submit(input: Payload, key: Text) (out: Id)
|
||||
| step | kind | do |
|
||||
| out | calc | enqueue(job.save, input, key) |
|
||||
flow submitLong(input: Payload, key: Text) (out: Id)
|
||||
| step | kind | do |
|
||||
| out | calc | enqueue(job.longSave, input, key) |
|
||||
flow submitSlow(input: Payload, key: Text) (out: Id)
|
||||
| step | kind | do |
|
||||
| out | calc | enqueue(job.slowSave, input, key) |
|
||||
transaction flow stage(input: Payload) ()
|
||||
| step | kind | do |
|
||||
| - | data | data.create({label = input.label}) |
|
||||
flow longHandle(input: Payload) ()
|
||||
| step | kind | do |
|
||||
| label | port | port.echo(input.label) |
|
||||
| - | flow | stage(Payload {label=label,accept=input.accept}) |
|
||||
| - | check | input.accept else Invalid |
|
||||
flow slowHandle(input: Payload) ()
|
||||
| step | kind | do |
|
||||
| - | flow | stage(input) |
|
||||
| - | port | port.hang() |
|
||||
flow delayed(input: Payload, key: Text, at: DateTime) (out: Id)
|
||||
| step | kind | do |
|
||||
| out | calc | enqueueAt(job.save, input, key, at) |
|
||||
flow rolledBack(input: Payload, key: Text) ()
|
||||
| step | kind | do |
|
||||
| - | calc | enqueue(job.save, input, key) |
|
||||
| - | check | input.accept else Invalid |
|
||||
flow handle(input: Payload) ()
|
||||
| step | kind | do |
|
||||
| - | data | data.create({label = input.label}) |
|
||||
| - | check | input.accept else Invalid |
|
||||
flow count() (out: Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.count() |
|
||||
"#,
|
||||
"job save(input: app.Payload) retry(1) timeout(1000) = app.handle\nlong job longSave(input: app.Payload) retry(1) timeout(1000) = app.longHandle\nlong job slowSave(input: app.Payload) retry(1) timeout(1000) = app.slowHandle\ncmd submitSlow = app.submitSlow\ncmd submitLong = app.submitLong\ncmd submit = app.submit\ncmd submitMany = app.submitMany\ncmd rollbackMany = app.rollbackMany\ncmd delayed = app.delayed\ncmd rolledBack = app.rolledBack\ncmd count = app.count",
|
||||
);
|
||||
write_source(
|
||||
root.join("module/demo/work/data/main.dever"),
|
||||
"type Work { label: Text unique }",
|
||||
)
|
||||
.unwrap();
|
||||
let domain = root.join("module/demo/work");
|
||||
fs::write(
|
||||
domain.join("port.dever"),
|
||||
"hang() ()\necho(value: Text) (out: Text)",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
domain.join("adapter.dever"),
|
||||
"external exec \"bin/worker\" {}",
|
||||
)
|
||||
.unwrap();
|
||||
crate::port::worker::executable(&domain);
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
let config = root.join("config/setting.json");
|
||||
fs::write(&config,serde_json::json!({"database":{"default":database_config},"job":{"workers":1,"poll_ms":1,"lease_ms":10000,"shutdown_ms":5000}}).to_string()).unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
assert_eq!(program.jobs.len(), 3);
|
||||
let formatted = dever::compiler::format::format(&loaded.declarations);
|
||||
assert!(formatted.contains("job save(input: app.Payload) retry(1) timeout(1000) = app.handle"));
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
fs::remove_file(domain.join("bin/worker")).unwrap();
|
||||
let resources = root.join("runtime-resources");
|
||||
fs::create_dir(&resources).unwrap();
|
||||
let call = |name: &str, input: serde_json::Value| {
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.args([name, &input.to_string()])
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
success(
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.arg("migrate")
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
let payload = serde_json::json!({"input":{"label":"success","accept":true},"key":"same"});
|
||||
let first = success(call("demo.work.submit", payload.clone()));
|
||||
assert_eq!(first, success(call("demo.work.submit", payload)));
|
||||
let item = |key: &str| serde_json::json!({"key":key,"payload":{"label":"batch","accept":true}});
|
||||
let data = |output: String| {
|
||||
serde_json::from_str::<serde_json::Value>(&output).unwrap()["data"].clone()
|
||||
};
|
||||
let first_id = data(first);
|
||||
assert_eq!(
|
||||
data(success(call(
|
||||
"demo.work.submitMany",
|
||||
serde_json::json!({"inputs":[]})
|
||||
))),
|
||||
serde_json::json!([])
|
||||
);
|
||||
assert_eq!(
|
||||
data(success(call(
|
||||
"demo.work.submitMany",
|
||||
serde_json::json!({"inputs":[item("same"),item("same")]})
|
||||
))),
|
||||
serde_json::json!([first_id.clone(), first_id])
|
||||
);
|
||||
assert!(
|
||||
!call(
|
||||
"demo.work.submitMany",
|
||||
serde_json::json!({"inputs":[item("invalid-batch"),item("")]})
|
||||
)
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
assert!(
|
||||
!call(
|
||||
"demo.work.rollbackMany",
|
||||
serde_json::json!({"inputs":[item("outer-rollback")],"accept":false})
|
||||
)
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
success(call(
|
||||
"demo.work.submit",
|
||||
serde_json::json!({"input":{"label":"failure","accept":false},"key":"bad"}),
|
||||
));
|
||||
assert!(
|
||||
!call(
|
||||
"demo.work.rolledBack",
|
||||
serde_json::json!({"input":{"label":"rolled back","accept":false},"key":"rollback"})
|
||||
)
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
success(call(
|
||||
"demo.work.delayed",
|
||||
serde_json::json!({"input":{"label":"future","accept":true},"key":"future","at":"2099-01-01T00:00:00Z"}),
|
||||
));
|
||||
success(call(
|
||||
"demo.work.submitLong",
|
||||
serde_json::json!({"input":{"label":"long failure","accept":false},"key":"long"}),
|
||||
));
|
||||
success(call(
|
||||
"demo.work.submitSlow",
|
||||
serde_json::json!({"input":{"label":"timed out","accept":true},"key":"slow"}),
|
||||
));
|
||||
let database_config: dever_runtime::database::config::Config =
|
||||
serde_json::from_value(database_config).unwrap();
|
||||
let snapshot = || {
|
||||
dever_runtime::task::run(true, 8, async |scope| {
|
||||
let database = database_config.open(&root, false).await.unwrap();
|
||||
database
|
||||
.acquire()
|
||||
.await
|
||||
.unwrap()
|
||||
.query(
|
||||
scope,
|
||||
"SELECT task_key,state,error FROM _dever_job ORDER BY task_key".into(),
|
||||
vec![],
|
||||
|row| {
|
||||
Ok((
|
||||
row.get::<String>(0)?,
|
||||
row.get::<String>(1)?,
|
||||
row.get::<Option<String>>(2)?,
|
||||
))
|
||||
},
|
||||
)
|
||||
.await
|
||||
})
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
};
|
||||
assert_eq!(snapshot().len(), 5);
|
||||
let mut worker = Worker(
|
||||
Command::new(&artifact.binary)
|
||||
.env("TMPDIR", &resources)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.arg("worker")
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap(),
|
||||
);
|
||||
let deadline = Instant::now() + Duration::from_secs(15);
|
||||
let mut external_pids = Vec::<u32>::new();
|
||||
loop {
|
||||
if external_pids.is_empty() {
|
||||
let pid = worker.0.id();
|
||||
external_pids = fs::read_to_string(format!("/proc/{pid}/task/{pid}/children"))
|
||||
.unwrap()
|
||||
.split_whitespace()
|
||||
.map(|pid| pid.parse().unwrap())
|
||||
.collect();
|
||||
}
|
||||
let rows = snapshot();
|
||||
if rows
|
||||
.iter()
|
||||
.any(|(key, state, _)| key == "same" && state == "completed")
|
||||
&& rows
|
||||
.iter()
|
||||
.any(|(key, state, _)| key == "bad" && state == "dead")
|
||||
&& rows
|
||||
.iter()
|
||||
.any(|(key, state, _)| key == "long" && state == "dead")
|
||||
&& rows.iter().any(|(key, state, cause)| {
|
||||
key == "slow"
|
||||
&& state == "dead"
|
||||
&& cause
|
||||
.as_deref()
|
||||
.is_some_and(|cause| cause.contains("handler deadline expired"))
|
||||
})
|
||||
{
|
||||
break;
|
||||
}
|
||||
if let Some(status) = worker.0.try_wait().unwrap() {
|
||||
let mut message = String::new();
|
||||
std::io::Read::read_to_string(worker.0.stderr.as_mut().unwrap(), &mut message).unwrap();
|
||||
panic!("worker exited {status}: {message}");
|
||||
}
|
||||
assert!(Instant::now() < deadline, "Job did not complete: {rows:?}");
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
// 取消已完成的请求后,根入口仍可复用空闲会话处理下一次真实调用。
|
||||
success(call(
|
||||
"demo.work.submitLong",
|
||||
serde_json::json!({"input":{"label":"after timeout","accept":true},"key":"after"}),
|
||||
));
|
||||
let deadline = Instant::now() + Duration::from_secs(15);
|
||||
while !snapshot()
|
||||
.iter()
|
||||
.any(|(key, state, _)| key == "after" && state == "completed")
|
||||
{
|
||||
assert!(
|
||||
Instant::now() < deadline,
|
||||
"Worker did not recover after Job timeout"
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
let result: serde_json::Value =
|
||||
serde_json::from_str(&success(call("demo.work.count", serde_json::json!({})))).unwrap();
|
||||
// long Job 的独立事务已提交;后续外部调用失败或超时不能撤掉该事务。
|
||||
assert_eq!(result["data"], 4);
|
||||
assert!(!external_pids.is_empty(), "external Worker never started");
|
||||
assert!(
|
||||
snapshot()
|
||||
.iter()
|
||||
.any(|(key, state, _)| key == "future" && state == "pending")
|
||||
);
|
||||
assert!(
|
||||
Command::new("sh")
|
||||
.args([
|
||||
"-c",
|
||||
"kill -TERM \"$1\"",
|
||||
"worker-stop",
|
||||
&worker.0.id().to_string()
|
||||
])
|
||||
.status()
|
||||
.unwrap()
|
||||
.success()
|
||||
);
|
||||
let status = worker.0.wait().unwrap();
|
||||
let mut diagnostics = String::new();
|
||||
std::io::Read::read_to_string(worker.0.stderr.as_mut().unwrap(), &mut diagnostics).unwrap();
|
||||
assert!(status.success(), "{status}: {diagnostics}");
|
||||
for pid in external_pids {
|
||||
assert!(
|
||||
!Path::new(&format!("/proc/{pid}")).exists(),
|
||||
"Worker {pid} survived owner shutdown"
|
||||
);
|
||||
}
|
||||
assert_eq!(fs::read_dir(&resources).unwrap().count(), 0);
|
||||
}
|
||||
|
||||
struct Worker(std::process::Child);
|
||||
impl Drop for Worker {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.0.kill();
|
||||
let _ = self.0.wait();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn job_declarations_and_long_transaction_boundaries_are_checked() {
|
||||
for (index, app, api) in [
|
||||
(
|
||||
0,
|
||||
"handle() () {}",
|
||||
"job save() retry(0) timeout(1000) = app.handle",
|
||||
),
|
||||
(
|
||||
1,
|
||||
"handle() (out:Int) {out=1}",
|
||||
"job save() retry(1) timeout(1000) = app.handle",
|
||||
),
|
||||
(
|
||||
2,
|
||||
"handle(input:Text) () {}",
|
||||
"job save(input:Int) retry(1) timeout(1000) = app.handle",
|
||||
),
|
||||
(
|
||||
3,
|
||||
"handle() () {}\nflow submit() (out:Id)\n| step | kind | do |\n| out | calc | enqueue(job.save,\"key\") |",
|
||||
"job save() retry(1) timeout(1000) = app.handle\nlong cmd submit = app.submit",
|
||||
),
|
||||
(
|
||||
4,
|
||||
"handle() () {}",
|
||||
"job save() retry(1) timeout(1000) = app.handle\njob save() retry(1) timeout(1000) = app.handle",
|
||||
),
|
||||
] {
|
||||
let root = project(&format!("job-invalid-{index}"), app, api);
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(loaded.diagnostics.is_empty(), "{:?}", loaded.diagnostics);
|
||||
assert!(
|
||||
program::check(&loaded.declarations, &loaded.modules).is_err(),
|
||||
"{api}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schedule_without_commands_executes_a_zero_input_job_and_drains_on_termination() {
|
||||
let root = project(
|
||||
"job-schedule-native",
|
||||
"tick() () {}",
|
||||
"job tick() retry(1) timeout(1000) = app.tick\nschedule minute = \"* * * * *\" = app.tick",
|
||||
);
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
let config = root.join("config/setting.json");
|
||||
fs::write(&config,r#"{"database":{"create":true,"default":{"type":"sqlite","path":"data/schedule.db","max_connections":2}},"job":{"workers":1,"poll_ms":1,"lease_ms":10000,"shutdown_ms":5000}}"#).unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
assert_eq!(program.jobs[0].cron.as_deref(), Some("* * * * *"));
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
let mut worker = Worker(
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.arg("worker")
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap(),
|
||||
);
|
||||
let database_path = root.join("data/schedule.db");
|
||||
let deadline = Instant::now() + Duration::from_secs(15);
|
||||
loop {
|
||||
let completed = dever_runtime::task::run(true, 8, async |scope| {
|
||||
if !database_path.is_file() {
|
||||
return Ok(0);
|
||||
}
|
||||
let database = dever_runtime::database::Database::sqlite(
|
||||
&database_path,
|
||||
false,
|
||||
dever_runtime::database::Options {
|
||||
max_page_size: 100,
|
||||
max_connections: 1,
|
||||
wait_timeout: Duration::from_secs(5),
|
||||
io_timeout: Duration::from_secs(10),
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut executor = database.acquire().await?;
|
||||
let prepared = executor
|
||||
.query(
|
||||
scope,
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE name='_dever_job')".into(),
|
||||
vec![],
|
||||
|row| row.get::<i64>(0),
|
||||
)
|
||||
.await?[0]
|
||||
!= 0;
|
||||
if !prepared {
|
||||
return Ok(0);
|
||||
}
|
||||
executor
|
||||
.query(
|
||||
scope,
|
||||
"SELECT count(*) FROM _dever_job WHERE state='completed'".into(),
|
||||
vec![],
|
||||
|row| row.get::<i64>(0),
|
||||
)
|
||||
.await
|
||||
.map(|counts| counts[0])
|
||||
})
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
if completed > 0 {
|
||||
break;
|
||||
}
|
||||
if let Some(status) = worker.0.try_wait().unwrap() {
|
||||
let mut message = String::new();
|
||||
std::io::Read::read_to_string(worker.0.stderr.as_mut().unwrap(), &mut message).unwrap();
|
||||
panic!("worker exited {status}: {message}");
|
||||
}
|
||||
assert!(Instant::now() < deadline, "schedule did not execute");
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
assert!(
|
||||
Command::new("sh")
|
||||
.args([
|
||||
"-c",
|
||||
"kill -TERM \"$1\"",
|
||||
"worker-stop",
|
||||
&worker.0.id().to_string()
|
||||
])
|
||||
.status()
|
||||
.unwrap()
|
||||
.success()
|
||||
);
|
||||
assert!(worker.0.wait().unwrap().success());
|
||||
for cron in ["* * * * * *", "* * * * 7", "invalid"] {
|
||||
fs::write(root.join("module/demo/work/api.dever"),format!("job tick() retry(1) timeout(1000) = app.tick\nschedule minute = {cron:?} = app.tick")).unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(program::check(&loaded.declarations, &loaded.modules).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
//! 独立 Worker 在一个池预算中轮询多个物理租户,不混入 HTTP 并发竞争。
|
||||
use super::*;
|
||||
use dever_runtime::{auth::tenant::Backend, database::Database, database::config::Config, task};
|
||||
|
||||
#[test]
|
||||
fn tenant_cron_worker_releases_the_previous_pool_before_switching() {
|
||||
exercise(
|
||||
"job-tenant-one-pool",
|
||||
serde_json::json!({"type":"sqlite","path":"data/control.db","tenant_directory":"data/tenants","max_connections":2}),
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires an isolated PostgreSQL database; run test/postgres.py"]
|
||||
fn postgres_tenant_cron_worker_with_one_pool() {
|
||||
exercise(
|
||||
"job-tenant-one-pool-postgres",
|
||||
serde_json::json!({"type":"postgres","url":std::env::var("DEVER_TEST_POSTGRES").unwrap(),"tls":"disabled","tenant_database_prefix":"dever_job_cron_tenant","max_connections":2}),
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tenant_cron_worker_runs_an_embedded_external_adapter_and_cleans_up() {
|
||||
exercise(
|
||||
"job-tenant-external",
|
||||
serde_json::json!({"type":"sqlite","path":"data/control.db","tenant_directory":"data/tenants","max_connections":2}),
|
||||
true,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires an isolated PostgreSQL database; run test/postgres.py"]
|
||||
fn postgres_tenant_cron_worker_with_an_embedded_external_adapter() {
|
||||
exercise(
|
||||
"job-tenant-external-postgres",
|
||||
serde_json::json!({"type":"postgres","url":std::env::var("DEVER_TEST_POSTGRES").unwrap(),"tls":"disabled","tenant_database_prefix":"dever_job_cron_external","max_connections":2}),
|
||||
true,
|
||||
);
|
||||
}
|
||||
|
||||
fn exercise(name: &str, database: serde_json::Value, external: bool) {
|
||||
let app = if external {
|
||||
"flow tick() ()\n| step | kind | do |\n| label | flow | demo.service.app.echo(\"tick\") |\n| - | flow | record(label) |\ntransaction flow record(label: Text) ()\n| step | kind | do |\n| - | data | data.create({label=label}) |"
|
||||
} else {
|
||||
"flow tick() ()\n| step | kind | do |\n| - | data | data.create({label=\"tick\"}) |"
|
||||
};
|
||||
let root = project(
|
||||
name,
|
||||
app,
|
||||
&format!(
|
||||
"{}job tick() retry(1) timeout(1000) = app.tick\nschedule minute = \"* * * * *\" = app.tick",
|
||||
if external { "long " } else { "" }
|
||||
),
|
||||
);
|
||||
let service = root.join("module/demo/service");
|
||||
if external {
|
||||
fs::create_dir_all(&service).unwrap();
|
||||
fs::write(service.join("port.dever"), "echo(value: Text) (out: Text)").unwrap();
|
||||
fs::write(
|
||||
service.join("adapter.dever"),
|
||||
"external exec \"bin/worker\" {}",
|
||||
)
|
||||
.unwrap();
|
||||
write_source(service.join("app/main.dever"), "flow echo(value: Text) (out: Text)\n| step | kind | do |\n| out | port | port.echo(value) |").unwrap();
|
||||
crate::port::worker::executable(&service);
|
||||
}
|
||||
write_source(
|
||||
root.join("module/demo/work/data/main.dever"),
|
||||
"type Work {label:Text}",
|
||||
)
|
||||
.unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
let config = root.join("config/setting.json");
|
||||
fs::write(
|
||||
&config,
|
||||
serde_json::json!({"database":{"default":database},
|
||||
"tenant":{"database":"default","max_pools":1,"idle_timeout_ms":1000},
|
||||
"job":{"workers":1,"poll_ms":5,"lease_ms":10000,"shutdown_ms":5000}})
|
||||
.to_string(),
|
||||
)
|
||||
.unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
if external {
|
||||
// 两个物理租户都必须从程序内嵌镜像启动,不依赖源码目录中的可执行文件。
|
||||
fs::remove_file(service.join("bin/worker")).unwrap();
|
||||
}
|
||||
let resources = root.join("runtime-resources");
|
||||
fs::create_dir(&resources).unwrap();
|
||||
let call = |name: &str, input: Option<&str>| {
|
||||
let mut command = Command::new(&artifact.binary);
|
||||
command.arg("--config").arg(&config).arg(name);
|
||||
if let Some(input) = input {
|
||||
command.arg(input);
|
||||
}
|
||||
success(command.output().unwrap())
|
||||
};
|
||||
call("migrate", None);
|
||||
for id in 1..=2 {
|
||||
call(
|
||||
"dever.tenant.migrate",
|
||||
Some(&format!(r#"{{"tenant":{id}}}"#)),
|
||||
);
|
||||
}
|
||||
let database: Config = serde_json::from_value(database).unwrap();
|
||||
assert_eq!(snapshot(&root, &database), vec![(0, 0, 0, 0, 0); 2]);
|
||||
let mut worker = Worker(
|
||||
Command::new(&artifact.binary)
|
||||
.env("TMPDIR", &resources)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.arg("worker")
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap(),
|
||||
);
|
||||
let deadline = Instant::now() + Duration::from_secs(15);
|
||||
loop {
|
||||
if let Some(status) = worker.0.try_wait().unwrap() {
|
||||
let mut message = String::new();
|
||||
std::io::Read::read_to_string(worker.0.stderr.as_mut().unwrap(), &mut message).unwrap();
|
||||
panic!("worker exited {status}: {message}");
|
||||
}
|
||||
if snapshot(&root, &database).iter().all(|counts| counts.0 > 0) {
|
||||
break;
|
||||
}
|
||||
assert!(
|
||||
Instant::now() < deadline,
|
||||
"cron did not execute in both tenants"
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
assert!(
|
||||
Command::new("sh")
|
||||
.args([
|
||||
"-c",
|
||||
"kill -TERM \"$1\"",
|
||||
"worker-stop",
|
||||
&worker.0.id().to_string()
|
||||
])
|
||||
.status()
|
||||
.unwrap()
|
||||
.success()
|
||||
);
|
||||
let status = worker.0.wait().unwrap();
|
||||
let mut diagnostics = String::new();
|
||||
std::io::Read::read_to_string(worker.0.stderr.as_mut().unwrap(), &mut diagnostics).unwrap();
|
||||
assert!(status.success(), "{status}: {diagnostics}");
|
||||
assert_eq!(fs::read_dir(&resources).unwrap().count(), 0);
|
||||
// 停止排空后核对任务、cron 去重记录、业务行及租户归属,不假定测试不会跨分钟。
|
||||
for (completed, jobs, effects, occurrences, invalid) in snapshot(&root, &database) {
|
||||
assert!(completed > 0);
|
||||
assert_eq!(
|
||||
(jobs, effects, occurrences, invalid),
|
||||
(completed, completed, completed, 0)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn snapshot(root: &Path, config: &Config) -> Vec<(i64, i64, i64, i64, i64)> {
|
||||
task::run(true, 8, async |scope| {
|
||||
// 独立读连接不持有 Worker 进程内的缓存租约。
|
||||
let backend = config.tenant_backend(root, scope, false, &[config]).await?;
|
||||
let mut counts = Vec::new();
|
||||
for tenant in 1..=2 {
|
||||
let database = 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?
|
||||
}
|
||||
};
|
||||
let row = database
|
||||
.acquire()
|
||||
.await?
|
||||
.query_one(
|
||||
scope,
|
||||
dever_runtime::database::Sql::same(
|
||||
"SELECT (SELECT count(*) FROM _dever_job WHERE state='completed'),
|
||||
(SELECT count(*) FROM _dever_job), (SELECT count(*) FROM demo_work),
|
||||
(SELECT count(*) FROM _dever_job_occurrence),
|
||||
(SELECT count(*) FROM _dever_job WHERE execution_tenant<>$1) +
|
||||
(SELECT count(*) FROM demo_work WHERE label<>'tick')",
|
||||
),
|
||||
vec![dever_runtime::database::Parameter::Integer(tenant)],
|
||||
|row| {
|
||||
Ok((
|
||||
row.get(0)?,
|
||||
row.get(1)?,
|
||||
row.get(2)?,
|
||||
row.get(3)?,
|
||||
row.get(4)?,
|
||||
))
|
||||
},
|
||||
)
|
||||
.await?
|
||||
.unwrap();
|
||||
counts.push(row);
|
||||
}
|
||||
Ok::<_, dever_runtime::database::Error>(counts)
|
||||
})
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn json_library_rejects_lost_errors_and_exposes_real_source_navigation() {
|
||||
let root = directory("json-library");
|
||||
let source = root.join("main.dever");
|
||||
for (text, code) in [
|
||||
(
|
||||
"type Hidden { private secret: Text }\nf(value: Hidden) (out: Json) { out = dever.json.encode(value) }",
|
||||
"C006",
|
||||
),
|
||||
(
|
||||
"type Hidden { private secret: Text }\nf(value: Json) (out: Hidden) { out = dever.json.decode(value) }",
|
||||
"C006",
|
||||
),
|
||||
(
|
||||
"f(value: Json) (out: Int) { decoded = dever.json.decode(value)\nout = 0 }",
|
||||
"C005",
|
||||
),
|
||||
(
|
||||
"f(text: Text) (out: Int) { pending: dever.json.JsonResult = result(dever.json.fromText(text))\nout = 1 }",
|
||||
"C012",
|
||||
),
|
||||
(
|
||||
"f(text: Text) (out: Int) { pending: dever.json.value.ParseResult = result(dever.json.parse(text))\nout = 1 }",
|
||||
"C012",
|
||||
),
|
||||
(
|
||||
"f(text: Text) (out: Json) { out = dever.system.jsonFromText(text) }",
|
||||
"C003",
|
||||
),
|
||||
(
|
||||
"f(text: Int) (out: Json) { out = dever.json.fromText(text) }",
|
||||
"C005",
|
||||
),
|
||||
(
|
||||
"f(text: Text) (out: Json) { out = dever.json.parse(text) }",
|
||||
"C005",
|
||||
),
|
||||
] {
|
||||
fs::write(&source, text).unwrap();
|
||||
let project = Project::load(&source).unwrap();
|
||||
assert!(project.diagnostics.is_empty(), "{:?}", project.diagnostics);
|
||||
let error = program::check(&project.declarations, &project.modules)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(error.code, code, "{error}");
|
||||
}
|
||||
fs::write(&source, "f(text: Text) (out: Text) { out = dever.json.stringify(dever.json.parse(text)) }\ninspectValue(value: Json) (empty: Bool, body: Text) { empty = dever.json.isEmptyObject(value)\nbody = dever.json.stringify(dever.json.document(value)) }\ncmd f = app.f\ncmd inspectValue = app.inspectValue").unwrap();
|
||||
success(cli(&["fmt", source.to_str().unwrap()]));
|
||||
let index: serde_json::Value = serde_json::from_str(&success(cli(&[
|
||||
"inspect",
|
||||
source.to_str().unwrap(),
|
||||
"--json",
|
||||
])))
|
||||
.unwrap();
|
||||
assert!(index["diagnostics"].as_array().unwrap().is_empty());
|
||||
for name in [
|
||||
"dever.json.app.parse",
|
||||
"dever.json.app.document",
|
||||
"dever.json.app.isEmptyObject",
|
||||
"dever.json.app.value.Document",
|
||||
"dever.json.app.value.Value",
|
||||
] {
|
||||
assert!(
|
||||
index["symbols"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|symbol| symbol["name"] == name),
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
for (input, empty, body) in [
|
||||
(r#"{"value":{ }}"#, true, "{}"),
|
||||
(r#"{"value":{"a":[1e9999]}}"#, false, r#"{"a":[1e9999]}"#),
|
||||
(r#"{"value":[]}"#, false, "[]"),
|
||||
] {
|
||||
let output = success(cli(&[
|
||||
"run",
|
||||
source.to_str().unwrap(),
|
||||
"--",
|
||||
"main.main.inspectValue",
|
||||
input,
|
||||
]));
|
||||
let value = serde_json::from_str::<serde_json::Value>(&output).unwrap();
|
||||
assert_eq!(
|
||||
value["data"],
|
||||
serde_json::json!({"empty":empty,"body":body})
|
||||
);
|
||||
}
|
||||
let output = success(cli(&[
|
||||
"run",
|
||||
source.to_str().unwrap(),
|
||||
"--",
|
||||
"main.main.f",
|
||||
r#"{"text":"{\"number\":1e9999}"}"#,
|
||||
]));
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(&output).unwrap()["data"],
|
||||
r#"{"number":1e9999}"#
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn runtime_feature_changes_refresh_generated_lock_without_changing_core_versions() {
|
||||
let stamp = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos();
|
||||
let temporary =
|
||||
std::env::temp_dir().join(format!("dever-feature-lock-{}-{stamp}", std::process::id()));
|
||||
let root = temporary.join("core");
|
||||
let runtime = root.join("src/runtime");
|
||||
let generated = temporary.join("generated");
|
||||
fs::create_dir_all(&runtime).unwrap();
|
||||
fs::create_dir_all(&generated).unwrap();
|
||||
fs::write(
|
||||
root.join("Cargo.toml"),
|
||||
r#"[package]
|
||||
name = "lock-core"
|
||||
version = "0.0.1"
|
||||
edition = "2024"
|
||||
[workspace]
|
||||
members = ["src/runtime"]
|
||||
[dependencies]
|
||||
lock-runtime = { path = "src/runtime", features = ["client", "server"] }
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(root.join("src/lib.rs"), "").unwrap();
|
||||
fs::write(runtime.join("lib.rs"), "").unwrap();
|
||||
let manifest = r#"[package]
|
||||
name = "lock-runtime"
|
||||
version = "0.0.1"
|
||||
edition = "2024"
|
||||
[lib]
|
||||
path = "lib.rs"
|
||||
[dependencies]
|
||||
bytes = { version = "=1.12.1", optional = true }
|
||||
[features]
|
||||
client = []
|
||||
server = ["dep:bytes"]
|
||||
"#;
|
||||
fs::write(runtime.join("Cargo.toml"), manifest).unwrap();
|
||||
fs::write(
|
||||
generated.join("Cargo.toml"),
|
||||
format!(
|
||||
r#"[package]
|
||||
name = "lock-client"
|
||||
version = "0.0.1"
|
||||
edition = "2024"
|
||||
[lib]
|
||||
path = "lib.rs"
|
||||
[dependencies]
|
||||
lock-runtime = {{ path = {:?}, features = ["client"] }}
|
||||
"#,
|
||||
runtime
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(generated.join("lib.rs"), "").unwrap();
|
||||
metadata(&root, false).unwrap();
|
||||
let core_lock = fs::read(root.join("Cargo.lock")).unwrap();
|
||||
prepare_lock(&root, &generated, true).unwrap();
|
||||
assert!(
|
||||
!packages(&metadata(&generated, true).unwrap())
|
||||
.iter()
|
||||
.any(|(name, _, _)| name == "bytes")
|
||||
);
|
||||
fs::write(
|
||||
runtime.join("Cargo.toml"),
|
||||
manifest.replace("client = []", "client = [\"dep:bytes\"]"),
|
||||
)
|
||||
.unwrap();
|
||||
metadata(&root, true).unwrap();
|
||||
assert_eq!(fs::read(root.join("Cargo.lock")).unwrap(), core_lock);
|
||||
assert!(metadata(&generated, true).is_err());
|
||||
prepare_lock(&root, &generated, false).unwrap();
|
||||
assert!(
|
||||
packages(&metadata(&generated, true).unwrap())
|
||||
.iter()
|
||||
.any(|(name, _, _)| name == "bytes")
|
||||
);
|
||||
prepare_lock(&root, &generated, false).unwrap();
|
||||
metadata(&generated, true).unwrap();
|
||||
fs::remove_dir_all(temporary).unwrap();
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
use super::*;
|
||||
use std::io::Write;
|
||||
|
||||
struct Fixture {
|
||||
root: PathBuf,
|
||||
home: PathBuf,
|
||||
digest: String,
|
||||
}
|
||||
impl Fixture {
|
||||
fn new(name: &str) -> Self {
|
||||
let base = directory(name);
|
||||
let root = base.join("project");
|
||||
let home = base.join("home");
|
||||
fs::create_dir_all(root.join("module/demo/main")).unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
fs::create_dir_all(&home).unwrap();
|
||||
write_source(
|
||||
root.join("module/demo/main/app/main.dever"),
|
||||
"start() (value: Int) { value = toolkit.math.answer() }",
|
||||
)
|
||||
.unwrap();
|
||||
let output = Command::new("python3").args(["-c", r#"
|
||||
import hashlib, io, json, pathlib, sys, zipfile
|
||||
root, home = map(pathlib.Path, sys.argv[1:])
|
||||
manifest = json.dumps(dict(format='dever-package-v1', name='toolkit', version='1.0.0', dependencies={}))
|
||||
archive = io.BytesIO()
|
||||
with zipfile.ZipFile(archive, 'w', compression=zipfile.ZIP_DEFLATED) as z:
|
||||
z.writestr('dever-package.json', manifest)
|
||||
z.writestr('module/toolkit/math/app/main.dever', 'answer() (value: Int) { value = 42 }')
|
||||
z.writestr('module/toolkit/math/doc/answer.md', '## toolkit.math.app.answer\n\nThe answer.\n')
|
||||
z.writestr('module/toolkit/front/dist/theme/main.txt', 'theme asset')
|
||||
z.writestr('module/toolkit/front/dist/theme/example.dever', 'not compiler input')
|
||||
z.writestr('module/toolkit/front/src/theme/main.txt', 'unbuilt theme')
|
||||
z.writestr('module/toolkit/front/build', '#!/bin/sh\nexit 7\n')
|
||||
raw = archive.getvalue()
|
||||
sha = hashlib.sha256(raw).hexdigest()
|
||||
cache = home / '.dever/packages'
|
||||
cache.mkdir(parents=True, exist_ok=True)
|
||||
(cache / sha).write_bytes(raw)
|
||||
registry = 'https://registry.invalid'
|
||||
(root/'config/setting.json').write_text(json.dumps({'package': {'registry': registry, 'use':['toolkit@^1']}}))
|
||||
(root/'dever.lock').write_text(json.dumps(dict(format='dever-lock-1', registry=registry, roots={'toolkit':'^1'}, packages=[dict(name='toolkit',version='1.0.0',sha256=sha,bytes=len(raw),manifest_sha256=hashlib.sha256(manifest.encode()).hexdigest(),dependencies={})])))
|
||||
print(sha)
|
||||
"#]).arg(&root).arg(&home).output().unwrap();
|
||||
let digest = success(output).trim().to_owned();
|
||||
Self { root, home, digest }
|
||||
}
|
||||
fn command(&self, args: &[&str]) -> Output {
|
||||
Command::new(env!("CARGO_BIN_EXE_dever"))
|
||||
.env("DEVER_HOME", self.home.join(".dever"))
|
||||
.args(args)
|
||||
.output()
|
||||
.unwrap()
|
||||
}
|
||||
fn root(&self) -> &str {
|
||||
self.root.to_str().unwrap()
|
||||
}
|
||||
fn archive(&self) -> PathBuf {
|
||||
self.home.join(".dever/packages").join(&self.digest)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locked_package_front_is_served_from_the_binary_after_cache_is_removed() {
|
||||
let fixture = Fixture::new("package-web");
|
||||
let local = fixture.root.join("module/demo/front/src");
|
||||
fs::create_dir_all(&local).unwrap();
|
||||
fs::write(local.join("index.html"), "local frontend").unwrap();
|
||||
let (config, port, mut settings) = super::api::config(&fixture.root);
|
||||
let old: serde_json::Value = serde_json::from_slice(&fs::read(&config).unwrap()).unwrap();
|
||||
settings["package"] = old["package"].clone();
|
||||
settings["sites"]["front"]["front"] = serde_json::json!({"component":"toolkit","path":"/"});
|
||||
fs::write(&config, settings.to_string()).unwrap();
|
||||
success(fixture.command(&["fmt", fixture.root()]));
|
||||
let binary = fixture.root.parent().unwrap().join("site");
|
||||
success(fixture.command(&[
|
||||
"build",
|
||||
fixture.root(),
|
||||
"--profile",
|
||||
"dev",
|
||||
"--output",
|
||||
binary.to_str().unwrap(),
|
||||
]));
|
||||
fs::rename(
|
||||
fixture.home.join(".dever/packages"),
|
||||
fixture.home.join("removed-packages"),
|
||||
)
|
||||
.unwrap();
|
||||
let server = super::api::Server::start(&binary, &config, port);
|
||||
let (status, body, _) = server.raw_response("GET", "/theme/main.txt", "", "");
|
||||
assert_eq!(status, 200);
|
||||
assert_eq!(body, "theme asset");
|
||||
let (status, _, _) = server.raw_response("GET", "/", "", "");
|
||||
assert_eq!(status, 404, "unselected local component must not be hosted");
|
||||
server.stop();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn package_offline_cli_build_navigation_and_export() {
|
||||
let fixture = Fixture::new("package-cli");
|
||||
success(fixture.command(&["fmt", fixture.root()]));
|
||||
success(fixture.command(&["check", fixture.root()]));
|
||||
assert_eq!(
|
||||
success(fixture.command(&["package", "list", fixture.root()])).trim(),
|
||||
"toolkit@1.0.0"
|
||||
);
|
||||
success(fixture.command(&["lib", "install", fixture.root()]));
|
||||
let index: serde_json::Value = serde_json::from_str(&success(fixture.command(&[
|
||||
"inspect",
|
||||
fixture.root(),
|
||||
"--json",
|
||||
])))
|
||||
.unwrap();
|
||||
assert!(
|
||||
index["symbols"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|s| s["name"] == "toolkit.math.app.answer")
|
||||
);
|
||||
assert!(
|
||||
index["documentation"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|s| s["symbol"] == "toolkit.math.app.answer")
|
||||
);
|
||||
success(fixture.command(&["inspect", fixture.root(), "--links"]));
|
||||
assert!(!fixture.root.join("module/toolkit").exists());
|
||||
let cached = fixture
|
||||
.archive()
|
||||
.with_file_name(format!("{}.unpacked", fixture.digest))
|
||||
.join("module/toolkit/math/app/main.dever");
|
||||
assert_eq!(
|
||||
fs::read_to_string(&cached).unwrap(),
|
||||
"answer() (value: Int) { value = 42 }"
|
||||
);
|
||||
assert_eq!(
|
||||
success(fixture.command(&["run", fixture.root(), "--entry", "demo.main.app.start"])).trim(),
|
||||
"42"
|
||||
);
|
||||
let output = fixture.root.parent().unwrap().join("exported");
|
||||
let args = [
|
||||
"package",
|
||||
"export",
|
||||
fixture.root(),
|
||||
"toolkit",
|
||||
"front/dist/theme",
|
||||
"--output",
|
||||
output.to_str().unwrap(),
|
||||
];
|
||||
let report: serde_json::Value = serde_json::from_str(&success(fixture.command(&args))).unwrap();
|
||||
assert_eq!(report["package"], "toolkit");
|
||||
assert_eq!(report["files"].as_array().unwrap().len(), 2);
|
||||
assert_eq!(fs::read(output.join("main.txt")).unwrap(), b"theme asset");
|
||||
assert!(!fixture.command(&args).status.success());
|
||||
assert_eq!(fs::read(output.join("main.txt")).unwrap(), b"theme asset");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn package_application_runs_without_local_module_directory() {
|
||||
let fixture = Fixture::new("package-only");
|
||||
fs::remove_dir_all(fixture.root.join("module")).unwrap();
|
||||
let path = fixture.root();
|
||||
assert_eq!(
|
||||
success(fixture.command(&["package", "list", path])).trim(),
|
||||
"toolkit@1.0.0"
|
||||
);
|
||||
success(fixture.command(&["package", "doctor", path]));
|
||||
success(fixture.command(&["check", path]));
|
||||
success(fixture.command(&["inspect", path, "--links", "--check"]));
|
||||
let entry = "toolkit.math.app.answer";
|
||||
assert_eq!(
|
||||
success(fixture.command(&["run", path, "--entry", entry])).trim(),
|
||||
"42"
|
||||
);
|
||||
let output = fixture.root.join("app");
|
||||
success(fixture.command(&[
|
||||
"build",
|
||||
path,
|
||||
"--entry",
|
||||
entry,
|
||||
"--profile",
|
||||
"dev",
|
||||
"--output",
|
||||
output.to_str().unwrap(),
|
||||
]));
|
||||
assert_eq!(run(&output), "42");
|
||||
assert!(!fixture.root.join("module").exists());
|
||||
|
||||
fs::remove_file(fixture.root.join("dever.lock")).unwrap();
|
||||
assert!(!fixture.command(&["check", path]).status.success());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn package_mutation_preserves_failures_and_remove_is_offline() {
|
||||
let fixture = Fixture::new("package-mutation");
|
||||
let settings = fixture.root.join("config/setting.json");
|
||||
let lock = fixture.root.join("dever.lock");
|
||||
let before = (fs::read(&settings).unwrap(), fs::read(&lock).unwrap());
|
||||
for args in [
|
||||
vec!["package", "add", fixture.root(), "../bad@*"],
|
||||
vec!["package", "update", fixture.root(), "absent"],
|
||||
vec!["package", "remove", fixture.root(), "absent"],
|
||||
vec!["package", "add", fixture.root(), "other@^1"],
|
||||
] {
|
||||
assert!(!fixture.command(&args).status.success());
|
||||
assert_eq!(
|
||||
(fs::read(&settings).unwrap(), fs::read(&lock).unwrap()),
|
||||
before
|
||||
);
|
||||
}
|
||||
success(fixture.command(&["package", "remove", fixture.root(), "toolkit"]));
|
||||
let removed: serde_json::Value = serde_json::from_slice(&fs::read(&lock).unwrap()).unwrap();
|
||||
assert_eq!(removed["packages"], serde_json::json!([]));
|
||||
success(fixture.command(&["package", "doctor", fixture.root()]));
|
||||
assert!(
|
||||
fixture.archive().exists(),
|
||||
"remove must not delete shared cached archives"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn package_rejects_stale_locks_local_conflicts_and_corrupt_cache() {
|
||||
let fixture = Fixture::new("package-integrity");
|
||||
let lock = fixture.root.join("dever.lock");
|
||||
let bytes = fs::read(&lock).unwrap();
|
||||
let mut altered: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
|
||||
altered["registry"] = "https://another.invalid".into();
|
||||
fs::write(&lock, altered.to_string()).unwrap();
|
||||
assert!(!fixture.command(&["check", fixture.root()]).status.success());
|
||||
fs::write(&lock, &bytes).unwrap();
|
||||
let conflict = fixture.root.join("module/toolkit");
|
||||
fs::create_dir(&conflict).unwrap();
|
||||
assert!(!fixture.command(&["check", fixture.root()]).status.success());
|
||||
fs::remove_dir(conflict).unwrap();
|
||||
fs::OpenOptions::new()
|
||||
.append(true)
|
||||
.open(fixture.archive())
|
||||
.unwrap()
|
||||
.write_all(b"changed")
|
||||
.unwrap();
|
||||
let output = fixture.command(&["package", "doctor", fixture.root()]);
|
||||
assert!(!output.status.success());
|
||||
assert!(
|
||||
String::from_utf8(output.stderr)
|
||||
.unwrap()
|
||||
.contains("SHA-256")
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
use super::*;
|
||||
|
||||
fn executable(domain: &Path) {
|
||||
let bin = domain.join("bin");
|
||||
fs::create_dir_all(&bin).unwrap();
|
||||
let source = bin.join("tool.rs");
|
||||
fs::write(
|
||||
&source,
|
||||
r#"use std::io::{Read,Write};
|
||||
fn main() {
|
||||
let mut bytes = Vec::new(); std::io::stdin().read_to_end(&mut bytes).unwrap();
|
||||
let argument = std::env::args().nth(1).unwrap();
|
||||
std::io::stdout().write_all(argument.as_bytes()).unwrap();
|
||||
std::io::stdout().write_all(&bytes).unwrap();
|
||||
std::io::stderr().write_all(b"diagnostic").unwrap();
|
||||
std::process::exit(7);
|
||||
}"#,
|
||||
)
|
||||
.unwrap();
|
||||
success(
|
||||
Command::new("rustc")
|
||||
.args(["+1.95.0", "-C", "target-feature=+crt-static"])
|
||||
.arg(&source)
|
||||
.arg("-o")
|
||||
.arg(bin.join("tool"))
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_command_runs_without_shell_and_is_embedded_in_published_binary() {
|
||||
let root = project(
|
||||
"external-command",
|
||||
"execute(args: List<Text>, stdin: Bytes?) (output: dever.process.Output) fails dever.process.Error",
|
||||
"external command \"bin/tool\" {}",
|
||||
r#"flow start() (code: Int, stdout: Text, stderr: Text)
|
||||
| step | kind | do |
|
||||
| output | port | port.execute(["$(printf wrong) 中文"], dever.bytes.fromText("input")) |
|
||||
| code | calc | output.code |
|
||||
| stdout | calc | dever.bytes.toText(output.stdout) |
|
||||
| stderr | calc | dever.bytes.toText(output.stderr) |
|
||||
"#,
|
||||
);
|
||||
let domain = root.join("module/demo/service");
|
||||
executable(&domain);
|
||||
let (loaded, program) = analyze(&root);
|
||||
let target = program
|
||||
.functions
|
||||
.iter()
|
||||
.find(|function| function.signature.name.ends_with("adapter.port.execute"))
|
||||
.unwrap();
|
||||
assert!(target.effects.process && target.effects.suspends && target.effects.scope());
|
||||
let artifact = build::build(
|
||||
&loaded,
|
||||
&program,
|
||||
"demo.service.app.start",
|
||||
Profile::Dev,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let output = root.join("published");
|
||||
artifact.publish(&output).unwrap();
|
||||
fs::remove_file(domain.join("bin/tool")).unwrap();
|
||||
let text = run(&output);
|
||||
assert!(text.contains("7"), "{text}");
|
||||
assert!(text.contains("diagnostic"), "{text}");
|
||||
assert!(text.contains("$(printf wrong) 中文input"), "{text}");
|
||||
success(cli(&["fmt", root.to_str().unwrap()]));
|
||||
success(cli(&["fmt", root.to_str().unwrap(), "--check"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_command_requires_adapter_matching_port_and_explicit_failures() {
|
||||
for (name, port, adapter) in [
|
||||
(
|
||||
"missing-fails",
|
||||
"execute(args: List<Text>, stdin: Bytes?) (output: dever.process.Output)",
|
||||
"external command \"bin/tool\" {}",
|
||||
),
|
||||
(
|
||||
"signature",
|
||||
"execute(args: List<Text>) (output: dever.process.Output) fails dever.process.Error",
|
||||
"external command \"bin/tool\" {}",
|
||||
),
|
||||
(
|
||||
"escape",
|
||||
"execute(args: List<Text>, stdin: Bytes?) (output: dever.process.Output) fails dever.process.Error",
|
||||
"external command \"../tool\" {}",
|
||||
),
|
||||
(
|
||||
"limit",
|
||||
"execute(args: List<Text>, stdin: Bytes?) (output: dever.process.Output) fails dever.process.Error",
|
||||
"external command \"bin/tool\" { timeout_ms = 0 }",
|
||||
),
|
||||
] {
|
||||
let root = project(
|
||||
&format!("external-{name}"),
|
||||
port,
|
||||
adapter,
|
||||
"flow start() (out: dever.process.Output)\n| step | kind | do |\n| out | port | port.execute([], null) |",
|
||||
);
|
||||
let project = Project::load(&root).unwrap();
|
||||
assert!(
|
||||
!project.diagnostics.is_empty()
|
||||
|| program::check(&project.declarations, &project.modules).is_err(),
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_command_failure_can_be_captured_but_not_discarded() {
|
||||
let root = project(
|
||||
"external-capture",
|
||||
"execute(args: List<Text>, stdin: Bytes?) (output: dever.process.Output) fails dever.process.Error",
|
||||
"external command \"bin/tool\" { output_limit = 1 }",
|
||||
r#"type Attempt { Done(output: dever.process.Output), error Failed(error: dever.process.Error) }
|
||||
flow start() (out: Attempt)
|
||||
| step | kind | do |
|
||||
| out | port | result(port.execute(["overflow"], null)) |
|
||||
"#,
|
||||
);
|
||||
executable(&root.join("module/demo/service"));
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(
|
||||
&loaded,
|
||||
&program,
|
||||
"demo.service.app.start",
|
||||
Profile::Dev,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let text = run(&artifact.binary);
|
||||
assert!(text.contains("output exceeds combined limit"), "{text}");
|
||||
write_source(
|
||||
root.join("module/demo/service/app/main.dever"),
|
||||
r#"type Attempt { Done(output: dever.process.Output), error Failed(error: dever.process.Error) }
|
||||
flow capture() (out: Attempt)
|
||||
| step | kind | do |
|
||||
| out | port | result(port.execute(["overflow"], null)) |
|
||||
|
||||
flow start() (out: Int)
|
||||
| step | kind | do |
|
||||
| ignored | flow | capture() |
|
||||
| out | calc | 1 |
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
let project = Project::load(&root).unwrap();
|
||||
assert!(program::check(&project.declarations, &project.modules).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_build_rejects_non_elf_and_assets_outside_domain() {
|
||||
let root = project(
|
||||
"external-assets",
|
||||
"execute(args: List<Text>, stdin: Bytes?) (output: dever.process.Output) fails dever.process.Error",
|
||||
"external command \"bin/tool\" {}",
|
||||
"flow start() (out: dever.process.Output)\n| step | kind | do |\n| out | port | port.execute([], null) |",
|
||||
);
|
||||
let domain = root.join("module/demo/service");
|
||||
executable(&domain);
|
||||
let (loaded, program) = analyze(&root);
|
||||
let binary = domain.join("bin/tool");
|
||||
let other = match build::Target::host().unwrap() {
|
||||
build::Target::LinuxX86_64 => build::Target::LinuxAarch64,
|
||||
build::Target::LinuxAarch64 => build::Target::LinuxX86_64,
|
||||
};
|
||||
let error = build::build(
|
||||
&loaded,
|
||||
&program,
|
||||
"demo.service.app.start",
|
||||
Profile::Dev,
|
||||
Some(other),
|
||||
)
|
||||
.err()
|
||||
.unwrap()
|
||||
.to_string();
|
||||
assert!(
|
||||
error.contains(&format!("not an executable for {}", other.arch())),
|
||||
"{error}"
|
||||
);
|
||||
fs::write(&binary, b"#!/bin/sh\nexit 0\n").unwrap();
|
||||
assert!(
|
||||
build::build(
|
||||
&loaded,
|
||||
&program,
|
||||
"demo.service.app.start",
|
||||
Profile::Dev,
|
||||
None
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
fs::remove_file(&binary).unwrap();
|
||||
std::os::unix::fs::symlink("/bin/true", &binary).unwrap();
|
||||
assert!(
|
||||
build::build(
|
||||
&loaded,
|
||||
&program,
|
||||
"demo.service.app.start",
|
||||
Profile::Dev,
|
||||
None
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dynamic_command_carries_transitive_libraries_and_cleans_its_private_directory() {
|
||||
let root = project(
|
||||
"dynamic-command",
|
||||
"execute(args: List<Text>, stdin: Bytes?) (output: dever.process.Output) fails dever.process.Error",
|
||||
"external command \"bin/tool\" {}",
|
||||
r#"flow start() (first: Text, second: Text)
|
||||
| step | kind | do |
|
||||
| one | port | port.execute([], null) |
|
||||
| two | port | port.execute([], null) |
|
||||
| first | calc | dever.bytes.toText(one.stdout) |
|
||||
| second | calc | dever.bytes.toText(two.stdout) |
|
||||
"#,
|
||||
);
|
||||
let bin = root.join("module/demo/service/bin");
|
||||
fs::create_dir_all(&bin).unwrap();
|
||||
fs::write(bin.join("leaf.c"), "int leaf(void) { return 37; }").unwrap();
|
||||
fs::write(
|
||||
bin.join("answer.c"),
|
||||
"extern int leaf(void); int answer(void) { return leaf()+5; }",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
bin.join("tool.c"),
|
||||
r#"#include <stdio.h>
|
||||
#include <unistd.h>
|
||||
extern int answer(void);
|
||||
int main(void) {
|
||||
char path[4096]; ssize_t size=readlink("/proc/self/exe",path,sizeof(path)-1);
|
||||
if(size<0) return 1;
|
||||
path[size]=0; printf("%d:%s",answer(),path); return 0;
|
||||
}"#,
|
||||
)
|
||||
.unwrap();
|
||||
for args in [
|
||||
vec![
|
||||
"-shared",
|
||||
"-fPIC",
|
||||
"leaf.c",
|
||||
"-Wl,-soname,libdever_leaf.so",
|
||||
"-o",
|
||||
"libdever_leaf.so",
|
||||
],
|
||||
vec![
|
||||
"-shared",
|
||||
"-fPIC",
|
||||
"answer.c",
|
||||
"-L.",
|
||||
"-ldever_leaf",
|
||||
"-Wl,-rpath,$ORIGIN",
|
||||
"-Wl,-soname,libdever_answer.so",
|
||||
"-o",
|
||||
"libdever_answer.so",
|
||||
],
|
||||
vec![
|
||||
"tool.c",
|
||||
"-L.",
|
||||
"-ldever_answer",
|
||||
"-Wl,-rpath,$ORIGIN",
|
||||
"-o",
|
||||
"tool",
|
||||
],
|
||||
] {
|
||||
success(
|
||||
Command::new("cc")
|
||||
.current_dir(&bin)
|
||||
.args(args)
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
}
|
||||
fs::write(
|
||||
root.join("module/demo/service/api.dever"),
|
||||
"cmd start = app.start",
|
||||
)
|
||||
.unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
let published = root.join("relocated");
|
||||
artifact.publish(&published).unwrap();
|
||||
fs::remove_dir_all(&bin).unwrap();
|
||||
let output = success(
|
||||
Command::new(&published)
|
||||
.args(["demo.service.start", "{}"])
|
||||
.env("LD_LIBRARY_PATH", "/does-not-exist")
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
let values: serde_json::Value = serde_json::from_str(&output).unwrap();
|
||||
let first = values["data"]["first"].as_str().unwrap();
|
||||
assert!(first.starts_with("42:"), "{output}");
|
||||
assert_eq!(first, values["data"]["second"].as_str().unwrap());
|
||||
assert_eq!(
|
||||
Path::new(first.strip_prefix("42:").unwrap())
|
||||
.file_name()
|
||||
.unwrap(),
|
||||
"program"
|
||||
);
|
||||
let directory = Path::new(first.strip_prefix("42:").unwrap())
|
||||
.parent()
|
||||
.unwrap();
|
||||
assert!(
|
||||
!directory.exists(),
|
||||
"resource directory leaked: {}",
|
||||
directory.display()
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
use super::*;
|
||||
mod command;
|
||||
mod native;
|
||||
mod native_package;
|
||||
mod selection;
|
||||
pub(crate) mod worker;
|
||||
|
||||
fn project(name: &str, port: &str, adapter: &str, app: &str) -> PathBuf {
|
||||
let root = directory(name);
|
||||
let domain = root.join("module/demo/service");
|
||||
for (file, source) in [
|
||||
("port.dever", port),
|
||||
("adapter.dever", adapter),
|
||||
("app/main.dever", app),
|
||||
] {
|
||||
write_source(domain.join(file), source).unwrap();
|
||||
}
|
||||
root
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn port_binds_directly_and_keeps_table_kind_in_inspect() {
|
||||
let root = project(
|
||||
"port-native",
|
||||
"add(value: Int) (out: Int)",
|
||||
"port.add(value: Int) (out: Int) { out = value + 1 }",
|
||||
"flow start() (out: Int)\n| step | kind | do |\n| out | port | port.add(41) |",
|
||||
);
|
||||
let (project, program) = analyze(&root);
|
||||
assert_eq!(program.functions.len(), 2, "no forwarding implementation");
|
||||
let files = emit::emit(&program, &ownership::analyze(&program), &project.sources);
|
||||
let app = &files["module/d_4_demo_7_service_3_app.rs"].text;
|
||||
assert!(
|
||||
app.contains("d_4_demo_7_service_7_adapter_4_port_3_add(41i64)"),
|
||||
"{app}"
|
||||
);
|
||||
let artifact = build::build(
|
||||
&project,
|
||||
&program,
|
||||
"demo.service.app.start",
|
||||
Profile::Dev,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(run(&artifact.binary), "42");
|
||||
let path = root.to_str().unwrap();
|
||||
success(cli(&["fmt", path]));
|
||||
success(cli(&["fmt", path, "--check"]));
|
||||
let index: serde_json::Value =
|
||||
serde_json::from_str(&success(cli(&["inspect", path, "--json"]))).unwrap();
|
||||
let contract = index["symbols"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|symbol| symbol["kind"] == "port")
|
||||
.unwrap();
|
||||
assert_eq!(contract["name"], "demo.service.port.add");
|
||||
assert!(
|
||||
index["calls"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|edge| edge["caller"] == contract["id"] && edge["kind"] == "implementation")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effectful_adapter_is_awaited_directly_and_cannot_be_called_around_its_port() {
|
||||
let root = project(
|
||||
"port-async",
|
||||
"pause() () fails dever.time.SleepResult",
|
||||
"flow port.pause() ()\n| step | kind | do |\n| - | flow | dever.time.sleep(0) |",
|
||||
"flow start() (out: Int)\n| step | kind | do |\n| - | port | port.pause() |\n| out | calc | 42 |",
|
||||
);
|
||||
let (loaded, program) = analyze(&root);
|
||||
let target = program
|
||||
.functions
|
||||
.iter()
|
||||
.find(|function| function.signature.name == "demo.service.app.start")
|
||||
.unwrap();
|
||||
assert!(target.effects.suspends && target.effects.clock);
|
||||
let artifact = build::build(
|
||||
&loaded,
|
||||
&program,
|
||||
"demo.service.app.start",
|
||||
Profile::Dev,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(run(&artifact.binary), "42");
|
||||
write_source(
|
||||
root.join("module/demo/service/app/main.dever"),
|
||||
"flow start() ()\n| step | kind | do |\n| - | - | demo.service.adapter.port.pause() |",
|
||||
)
|
||||
.unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(program::check(&loaded.declarations, &loaded.modules).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adapter_contract_rejects_mismatch_hidden_effects_and_undeclared_failures() {
|
||||
let app = "flow start() (out: Int)\n| step | kind | do |\n| out | port | port.read(1) |";
|
||||
for (name, contract, implementation, message) in [
|
||||
(
|
||||
"signature",
|
||||
"read(value: Int) (out: Int)",
|
||||
"port.read(value: Bool) (out: Int) { out = 1 }",
|
||||
"signature",
|
||||
),
|
||||
(
|
||||
"failure",
|
||||
"read(value: Int) (out: Int)",
|
||||
"port.read(value: Int) (out: Int) { check value > 0 else Invalid\nout = value }",
|
||||
"failures",
|
||||
),
|
||||
(
|
||||
"effect",
|
||||
"read(value: Int) (out: Int)",
|
||||
"port.read(value: Int) (out: Int) { time = dever.time.now()\nout = value }",
|
||||
"effectful",
|
||||
),
|
||||
(
|
||||
"missing",
|
||||
"read(value: Int) (out: Int)",
|
||||
"helper() () {}",
|
||||
"requires an Adapter",
|
||||
),
|
||||
] {
|
||||
let root = project(&format!("port-{name}"), contract, implementation, app);
|
||||
let project = Project::load(&root).unwrap();
|
||||
assert!(project.diagnostics.is_empty(), "{:?}", project.diagnostics);
|
||||
let error = program::check(&project.declarations, &project.modules)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert!(error.message.contains(message), "{name}: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adapter_propagates_declared_error_through_a_rule_without_wrapping() {
|
||||
let root = project(
|
||||
"port-fails",
|
||||
"type Error { error Rejected }\nread(value: Int) (out: Int) fails Error",
|
||||
"rule port.read(value: Int) (out: Int)\n| value | out |\n| < 0 | fail(port.Error.Rejected) |\n| >= 0 | value |",
|
||||
"flow start() (out: Int)\n| step | kind | do |\n| out | port | port.read(-1) |",
|
||||
);
|
||||
let (project, program) = analyze(&root);
|
||||
let artifact = build::build(
|
||||
&project,
|
||||
&program,
|
||||
"demo.service.app.start",
|
||||
Profile::Dev,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let output = Command::new(&artifact.binary).output().unwrap();
|
||||
assert!(!output.status.success());
|
||||
assert!(
|
||||
String::from_utf8_lossy(&output.stderr).contains("Rejected"),
|
||||
"{:?}",
|
||||
output
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adapter_private_settings_load_once_from_their_own_namespace() {
|
||||
let root = project(
|
||||
"port-private-setting",
|
||||
"read() (out: Text)",
|
||||
"setting { prefix: Text\nlimit: Int >= 1 and <= 100\nkey: Secret }\nport.read() (out: Text) { out = setting.prefix }",
|
||||
"setting prefix: Text\nflow start() (out: Text)\n| step | kind | do |\n| out | port | port.read() |",
|
||||
);
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
let configuration = root.join("config/setting.json");
|
||||
fs::write(&configuration,r#"{"module":{"demo":{"service":{"prefix":"domain"}}},"adapter":{"demo.service":{"setting":{"prefix":"adapter","limit":10,"key":"private-value"}}}}"#).unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(
|
||||
&loaded,
|
||||
&program,
|
||||
"demo.service.app.start",
|
||||
Profile::Dev,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let run = || {
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&configuration)
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
let result = run();
|
||||
assert!(
|
||||
result.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&result.stderr)
|
||||
);
|
||||
assert_eq!(
|
||||
String::from_utf8_lossy(&result.stdout).trim(),
|
||||
"\"adapter\""
|
||||
);
|
||||
success(cli(&["fmt", root.to_str().unwrap()]));
|
||||
success(cli(&["fmt", root.to_str().unwrap(), "--check"]));
|
||||
assert!(
|
||||
fs::read_to_string(root.join("module/demo/service/adapter.dever"))
|
||||
.unwrap()
|
||||
.starts_with("setting {")
|
||||
);
|
||||
success(cli(&["inspect", root.to_str().unwrap(), "--json"]));
|
||||
for bad in [
|
||||
r#"{"module":{"demo":{"service":{"prefix":"domain"}}},"adapter":{"demo.service":{"setting":{"prefix":"adapter","limit":0,"key":"private-value"}}}}"#,
|
||||
r#"{"module":{"demo":{"service":{"prefix":"domain"}}},"adapter":{"demo.service":{"setting":{"prefix":"adapter","limit":10}}}}"#,
|
||||
r#"{"module":{"demo":{"service":{"prefix":"domain"}}}}"#,
|
||||
] {
|
||||
fs::write(&configuration, bad).unwrap();
|
||||
let result = run();
|
||||
assert!(!result.status.success());
|
||||
assert!(!String::from_utf8_lossy(&result.stderr).contains("private-value"));
|
||||
}
|
||||
write_source(
|
||||
root.join("module/demo/service/app/main.dever"),
|
||||
"start() (out: Text) { out = adapter.setting.prefix }",
|
||||
)
|
||||
.unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(program::check(&loaded.declarations, &loaded.modules).is_err());
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn native_install_rejects_shared_source_and_directory_conflicts_before_preparation() {
|
||||
for same_entry in [true, false] {
|
||||
let root = project(
|
||||
&format!("native-conflict-{same_entry}"),
|
||||
"render(source: Text) (html: Text)",
|
||||
"external npm \"javascript/render.mjs\" { lib \"marked@15.0.12\" }",
|
||||
"flow start() (out: Text)\n| step | kind | do |\n| out | port | port.render(\"hello\") |",
|
||||
);
|
||||
let domain = root.join("module/demo/service");
|
||||
fs::create_dir(domain.join("javascript")).unwrap();
|
||||
fs::create_dir(domain.join("adapter")).unwrap();
|
||||
fs::rename(
|
||||
domain.join("adapter.dever"),
|
||||
domain.join("adapter/first.dever"),
|
||||
)
|
||||
.unwrap();
|
||||
let second = if same_entry {
|
||||
"render.mjs"
|
||||
} else {
|
||||
"second.mjs"
|
||||
};
|
||||
fs::write(
|
||||
domain.join("adapter/second.dever"),
|
||||
format!("external npm \"javascript/{second}\" {{ lib \"marked@14.0.0\" }}"),
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(domain.join("javascript/render.mjs"), "").unwrap();
|
||||
fs::write(domain.join("javascript").join(second), "").unwrap();
|
||||
let output = cli(&["lib", "install", root.to_str().unwrap()]);
|
||||
assert!(!output.status.success());
|
||||
assert!(
|
||||
String::from_utf8_lossy(&output.stderr).contains("different dependencies"),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
assert!(!root.join("dever.lock").exists());
|
||||
assert!(!domain.join("javascript/package.json").exists());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_go_keeps_port_contracts_and_formats_dependencies_without_preparing_tools() {
|
||||
let root = project(
|
||||
"go-contract",
|
||||
"render(source: Text) (html: Text)",
|
||||
"external go \"go/render.go\" { lib \"github.com/yuin/goldmark@v1.7.8\"
|
||||
allow file }",
|
||||
"flow start() (out: Text)\n| step | kind | do |\n| out | port | port.render(\"hello\") |",
|
||||
);
|
||||
success(cli(&["fmt", root.to_str().unwrap()]));
|
||||
success(cli(&["check", root.to_str().unwrap()]));
|
||||
let text = fs::read_to_string(root.join("module/demo/service/adapter.dever")).unwrap();
|
||||
assert!(
|
||||
text.contains("external go") && text.contains("lib \"github.com/yuin/goldmark@v1.7.8\"")
|
||||
);
|
||||
assert!(!root.join("dever.lock").exists());
|
||||
let index: serde_json::Value = serde_json::from_str(&success(cli(&[
|
||||
"inspect",
|
||||
root.to_str().unwrap(),
|
||||
"--json",
|
||||
])))
|
||||
.unwrap();
|
||||
assert_eq!(index["worker_contracts"][0]["ecosystem"], "go");
|
||||
let adapter = root.join("module/demo/service/adapter.dever");
|
||||
for body in [
|
||||
"file \"../private\"",
|
||||
"file \"/private\"",
|
||||
"file \"helper.go\"\nfile \"helper.go\"",
|
||||
] {
|
||||
fs::write(
|
||||
&adapter,
|
||||
format!("external go \"go/render.go\" {{ {body} }}"),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!cli(&["check", root.to_str().unwrap()]).status.success());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "downloads checksum-pinned official Node/npm and a real package through lib install"]
|
||||
fn npm_native_lock_bundles_node_and_packages_and_cleans_runtime_files() {
|
||||
let root = project(
|
||||
"npm-native",
|
||||
"render(source: Text) (html: Text)",
|
||||
"external npm \"javascript/render.mjs\" { lib \"marked@15.0.12\"\nfile \"helper.mjs\"\nfile \"message.txt\"\nallow process }",
|
||||
"flow start() (html: Text)\n| step | kind | do |\n| html | port | port.render(\"# Hello\") |",
|
||||
);
|
||||
let domain = root.join("module/demo/service");
|
||||
let source = domain.join("javascript");
|
||||
fs::create_dir(&source).unwrap();
|
||||
fs::write(source.join("render.mjs"), "import {renderText} from './helper.mjs'; import {spawnSync} from 'node:child_process'; export async function render(payload) { const child=spawnSync(process.execPath,['-e','process.stdout.write(String(21*2))']); if(child.status!==0 || String(child.stdout)!=='42') throw new Error(String(child.stderr)); return {html:renderText(payload.source)}; }").unwrap();
|
||||
fs::write(source.join("helper.mjs"), "import {marked} from 'marked'; import {readFileSync,existsSync} from 'node:fs'; export function renderText(value) { if(existsSync(new URL('./.env',import.meta.url))) throw new Error('undeclared secret copied'); return marked(value+readFileSync(new URL('./message.txt',import.meta.url),'utf8')); }").unwrap();
|
||||
fs::write(source.join("message.txt"), "").unwrap();
|
||||
fs::write(source.join(".env"), "not a runtime resource").unwrap();
|
||||
fs::write(domain.join("api.dever"), "cmd start = app.start").unwrap();
|
||||
success(cli(&["fmt", root.to_str().unwrap()]));
|
||||
success(cli(&["check", root.to_str().unwrap()]));
|
||||
success(cli(&["lib", "install", root.to_str().unwrap()]));
|
||||
let lock = fs::read(source.join("package-lock.json")).unwrap();
|
||||
assert!(String::from_utf8_lossy(&lock).contains("sha512-"));
|
||||
success(cli(&["lib", "install", root.to_str().unwrap()]));
|
||||
assert_eq!(fs::read(source.join("package-lock.json")).unwrap(), lock);
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
let output = root.join("published");
|
||||
artifact.publish(&output).unwrap();
|
||||
fs::remove_dir_all(&source).unwrap();
|
||||
let resources = root.join("runtime-resources");
|
||||
fs::create_dir(&resources).unwrap();
|
||||
let result = success(
|
||||
Command::new(output)
|
||||
.args(["demo.service.start", "{}"])
|
||||
.env("PATH", "")
|
||||
.env("TMPDIR", &resources)
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
let value: serde_json::Value = serde_json::from_str(&result).unwrap();
|
||||
assert_eq!(value["data"], "<h1>Hello</h1>\n");
|
||||
assert_eq!(fs::read_dir(&resources).unwrap().count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "downloads checksum-pinned uv, managed Python and real packages through lib install"]
|
||||
fn python_native_lock_bundles_python_standard_library_extensions_and_packages() {
|
||||
let root = project(
|
||||
"pip-native",
|
||||
"render(source: Text) (html: Text)",
|
||||
"external pip \"python/render.py\" { lib \"Markdown@3.8.2\"\nfile \"helper.py\"\nfile \"message.txt\"\nallow process }",
|
||||
"flow start() (html: Text)\n| step | kind | do |\n| html | port | port.render(\"# Hello\") |",
|
||||
);
|
||||
let domain = root.join("module/demo/service");
|
||||
let source = domain.join("python");
|
||||
fs::create_dir(&source).unwrap();
|
||||
fs::write(source.join("render.py"), "import ssl, sqlite3, subprocess, sys\nfrom helper import render_text\nasync def render(payload, setting):\n child=subprocess.run([sys.executable,'-c','import ssl,sqlite3;print(21*2)'],check=True,capture_output=True,text=True)\n assert child.stdout.strip()=='42'\n return {'html':render_text(payload['source'])}\n").unwrap();
|
||||
fs::write(source.join("helper.py"), "from pathlib import Path\nimport markdown\ndef render_text(value):\n assert not Path(__file__).with_name('.env').exists()\n return markdown.markdown(value + Path(__file__).with_name('message.txt').read_text())\n").unwrap();
|
||||
fs::write(source.join("message.txt"), "").unwrap();
|
||||
fs::write(source.join(".env"), "not a runtime resource").unwrap();
|
||||
fs::write(domain.join("api.dever"), "cmd start = app.start").unwrap();
|
||||
success(cli(&["fmt", root.to_str().unwrap()]));
|
||||
success(cli(&["check", root.to_str().unwrap()]));
|
||||
success(cli(&["lib", "install", root.to_str().unwrap()]));
|
||||
let lock = fs::read(source.join("uv.lock")).unwrap();
|
||||
assert!(String::from_utf8_lossy(&lock).contains("sha256:"));
|
||||
success(cli(&["lib", "install", root.to_str().unwrap()]));
|
||||
assert_eq!(fs::read(source.join("uv.lock")).unwrap(), lock);
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
let output = root.join("published");
|
||||
artifact.publish(&output).unwrap();
|
||||
fs::remove_dir_all(&source).unwrap();
|
||||
let resources = root.join("runtime-resources");
|
||||
fs::create_dir(&resources).unwrap();
|
||||
let result = success(
|
||||
Command::new(&output)
|
||||
.args(["demo.service.start", "{}"])
|
||||
.env("PATH", "")
|
||||
.env("PYTHONPATH", "/does-not-exist")
|
||||
.env("TMPDIR", &resources)
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
let value: serde_json::Value = serde_json::from_str(&result).unwrap();
|
||||
assert_eq!(value["data"], "<h1>Hello</h1>");
|
||||
assert_eq!(fs::read_dir(&resources).unwrap().count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "downloads checksum-pinned official Go and a real module through lib install"]
|
||||
fn go_native_lock_offline_build_and_generated_worker_run_without_source_or_system_go() {
|
||||
let root = project(
|
||||
"go-native",
|
||||
"render(source: Text) (html: Text)",
|
||||
"external go \"go/render.go\" { lib \"github.com/yuin/goldmark@v1.7.8\"\nfile \"helper.go\"\nfile \"message.txt\" }",
|
||||
"flow start() (html: Text)\n| step | kind | do |\n| html | port | port.render(\"# Hello\") |",
|
||||
);
|
||||
let domain = root.join("module/demo/service");
|
||||
let source = domain.join("go");
|
||||
fs::create_dir(&source).unwrap();
|
||||
fs::write(source.join("render.go"), r#"package main
|
||||
import ("context"; "bytes"; "github.com/yuin/goldmark")
|
||||
func Render(ctx context.Context, payload any, setting any) (any,error) {
|
||||
var out bytes.Buffer
|
||||
if err:=goldmark.Convert([]byte(payload.(map[string]any)["source"].(string)+suffix), &out); err!=nil { return nil,err }
|
||||
return map[string]any{"html":out.String()},nil
|
||||
}
|
||||
"#).unwrap();
|
||||
fs::write(
|
||||
source.join("helper.go"),
|
||||
"package main\nimport _ \"embed\"\n//go:embed message.txt\nvar suffix string\n",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(source.join("message.txt"), "").unwrap();
|
||||
fs::write(domain.join("api.dever"), "cmd start = app.start").unwrap();
|
||||
success(cli(&["fmt", root.to_str().unwrap()]));
|
||||
let (loaded, program) = analyze(&root);
|
||||
assert!(
|
||||
build::build(&loaded, &program, "main", Profile::Dev, None)
|
||||
.err()
|
||||
.unwrap()
|
||||
.to_string()
|
||||
.contains("not locked")
|
||||
);
|
||||
success(cli(&["lib", "install", root.to_str().unwrap()]));
|
||||
let lock = fs::read(root.join("dever.lock")).unwrap();
|
||||
let native_mod = fs::read(source.join("go.mod")).unwrap();
|
||||
let native_sum = fs::read(source.join("go.sum")).unwrap();
|
||||
assert!(String::from_utf8_lossy(&native_sum).contains("github.com/yuin/goldmark v1.7.8 h1:"));
|
||||
assert!(!String::from_utf8_lossy(&native_mod).contains("dever/component"));
|
||||
success(cli(&["lib", "install", root.to_str().unwrap()]));
|
||||
assert_eq!(fs::read(root.join("dever.lock")).unwrap(), lock);
|
||||
let (loaded, program) = analyze(&root);
|
||||
fs::write(source.join("go.sum"), b"tampered").unwrap();
|
||||
assert!(
|
||||
build::build(&loaded, &program, "main", Profile::Dev, None)
|
||||
.err()
|
||||
.unwrap()
|
||||
.to_string()
|
||||
.contains("digest mismatch")
|
||||
);
|
||||
fs::write(source.join("go.sum"), &native_sum).unwrap();
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
assert_eq!(fs::read(source.join("go.mod")).unwrap(), native_mod);
|
||||
assert_eq!(fs::read(source.join("go.sum")).unwrap(), native_sum);
|
||||
let output = root.join("published");
|
||||
artifact.publish(&output).unwrap();
|
||||
fs::remove_dir_all(&source).unwrap();
|
||||
let value: serde_json::Value = serde_json::from_str(&success(
|
||||
Command::new(&output)
|
||||
.args(["demo.service.start", "{}"])
|
||||
.env("PATH", "")
|
||||
.output()
|
||||
.unwrap(),
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(value["data"], "<h1>Hello</h1>\n");
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
#[ignore = "uses the checksum-pinned official Go toolchain prepared by lib install"]
|
||||
fn package_native_lock_is_restored_without_mutating_cached_sources() {
|
||||
let author = project(
|
||||
"native-package-author",
|
||||
"render(source: Text) (html: Text)",
|
||||
"external go \"go/render.go\" {}",
|
||||
"flow start() (html: Text)\n| step | kind | do |\n| html | port | port.render(\"packaged\") |",
|
||||
);
|
||||
let directory = author.join("module/demo/service/go");
|
||||
fs::create_dir(&directory).unwrap();
|
||||
fs::write(
|
||||
directory.join("render.go"),
|
||||
r#"package main
|
||||
import "context"
|
||||
func Render(ctx context.Context, payload any, setting any) (any,error) {
|
||||
return map[string]any{"html":payload.(map[string]any)["source"]},nil
|
||||
}
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
success(cli(&["lib", "install", author.to_str().unwrap()]));
|
||||
let consumer = super::super::directory("native-package-consumer");
|
||||
let home = std::env::var_os("DEVER_HOME").expect("native tests require DEVER_HOME");
|
||||
let output = Command::new("python3").args(["-c", r#"
|
||||
import hashlib, io, json, pathlib, sys, zipfile
|
||||
author, root, home = map(pathlib.Path, sys.argv[1:])
|
||||
manifest = json.dumps(dict(format='dever-package-v1', name='demo', version='1.0.0', dependencies={}))
|
||||
archive = io.BytesIO()
|
||||
with zipfile.ZipFile(archive, 'w', compression=zipfile.ZIP_DEFLATED) as z:
|
||||
z.writestr('dever-package.json', manifest)
|
||||
for path in sorted((author/'module').rglob('*')):
|
||||
if path.is_file(): z.write(path, path.relative_to(author))
|
||||
raw = archive.getvalue()
|
||||
digest = hashlib.sha256(raw).hexdigest()
|
||||
(home/'packages').mkdir(exist_ok=True)
|
||||
(home/'packages'/digest).write_bytes(raw)
|
||||
(root/'module/client/start/app').mkdir(parents=True)
|
||||
(root/'module/client/start/app/main.dever').write_text('flow start() (out: Text)\n| step | kind | do |\n| out | flow | demo.service.start() |')
|
||||
(root/'config').mkdir()
|
||||
registry = 'https://registry.invalid'
|
||||
(root/'config/setting.json').write_text(json.dumps({'package':{'registry':registry,'use':['demo@1.0.0']}}))
|
||||
(root/'dever.lock').write_text(json.dumps(dict(format='dever-lock-1',registry=registry,roots={'demo':'1.0.0'},packages=[dict(name='demo',version='1.0.0',sha256=digest,bytes=len(raw),manifest_sha256=hashlib.sha256(manifest.encode()).hexdigest(),dependencies={})])))
|
||||
print(digest)
|
||||
"#]).arg(&author).arg(&consumer).arg(&home).output().unwrap();
|
||||
let digest = success(output).trim().to_owned();
|
||||
success(cli(&["fmt", consumer.to_str().unwrap()]));
|
||||
let cached = PathBuf::from(home)
|
||||
.join("packages")
|
||||
.join(format!("{digest}.unpacked"));
|
||||
success(cli(&["lib", "install", consumer.to_str().unwrap()]));
|
||||
let lock = fs::read(consumer.join("dever.lock")).unwrap();
|
||||
let manifest = fs::read(cached.join("module/demo/service/go/go.mod")).unwrap();
|
||||
assert_eq!(manifest, fs::read(directory.join("go.mod")).unwrap());
|
||||
assert_eq!(
|
||||
success(cli(&[
|
||||
"run",
|
||||
consumer.to_str().unwrap(),
|
||||
"--entry",
|
||||
"client.start.app.start"
|
||||
]))
|
||||
.trim(),
|
||||
"\"packaged\""
|
||||
);
|
||||
success(cli(&["lib", "install", consumer.to_str().unwrap()]));
|
||||
assert_eq!(fs::read(consumer.join("dever.lock")).unwrap(), lock);
|
||||
assert_eq!(
|
||||
fs::read(cached.join("module/demo/service/go/go.mod")).unwrap(),
|
||||
manifest
|
||||
);
|
||||
success(cli(&["package", "doctor", consumer.to_str().unwrap()]));
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
use super::*;
|
||||
|
||||
fn multi(name: &str, port: &str, first: &str, second: &str, app: &str) -> PathBuf {
|
||||
let root = project(name, port, first, app);
|
||||
let domain = root.join("module/demo/service");
|
||||
fs::create_dir(domain.join("adapter")).unwrap();
|
||||
fs::rename(
|
||||
domain.join("adapter.dever"),
|
||||
domain.join("adapter/first.dever"),
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(domain.join("adapter/second.dever"), second).unwrap();
|
||||
fs::create_dir(root.join("config")).unwrap();
|
||||
root
|
||||
}
|
||||
fn selected(binary: &Path, root: &Path, configuration: &str) -> std::process::Output {
|
||||
let path = root.join("config/setting.json");
|
||||
fs::write(&path, configuration).unwrap();
|
||||
Command::new(binary)
|
||||
.arg("--config")
|
||||
.arg(path)
|
||||
.output()
|
||||
.unwrap()
|
||||
}
|
||||
#[test]
|
||||
fn multi_adapter_selects_at_startup_and_decodes_only_selected_settings() {
|
||||
let root = multi(
|
||||
"port-selection",
|
||||
"read(value: Text) (out: Text)",
|
||||
"setting { prefix: Text }\nport.read(value: Text) (out: Text) { out = prefix() + value }\nprefix() (out: Text) { out = setting.prefix }",
|
||||
"setting { count: Int >= 1 and <= 3\nkey: Secret }\nport.read(value: Text) (out: Text) { out = value + value }",
|
||||
"flow start() (out: Text)\n| step | kind | do |\n| out | port | port.read(\"x\") |",
|
||||
);
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(
|
||||
&loaded,
|
||||
&program,
|
||||
"demo.service.app.start",
|
||||
Profile::Dev,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
for (config, expected) in [
|
||||
(
|
||||
r#"{"adapter":{"demo.service":{"use":"first","setting":{"prefix":"A"}}}}"#,
|
||||
"\"Ax\"",
|
||||
),
|
||||
(
|
||||
r#"{"adapter":{"demo.service":{"setting":{"count":2,"key":"private-value"},"use":"second"}}}"#,
|
||||
"\"xx\"",
|
||||
),
|
||||
] {
|
||||
let output = selected(&artifact.binary, &root, config);
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), expected);
|
||||
}
|
||||
for config in [
|
||||
r#"{"adapter":{"demo.service":{"setting":{"prefix":"A"}}}}"#,
|
||||
r#"{"adapter":{"demo.service":{"use":"unknown"}}}"#,
|
||||
r#"{"adapter":{"demo.service":{"use":"first","use":"second","setting":{"prefix":"A"}}}}"#,
|
||||
r#"{"adapter":{"demo.service":{"use":"second","setting":{"count":0,"key":"private-value"}}}}"#,
|
||||
r#"{"adapter":{"demo.service":{"use":"first","setting":{"prefix":"A","prefix":"B"}}}}"#,
|
||||
r#"{"adapter":{"demo.service":{"setting":{"prefix":"A","prefix":"B"},"use":"first"}}}"#,
|
||||
r#"{"adapter":{"demo.service":{"use":"first","setting":{"prefix":"A"},"other":1}}}"#,
|
||||
] {
|
||||
let output = selected(&artifact.binary, &root, config);
|
||||
assert!(!output.status.success(), "accepted {config}");
|
||||
assert!(!String::from_utf8_lossy(&output.stderr).contains("private-value"));
|
||||
}
|
||||
let index: serde_json::Value = serde_json::from_str(&success(cli(&[
|
||||
"inspect",
|
||||
root.to_str().unwrap(),
|
||||
"--json",
|
||||
])))
|
||||
.unwrap();
|
||||
let ports = index["symbols"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|s| s["name"] == "demo.service.port.read")
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(ports.len(), 1);
|
||||
assert_eq!(
|
||||
index["calls"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|edge| edge["caller"] == ports[0]["id"] && edge["kind"] == "implementation")
|
||||
.count(),
|
||||
2
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_adapter_returns_multiple_fields_with_one_call_per_branch() {
|
||||
let root = multi(
|
||||
"port-selection-outputs",
|
||||
"read(value: Text) (first: Text, second: Int)",
|
||||
"port.read(value: Text) (first: Text, second: Int) { first = value\nsecond = 1 }",
|
||||
"port.read(value: Text) (first: Text, second: Int) { first = value\nsecond = 2 }",
|
||||
"flow start() (out: Int)\n| step | kind | do |\n| answer | port | port.read(\"hello\") |\n| out | calc | answer.second |",
|
||||
);
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(
|
||||
&loaded,
|
||||
&program,
|
||||
"demo.service.app.start",
|
||||
Profile::Dev,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
for (name, expected) in [("first", "1"), ("second", "2")] {
|
||||
let output = selected(
|
||||
&artifact.binary,
|
||||
&root,
|
||||
&format!(r#"{{"adapter":{{"demo.service":{{"use":"{name}"}}}}}}"#),
|
||||
);
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_adapter_must_implement_the_whole_port_and_obey_its_contract() {
|
||||
for (name, second, message) in [
|
||||
(
|
||||
"incomplete",
|
||||
"port.read(value: Int) (out: Int) { out = value }",
|
||||
"requires an Adapter",
|
||||
),
|
||||
(
|
||||
"signature",
|
||||
"port.read(value: Bool) (out: Int) { out = 1 }\nport.write() () {}",
|
||||
"signature",
|
||||
),
|
||||
(
|
||||
"failure",
|
||||
"port.read(value: Int) (out: Int) { check value > 0 else Invalid\nout = value }\nport.write() () {}",
|
||||
"failures",
|
||||
),
|
||||
(
|
||||
"cycle",
|
||||
"port.read(value: Int) (out: Int) { out = helper(value) }\nhelper(value: Int) (out: Int) { out = helper(value) }\nport.write() () {}",
|
||||
"recursive",
|
||||
),
|
||||
] {
|
||||
let root = multi(
|
||||
&format!("port-selection-{name}"),
|
||||
"read(value: Int) (out: Int)\nwrite() ()",
|
||||
"port.read(value: Int) (out: Int) { out = value }\nport.write() () {}",
|
||||
second,
|
||||
"flow start() (out: Int)\n| step | kind | do |\n| out | port | port.read(1) |",
|
||||
);
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
let error = program::check(&loaded.declarations, &loaded.modules)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert!(error.message.contains(message), "{name}: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_adapter_keeps_async_failures_and_private_settings_in_child_tasks() {
|
||||
let root = multi(
|
||||
"port-selection-task",
|
||||
"read() (out: Text) fails dever.time.SleepResult",
|
||||
"setting { message: Text }\nflow port.read() (out: Text)\n| step | kind | do |\n| work | calc | run(pause()) |\n| out | calc | wait(work) |\nflow pause() (out: Text)\n| step | kind | do |\n| - | flow | dever.time.sleep(0) |\n| out | calc | setting.message |",
|
||||
"port.read() (out: Text) { out = \"immediate\" }",
|
||||
"flow start() (out: Text)\n| step | kind | do |\n| work | calc | run(port.read()) |\n| out | calc | wait(work) |",
|
||||
);
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(
|
||||
&loaded,
|
||||
&program,
|
||||
"demo.service.app.start",
|
||||
Profile::Dev,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
for (config, expected) in [
|
||||
(
|
||||
r#"{"adapter":{"demo.service":{"use":"first","setting":{"message":"async"}}}}"#,
|
||||
"\"async\"",
|
||||
),
|
||||
(
|
||||
r#"{"adapter":{"demo.service":{"use":"second"}}}"#,
|
||||
"\"immediate\"",
|
||||
),
|
||||
] {
|
||||
let output = selected(&artifact.binary, &root, config);
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_adapter_propagates_selected_failure_without_fallback() {
|
||||
let root = multi(
|
||||
"port-selection-propagate",
|
||||
"type Error { error Rejected }\nread() (out: Int) fails Error",
|
||||
"port.read() (out: Int) { out = 1 }",
|
||||
"port.read() (out: Int) { out = fail(port.Error.Rejected) }",
|
||||
"flow start() (out: Int)\n| step | kind | do |\n| out | port | port.read() |",
|
||||
);
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(
|
||||
&loaded,
|
||||
&program,
|
||||
"demo.service.app.start",
|
||||
Profile::Dev,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let output = selected(
|
||||
&artifact.binary,
|
||||
&root,
|
||||
r#"{"adapter":{"demo.service":{"use":"second"}}}"#,
|
||||
);
|
||||
assert!(!output.status.success());
|
||||
assert!(String::from_utf8_lossy(&output.stderr).contains("Rejected"));
|
||||
let output = selected(
|
||||
&artifact.binary,
|
||||
&root,
|
||||
r#"{"adapter":{"demo.service":{"use":"first"}}}"#,
|
||||
);
|
||||
assert_eq!(success(output).trim(), "1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_adapter_test_fake_replaces_all_production_choices() {
|
||||
let root = multi(
|
||||
"port-selection-fake",
|
||||
"read() (out: Int)",
|
||||
"setting { value: Int }\nport.read() (out: Int) { out = setting.value }",
|
||||
"setting { label: Text }\nport.read() (out: Int) { out = 2 }",
|
||||
"start() (out: Int) { out = port.read() }",
|
||||
);
|
||||
let tests = root.join("test/demo/service");
|
||||
fs::create_dir_all(&tests).unwrap();
|
||||
fs::write(
|
||||
tests.join("fake.dever"),
|
||||
"fake() () { assertEq(app.start(), 42) }\nport.read() (out: Int) { out = 42 }",
|
||||
)
|
||||
.unwrap();
|
||||
success(cli(&["fmt", root.to_str().unwrap()]));
|
||||
let result = success(cli(&["test", root.to_str().unwrap()]));
|
||||
assert!(result.contains("PASS demo.service.fake"), "{result}");
|
||||
assert!(!root.join("config/setting.json").exists());
|
||||
|
||||
write_source(
|
||||
root.join("module/demo/service/app/main.dever"),
|
||||
"setting base:Int\nstart() (out:Int) { out=port.read()+base }",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
tests.join("fake.dever"),
|
||||
"fake() () { assertEq(app.start(),44) }\nport.read() (out:Int) { out=42 }",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(root.join("test/setting.json"), r#"{"module":{"demo":{"service":{"base":2}}},"adapter":{"demo.service":{"use":"first","setting":{"value":7}}}}"#).unwrap();
|
||||
success(cli(&["fmt", root.to_str().unwrap()]));
|
||||
assert!(success(cli(&["test", root.to_str().unwrap()])).contains("PASS demo.service.fake"));
|
||||
fs::write(root.join("test/setting.json"), r#"{"module":{"demo":{"service":{"base":2}}},"adapter":{"demo.service":{},"demo.service":{}}}"#).unwrap();
|
||||
let output = cli(&["test", root.to_str().unwrap()]);
|
||||
assert!(!output.status.success());
|
||||
assert!(String::from_utf8_lossy(&output.stderr).contains("duplicate adapter configuration"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_adapter_does_not_erase_returned_error_obligations_or_effects() {
|
||||
for (name, contract, first, second, app, message) in [
|
||||
(
|
||||
"port-body",
|
||||
"read() (out: Int) { out = 1 }",
|
||||
"port.read() (out: Int) { out = 1 }",
|
||||
"port.read() (out: Int) { out = 2 }",
|
||||
"start() (out: Int) { out = port.read() }",
|
||||
"does not allow function bodies",
|
||||
),
|
||||
(
|
||||
"error-value",
|
||||
"type Outcome { Good\nerror Rejected }\nread() (out: Outcome)",
|
||||
"port.read() (out: port.Outcome) { out = port.Outcome.Good }",
|
||||
"port.read() (out: port.Outcome) { out = port.Outcome.Rejected }",
|
||||
"start() () { ignored = port.read() }",
|
||||
"failure is not handled",
|
||||
),
|
||||
(
|
||||
"effect-union",
|
||||
"read() () fails dever.time.SleepResult",
|
||||
"port.read() () {}",
|
||||
"flow port.read() ()\n| step | kind | do |\n| - | flow | dever.time.sleep(0) |",
|
||||
"start() () { port.read() }",
|
||||
"effectful",
|
||||
),
|
||||
] {
|
||||
let root = multi(
|
||||
&format!("port-selection-{name}"),
|
||||
contract,
|
||||
first,
|
||||
second,
|
||||
app,
|
||||
);
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
let error = program::check(&loaded.declarations, &loaded.modules)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert!(error.message.contains(message), "{name}: {error}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,424 @@
|
||||
use super::*;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
pub(crate) fn executable(domain: &Path) {
|
||||
static BINARY: OnceLock<PathBuf> = OnceLock::new();
|
||||
let binary=BINARY.get_or_init(|| {
|
||||
let root=directory("worker-fixture");
|
||||
fs::write(root.join("Cargo.toml"),"[package]\nname=\"worker-fixture\"\nversion=\"0.0.1\"\nedition=\"2024\"\n[workspace]\n[[bin]]\nname=\"worker-fixture\"\npath=\"main.rs\"\n[dependencies]\nserde_json=\"=1.0.145\"\n").unwrap();
|
||||
fs::write(root.join("main.rs"),include_str!("worker_fixture.rs.txt")).unwrap();
|
||||
success(Command::new("cargo").args(["+1.95.0","build","--offline","--release"]).env("CARGO_TARGET_DIR",root.join("target")).current_dir(&root).output().unwrap());
|
||||
root.join("target/release/worker-fixture")
|
||||
});
|
||||
fs::create_dir_all(domain.join("bin")).unwrap();
|
||||
fs::copy(binary, domain.join("bin/worker")).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_worker_reuses_typed_session_settings_and_embedded_image() {
|
||||
let root = project(
|
||||
"worker-native",
|
||||
"add(value: Int) (out: Int, calls: Int)\necho(value: Text) (out: Text)\nunit() ()",
|
||||
"setting { offset: Int, token: Secret }\nexternal exec \"bin/worker\" {}",
|
||||
"flow start() (out: Int, calls: Int, text: Text)\n| step | kind | do |\n| first | port | port.add(30) |\n| next | port | port.add(first.out) |\n| out | calc | next.out |\n| calls | calc | next.calls |\n| text | port | port.echo(\"中文\") |\n| - | port | port.unit() |",
|
||||
);
|
||||
let domain = root.join("module/demo/service");
|
||||
executable(&domain);
|
||||
fs::create_dir(root.join("config")).unwrap();
|
||||
fs::write(
|
||||
root.join("config/setting.json"),
|
||||
r#"{"adapter":{"demo.service":{"setting":{"offset":6,"token":"private setting"}}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(
|
||||
&loaded,
|
||||
&program,
|
||||
"demo.service.app.start",
|
||||
Profile::Dev,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let resources = fs::read_to_string(artifact.directory.join("external.rs")).unwrap();
|
||||
assert_eq!(resources.matches("static IMAGE_").count(), 1);
|
||||
let output = root.join("published");
|
||||
artifact.publish(&output).unwrap();
|
||||
fs::remove_file(domain.join("bin/worker")).unwrap();
|
||||
let text = run(&output);
|
||||
assert!(
|
||||
text.contains("42") && text.contains("2") && text.contains("中文"),
|
||||
"{text}"
|
||||
);
|
||||
success(cli(&["fmt", root.to_str().unwrap()]));
|
||||
success(cli(&["fmt", root.to_str().unwrap(), "--check"]));
|
||||
let index: serde_json::Value = serde_json::from_str(&success(cli(&[
|
||||
"inspect",
|
||||
root.to_str().unwrap(),
|
||||
"--json",
|
||||
])))
|
||||
.unwrap();
|
||||
assert_eq!(index["worker_contracts"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(
|
||||
index["worker_contracts"][0]["operations"],
|
||||
serde_json::json!(["add", "echo", "unit"])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_worker_decodes_declared_errors_and_rejects_range_violations() {
|
||||
for (name, port, call, expected) in [
|
||||
(
|
||||
"error",
|
||||
"type Error { error Rejected(message: Text) }\nfail() (out: Int) fails Error",
|
||||
"fail",
|
||||
"demo.service.port.Error.Rejected",
|
||||
),
|
||||
(
|
||||
"range",
|
||||
"invalid() (out: Int >= 0 and <= 100)",
|
||||
"invalid",
|
||||
"out is outside its declared range",
|
||||
),
|
||||
] {
|
||||
let root = project(
|
||||
&format!("worker-{name}"),
|
||||
port,
|
||||
"external exec \"bin/worker\" {}",
|
||||
&format!(
|
||||
"flow start() (out: Int)\n| step | kind | do |\n| out | port | port.{call}() |"
|
||||
),
|
||||
);
|
||||
executable(&root.join("module/demo/service"));
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(
|
||||
&loaded,
|
||||
&program,
|
||||
"demo.service.app.start",
|
||||
Profile::Dev,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let resources = root.join("runtime-resources");
|
||||
fs::create_dir(&resources).unwrap();
|
||||
let output = Command::new(&artifact.binary)
|
||||
.env("TMPDIR", &resources)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(!output.status.success());
|
||||
let error = String::from_utf8(output.stderr).unwrap();
|
||||
assert!(error.contains(expected), "{error}");
|
||||
assert_eq!(
|
||||
fs::read_dir(&resources).unwrap().count(),
|
||||
0,
|
||||
"failed Worker left runtime resources"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_worker_rejects_nonportable_ports_and_mixed_implementation() {
|
||||
for (name, port, adapter) in [
|
||||
(
|
||||
"payload-choice",
|
||||
"type State { Value(value: Text) }\nread(value: State) (out: Text)",
|
||||
"external exec \"bin/worker\" {}",
|
||||
),
|
||||
(
|
||||
"error-choice",
|
||||
"type State { Ready, error Failed }\nread(value: State) (out: Text)",
|
||||
"external exec \"bin/worker\" {}",
|
||||
),
|
||||
(
|
||||
"secret",
|
||||
"read(value: Secret) (out: Text)",
|
||||
"external exec \"bin/worker\" {}",
|
||||
),
|
||||
(
|
||||
"resource",
|
||||
"read(value: Bytes) (out: Text)",
|
||||
"external exec \"bin/worker\" {}",
|
||||
),
|
||||
(
|
||||
"mixed",
|
||||
"read() (out: Text)",
|
||||
"external exec \"bin/worker\" {}\nhelper() (out: Int) { out = 1 }",
|
||||
),
|
||||
(
|
||||
"duplicate",
|
||||
"read() (out: Text)",
|
||||
"external exec \"bin/worker\" {}\nexternal exec \"bin/other\" {}",
|
||||
),
|
||||
] {
|
||||
let root = project(
|
||||
&format!("worker-reject-{name}"),
|
||||
port,
|
||||
adapter,
|
||||
"start() (out: Int) { out = 1 }",
|
||||
);
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(
|
||||
!loaded.diagnostics.is_empty()
|
||||
|| program::check(&loaded.declarations, &loaded.modules).is_err(),
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_worker_captures_business_payload_without_losing_error_obligation() {
|
||||
let root = project(
|
||||
"worker-capture",
|
||||
"type Error { error Rejected(message: Text) }\nfail() (out: Int) fails Error",
|
||||
r#"external exec "bin/worker" {}"#,
|
||||
r#"type Attempt { Done(out: Int), error Failed(error: port.Error) }
|
||||
flow start() (out: Attempt)
|
||||
| step | kind | do |
|
||||
| out | port | result(port.fail()) |
|
||||
"#,
|
||||
);
|
||||
executable(&root.join("module/demo/service"));
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(
|
||||
&loaded,
|
||||
&program,
|
||||
"demo.service.app.start",
|
||||
Profile::Dev,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(run(&artifact.binary).contains("business rejection"));
|
||||
}
|
||||
|
||||
fn sdk_contract(name: &str) -> (PathBuf, PathBuf) {
|
||||
let root = project(
|
||||
name,
|
||||
r#"
|
||||
type Error { error Rejected(message: Text) }
|
||||
type ToolName { Add, Multiply }
|
||||
tool(value: ToolName, maybe: ToolName?, items: List<ToolName>) (out: ToolName)
|
||||
echo(value: Int, label: Text?, items: List<Int>) (out: Int, name: Text?)
|
||||
fail() (out: Int) fails Error
|
||||
hang() ()
|
||||
invalid() (out: Int >= 0 and <= 100)
|
||||
raw(value: Json) (out: Json)
|
||||
floating(value: Float) (out: Float)
|
||||
"#,
|
||||
r#"setting { marker: Text }
|
||||
external exec "bin/worker" {}"#,
|
||||
"start() (out: Int) { out = 1 }",
|
||||
);
|
||||
success(cli(&["fmt", root.to_str().unwrap()]));
|
||||
success(cli(&["check", root.to_str().unwrap()]));
|
||||
let index: serde_json::Value = serde_json::from_str(&success(cli(&[
|
||||
"inspect",
|
||||
root.to_str().unwrap(),
|
||||
"--json",
|
||||
])))
|
||||
.unwrap();
|
||||
let manifest = root.join("manifest.json");
|
||||
fs::write(
|
||||
&manifest,
|
||||
serde_json::to_vec(&index["worker_contracts"][0]).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
(root, manifest)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn worker_sdks_use_the_compilers_exact_port_manifest() {
|
||||
let (root, manifest) = sdk_contract("worker-sdks");
|
||||
let repository = Path::new(env!("CARGO_MANIFEST_DIR")).parent().unwrap();
|
||||
let go = root.join("go");
|
||||
fs::create_dir(&go).unwrap();
|
||||
fs::write(go.join("go.mod"),format!("module sdkfixture\ngo 1.25.0\nrequire dever/component v0.0.1\nreplace dever/component => {}\n",repository.join("sdk/go").display())).unwrap();
|
||||
fs::write(
|
||||
go.join("main.go"),
|
||||
include_str!("../../../external-sdk/go_worker.go.txt"),
|
||||
)
|
||||
.unwrap();
|
||||
fs::copy(&manifest, go.join("manifest.json")).unwrap();
|
||||
let go_binary = go.join("worker");
|
||||
success(
|
||||
Command::new("go")
|
||||
.args(["build", "-buildvcs=false", "-o"])
|
||||
.arg(&go_binary)
|
||||
.arg(".")
|
||||
.current_dir(&go)
|
||||
.env("GOTOOLCHAIN", "local")
|
||||
.env("GOWORK", "off")
|
||||
.env("CGO_ENABLED", "0")
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
for language in ["python", "javascript", "go"] {
|
||||
let sdk = if language == "go" {
|
||||
go_binary.clone()
|
||||
} else {
|
||||
repository.join("sdk").join(language)
|
||||
};
|
||||
success(
|
||||
Command::new(std::env::var_os("DEVER_SDK_PYTHON").unwrap_or_else(|| "python3".into()))
|
||||
.arg("-B")
|
||||
.arg(repository.join("test/external-sdk/check.py"))
|
||||
.arg(&manifest)
|
||||
.arg(sdk)
|
||||
.arg(language)
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
}
|
||||
let domain = root.join("module/demo/service");
|
||||
fs::create_dir(domain.join("bin")).unwrap();
|
||||
fs::copy(&go_binary, domain.join("bin/worker")).unwrap();
|
||||
write_source(
|
||||
domain.join("app/main.dever"),
|
||||
r#"type Attempt { Done(out: Int), error Failed(error: port.Error) }
|
||||
flow start() (out: Int, name: Text?, tool: port.ToolName, rejected: Attempt)
|
||||
| step | kind | do |
|
||||
| reply | port | port.echo(42, "中文", []) |
|
||||
| out | calc | reply.out |
|
||||
| name | calc | reply.name |
|
||||
| tool | port | port.tool(port.ToolName.Multiply, null, [port.ToolName.Add]) |
|
||||
| rejected | port | result(port.fail()) |
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
fs::create_dir(root.join("config")).unwrap();
|
||||
fs::write(
|
||||
root.join("config/setting.json"),
|
||||
r#"{"adapter":{"demo.service":{"setting":{"marker":"unused"}}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(
|
||||
&loaded,
|
||||
&program,
|
||||
"demo.service.app.start",
|
||||
Profile::Dev,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let binary = root.join("published");
|
||||
artifact.publish(&binary).unwrap();
|
||||
fs::remove_file(domain.join("bin/worker")).unwrap();
|
||||
fs::remove_file(go_binary).unwrap();
|
||||
let output = run(&binary);
|
||||
assert!(
|
||||
output.contains("42")
|
||||
&& output.contains("中文")
|
||||
&& output.contains("Multiply")
|
||||
&& output.contains("business rejection"),
|
||||
"{output}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires YYJSON_ROOT pointing to yyjson 0.12.0 sources"]
|
||||
fn c_and_cpp_sdks_use_the_compilers_exact_port_manifest() {
|
||||
let (root, manifest) = sdk_contract("worker-c-sdk");
|
||||
let repository = Path::new(env!("CARGO_MANIFEST_DIR")).parent().unwrap();
|
||||
let library = PathBuf::from(std::env::var("YYJSON_ROOT").expect("YYJSON_ROOT"));
|
||||
let source = root.join("native");
|
||||
fs::create_dir(&source).unwrap();
|
||||
let contract = fs::read_to_string(&manifest).unwrap();
|
||||
fs::write(
|
||||
source.join("manifest.h"),
|
||||
serde_json::to_string(&contract).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
fs::copy(
|
||||
repository.join("test/external-sdk/c_worker.c"),
|
||||
source.join("main.c"),
|
||||
)
|
||||
.unwrap();
|
||||
let mut objects = Vec::new();
|
||||
for (name, path) in [
|
||||
("yyjson", library.join("src/yyjson.c")),
|
||||
("wire", repository.join("sdk/c/wire.c")),
|
||||
("ffi", repository.join("sdk/c/dever_ffi.c")),
|
||||
] {
|
||||
let object = source.join(format!("{name}.o"));
|
||||
success(
|
||||
Command::new("cc")
|
||||
.args(["-std=c11", "-Wall", "-Wextra", "-Werror", "-c"])
|
||||
.arg(path)
|
||||
.arg("-I")
|
||||
.arg(library.join("src"))
|
||||
.arg("-I")
|
||||
.arg(repository.join("sdk/c"))
|
||||
.arg("-o")
|
||||
.arg(&object)
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
objects.push(object);
|
||||
}
|
||||
for (compiler, standard) in [("cc", "-std=c11"), ("c++", "-std=c++17")] {
|
||||
let binary = source.join(compiler);
|
||||
success(
|
||||
Command::new(compiler)
|
||||
.args([standard, "-Wall", "-Wextra", "-Werror"])
|
||||
.arg(source.join("main.c"))
|
||||
.args(&objects)
|
||||
.arg("-I")
|
||||
.arg(library.join("src"))
|
||||
.arg("-I")
|
||||
.arg(repository.join("sdk/c"))
|
||||
.arg("-o")
|
||||
.arg(&binary)
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
success(
|
||||
Command::new(std::env::var_os("DEVER_SDK_PYTHON").unwrap_or_else(|| "python3".into()))
|
||||
.arg("-B")
|
||||
.arg(repository.join("test/external-sdk/c_check.py"))
|
||||
.arg(&manifest)
|
||||
.arg(&binary)
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn worker_gpu_capability_passes_device_selection_without_inheriting_application_secrets() {
|
||||
for gpu in [false, true] {
|
||||
let root = project(
|
||||
&format!("worker-gpu-{gpu}"),
|
||||
"device() (out: Text?, secret: Text?)",
|
||||
if gpu {
|
||||
r#"external exec "bin/worker" {allow gpu}"#
|
||||
} else {
|
||||
r#"external exec "bin/worker" {}"#
|
||||
},
|
||||
"flow start() (out: Text?, secret: Text?)\n| step | kind | do |\n| device | port | port.device() |\n| out | calc | device.out |\n| secret | calc | device.secret |",
|
||||
);
|
||||
executable(&root.join("module/demo/service"));
|
||||
fs::write(
|
||||
root.join("module/demo/service/api.dever"),
|
||||
"cmd start = app.start",
|
||||
)
|
||||
.unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
let text = success(
|
||||
Command::new(&artifact.binary)
|
||||
.args(["demo.service.start", "{}"])
|
||||
.env("CUDA_VISIBLE_DEVICES", "7")
|
||||
.env("DEVER_TEST_SECRET", "private")
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
let value: serde_json::Value = serde_json::from_str(&text).unwrap();
|
||||
assert_eq!(
|
||||
value["data"]["out"],
|
||||
if gpu {
|
||||
serde_json::json!("7")
|
||||
} else {
|
||||
serde_json::Value::Null
|
||||
}
|
||||
);
|
||||
assert!(value["data"]["secret"].is_null());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
use serde_json::{Value,json};
|
||||
use std::io::{Read,Write};
|
||||
fn receive() -> Value {
|
||||
let mut prefix=[0u8;4];std::io::stdin().read_exact(&mut prefix).unwrap();
|
||||
let mut body=vec![0;u32::from_be_bytes(prefix) as usize];std::io::stdin().read_exact(&mut body).unwrap();
|
||||
serde_json::from_slice(&body).unwrap()
|
||||
}
|
||||
fn send(value:Value){let bytes=serde_json::to_vec(&value).unwrap();let mut out=std::io::stdout().lock();out.write_all(&(bytes.len() as u32).to_be_bytes()).unwrap();out.write_all(&bytes).unwrap();out.flush().unwrap();}
|
||||
fn main(){
|
||||
let mut hello=receive();let setting=hello.as_object_mut().unwrap().remove("setting").unwrap();hello["kind"]="ready".into();send(hello);
|
||||
let mut calls=0;
|
||||
loop {let message=receive();match message["kind"].as_str().unwrap(){
|
||||
"health"=>send(message),
|
||||
"shutdown"=>{send(message);return},
|
||||
"cancel"=>send(json!({"kind":"error","id":message["id"],"error":"dever.cancelled","payload":null})),
|
||||
"call"=>{calls+=1;let operation=message["operation"].as_str().unwrap();let payload=match operation{
|
||||
"add"=>json!({"out":message["payload"]["value"].as_i64().unwrap()+setting["offset"].as_i64().unwrap(),"calls":calls}),
|
||||
"echo"=>json!({"out":message["payload"]["value"]}),
|
||||
"fail"=>{send(json!({"kind":"error","id":message["id"],"error":"demo.service.port.Error.Rejected","payload":{"message":"business rejection"}}));continue},
|
||||
"invalid"=>json!({"out":200}),
|
||||
"hang"=>continue,
|
||||
"unit"=>json!({}),
|
||||
"device"=>json!({"out":std::env::var("CUDA_VISIBLE_DEVICES").ok(),"secret":std::env::var("DEVER_TEST_SECRET").ok()}),
|
||||
_=>panic!("unknown test operation"),
|
||||
};send(json!({"kind":"result","id":message["id"],"payload":payload}));},
|
||||
_=>panic!("unknown protocol message"),
|
||||
}}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
//! 真实 CLI 拒绝合同漂移;只改实现或移动文件不改变稳定合同。
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn api_baseline_is_stable_and_never_overwritten() {
|
||||
let root = directory("api-baseline");
|
||||
let domain = root.join("module/demo/catalog");
|
||||
fs::create_dir_all(&domain).unwrap();
|
||||
let app = domain.join("app/main.dever");
|
||||
let initial = "type Item {name:Text,private key:Int}\necho(value:Item) (out:Text) {out=value.name}\napply(callback:handler(value:Text) (out:Text), value:Text) (out:Text) {out=callback(value)}";
|
||||
write_source(&app, initial).unwrap();
|
||||
fs::write(domain.join("api.dever"), "public get echo = app.hello").unwrap();
|
||||
write_source(
|
||||
&app,
|
||||
format!("{initial}\nhello() (out:Text) {{out=\"one\"}}"),
|
||||
)
|
||||
.unwrap();
|
||||
let source = root.to_str().unwrap();
|
||||
success(cli(&["fmt", source]));
|
||||
let snapshot = success(cli(&["api", source]));
|
||||
assert!(snapshot.contains("demo.catalog.app.Item"));
|
||||
assert!(snapshot.contains("handler(value: Text)"));
|
||||
assert!(snapshot.contains("/demo/catalog/echo"));
|
||||
assert!(!snapshot.contains("key"));
|
||||
assert!(!snapshot.contains(source));
|
||||
let baseline = root.join("dever.api");
|
||||
success(cli(&[
|
||||
"api",
|
||||
source,
|
||||
"--output",
|
||||
baseline.to_str().unwrap(),
|
||||
]));
|
||||
assert_eq!(fs::read_to_string(&baseline).unwrap(), snapshot);
|
||||
assert!(
|
||||
!cli(&["api", source, "--output", baseline.to_str().unwrap()])
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
success(cli(&["check", source]));
|
||||
|
||||
// 新增不导出的 Domain 定义会移动类型编号,不应改变合同。
|
||||
fs::write(domain.join("domain.dever"), "type Earlier {extra:Bool}").unwrap();
|
||||
write_source(
|
||||
&app,
|
||||
format!("{initial}\nhello() (out:Text) {{out=\"two\"}}"),
|
||||
)
|
||||
.unwrap();
|
||||
success(cli(&["fmt", source]));
|
||||
assert_eq!(success(cli(&["api", source])), snapshot);
|
||||
success(cli(&["check", source]));
|
||||
|
||||
fs::write(
|
||||
domain.join("api.dever"),
|
||||
"authenticated get echo = app.hello",
|
||||
)
|
||||
.unwrap();
|
||||
success(cli(&["fmt", source]));
|
||||
for command in ["check", "run", "build"] {
|
||||
let output = root.join("must-not-build");
|
||||
let mut args = vec![command, source];
|
||||
if command == "build" {
|
||||
args.extend(["--output", output.to_str().unwrap()]);
|
||||
}
|
||||
let result = cli(&args);
|
||||
assert!(!result.status.success());
|
||||
assert!(String::from_utf8_lossy(&result.stderr).contains("public API differs"));
|
||||
assert!(!output.exists());
|
||||
}
|
||||
assert_eq!(fs::read_to_string(&baseline).unwrap(), snapshot);
|
||||
let changed = success(cli(&["api", source]));
|
||||
assert_ne!(changed, snapshot);
|
||||
fs::write(&baseline, "dever-api 5\n").unwrap();
|
||||
assert!(
|
||||
String::from_utf8_lossy(&cli(&["check", source]).stderr).contains("expected dever-api 6")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn api_snapshot_tracks_model_defaults_and_nominal_ids() {
|
||||
let root = directory("api-model-contract");
|
||||
let domain = root.join("module/demo/article");
|
||||
fs::create_dir_all(&domain).unwrap();
|
||||
let model = domain.join("data/main.dever");
|
||||
write_source(
|
||||
&model,
|
||||
"type Article {title:Text(1,80) unique,score:Int default 7}",
|
||||
)
|
||||
.unwrap();
|
||||
let source = root.to_str().unwrap();
|
||||
success(cli(&["fmt", source]));
|
||||
let first = success(cli(&["api", source]));
|
||||
assert!(first.contains("demo.article.data.id"));
|
||||
assert!(first.contains("default 7"));
|
||||
fs::write(root.join("dever.api"), &first).unwrap();
|
||||
write_source(
|
||||
&model,
|
||||
"type Article {title:Text(1,80) unique,score:Int default 9}",
|
||||
)
|
||||
.unwrap();
|
||||
success(cli(&["fmt", source]));
|
||||
assert!(!cli(&["check", source]).status.success());
|
||||
assert!(success(cli(&["api", source])).contains("default 9"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn api_snapshot_names_related_types_and_tracks_foreign_key_changes() {
|
||||
let root = directory("api-relations");
|
||||
let domain = root.join("module/demo/catalog/data");
|
||||
fs::create_dir_all(&domain).unwrap();
|
||||
fs::write(
|
||||
domain.join("user.dever"),
|
||||
"type User {name:Text}\nrelation posts=data.post.author_id",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
domain.join("post.dever"),
|
||||
"type Post {title:Text,author_id:data.user.id,editor_id:data.user.id}",
|
||||
)
|
||||
.unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let first = loaded.api_snapshot(&program);
|
||||
assert!(
|
||||
first.contains("Related<List<demo.catalog.data.post.Post>>"),
|
||||
"{first}"
|
||||
);
|
||||
assert!(first.contains("target=demo.catalog.data.post.Post key=author_id many=true"));
|
||||
assert!(!first.contains("Value_"));
|
||||
fs::write(
|
||||
domain.join("user.dever"),
|
||||
"type User {name:Text}\nrelation posts=data.post.editor_id",
|
||||
)
|
||||
.unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let second = loaded.api_snapshot(&program);
|
||||
assert_ne!(first, second);
|
||||
assert!(second.contains("key=editor_id many=true"));
|
||||
let formatted = dever::compiler::format::format(&loaded.declarations);
|
||||
assert!(
|
||||
formatted.contains("relation posts = data.post.editor_id"),
|
||||
"{formatted}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn data_display_metadata_is_public_only_and_does_not_change_api_baseline() {
|
||||
let root = directory("api-field-metadata");
|
||||
let domain = root.join("module/demo/article/data");
|
||||
fs::create_dir_all(&domain).unwrap();
|
||||
let file = domain.join("article.dv");
|
||||
fs::write(&file, "type State { Draft, Published }\ntype Article { title: Text(1,80), state: State, private token: Text? }").unwrap();
|
||||
let (project, program) = analyze(&root);
|
||||
let baseline = project.api_snapshot(&program);
|
||||
fs::write(&file, r#"type State { Draft name "草稿", Published name "发布" }
|
||||
type Article name "文章" { title: Text(1,80) name "标题" description "Editor’s title", state: State, private token: Text? name "私有" }"#).unwrap();
|
||||
let (project, program) = analyze(&root);
|
||||
assert_eq!(project.api_snapshot(&program), baseline);
|
||||
let model = &project.data_metadata(&program)["demo.article.data.Article"];
|
||||
assert_eq!(model["name"], "文章");
|
||||
let fields = &model["fields"];
|
||||
assert_eq!(
|
||||
fields["title"],
|
||||
serde_json::json!({"type":"Text","length":[1,80],"name":"标题","description":"Editor’s title"})
|
||||
);
|
||||
assert_eq!(
|
||||
fields["state"]["options"][0],
|
||||
serde_json::json!({"value":"Draft","label":"草稿"})
|
||||
);
|
||||
assert!(fields.get("token").is_none());
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
use super::*;
|
||||
use crate::api::{Server, config};
|
||||
|
||||
#[test]
|
||||
fn component_build_uses_fresh_custom_output_and_stops_on_failure() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let root = directory("custom-front");
|
||||
let front = root.join("module/demo/front");
|
||||
fs::create_dir_all(front.join("src")).unwrap();
|
||||
fs::create_dir_all(front.join("dist")).unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
fs::write(front.join("src/index.html"), "source").unwrap();
|
||||
fs::write(front.join("dist/index.html"), "stale").unwrap();
|
||||
let desktop = root.join("module/desktop/front");
|
||||
fs::create_dir_all(desktop.join("src")).unwrap();
|
||||
fs::write(desktop.join("src/desktop.txt"), "desktop artifact").unwrap();
|
||||
let script = front.join("build");
|
||||
fs::write(&script, "#!/bin/sh\nexit 7\n").unwrap();
|
||||
fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).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();
|
||||
let binary = root.join("site");
|
||||
let args = [
|
||||
"build",
|
||||
root.to_str().unwrap(),
|
||||
"--profile",
|
||||
"dev",
|
||||
"--output",
|
||||
binary.to_str().unwrap(),
|
||||
];
|
||||
let failed = cli(&args);
|
||||
assert!(!failed.status.success());
|
||||
assert!(String::from_utf8_lossy(&failed.stderr).contains("exit status: 7"));
|
||||
assert!(!binary.exists());
|
||||
assert_eq!(
|
||||
fs::read_to_string(front.join("dist/index.html")).unwrap(),
|
||||
"stale"
|
||||
);
|
||||
fs::write(
|
||||
&script,
|
||||
r#"#!/bin/sh
|
||||
set -eu
|
||||
cat src/index.html > "$1/index.html"
|
||||
printf '%s' ' transformed' >> "$1/index.html"
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
success(cli(&args));
|
||||
assert_eq!(
|
||||
fs::read_to_string(front.join("dist/index.html")).unwrap(),
|
||||
"source transformed"
|
||||
);
|
||||
let server = Server::start(&binary, &path, port);
|
||||
let (status, body, _) = server.raw_response("GET", "/", "", "");
|
||||
assert_eq!(status, 200);
|
||||
assert_eq!(body, "source transformed");
|
||||
assert_eq!(
|
||||
fs::read_to_string(desktop.join("dist/desktop.txt")).unwrap(),
|
||||
"desktop artifact"
|
||||
);
|
||||
assert_eq!(server.raw_response("GET", "/desktop.txt", "", "").0, 404);
|
||||
server.stop();
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
use super::*;
|
||||
mod api;
|
||||
mod front;
|
||||
mod target;
|
||||
mod testing;
|
||||
mod testing_jobs;
|
||||
|
||||
#[test]
|
||||
fn new_project_runs_and_preserves_existing_directories() {
|
||||
let root = directory("new-project").join("hello");
|
||||
let source = root.to_str().unwrap();
|
||||
success(cli(&["new", source]));
|
||||
success(cli(&["check", source]));
|
||||
let response = success(cli(&[
|
||||
"run",
|
||||
source,
|
||||
"--",
|
||||
"hello.greeting.greet",
|
||||
r#"{"name":"Dever"}"#,
|
||||
]));
|
||||
let response: serde_json::Value = serde_json::from_str(&response).unwrap();
|
||||
assert_eq!(response["data"], "Hello, Dever");
|
||||
success(cli(&["inspect", source, "--links"]));
|
||||
success(cli(&["inspect", source, "--links", "--check"]));
|
||||
let app = root.join("module/hello/greeting/flow/greeting.dv");
|
||||
write_source(&app, "user-owned content").unwrap();
|
||||
assert!(!cli(&["new", source]).status.success());
|
||||
assert_eq!(fs::read_to_string(app).unwrap(), "user-owned content");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_rejects_flat_sources_and_removed_model_role() {
|
||||
let root = directory("flat-source-role");
|
||||
let domain = root.join("module/demo/article");
|
||||
write_source(domain.join("app/main.dever"), "").unwrap();
|
||||
write_source(
|
||||
domain.join("data/main.dever"),
|
||||
"type Article {
|
||||
title: Text
|
||||
}
|
||||
",
|
||||
)
|
||||
.unwrap();
|
||||
success(cli(&["check", root.to_str().unwrap()]));
|
||||
for (flat_name, suggested) in [
|
||||
("app.dever", "flow/article.dv"),
|
||||
("data.dever", "data/article.dv"),
|
||||
("rule.dv", "rule/article.dv"),
|
||||
] {
|
||||
let flat = domain.join(flat_name);
|
||||
fs::write(&flat, "").unwrap();
|
||||
let output = cli(&["check", root.to_str().unwrap()]);
|
||||
assert!(!output.status.success());
|
||||
assert!(String::from_utf8_lossy(&output.stderr).contains(suggested));
|
||||
fs::remove_file(flat).unwrap();
|
||||
}
|
||||
let old = domain.join("model/article.dv");
|
||||
write_source(&old, "type Article {title: Text}").unwrap();
|
||||
let failure = cli(&["check", root.to_str().unwrap()]);
|
||||
assert!(!failure.status.success());
|
||||
assert!(String::from_utf8_lossy(&failure.stderr).contains("use the data/ source directory"));
|
||||
fs::remove_file(&old).unwrap();
|
||||
fs::remove_dir(old.parent().unwrap()).unwrap();
|
||||
let flow = domain.join("app/main.dever");
|
||||
for old_role in ["model", "demo.article.model"] {
|
||||
write_source(
|
||||
&flow,
|
||||
format!("flow total() (n:Int) {{ n = {old_role}.count() }}"),
|
||||
)
|
||||
.unwrap();
|
||||
success(cli(&["fmt", root.to_str().unwrap()]));
|
||||
let output = cli(&["check", root.to_str().unwrap()]);
|
||||
assert!(!output.status.success());
|
||||
assert!(String::from_utf8_lossy(&output.stderr).contains("count"));
|
||||
}
|
||||
write_source(&flow, "flow total() (n:Int) { n = data.count() }").unwrap();
|
||||
success(cli(&["fmt", root.to_str().unwrap()]));
|
||||
success(cli(&["check", root.to_str().unwrap()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_tenant_commands_stop_before_project_loading() {
|
||||
for arguments in [
|
||||
vec!["tenant", "migrate", "missing-project", "0"],
|
||||
vec!["tenant", "migrate", "missing-project", "-1"],
|
||||
vec!["tenant", "migrate", "missing-project", "1", "extra"],
|
||||
vec!["tenant", "owner", "missing-project", "1", "front", "0"],
|
||||
vec![
|
||||
"tenant",
|
||||
"component",
|
||||
"unknown",
|
||||
"missing-project",
|
||||
"1",
|
||||
"demo",
|
||||
],
|
||||
] {
|
||||
let output = cli(&arguments);
|
||||
assert!(!output.status.success());
|
||||
assert!(!String::from_utf8_lossy(&output.stderr).contains("No such file"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
//! 检查真实 CLI 和 ELF;交叉执行由目标机器验收,不把宿主执行当作目标执行。
|
||||
use super::*;
|
||||
use dever::compiler::build::Target;
|
||||
|
||||
#[test]
|
||||
fn build_target_is_explicit_and_invalid_targets_stop_before_loading() {
|
||||
for arguments in [
|
||||
vec![
|
||||
"build", "missing", "--target", "windows", "--output", "unused",
|
||||
],
|
||||
vec!["build", "missing", "--target"],
|
||||
vec!["run", "missing", "--target", "linux-aarch64"],
|
||||
vec![
|
||||
"build",
|
||||
"missing",
|
||||
"--target",
|
||||
"linux-aarch64",
|
||||
"--target",
|
||||
"linux-x86_64",
|
||||
],
|
||||
] {
|
||||
let output = cli(&arguments);
|
||||
assert!(!output.status.success());
|
||||
assert!(!String::from_utf8_lossy(&output.stderr).contains("No such file"));
|
||||
}
|
||||
let root = directory("native-target").join("hello");
|
||||
let source = root.to_str().unwrap();
|
||||
success(cli(&["new", source]));
|
||||
let target = format!("linux-{}", Target::host().unwrap().arch());
|
||||
let binary = root.join("program");
|
||||
success(cli(&[
|
||||
"build",
|
||||
source,
|
||||
"--target",
|
||||
&target,
|
||||
"--profile",
|
||||
"dev",
|
||||
"--output",
|
||||
binary.to_str().unwrap(),
|
||||
]));
|
||||
let response = success(
|
||||
Command::new(&binary)
|
||||
.args(["hello.greeting.greet", r#"{"name":"target"}"#])
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(&response).unwrap()["data"],
|
||||
"Hello, target"
|
||||
);
|
||||
let repeated = cli(&[
|
||||
"build",
|
||||
source,
|
||||
"--target",
|
||||
&target,
|
||||
"--profile",
|
||||
"dev",
|
||||
"--output",
|
||||
binary.to_str().unwrap(),
|
||||
]);
|
||||
assert!(
|
||||
!repeated.status.success(),
|
||||
"published files must not be overwritten"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires the official Rust 1.95 aarch64 standard library and a configured C cross linker"]
|
||||
fn aarch64_build_produces_target_elf_and_keeps_native_cache_separate() {
|
||||
assert_eq!(Target::host().unwrap(), Target::LinuxX86_64);
|
||||
let root = directory("cross-target").join("hello");
|
||||
let source = root.to_str().unwrap();
|
||||
success(cli(&["new", source]));
|
||||
let binary = root.join("arm-program");
|
||||
success(cli(&[
|
||||
"build",
|
||||
source,
|
||||
"--target",
|
||||
"linux-aarch64",
|
||||
"--profile",
|
||||
"dev",
|
||||
"--output",
|
||||
binary.to_str().unwrap(),
|
||||
]));
|
||||
let bytes = fs::read(&binary).unwrap();
|
||||
let elf = goblin::elf::Elf::parse(&bytes).unwrap();
|
||||
assert_eq!(elf.header.e_machine, goblin::elf::header::EM_AARCH64);
|
||||
assert!(elf.is_64 && elf.little_endian && elf.entry != 0);
|
||||
let result = success(cli(&[
|
||||
"run",
|
||||
source,
|
||||
"--",
|
||||
"hello.greeting.greet",
|
||||
r#"{"name":"native"}"#,
|
||||
]));
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(&result).unwrap()["data"],
|
||||
"Hello, native"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,440 @@
|
||||
//! CLI 必须实际执行用例、隔离 fake 与数据,并在失败或超时后继续。
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn workflow_examples_use_real_models_and_explicit_external_fakes() {
|
||||
let example = Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../examples/next/workflows")
|
||||
.canonicalize()
|
||||
.unwrap();
|
||||
let root = directory("workflow-examples");
|
||||
let project = Project::load(&example).unwrap();
|
||||
assert!(project.diagnostics.is_empty(), "{:?}", project.diagnostics);
|
||||
for source in &project.sources {
|
||||
if let Ok(relative) = source.path.strip_prefix(&example) {
|
||||
let target = root.join(relative);
|
||||
fs::create_dir_all(target.parent().unwrap()).unwrap();
|
||||
fs::copy(&source.path, target).unwrap();
|
||||
}
|
||||
}
|
||||
// 仅测试副本补齐外部合同;不会往正式样例写入假支付、通知或身份。
|
||||
fs::write(root.join("module/demo/order/adapter.dever"),
|
||||
"port.pay(key:Uuid,amount:Decimal) (receipt:Text) {receipt=uuid.toText(key)}\nport.notify(key:Uuid,receipt:Text) () {}").unwrap();
|
||||
fs::write(
|
||||
root.join("module/demo/selection/adapter.dever"),
|
||||
"port.accept(value:Text) (accepted:Bool) {accepted=value==\"yes\"}",
|
||||
)
|
||||
.unwrap();
|
||||
for (domain, source) in [
|
||||
(
|
||||
"approval",
|
||||
r#"
|
||||
flow behavior() ()
|
||||
| step | kind | do |
|
||||
| request | flow | app.create(" approval ") |
|
||||
| - | calc | assertEq(request.title,"approval") |
|
||||
| - | calc | assertEq(request.status,data.request.Status.Pending) |
|
||||
| - | flow | app.review(request.id,true) |
|
||||
| updated | data | data.request.get(request.id) |
|
||||
| - | calc | assertEq(updated.status,data.request.Status.Approved) |
|
||||
"#,
|
||||
),
|
||||
(
|
||||
"catalog",
|
||||
r#"
|
||||
flow behavior() ()
|
||||
| step | kind | do |
|
||||
| category | data | data.category.create({name="News"}) |
|
||||
| - | data | data.item.create({title="First",category_id=category.id,supplier_cost=1.25}) |
|
||||
| - | data | data.item.create({title="Second",category_id=null,supplier_cost=2.50}) |
|
||||
| page | flow | app.list(1) |
|
||||
| - | calc | assertEq(page.total,2) |
|
||||
| first | calc | get(page.items,0) |
|
||||
| second | calc | get(page.items,1) |
|
||||
| - | check | first!=null else Invalid |
|
||||
| - | check | second!=null else Invalid |
|
||||
| - | calc | assertEq(first.category,"News") |
|
||||
| - | calc | assertEq(second.category,null) |
|
||||
| titles | flow | app.titles(1) |
|
||||
| - | calc | assertEq(length(titles),1) |
|
||||
| title | calc | get(titles,0) |
|
||||
| - | check | title!=null else Invalid |
|
||||
| - | calc | assertEq(title.title,"First") |
|
||||
"#,
|
||||
),
|
||||
(
|
||||
"selection",
|
||||
r#"
|
||||
flow behavior() ()
|
||||
| step | kind | do |
|
||||
| found | loop | app.find(["no","yes","fail"]) |
|
||||
| - | calc | assertEq(found,"yes") |
|
||||
| selected | loop | app.select(["no","yes","yes"]) |
|
||||
| - | calc | assertEq(selected,["yes","yes"]) |
|
||||
|
||||
flow port.accept(value:Text) (accepted:Bool)
|
||||
| step | kind | do |
|
||||
| - | check | value!="fail" else dever.process.Error.Failed("test external failure") |
|
||||
| accepted | calc | value=="yes" |
|
||||
"#,
|
||||
),
|
||||
] {
|
||||
let tests = root.join(format!("test/demo/{domain}"));
|
||||
fs::create_dir_all(&tests).unwrap();
|
||||
fs::write(tests.join("behavior.dever"), source).unwrap();
|
||||
}
|
||||
success(cli(&["fmt", root.to_str().unwrap()]));
|
||||
success(cli(&["check", root.to_str().unwrap()]));
|
||||
let output = success(cli(&["test", root.to_str().unwrap()]));
|
||||
for domain in ["approval", "catalog", "selection"] {
|
||||
assert!(
|
||||
output.contains(&format!("PASS demo.{domain}.behavior")),
|
||||
"{output}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_command_runs_isolated_cases_and_checks_production_contract() {
|
||||
let root = directory("test-runner");
|
||||
let domain = root.join("module/demo/value");
|
||||
let tests = root.join("test/demo/value");
|
||||
fs::create_dir_all(&domain).unwrap();
|
||||
fs::create_dir_all(&tests).unwrap();
|
||||
write_source(domain.join("data/main.dever"), "type Value {name:Text}").unwrap();
|
||||
fs::write(domain.join("port.dever"), "read(value:Int) (out:Int)").unwrap();
|
||||
let adapter = "port.read(value:Int) (out:Int) {out=value}";
|
||||
fs::write(domain.join("adapter.dever"), adapter).unwrap();
|
||||
write_source(
|
||||
domain.join("app/main.dever"),
|
||||
r#"
|
||||
read(value:Int) (out:Int) {out=port.read(value)}
|
||||
rule sign(value:Int) (out:Int)
|
||||
| name | value | out |
|
||||
| negative | < 0 | -1 |
|
||||
| zero | 0 | 0 |
|
||||
| positive | > 0 | 1 |
|
||||
flow write() (out:Int)
|
||||
| step | kind | do |
|
||||
| - | data | data.create({name="isolated"}) |
|
||||
| out | data | data.count() |
|
||||
rule record(value:Bool) (out:Int)
|
||||
| name | value | out |
|
||||
| written | true | app.write() |
|
||||
| skipped | false | 0 |
|
||||
rule nested(value:Int) (out:Int)
|
||||
| name | value | out |
|
||||
| all | - | app.sign(value) |
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
for (name, source) in [
|
||||
(
|
||||
"a_fake",
|
||||
"aFake() () {assertEq(app.read(4),5)}\nport.read(value:Int) (out:Int) {out=value+1}",
|
||||
),
|
||||
(
|
||||
"b_database",
|
||||
"flow bDatabase() ()\n| step | kind | do |\n| count | flow | app.write() |\n| - | calc | assertEq(count,1) |",
|
||||
),
|
||||
(
|
||||
"c_database",
|
||||
"flow cDatabase() ()\n| step | kind | do |\n| count | flow | app.write() |\n| - | calc | assertEq(count,1) |",
|
||||
),
|
||||
(
|
||||
"c_rows",
|
||||
r#"cRows() () {assertRow(app.sign(-1),"negative")
|
||||
assertRow(app.sign(0),"zero")
|
||||
assertRow(app.sign(1),"positive")
|
||||
assertEq(app.sign(1),1)}"#,
|
||||
),
|
||||
(
|
||||
"c_once",
|
||||
r#"flow cOnce() ()
|
||||
| step | kind | do |
|
||||
| - | calc | assertRow(app.record(true),"written") |
|
||||
| count | data | data.count() |
|
||||
| - | calc | assertEq(count,1) |
|
||||
| - | calc | assertRow(app.nested(-1),"all") |
|
||||
| task | calc | run(app.sign(1)) |
|
||||
| value | calc | wait(task) |
|
||||
| - | calc | assertEq(value,1) |"#,
|
||||
),
|
||||
(
|
||||
"c_clock",
|
||||
r#"flow cClock() ()
|
||||
| step | kind | do |
|
||||
| before | flow | dever.time.now() |
|
||||
| - | calc | dever.test.advanceClock(86400000) |
|
||||
| after | flow | dever.time.now() |
|
||||
| - | calc | assertEq(dever.time.difference(after,before),dever.time.duration(86400000)) |
|
||||
| task | calc | run(dever.time.now()) |
|
||||
| shared | calc | wait(task) |
|
||||
| - | calc | assertEq(after,shared) |"#,
|
||||
),
|
||||
("d_failure", "dFailure() () {assert(false)}"),
|
||||
(
|
||||
"d_missing_fake",
|
||||
"dMissingFake() () {assertEq(app.read(1),1)}",
|
||||
),
|
||||
(
|
||||
"d_wrong_row",
|
||||
"dWrongRow() () {assertRow(app.sign(-1),\"positive\")}",
|
||||
),
|
||||
(
|
||||
"e_timeout",
|
||||
"flow eTimeout() ()\n| step | kind | do |\n| - | flow | dever.time.sleep(500) |",
|
||||
),
|
||||
(
|
||||
"f_secret",
|
||||
"fSecret() () {key=secret(\"test-only\")\nassertEq(length(dever.crypto.hmacSha256(key,dever.bytes.fromText(\"x\"))),32)}",
|
||||
),
|
||||
] {
|
||||
fs::write(tests.join(format!("{name}.dever")), source).unwrap();
|
||||
}
|
||||
let source = root.to_str().unwrap();
|
||||
success(cli(&["fmt", source]));
|
||||
let adapter = fs::read_to_string(domain.join("adapter.dever")).unwrap();
|
||||
let output = cli(&["test", source, "--timeout-ms", "150"]);
|
||||
assert!(!output.status.success());
|
||||
let stdout = String::from_utf8(output.stdout).unwrap();
|
||||
let stderr = String::from_utf8(output.stderr).unwrap();
|
||||
for name in [
|
||||
"a_fake",
|
||||
"b_database",
|
||||
"c_database",
|
||||
"c_rows",
|
||||
"c_once",
|
||||
"f_secret",
|
||||
] {
|
||||
assert!(
|
||||
stdout.contains(&format!("PASS demo.value.{name}")),
|
||||
"{stdout}\n{stderr}"
|
||||
);
|
||||
}
|
||||
assert!(stderr.contains("d_failure.dever"), "{stderr}");
|
||||
assert!(stderr.contains("assert failed"), "{stderr}");
|
||||
assert!(stderr.contains("assertRow failed"), "{stderr}");
|
||||
assert!(stderr.contains("complete case-local fake"), "{stderr}");
|
||||
assert!(stderr.contains("test timed out"), "{stderr}");
|
||||
assert!(!root.join("data").exists());
|
||||
assert_eq!(
|
||||
fs::read_to_string(domain.join("adapter.dever")).unwrap(),
|
||||
adapter
|
||||
);
|
||||
let filtered = success(cli(&["test", source, "--filter", "demo.value.a_fake"]));
|
||||
assert!(filtered.contains("PASS demo.value.a_fake"));
|
||||
assert!(!filtered.contains("b_database"));
|
||||
fs::write(tests.join("d_failure.dever"), "invalid unselected source").unwrap();
|
||||
success(cli(&["test", source, "--filter", "demo.value.a_fake"]));
|
||||
assert!(
|
||||
!cli(&["test", source, "--filter", "demo.valu"])
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
fs::write(root.join("dever.api"), "dever-api 6\n").unwrap();
|
||||
assert!(String::from_utf8_lossy(&cli(&["test", source]).stderr).contains("public API differs"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn production_rejects_test_primitives() {
|
||||
let root = directory("test-primitives-boundary");
|
||||
let source = root.join("main.dever");
|
||||
for body in [
|
||||
"assert(true)",
|
||||
"dever.test.advanceClock(1)",
|
||||
"value=dever.test.drainJobs(1)",
|
||||
"assertEq(1,1)",
|
||||
"assertRow(1,\"row\")",
|
||||
"value=secret(\"fixture\")",
|
||||
] {
|
||||
fs::write(&source, format!("main() () {{{body}}}")).unwrap();
|
||||
let loaded = Project::load(&source).unwrap();
|
||||
let error = program::check(&loaded.declarations, &loaded.modules)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert!(error.message.contains("test operations"), "{error:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn assert_row_rejects_non_rules_and_unknown_or_dynamic_names() {
|
||||
let root = directory("test-rule-diagnostics");
|
||||
let domain = root.join("module/demo/value");
|
||||
let test = root.join("test/demo/value/rows.dever");
|
||||
fs::create_dir_all(&domain).unwrap();
|
||||
fs::create_dir_all(test.parent().unwrap()).unwrap();
|
||||
write_source(domain.join("app/main.dever"),
|
||||
"read(value:Int) (out:Int) {out=value}\nrule sign(value:Int) (out:Int)\n| name | value | out |\n| negative | < 0 | -1 |\n| zero | 0 | 0 |\n| positive | > 0 | 1 |").unwrap();
|
||||
success(cli(&["fmt", root.to_str().unwrap()]));
|
||||
for (body, message) in [
|
||||
("assertRow(app.read(1),\"positive\")", "requires a rule"),
|
||||
("assertRow(1,\"positive\")", "direct rule call"),
|
||||
("assertRow(app.sign(1),\"missing\")", "unknown rule row"),
|
||||
(
|
||||
"row=\"positive\"\nassertRow(app.sign(1),row)",
|
||||
"literal row name",
|
||||
),
|
||||
] {
|
||||
fs::write(&test, format!("rows() () {{{body}}}")).unwrap();
|
||||
success(cli(&["fmt", root.to_str().unwrap()]));
|
||||
let output = cli(&["test", root.to_str().unwrap()]);
|
||||
assert!(!output.status.success());
|
||||
let error = String::from_utf8_lossy(&output.stderr);
|
||||
assert!(error.contains(message), "{body}: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_configuration_is_explicit_and_cannot_replace_isolated_resources() {
|
||||
let root = directory("test-settings");
|
||||
let domain = root.join("module/demo/value");
|
||||
let cases = root.join("test/demo/value");
|
||||
fs::create_dir_all(&domain).unwrap();
|
||||
fs::create_dir_all(&cases).unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
write_source(
|
||||
domain.join("app/main.dever"),
|
||||
"setting label:Text\nread() (out:Text) {out=label}",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
cases.join("settings.dever"),
|
||||
"settings() () {assertEq(app.read(),\"fixture\")}",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("config/setting.json"),
|
||||
r#"{"module":{"demo":{"value":{"label":"production"}}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
success(cli(&["fmt", root.to_str().unwrap()]));
|
||||
assert!(!cli(&["test", root.to_str().unwrap()]).status.success());
|
||||
let path = root.join("test/setting.json");
|
||||
fs::write(
|
||||
&path,
|
||||
r#"{"module":{"demo":{"value":{"label":"fixture"}}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
success(cli(&["test", root.to_str().unwrap()]));
|
||||
fs::write(
|
||||
&path,
|
||||
r#"{"database":{"default":{"type":"sqlite","path":"data/business.sqlite"}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let denied = cli(&["test", root.to_str().unwrap()]);
|
||||
assert!(!denied.status.success());
|
||||
assert!(String::from_utf8_lossy(&denied.stderr).contains("unknown field `database`"));
|
||||
fs::write(
|
||||
&path,
|
||||
r#"{"module":{"demo":{"value":{"label":"fixture","label":"duplicate"}}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!cli(&["test", root.to_str().unwrap()]).status.success());
|
||||
assert!(!root.join("data").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_clock_and_drain_report_invalid_limits_and_keep_running() {
|
||||
let root = directory("test-time-bounds");
|
||||
let domain = root.join("module/demo/value");
|
||||
let cases = root.join("test/demo/value");
|
||||
fs::create_dir_all(&domain).unwrap();
|
||||
fs::create_dir_all(&cases).unwrap();
|
||||
write_source(domain.join("app/main.dever"), "read() (out:Int) {out=1}").unwrap();
|
||||
for (name, source) in [
|
||||
(
|
||||
"a_empty",
|
||||
"aEmpty() () {assertEq(dever.test.drainJobs(1),0)}",
|
||||
),
|
||||
(
|
||||
"b_invalid",
|
||||
"bInvalid() () {assertEq(dever.test.drainJobs(0),0)}",
|
||||
),
|
||||
(
|
||||
"c_negative",
|
||||
"flow cNegative() ()\n| step | kind | do |\n| - | calc | dever.test.advanceClock(-1) |",
|
||||
),
|
||||
(
|
||||
"d_overflow",
|
||||
"flow dOverflow() ()\n| step | kind | do |\n| - | calc | dever.test.advanceClock(9223372036854775807) |",
|
||||
),
|
||||
("z_valid", "zValid() () {assertEq(app.read(),1)}"),
|
||||
] {
|
||||
fs::write(cases.join(format!("{name}.dever")), source).unwrap();
|
||||
}
|
||||
success(cli(&["fmt", root.to_str().unwrap()]));
|
||||
let result = cli(&["test", root.to_str().unwrap()]);
|
||||
assert!(!result.status.success());
|
||||
let stdout = String::from_utf8_lossy(&result.stdout);
|
||||
let stderr = String::from_utf8_lossy(&result.stderr);
|
||||
assert!(
|
||||
stdout.contains("PASS demo.value.a_empty"),
|
||||
"{stdout}{stderr}"
|
||||
);
|
||||
assert!(
|
||||
stdout.contains("PASS demo.value.z_valid"),
|
||||
"{stdout}{stderr}"
|
||||
);
|
||||
for error in [
|
||||
"Job drain limit must be 1..10000",
|
||||
"must be nonnegative",
|
||||
"advance overflows",
|
||||
] {
|
||||
assert!(stderr.contains(error), "{stderr}");
|
||||
}
|
||||
success(cli(&[
|
||||
"test",
|
||||
root.to_str().unwrap(),
|
||||
"--filter",
|
||||
"demo.value.a_empty",
|
||||
"--profile",
|
||||
"release",
|
||||
]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dv_directories_load_and_execute_together() {
|
||||
let root = directory("dv-directories");
|
||||
for (path, source) in [
|
||||
("module/demo/cart/data/cart.dv", "type Cart {amount:Int}"),
|
||||
(
|
||||
"module/demo/cart/port/pricing.dv",
|
||||
"price(value:Int) (out:Int)",
|
||||
),
|
||||
(
|
||||
"module/demo/cart/adapter/cart.dv",
|
||||
"port.price(value:Int) (out:Int) {out=value+1}",
|
||||
),
|
||||
(
|
||||
"module/demo/cart/rule/price.dv",
|
||||
"rule price(active:Bool, value:Int) (out:Int) active {true => port.price(value)
|
||||
false => 0}",
|
||||
),
|
||||
(
|
||||
"module/demo/cart/loop/cart.dv",
|
||||
"loop total(values:List<Int>) (out:Int) value in values {sum value}",
|
||||
),
|
||||
(
|
||||
"module/demo/cart/flow/cart.dv",
|
||||
"flow add(values:List<Int>) (out:Int) {amount=price(true,total(values))
|
||||
row=data.create({amount=amount})
|
||||
out=row.amount}",
|
||||
),
|
||||
(
|
||||
"test/demo/cart/checkout.dv",
|
||||
"flow checkout() () {amount=app.add([2,3])
|
||||
assertEq(amount,6)
|
||||
count=data.count()
|
||||
assertEq(count,1)}
|
||||
port.price(value:Int) (out:Int) {out=value+1}",
|
||||
),
|
||||
] {
|
||||
write_source(root.join(path), source).unwrap();
|
||||
}
|
||||
let path = root.to_str().unwrap();
|
||||
success(cli(&["fmt", path]));
|
||||
success(cli(&["fmt", path, "--check"]));
|
||||
success(cli(&["check", path]));
|
||||
assert!(success(cli(&["test", path])).contains("PASS demo.cart.checkout"));
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
//! 排空真实队列,验证延迟、幂等、失败回滚和重试;不模拟 SQL 或确认结果。
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn draining_jobs_keeps_the_network_driver_required_by_the_handler() {
|
||||
let root = directory("test-job-network");
|
||||
let domain = root.join("module/demo/work");
|
||||
let cases = root.join("test/demo/work");
|
||||
fs::create_dir_all(&domain).unwrap();
|
||||
fs::create_dir_all(&cases).unwrap();
|
||||
write_source(domain.join("data/main.dever"), "type Work { host:Text }").unwrap();
|
||||
fs::write(
|
||||
domain.join("api.dever"),
|
||||
"long job save(input:app.Input) retry(1) timeout(1000) = app.save",
|
||||
)
|
||||
.unwrap();
|
||||
write_source(
|
||||
domain.join("app/main.dever"),
|
||||
r#"
|
||||
type Input {host:Text}
|
||||
flow submit(host:Text) (out:Id)
|
||||
| step | kind | do |
|
||||
| out | calc | enqueue(job.save,Input {host=host},host) |
|
||||
flow save(input:Input) ()
|
||||
| step | kind | do |
|
||||
| listener | flow | dever.net.listen(input.host,0) |
|
||||
| - | flow | dever.net.closeListener(listener) |
|
||||
| - | flow | persist(input) |
|
||||
transaction flow persist(input:Input) ()
|
||||
| step | kind | do |
|
||||
| - | data | data.create({host=input.host}) |
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
cases.join("network.dever"),
|
||||
r#"
|
||||
flow network() ()
|
||||
| step | kind | do |
|
||||
| - | flow | app.submit("127.0.0.1") |
|
||||
| done | calc | dever.test.drainJobs(1) |
|
||||
| - | calc | assertEq(done,1) |
|
||||
| saved | data | data.count() |
|
||||
| - | calc | assertEq(saved,1) |
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
success(cli(&["fmt", root.to_str().unwrap()]));
|
||||
let output = success(cli(&["test", root.to_str().unwrap()]));
|
||||
assert!(output.contains("PASS demo.work.network"), "{output}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_clock_drives_real_jobs_without_background_workers() {
|
||||
let root = directory("test-job-drain");
|
||||
let domain = root.join("module/demo/work");
|
||||
let cases = root.join("test/demo/work");
|
||||
fs::create_dir_all(&domain).unwrap();
|
||||
fs::create_dir_all(&cases).unwrap();
|
||||
write_source(
|
||||
domain.join("data/main.dever"),
|
||||
"type Work { label: Text unique }",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
domain.join("api.dever"),
|
||||
"job save(input:app.Input) retry(2) timeout(1000) = app.save",
|
||||
)
|
||||
.unwrap();
|
||||
write_source(
|
||||
domain.join("app/main.dever"),
|
||||
r#"
|
||||
type Input { label:Text, accept:Bool }
|
||||
flow submit(input:Input,key:Text) (out:Id)
|
||||
| step | kind | do |
|
||||
| out | calc | enqueue(job.save,input,key) |
|
||||
flow delayed(input:Input,key:Text,at:DateTime) (out:Id)
|
||||
| step | kind | do |
|
||||
| out | calc | enqueueAt(job.save,input,key,at) |
|
||||
flow save(input:Input) ()
|
||||
| step | kind | do |
|
||||
| - | data | data.create({label=input.label}) |
|
||||
| - | check | input.accept else Invalid |
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(cases.join("queue.dever"), r#"
|
||||
flow queue() ()
|
||||
| step | kind | do |
|
||||
| first | flow | app.submit(app.Input {label="now",accept=true},"same") |
|
||||
| duplicate | flow | app.submit(app.Input {label="now",accept=true},"same") |
|
||||
| - | calc | assertEq(first,duplicate) |
|
||||
| done | calc | dever.test.drainJobs(10) |
|
||||
| - | calc | assertEq(done,1) |
|
||||
| now | flow | dever.time.now() |
|
||||
| before | flow | dever.time.unixMillis() |
|
||||
| monotonic | flow | dever.time.monotonicNanos() |
|
||||
| - | flow | app.delayed(app.Input {label="later",accept=true},"later",dever.time.add(now,dever.time.duration(100))) |
|
||||
| early | calc | dever.test.drainJobs(10) |
|
||||
| - | calc | assertEq(early,0) |
|
||||
| - | calc | dever.test.advanceClock(100) |
|
||||
| after | flow | dever.time.unixMillis() |
|
||||
| elapsed | flow | dever.time.monotonicNanos() |
|
||||
| - | calc | assertEq(after-before,100) |
|
||||
| - | calc | assert(elapsed>=monotonic) |
|
||||
| later | calc | dever.test.drainJobs(10) |
|
||||
| - | calc | assertEq(later,1) |
|
||||
| - | flow | app.submit(app.Input {label="rollback",accept=false},"retry") |
|
||||
| failed | calc | dever.test.drainJobs(10) |
|
||||
| - | calc | assertEq(failed,1) |
|
||||
| - | calc | dever.test.advanceClock(1000) |
|
||||
| retried | calc | dever.test.drainJobs(10) |
|
||||
| - | calc | assertEq(retried,1) |
|
||||
| empty | calc | dever.test.drainJobs(10) |
|
||||
| - | calc | assertEq(empty,0) |
|
||||
| count | data | data.count() |
|
||||
| - | calc | assertEq(count,2) |
|
||||
"#).unwrap();
|
||||
success(cli(&["fmt", root.to_str().unwrap()]));
|
||||
let output = success(cli(&["test", root.to_str().unwrap()]));
|
||||
assert!(output.contains("PASS demo.work.queue"), "{output}");
|
||||
assert!(!root.join("data").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_schedule_uses_clock_and_drains_a_bounded_number_of_attempts() {
|
||||
let root = directory("test-schedule-drain");
|
||||
let domain = root.join("module/demo/work");
|
||||
let cases = root.join("test/demo/work");
|
||||
fs::create_dir_all(&domain).unwrap();
|
||||
fs::create_dir_all(&cases).unwrap();
|
||||
write_source(domain.join("data/main.dever"), "type Work { label:Text }").unwrap();
|
||||
write_source(
|
||||
domain.join("app/main.dever"),
|
||||
"flow save() ()\n| step | kind | do |\n| - | data | data.create({label=\"scheduled\"}) |",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
domain.join("api.dever"),
|
||||
"job save() retry(1) timeout(1000) = app.save\nschedule save = \"* * * * *\" = app.save",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
cases.join("schedule.dever"),
|
||||
r#"
|
||||
flow schedule() ()
|
||||
| step | kind | do |
|
||||
| first | calc | dever.test.drainJobs(1) |
|
||||
| - | calc | assertEq(first,1) |
|
||||
| repeated | calc | dever.test.drainJobs(1) |
|
||||
| - | calc | assertEq(repeated,0) |
|
||||
| - | calc | dever.test.advanceClock(180000) |
|
||||
| bounded | calc | dever.test.drainJobs(2) |
|
||||
| - | calc | assertEq(bounded,2) |
|
||||
| remaining | calc | dever.test.drainJobs(10) |
|
||||
| - | calc | assertEq(remaining,1) |
|
||||
| count | data | data.count() |
|
||||
| - | calc | assertEq(count,4) |
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
success(cli(&["fmt", root.to_str().unwrap()]));
|
||||
assert!(success(cli(&["test", root.to_str().unwrap()])).contains("PASS demo.work.schedule"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn importer_example_runs_real_jobs_and_rolls_back_partial_batches() {
|
||||
let root = directory("workflow-importer-jobs");
|
||||
let example = Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../examples/next/workflows/module/demo/importer");
|
||||
let domain = root.join("module/demo/importer");
|
||||
let cases = root.join("test/demo/importer");
|
||||
fs::create_dir_all(domain.join("data")).unwrap();
|
||||
fs::create_dir_all(&cases).unwrap();
|
||||
// 使用样例原文件;独立验证导入队列,不引入支付/通知领域的外部合同。
|
||||
for name in [
|
||||
"flow/importer.dv",
|
||||
"loop/importer.dv",
|
||||
"api/importer.dv",
|
||||
"data/item.dv",
|
||||
] {
|
||||
write_source(domain.join(name), fs::read(example.join(name)).unwrap()).unwrap();
|
||||
}
|
||||
fs::write(cases.join("behavior.dever"), r#"
|
||||
flow behavior() ()
|
||||
| step | kind | do |
|
||||
| input | calc | app.Request {key="batch",rows=[app.Row {code="one",title=" First "},app.Row {code="two",title="Second"}]} |
|
||||
| queued | flow | app.submit(input) |
|
||||
| repeated | flow | app.submit(input) |
|
||||
| - | calc | assertEq(queued,repeated) |
|
||||
| done | calc | dever.test.drainJobs(1) |
|
||||
| - | calc | assertEq(done,1) |
|
||||
| count | data | data.item.count() |
|
||||
| - | calc | assertEq(count,2) |
|
||||
| first | data | data.item.first(code=="one") |
|
||||
| - | check | first!=null else Invalid |
|
||||
| - | calc | assertEq(first.title,"First") |
|
||||
| - | flow | app.submit(app.Request {key="empty",rows=[]}) |
|
||||
| empty | calc | dever.test.drainJobs(1) |
|
||||
| - | calc | assertEq(empty,1) |
|
||||
| after_empty | data | data.item.count() |
|
||||
| - | calc | assertEq(after_empty,2) |
|
||||
| - | flow | app.submit(app.Request {key="conflict",rows=[app.Row {code="three",title="Must roll back"},app.Row {code="one",title="Duplicate"}]}) |
|
||||
| failed | calc | dever.test.drainJobs(1) |
|
||||
| - | calc | assertEq(failed,1) |
|
||||
| after_failure | data | data.item.count() |
|
||||
| - | calc | assertEq(after_failure,2) |
|
||||
| partial | data | data.item.exists(code=="three") |
|
||||
| - | calc | assertEq(partial,false) |
|
||||
| - | flow | app.submit(app.Request {key="after-failure",rows=[app.Row {code="four",title="Connection reused"}]}) |
|
||||
| resumed | calc | dever.test.drainJobs(1) |
|
||||
| - | calc | assertEq(resumed,1) |
|
||||
| after_resume | data | data.item.count() |
|
||||
| - | calc | assertEq(after_resume,3) |
|
||||
"#).unwrap();
|
||||
success(cli(&["fmt", root.to_str().unwrap()]));
|
||||
let output = success(cli(&["test", root.to_str().unwrap()]));
|
||||
assert!(output.contains("PASS demo.importer.behavior"), "{output}");
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn settings_load_once_validate_nested_shapes_and_keep_configuration_out_of_builds() {
|
||||
let root = directory("settings");
|
||||
let domain = root.join("module/demo/site");
|
||||
fs::create_dir_all(&domain).unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
write_source(
|
||||
domain.join("app/main.dever"),
|
||||
r#"
|
||||
type Mode { Active, Paused }
|
||||
type Banner { title: Text, note: Text?, limit: Int >= 1 and <= 20 }
|
||||
setting banner: Banner
|
||||
setting modes: List<Mode>
|
||||
setting size: Int >= 1 and <= 20
|
||||
setting note: Text?
|
||||
read() (out: Text) { out = banner.title }
|
||||
measure() (out: Int >= 1 and <= 20) { out = size }
|
||||
flow start() (out: Text)
|
||||
| step | kind | do |
|
||||
| out | calc | read() |
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
domain.join("api.dever"),
|
||||
"cmd read = app.start\ncmd size = app.measure",
|
||||
)
|
||||
.unwrap();
|
||||
let path = root.to_str().unwrap();
|
||||
success(cli(&["fmt", path]));
|
||||
success(cli(&["check", path])); // 检查和构建不要求配置存在。
|
||||
let index: serde_json::Value =
|
||||
serde_json::from_str(&success(cli(&["inspect", path, "--json"]))).unwrap();
|
||||
assert_eq!(
|
||||
index["symbols"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|symbol| symbol["kind"] == "setting")
|
||||
.count(),
|
||||
4
|
||||
);
|
||||
assert_eq!(
|
||||
index["calls"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|edge| edge["kind"] == "reference")
|
||||
.count(),
|
||||
2
|
||||
);
|
||||
let (project, program) = analyze(&root);
|
||||
let artifact = build::build(&project, &program, "main", Profile::Dev, None).unwrap();
|
||||
let binary = root.join("application");
|
||||
artifact.publish(&binary).unwrap();
|
||||
drop(artifact);
|
||||
let config = root.join("config/setting.json");
|
||||
let input = r#"{"module":{"demo":{"site":{"banner":{"title":"雪😀","note":null,"limit":8},"modes":["Active"],"size":12,"note":null}}}}"#;
|
||||
fs::write(&config, input).unwrap();
|
||||
let run = || {
|
||||
Command::new(&binary)
|
||||
.args(["demo.site.read", "{}"])
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(&success(run())).unwrap()["data"],
|
||||
"雪😀"
|
||||
);
|
||||
fs::write(&config, input.replace("雪😀", "更新")).unwrap();
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(&success(run())).unwrap()["data"],
|
||||
"更新"
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(&success(cli(&[
|
||||
"run",
|
||||
path,
|
||||
"--",
|
||||
"demo.site.size",
|
||||
"{}"
|
||||
])))
|
||||
.unwrap()["data"],
|
||||
12
|
||||
);
|
||||
let invalid = [
|
||||
input.replace("\"size\":12", "\"size\":0"),
|
||||
input.replace("\"limit\":8", "\"limit\":21"),
|
||||
input.replace("\"size\":12,", ""),
|
||||
input.replace("\"note\":null,", ""),
|
||||
input.replace(",\"note\":null", ""),
|
||||
input.replace("\"size\":12", "\"size\":12,\"size\":13"),
|
||||
input.replace("\"limit\":8", "\"limit\":8,\"extra\":1"),
|
||||
input.replace("\"Active\"", "\"Unknown\""),
|
||||
input.replace(
|
||||
"\"banner\":{\"title\":\"雪😀\",\"note\":null,\"limit\":8}",
|
||||
"\"banner\":[\"雪😀\",null,8]",
|
||||
),
|
||||
input.replace("\"size\":12", "\"size\":true"),
|
||||
format!("{input} null"),
|
||||
"{}".into(),
|
||||
];
|
||||
for invalid in invalid {
|
||||
fs::write(&config, &invalid).unwrap();
|
||||
let result = run();
|
||||
assert!(!result.status.success(), "accepted {invalid}");
|
||||
assert!(result.stdout.is_empty());
|
||||
assert!(String::from_utf8_lossy(&result.stderr).contains("setting.json"));
|
||||
}
|
||||
fs::remove_file(&config).unwrap();
|
||||
assert!(!run().status.success());
|
||||
let custom = root.join("custom.json");
|
||||
fs::write(&custom, input).unwrap();
|
||||
success(
|
||||
Command::new(&binary)
|
||||
.args(["--config", custom.to_str().unwrap(), "demo.site.read", "{}"])
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
success(cli(&[
|
||||
"run",
|
||||
path,
|
||||
"--",
|
||||
"--config",
|
||||
custom.to_str().unwrap(),
|
||||
"demo.site.read",
|
||||
"{}",
|
||||
]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn setting_references_obey_roles_and_participate_in_domain_cycles() {
|
||||
let root = directory("setting-access");
|
||||
let first = root.join("module/demo/first");
|
||||
let second = root.join("module/demo/second");
|
||||
for directory in [&first, &second] {
|
||||
fs::create_dir_all(directory).unwrap();
|
||||
}
|
||||
fs::write(first.join("domain.dever"), "setting capacity: Int >= 1").unwrap();
|
||||
write_source(
|
||||
first.join("app/main.dever"),
|
||||
"setting label: Text\nget() (out: Int >= 1) { out = domain.capacity }",
|
||||
)
|
||||
.unwrap();
|
||||
write_source(
|
||||
second.join("app/main.dever"),
|
||||
"setting limit: Int\nname() (out: Text) { out = first.label }",
|
||||
)
|
||||
.unwrap();
|
||||
analyze(&root);
|
||||
for (first_source, second_source, code) in [
|
||||
(
|
||||
"setting label: Text\nf() (out: Int) { out = second.limit }",
|
||||
"setting limit: Int\nf() (out: Text) { out = first.label }",
|
||||
"C010",
|
||||
),
|
||||
(
|
||||
"setting label: Text",
|
||||
"f() (out: Int) { out = demo.first.domain.capacity }",
|
||||
"C003",
|
||||
),
|
||||
("setting label: Text\nconst text = label", "", "C005"),
|
||||
("setting capacity: Int", "", "C001"),
|
||||
("setting label: Text\nconst label = 1", "", "C001"),
|
||||
("setting get: Text\nget() () {}", "", "C001"),
|
||||
] {
|
||||
write_source(first.join("app/main.dever"), first_source).unwrap();
|
||||
write_source(second.join("app/main.dever"), second_source).unwrap();
|
||||
let project = Project::load(&root).unwrap();
|
||||
let error = program::check(&project.declarations, &project.modules)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(error.code, code, "{error}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_settings_do_not_survive_in_navigation() {
|
||||
let root = directory("settings-navigation");
|
||||
let path = root.join("app.dever");
|
||||
fs::write(&path, "setting value: Int\nsetting value: Int\nf() (out: Int) { out = value }\nindependent() (out: Int) { out = 1 }").unwrap();
|
||||
let project = Project::load(&path).unwrap();
|
||||
let index = dever::compiler::inspect::analyze(&project, None, 1, false).unwrap();
|
||||
assert_eq!(index.symbols.len(), 1);
|
||||
assert_eq!(index.symbols[0].name, "main.main.app.independent");
|
||||
assert!(index.diagnostics.iter().any(|error| error.code == "C001"));
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn standard_names_resolve_in_domains_and_navigation_opens_bundled_sources() {
|
||||
let root = directory("standard-library");
|
||||
let domain = root.join("module/demo/value");
|
||||
fs::create_dir_all(&domain).unwrap();
|
||||
fs::write(
|
||||
domain.join("domain.dever"),
|
||||
"clean(value: Text) (out: Text) { out = text.trim(value) }
|
||||
id(value: Text) (out: Uuid?) { out = uuid.parse(value) }",
|
||||
)
|
||||
.unwrap();
|
||||
write_source(
|
||||
domain.join("app/main.dever"),
|
||||
"clean(value: Text) (out: Text) { out = domain.clean(value) }",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(domain.join("api.dever"), "cmd clean = app.clean").unwrap();
|
||||
let library = Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../lib/text.dv")
|
||||
.canonicalize()
|
||||
.unwrap();
|
||||
let original = fs::read(&library).unwrap();
|
||||
let uuid_library = library.parent().unwrap().join("uuid.dv");
|
||||
let uuid_original = fs::read(&uuid_library).unwrap();
|
||||
let path = root.to_str().unwrap();
|
||||
success(cli(&["fmt", path]));
|
||||
success(cli(&["check", path]));
|
||||
let index: serde_json::Value =
|
||||
serde_json::from_str(&success(cli(&["inspect", path, "--json"]))).unwrap();
|
||||
assert!(index["diagnostics"].as_array().unwrap().is_empty());
|
||||
let symbols = index["symbols"].as_array().unwrap();
|
||||
let trim = symbols
|
||||
.iter()
|
||||
.find(|value| value["name"] == "dever.text.app.trim")
|
||||
.unwrap();
|
||||
let file = trim["declarations"][0][0].as_u64().unwrap() as usize;
|
||||
assert_eq!(index["files"][file]["path"], library.to_str().unwrap());
|
||||
let parse_uuid = symbols
|
||||
.iter()
|
||||
.find(|value| value["name"] == "dever.uuid.app.parse")
|
||||
.unwrap();
|
||||
let file = parse_uuid["declarations"][0][0].as_u64().unwrap() as usize;
|
||||
assert_eq!(index["files"][file]["path"], uuid_library.to_str().unwrap());
|
||||
assert!(
|
||||
!symbols
|
||||
.iter()
|
||||
.any(|value| value["name"] == "dever.int.app.parse")
|
||||
);
|
||||
success(cli(&["inspect", path, "--links"]));
|
||||
success(cli(&["inspect", path, "--links", "--check"]));
|
||||
assert_eq!(fs::read(&library).unwrap(), original);
|
||||
assert_eq!(fs::read(&uuid_library).unwrap(), uuid_original);
|
||||
let output = success(cli(&[
|
||||
"run",
|
||||
path,
|
||||
"--",
|
||||
"demo.value.clean",
|
||||
r#"{"value":" 雪 \n"}"#,
|
||||
]));
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(&output).unwrap()["data"],
|
||||
"雪"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn standard_primitives_are_private_and_calls_keep_static_types() {
|
||||
let root = directory("standard-invalid");
|
||||
let source = root.join("main.dever");
|
||||
for (text, code) in [
|
||||
(
|
||||
"f(text: Text) (out: Int) { pending: dever.time.DateResult = result(dever.time.parseDate(text))\nout = 1 }",
|
||||
"C012",
|
||||
),
|
||||
("f(value: Date) (out: DateTime) { out = value }", "C005"),
|
||||
(
|
||||
"f(value: DateTime, offset: Int) (out: DateTime) { out = dever.time.add(value, offset) }",
|
||||
"C005",
|
||||
),
|
||||
(
|
||||
"f(text: Text) (out: Date) { out = dever.system.timeParseDate(text) }",
|
||||
"C003",
|
||||
),
|
||||
(
|
||||
"f(value: Time) (out: dever.time.TextResult) { out = result(dever.time.formatTime(value)) }",
|
||||
"C012",
|
||||
),
|
||||
(
|
||||
"f(value: Text) (out: Text) { out = dever.system.textTrim(value) }",
|
||||
"C003",
|
||||
),
|
||||
(
|
||||
"f(value: Int) (out: Text) { out = text.trim(value) }",
|
||||
"C005",
|
||||
),
|
||||
(
|
||||
"f(value: Text) (out: Int) { out = int.parse(value) }",
|
||||
"C005",
|
||||
),
|
||||
(
|
||||
"f(value: Decimal) (out: Decimal) { out = decimal.round(value) }",
|
||||
"C005",
|
||||
),
|
||||
(
|
||||
"f(value: Float) (out: Float) { out = math.missing(value) }",
|
||||
"C004",
|
||||
),
|
||||
("f(value: Uuid) (out: Bool) { out = value < value }", "C005"),
|
||||
(
|
||||
"loop f(values: List<Uuid>) (out: List<Uuid>)\n| each value in values | sort | result |\n| out | [value.asc] | list value |",
|
||||
"C005",
|
||||
),
|
||||
("f(value: Uuid) (out: Text) { out = value }", "C005"),
|
||||
(
|
||||
"f(value: Text) (out: Uuid) { out = uuid.parse(value) }",
|
||||
"C005",
|
||||
),
|
||||
] {
|
||||
fs::write(&source, text).unwrap();
|
||||
let project = Project::load(&source).unwrap();
|
||||
assert!(project.diagnostics.is_empty(), "{:?}", project.diagnostics);
|
||||
let error = program::check(&project.declarations, &project.modules)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(error.code, code, "{error}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,396 @@
|
||||
use super::*;
|
||||
use std::{
|
||||
io::Write,
|
||||
net::TcpStream,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
fn project(name: &str) -> PathBuf {
|
||||
let root = directory(name);
|
||||
let domain = root.join("module/demo/files");
|
||||
fs::create_dir_all(domain.join("api/front")).unwrap();
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
fs::create_dir_all(root.join("store")).unwrap();
|
||||
fs::write(
|
||||
domain.join("port.dever"),
|
||||
"save(file: Upload) (key: Uuid) fails dever.storage.PutResult",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(domain.join("adapter.dever"),"flow port.save(file: Upload) (key: Uuid)\n| step | kind | do |\n| key | flow | dever.storage.put(file) |").unwrap();
|
||||
write_source(
|
||||
domain.join("app/main.dever"),
|
||||
r#"
|
||||
type Receipt { key: Uuid, filename: Text, size: Int, title: Text }
|
||||
flow save(file: Upload, title: Text) (out: Receipt)
|
||||
| step | kind | do |
|
||||
| filename | calc | file.filename |
|
||||
| size | calc | file.size |
|
||||
| key | port | port.save(file) |
|
||||
| out | calc | Receipt {key = key, filename = filename, size = size, title = title} |
|
||||
|
||||
flow discard(file: Upload) ()
|
||||
| step | kind | do |
|
||||
| - | calc | close(file) |
|
||||
|
||||
flow reject(file: Upload) ()
|
||||
| step | kind | do |
|
||||
| - | check | file.size == 0 else Conflict |
|
||||
| - | calc | close(file) |
|
||||
|
||||
echo(value: Text) (out: Text) {out = value}
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(domain.join("api/front/main.dever"),"public post save = app.save\npublic post discard = app.discard\npublic post reject = app.reject\npublic post echo = app.echo").unwrap();
|
||||
root
|
||||
}
|
||||
fn body(content: &str, extra: &str) -> String {
|
||||
format!(
|
||||
"--test\r\nContent-Disposition: form-data; name=\"file\"; filename=\"../hello.txt\"\r\nContent-Type: text/plain\r\n\r\n{content}\r\n{extra}--test--\r\n"
|
||||
)
|
||||
}
|
||||
const HEADER: &str = "Content-Type: multipart/form-data; boundary=test\r\n";
|
||||
const TITLE: &str = "--test\r\nContent-Disposition: form-data; name=\"title\"\r\n\r\n中文\r\n";
|
||||
|
||||
#[test]
|
||||
fn multipart_streams_to_storage_and_cleans_failed_discarded_and_disconnected_uploads() {
|
||||
let root = project("multipart-storage");
|
||||
success(cli(&["fmt", root.to_str().unwrap()]));
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
let (path, port, mut settings) = api::config(&root);
|
||||
settings["sites"]["front"]["hosts"] = serde_json::json!(["localhost", "127.0.0.1"]);
|
||||
settings["http"]["limits"] = serde_json::json!({"header_bytes":16384,"body_bytes":16777216,"timeout_ms":2000,"connections":128,"http2":null});
|
||||
settings["http"]["upload"] =
|
||||
serde_json::json!({"directory":"../store","limits":{"file_bytes":64,"total_bytes":2048}});
|
||||
fs::write(&path, settings.to_string()).unwrap();
|
||||
let server = api::Server::start(&artifact.binary, &path, port);
|
||||
let (status, response) = server.call(
|
||||
"POST",
|
||||
"/demo/files/front/main/save",
|
||||
&body("hello", TITLE),
|
||||
HEADER,
|
||||
);
|
||||
assert_eq!(status, 200, "{response}");
|
||||
assert_eq!(response["data"]["filename"], "../hello.txt");
|
||||
assert_eq!(response["data"]["size"], 5);
|
||||
assert_eq!(response["data"]["title"], "中文");
|
||||
let stored = root.join("store/global");
|
||||
let key = response["data"]["key"].as_str().unwrap();
|
||||
assert_eq!(fs::read(stored.join(key)).unwrap(), b"hello");
|
||||
for (route, payload, expected) in [
|
||||
("discard", body("discard", ""), 200),
|
||||
("reject", body("reject", ""), 409),
|
||||
("save", body("bad", &format!("{TITLE}{TITLE}")), 400),
|
||||
("save", body("bad", ""), 400),
|
||||
("save", body(&"x".repeat(65), TITLE), 413),
|
||||
(
|
||||
"save",
|
||||
body(
|
||||
"bad",
|
||||
"--test\r\nContent-Disposition: form-data; name=\"unknown\"\r\n\r\nx\r\n",
|
||||
),
|
||||
400,
|
||||
),
|
||||
] {
|
||||
let (status, response) = server.call(
|
||||
"POST",
|
||||
&format!("/demo/files/front/main/{route}"),
|
||||
&payload,
|
||||
HEADER,
|
||||
);
|
||||
assert_eq!(status, expected, "{route}: {response}");
|
||||
assert_eq!(
|
||||
fs::read_dir(&stored).unwrap().count(),
|
||||
1,
|
||||
"temporary file leaked"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
server
|
||||
.call(
|
||||
"POST",
|
||||
"/demo/files/front/main/echo",
|
||||
r#"{"value":"json still works"}"#,
|
||||
"Content-Type: application/json\r\n"
|
||||
)
|
||||
.1["data"],
|
||||
"json still works"
|
||||
);
|
||||
for (route, payload, content_type) in [
|
||||
(
|
||||
"discard",
|
||||
body("trailer", ""),
|
||||
"multipart/form-data; boundary=test",
|
||||
),
|
||||
(
|
||||
"echo",
|
||||
r#"{"value":"trailer"}"#.to_owned(),
|
||||
"application/json",
|
||||
),
|
||||
] {
|
||||
use std::io::{BufRead, BufReader};
|
||||
let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap();
|
||||
stream
|
||||
.set_read_timeout(Some(Duration::from_secs(5)))
|
||||
.unwrap();
|
||||
write!(stream,"POST /demo/files/front/main/{route} HTTP/1.1\r\nHost: localhost\r\nContent-Type: {content_type}\r\nTransfer-Encoding: chunked\r\n\r\n{:x}\r\n{payload}\r\n0\r\nX-Budget: {}\r\n\r\n",payload.len(),"x".repeat(17000)).unwrap();
|
||||
let mut status = String::new();
|
||||
BufReader::new(stream).read_line(&mut status).unwrap();
|
||||
assert!(
|
||||
status.contains("400"),
|
||||
"oversized trailer accepted: {status}"
|
||||
);
|
||||
assert_eq!(fs::read_dir(&stored).unwrap().count(), 1);
|
||||
}
|
||||
assert_eq!(
|
||||
server
|
||||
.call(
|
||||
"POST",
|
||||
"/demo/files/front/main/discard",
|
||||
&(body("data", "") + &"x".repeat(2048)),
|
||||
HEADER
|
||||
)
|
||||
.0,
|
||||
413
|
||||
);
|
||||
assert_eq!(
|
||||
fs::read_dir(&stored).unwrap().count(),
|
||||
1,
|
||||
"oversized epilogue leaked file"
|
||||
);
|
||||
let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap();
|
||||
write!(stream,"POST /demo/files/front/main/save HTTP/1.1\r\nHost: localhost\r\n{HEADER}Content-Length: 9999\r\n\r\n--test\r\nContent-Disposition: form-data; name=\"file\"; filename=\"partial.txt\"\r\n\r\npartial").unwrap();
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
drop(stream);
|
||||
let until = Instant::now() + Duration::from_secs(5);
|
||||
while fs::read_dir(&stored).unwrap().count() != 1 {
|
||||
assert!(Instant::now() < until, "disconnected upload leaked");
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
{
|
||||
use std::io::{BufRead, BufReader};
|
||||
let mut waiting = TcpStream::connect(("127.0.0.1", port)).unwrap();
|
||||
waiting
|
||||
.set_read_timeout(Some(Duration::from_secs(5)))
|
||||
.unwrap();
|
||||
write!(waiting,"POST /demo/files/front/main/discard HTTP/1.1\r\nHost: localhost\r\n{HEADER}Content-Length: 9999\r\n\r\n--test\r\nContent-Disposition: form-data; name=\"file\"; filename=\"timeout.txt\"\r\n\r\npartial").unwrap();
|
||||
let mut status = String::new();
|
||||
BufReader::new(waiting).read_line(&mut status).unwrap();
|
||||
assert!(status.contains("504"), "{status}");
|
||||
assert_eq!(
|
||||
fs::read_dir(&stored).unwrap().count(),
|
||||
1,
|
||||
"timed-out upload leaked"
|
||||
);
|
||||
}
|
||||
success(cli(&[
|
||||
"client",
|
||||
root.to_str().unwrap(),
|
||||
"--output",
|
||||
root.join("client.ts").to_str().unwrap(),
|
||||
]));
|
||||
fs::write(root.join("client.mjs"),r#"
|
||||
import assert from 'node:assert/strict';
|
||||
import {createClient} from './client.ts';
|
||||
const client=createClient(process.argv[2]);
|
||||
const value=await client['POST /demo/files/front/main/save']({file:new File(['from browser'],'client.txt'),title:'typed upload'});
|
||||
assert.equal(value.filename,'client.txt');assert.equal(value.size,12);assert.equal(value.title,'typed upload');
|
||||
console.log(value.key);
|
||||
"#).unwrap();
|
||||
let key = success(
|
||||
Command::new("node")
|
||||
.arg(root.join("client.mjs"))
|
||||
.arg(format!("http://127.0.0.1:{port}"))
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
assert_eq!(fs::read(stored.join(key.trim())).unwrap(), b"from browser");
|
||||
server.stop();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn upload_rejects_alias_reuse_escape_and_non_post_entry() {
|
||||
let root = project("multipart-contracts");
|
||||
let domain = root.join("module/demo/files");
|
||||
for source in [
|
||||
"flow save(file: Upload) ()\n| step | kind | do |\n| - | calc | close(file) |\n| - | calc | close(file) |",
|
||||
"flow save(file: Upload) ()\n| step | kind | do |\n| alias | calc | file |\n| - | calc | close(alias) |",
|
||||
"save(file: Upload) (out: Int) {out = file.size}",
|
||||
"type Box {file: Upload}\nsave(file: Box) () {}",
|
||||
"save(file: Upload?) () {}",
|
||||
"flow save(file: Upload) (key: Uuid)\n| step | kind | do |\n| key | flow | dever.storage.put(file) |",
|
||||
] {
|
||||
write_source(domain.join("app/main.dever"), source).unwrap();
|
||||
fs::write(
|
||||
domain.join("api/front/main.dever"),
|
||||
"public post save = app.save",
|
||||
)
|
||||
.unwrap();
|
||||
let project = Project::load(&root).unwrap();
|
||||
assert!(project.diagnostics.is_empty(), "{source}");
|
||||
assert!(
|
||||
program::check(&project.declarations, &project.modules).is_err(),
|
||||
"{source}"
|
||||
);
|
||||
}
|
||||
write_source(
|
||||
domain.join("app/main.dever"),
|
||||
"flow save(file: Upload) ()\n| step | kind | do |\n| - | calc | close(file) |",
|
||||
)
|
||||
.unwrap();
|
||||
for entry in [
|
||||
"public get save = app.save",
|
||||
"cmd save = app.save",
|
||||
"public put save = app.save",
|
||||
] {
|
||||
fs::write(domain.join("api/front/main.dever"), entry).unwrap();
|
||||
let project = Project::load(&root).unwrap();
|
||||
assert!(
|
||||
program::check(&project.declarations, &project.modules).is_err(),
|
||||
"{entry}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn tenant_setup(root: &Path) {
|
||||
use std::io::Write;
|
||||
let domain = root.join("module/demo/service");
|
||||
fs::create_dir(root.join("upload-store")).unwrap();
|
||||
let mut app = fs::OpenOptions::new()
|
||||
.append(true)
|
||||
.open(domain.join("app/main.dever"))
|
||||
.unwrap();
|
||||
writeln!(app,"\nflow upload(file:Upload) (key:Uuid)\n| step | kind | do |\n| key | port | port.store(file) |").unwrap();
|
||||
let mut api = fs::OpenOptions::new()
|
||||
.append(true)
|
||||
.open(domain.join("api/front/main.dever"))
|
||||
.unwrap();
|
||||
writeln!(api, "\npost upload = app.upload").unwrap();
|
||||
fs::write(
|
||||
domain.join("port.dever"),
|
||||
"store(file:Upload) (key:Uuid) fails dever.storage.PutResult",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(domain.join("adapter.dever"),"flow port.store(file:Upload) (key:Uuid)\n| step | kind | do |\n| key | flow | dever.storage.put(file) |").unwrap();
|
||||
}
|
||||
|
||||
pub(super) fn unauthorized(port: u16, root: &Path) {
|
||||
use std::io::{BufRead, BufReader};
|
||||
let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap();
|
||||
stream
|
||||
.set_read_timeout(Some(Duration::from_secs(2)))
|
||||
.unwrap();
|
||||
write!(stream,"POST /demo/service/front/main/upload HTTP/1.1\r\nHost: localhost\r\nContent-Type: multipart/form-data; boundary=test\r\nContent-Length: 10000\r\n\r\n").unwrap();
|
||||
let mut status = String::new();
|
||||
BufReader::new(stream).read_line(&mut status).unwrap();
|
||||
assert!(status.contains("401"), "{status}");
|
||||
assert_eq!(
|
||||
fs::read_dir(root.join("upload-store")).unwrap().count(),
|
||||
0,
|
||||
"unauthorized body created files"
|
||||
);
|
||||
}
|
||||
|
||||
pub(super) fn tenant_isolation(server: &api::Server, root: &Path, first: &str, second: &str) {
|
||||
let route = "/demo/service/front/main/upload";
|
||||
for (id, headers, content) in [(1, first, "first tenant"), (2, second, "second tenant")] {
|
||||
let headers = headers.replace("Content-Type: application/json\r\n", HEADER);
|
||||
let (status, response) = server.call("POST", route, &body(content, ""), &headers);
|
||||
assert_eq!(status, 200, "{response}");
|
||||
let key = response["data"].as_str().unwrap();
|
||||
assert_eq!(
|
||||
fs::read(root.join(format!("upload-store/tenant/{id}/{key}"))).unwrap(),
|
||||
content.as_bytes()
|
||||
);
|
||||
assert!(
|
||||
!root
|
||||
.join(format!("upload-store/tenant/{}/{key}", 3 - id))
|
||||
.exists()
|
||||
);
|
||||
}
|
||||
assert!(!root.join("upload-store/global").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmd_stores_generated_bytes_without_http_and_rolls_back_rejected_input() {
|
||||
let root = directory("transaction-stored-bytes");
|
||||
let domain = root.join("module/demo/files");
|
||||
write_source(domain.join("api/files.dv"), "cmd store = app.store").unwrap();
|
||||
write_source(
|
||||
domain.join("flow/files.dv"),
|
||||
r#"transaction flow store(encoded: Text, accept: Bool) (key: Uuid) {
|
||||
body = dever.bytes.fromBase64(encoded)
|
||||
key = dever.storage.putBytes(body)
|
||||
check accept else Conflict
|
||||
}"#,
|
||||
)
|
||||
.unwrap();
|
||||
fs::create_dir_all(root.join("files")).unwrap();
|
||||
fs::create_dir_all(root.join("data")).unwrap();
|
||||
let config = root.join("config/setting.json");
|
||||
write_source(&config, r#"{"http":{"upload":{"directory":"../files","limits":{"file_bytes":4}}},"database":{"default":{"type":"sqlite","path":"data/test.db"}}}"#).unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
let run = |args: &[&str]| {
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.args(args)
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
success(run(&["migrate"]));
|
||||
let value: serde_json::Value = serde_json::from_str(&success(run(&[
|
||||
"demo.files.store",
|
||||
r#"{"encoded":"AP9h","accept":true}"#,
|
||||
])))
|
||||
.unwrap();
|
||||
let files = root.join("files/global");
|
||||
assert_eq!(
|
||||
fs::read(files.join(value["data"].as_str().unwrap())).unwrap(),
|
||||
[0, 255, 97]
|
||||
);
|
||||
for payload in [
|
||||
r#"{"encoded":"AQ==","accept":false}"#,
|
||||
r#"{"encoded":"***","accept":true}"#,
|
||||
r#"{"encoded":"MTIzNDU=","accept":true}"#,
|
||||
] {
|
||||
assert!(!run(&["demo.files.store", payload]).status.success());
|
||||
assert_eq!(fs::read_dir(&files).unwrap().count(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_and_test_can_both_store_bytes() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
write_source(
|
||||
root.path().join("module/demo/files/flow/files.dv"),
|
||||
r#"transaction flow store(body: Bytes) (key: Uuid) {
|
||||
key = dever.storage.putBytes(body)
|
||||
}"#,
|
||||
)
|
||||
.unwrap();
|
||||
write_source(
|
||||
root.path().join("test/demo/files/save.dv"),
|
||||
r#"type Attempt { Stored(key: Uuid), error Rejected(cause: dever.storage.PutResult) }
|
||||
|
||||
rule rejected(value: Attempt) (out: Bool) recover("验证事务外写入被拒绝") value {
|
||||
Stored(key) => false
|
||||
Rejected(cause) => true
|
||||
}
|
||||
|
||||
flow save() () {
|
||||
body = dever.bytes.fromBase64("AQ==")
|
||||
key = app.store(body)
|
||||
second = app.store(body)
|
||||
assert(key != second)
|
||||
attempt: Attempt = result(dever.storage.putBytes(body))
|
||||
assert(rejected(attempt))
|
||||
}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let path = root.path().to_str().unwrap();
|
||||
success(cli(&["fmt", path]));
|
||||
assert!(success(cli(&["test", path])).contains("PASS demo.files.save"));
|
||||
}
|
||||
Reference in new issue
Block a user