Dever v0.0.2

This commit is contained in:
Codex committed 2026-11-27 06:03:56 +00:00
commit e6e175ebcf
816 files changed
+120349

No files matched your search

+190
View File
@@ -0,0 +1,190 @@
use super::*;
use auth::{Access, Role, schema};
#[test]
fn authorization_requires_a_live_catalog_entry_even_for_owner_and_a_separate_catalog() {
let file = File::new("authorization-catalog");
let other = File::new("authorization-roles");
task::run(false, 16, async |scope| {
let catalog = Database::sqlite(&file.0, true, options(), None).await?;
let roles = Database::sqlite(&other.0, true, options(), None).await?;
for database in [&catalog, &roles] {
database.acquire().await?.migrate_group(scope,
schema::CATALOG.into_iter().chain(schema::ROLES)
.map(|(name, sql)| (name, sql, None)).collect(),
).await?;
auth::initialize_owner(scope, database, "admin", 7).await?;
}
catalog.acquire().await?.execute(scope, Sql::same(
"INSERT INTO _dever_permission VALUES ('content.article.admin.read','admin','content','article','read',TRUE,'GET','http')",
), vec![]).await?;
let identity = verified("admin", 7, None).await;
for database in [&catalog, &roles] {
let mut context = Context::default();
let mut access = Access::global(&identity, database, &mut context)?;
access.authorize(scope, &catalog, "content.article.admin.read").await?;
assert!(matches!(access.authorize(scope, &catalog, "missing").await, Err(Error::Forbidden)));
}
catalog.acquire().await?.execute(scope, Sql::same(
"UPDATE _dever_permission SET active=FALSE",
), vec![]).await?;
for database in [&catalog, &roles] {
let mut context = Context::default();
assert!(matches!(
Access::global(&identity, database, &mut context)?.authorize(
scope, &catalog, "content.article.admin.read",
).await,
Err(Error::Forbidden)
));
}
Ok::<_, Error>(())
}).unwrap().unwrap();
}
#[test]
#[ignore = "explicit release performance probe; real SQLite authorization, fixed rounds"]
fn authorization_cost() {
let file = File::new("authorization-cost");
let other = File::new("authorization-cost-catalog");
task::run(false, 16, async |scope| {
let database = Database::sqlite(&file.0, true, options(), None).await?;
let separate = Database::sqlite(&other.0, true, options(), None).await?;
for database in [&database, &separate] {
database.acquire().await?.migrate_group(scope,
schema::CATALOG.into_iter().chain(schema::ROLES)
.map(|(name, sql)| (name, sql, None)).collect(),
).await?;
database.acquire().await?.execute(scope, Sql::same(
"INSERT INTO _dever_permission VALUES ('content.article.admin.read','admin','content','article','read',TRUE,'GET','http')",
), vec![]).await?;
}
auth::initialize_owner(scope, &database, "admin", 7).await?;
let owner = verified("admin", 7, None).await;
let visitor = verified("admin", 8, None).await;
println!("case,sample,iterations,elapsed_ns,allowed");
for (name, catalog) in [("same", &database), ("separate", &separate)] {
for (identity, expected) in [(&owner, true), (&visitor, false)] {
let mut context = Context::default();
let mut access = Access::global(identity, &database, &mut context)?;
for sample in -1..7 {
let started = std::time::Instant::now();
let mut allowed = 0;
for _ in 0..256 {
let result = access.authorize(scope, catalog, "content.article.admin.read").await;
match result {
Ok(()) => { assert!(expected); allowed += 1; }
Err(Error::Forbidden) => assert!(!expected),
Err(error) => return Err(error),
}
}
println!("{name}_{expected},{sample},256,{},{}", started.elapsed().as_nanos(), allowed);
}
}
}
Ok::<_, Error>(())
}).unwrap().unwrap();
}
#[test]
fn exact_permissions_live_role_changes_and_site_isolation_use_one_connection() {
let file = File::new("authorization");
task::run(true, 16,async |scope| {
let database=Database::sqlite(&file.0,true,options(), None).await?;
database.acquire().await?.migrate_group(scope,schema::CATALOG.into_iter().chain(schema::ROLES).map(|(name,sql)|(name,sql,None)).collect()).await?;
database.acquire().await?.execute(scope,Sql::same("INSERT INTO _dever_permission VALUES ('content.article.admin.read','admin','content','article','read',TRUE,'GET','http')"), vec![]).await?;
auth::initialize_owner(scope,&database,"admin",99).await?;
auth::initialize_owner(scope,&database,"admin",99).await?;
let owner_identity=verified("admin",99,None).await;
let mut owner_context=Context::default();
Access::global(&owner_identity,&database,&mut owner_context)?.authorize(scope,&database,"content.article.admin.read").await?;
drop(owner_context);
let identity=verified("admin",7,None).await;
let mut context=Context::default();
let mut access=Access::global(&identity,&database,&mut context)?;
assert!(matches!(access.authorize(scope,&database,"content.article.admin.read").await,Err(Error::Forbidden)));
access.save_role(scope,&database,Role { id: "reader".into(),name:"Reader".into(),all_permissions:false,permissions:vec!["content.article.admin.read".into()] }).await?;
access.grant_role(scope,7,"reader").await?;
access.authorize(scope,&database,"content.article.admin.read").await?;
assert!(matches!(access.authorize(scope,&database,"content.article.admin.write").await,Err(Error::Forbidden)));
assert_eq!(access.current_permissions(scope,&database).await?,["content.article.admin.read"]);
let roles=access.roles(scope,auth::Selector::User(7)).await?;
assert_eq!(roles.len(),1);assert_eq!(roles[0].role.id,"reader");
assert_eq!(roles[0].role.permissions,["content.article.admin.read"]);
access.revoke_role(scope,7,"reader").await?;
access.revoke_role(scope,7,"reader").await?;
assert!(matches!(access.authorize(scope,&database,"content.article.admin.read").await,Err(Error::Forbidden)));
access.grant_role(scope,7,"reader").await?;
access.disable_role(scope,"reader").await?;
access.grant_role(scope,8,"reader").await?;
assert!(!access.roles(scope,auth::Selector::User(8)).await?[0].enabled);
assert!(matches!(access.authorize(scope,&database,"content.article.admin.read").await,Err(Error::Forbidden)));
assert!(matches!(access.disable_role(scope,"owner").await,Err(Error::Forbidden)));
assert!(matches!(access.revoke_role(scope,99,"owner").await,Err(Error::Forbidden)));
assert!(matches!(access.save_role(scope,&database,Role { id:"owner".into(),name:"changed".into(),all_permissions:false,permissions:vec![] }).await,Err(Error::Forbidden)));
access.remove_role(scope,"reader").await?;
assert!(matches!(access.remove_role(scope,"reader").await,Err(Error::NotFound)));
assert!(matches!(access.disable_role(scope,"missing").await,Err(Error::NotFound)));
assert!(matches!(access.grant_role(scope,7,"missing").await,Err(Error::NotFound)));
assert!(matches!(access.revoke_role(scope,7,"missing").await,Err(Error::NotFound)));
assert!(access.roles(scope,auth::Selector::User(7)).await?.is_empty());
assert!(matches!(access.remove_role(scope,"owner").await,Err(Error::Forbidden)));
drop(context);
let other=verified("public",99,None).await;
let mut context=Context::default();
let mut access=Access::global(&other,&database,&mut context)?;
assert!(matches!(access.authorize(scope,&database,"content.article.admin.read").await,Err(Error::Forbidden)));
Ok::<_,Error>(())
}).unwrap().unwrap();
}
#[test]
fn owner_initialization_does_not_overwrite_a_business_role_or_grant_invalid_users() {
let file = File::new("owner-initialization");
task::run(true, 16, async |scope| {
let database = Database::sqlite(&file.0, true, options(), None).await?;
database
.acquire()
.await?
.migrate_group(
scope,
schema::ROLES
.into_iter()
.map(|(name, sql)| (name, sql, None))
.collect(),
)
.await?;
database.acquire().await?.execute(scope, Sql::same(
"INSERT INTO _dever_role VALUES ('admin','owner','Business role',FALSE,TRUE,FALSE)"
), vec![]).await?;
assert!(matches!(
auth::initialize_owner(scope, &database, "admin", 7).await,
Err(Error::Conflict)
));
assert!(matches!(
auth::initialize_owner(scope, &database, "front", 0).await,
Err(Error::Invalid)
));
let mut executor = database.acquire().await?;
let roles = executor
.query(
scope,
Sql::same("SELECT name,protected FROM _dever_role"),
vec![],
|row| Ok((row.get::<String>(0)?, row.get::<bool>(1)?)),
)
.await?;
assert_eq!(roles, [("Business role".into(), false)]);
let members = executor
.query(
scope,
Sql::same("SELECT count(*) FROM _dever_user_role"),
vec![],
|row| row.get::<i64>(0),
)
.await?;
assert_eq!(members, [0]);
Ok::<_, Error>(())
})
.unwrap()
.unwrap();
}
+175
View File
@@ -0,0 +1,175 @@
use super::*;
use auth::{
Access, Namespace, Role, schema,
tenant::{Backend, Directory},
};
use std::time::Duration;
fn namespace() -> Namespace {
Namespace {
component: "content",
domain: "article",
}
}
fn reader(key: &str) -> Role {
Role {
id: "reader".into(),
name: "Reader".into(),
all_permissions: false,
permissions: vec![key.into()],
}
}
#[test]
fn capabilities_share_business_transactions_and_revocation_does_not_restore_old_grants() {
let control_file = File::new("capability-control");
let directory = control_file.0.with_extension("tenants");
std::fs::create_dir(&directory).unwrap();
let first = File(directory.join("1.sqlite"));
let second = File(directory.join("2.sqlite"));
task::run(true, 16, async |scope| {
let control = Database::sqlite(&control_file.0, true, options(), None).await?;
control.acquire().await?.migrate_group(scope, schema::CATALOG.into_iter()
.chain([("_dever_tenant_database", auth::tenant::CATALOG)])
.map(|(name, sql)| (name, sql, None)).collect()).await?;
{
let mut fixture = control.acquire().await?;
for sql in [
"INSERT INTO _dever_tenant_database VALUES (1,'ready','v1'),(2,'ready','v1')",
"INSERT INTO _dever_tenant_component VALUES (1,'content',TRUE),(2,'content',TRUE)",
"INSERT INTO _dever_permission VALUES ('content.article.admin.read','admin','content','article','read',TRUE,'GET','http')",
] {
fixture.execute(scope, Sql::same(sql), vec![]).await?;
}
}
for file in [&first, &second] {
let database = Database::sqlite(&file.0, true, options(), None).await?;
database.acquire().await?.migrate_group(scope, schema::ROLES.into_iter()
.map(|(name, sql)| (name, sql, None)).collect()).await?;
}
let pools = Directory::new( control.clone(), Backend::Sqlite { cache_size_kib: None,
directory: directory.clone(), options: options(),
}, "v1".into(), &schema::ROLES, (2, Duration::from_secs(60)))?;
let identity = verified("admin", 7, Some(1)).await;
let selected = pools.select(scope, &identity).await?;
let resource = dever_runtime::value::uuid::Uuid::parse("00000000-0000-0000-0000-00000000002a").unwrap();
let mut context = Context::default();
let key;
{
let mut access = Access::tenant(&identity, &selected, &mut context)?;
access.save_role(scope, &control, reader("content.article.admin.read")).await?;
access.grant_role(scope, 7, "reader").await?;
access.authorize(scope, &control, "content.article.admin.read").await?;
assert!(matches!(access.authorize(scope, &control, "missing").await, Err(Error::Forbidden)));
key = access.register_capability(scope, &control, namespace(), resource).await?;
assert!(matches!(access.authorize(scope, &control, &key).await, Err(Error::Forbidden)));
access.save_role(scope, &control, reader(&key)).await?;
access.grant_role(scope, 7, "reader").await?;
access.authorize(scope, &control, &key).await?;
assert!(matches!(access.authorize(scope, &control, "capability:content.article.admin.missing").await, Err(Error::Forbidden)));
access.disable_role(scope, "reader").await?;
assert!(matches!(access.authorize(scope, &control, &key).await, Err(Error::Forbidden)));
access.save_role(scope, &control, reader(&key)).await?;
access.authorize(scope, &control, &key).await?;
access.remove_capability(scope, &control, namespace(), resource).await?;
access.register_capability(scope, &control, namespace(), resource).await?;
assert!(matches!(access.authorize(scope, &control, &key).await, Err(Error::Forbidden)));
assert!(access.current_permissions(scope, &control).await?.is_empty());
access.save_role(scope, &control, reader(&key)).await?;
}
let owner = context.enter();
{
let mut access = Access::tenant(&identity, &selected, &mut context)?;
access.remove_capability(scope, &control, namespace(), resource).await?;
assert!(matches!(access.authorize(scope, &control, &key).await, Err(Error::Forbidden)));
}
context.finish(scope, owner, false).await?;
{
let mut access = Access::tenant(&identity, &selected, &mut context)?;
access.authorize(scope, &control, &key).await?;
}
drop(context);
let other = verified("admin", 7, Some(2)).await;
let other_selection = pools.select(scope, &other).await?;
let mut other_context = Context::default();
let mut other_access = Access::tenant(&other, &other_selection, &mut other_context)?;
assert!(matches!(other_access.authorize(scope, &control, &key).await, Err(Error::Forbidden)));
let public = verified("front", 7, Some(1)).await;
let mut public_context = Context::default();
let mut public_access = Access::tenant(&public, &selected, &mut public_context)?;
assert!(matches!(public_access.authorize(scope, &control, &key).await, Err(Error::Forbidden)));
drop(public_context);
auth::initialize_owner(scope, selected.database(), "admin", 7).await?;
control.acquire().await?.execute(scope, Sql::same("UPDATE _dever_tenant_component SET enabled=FALSE WHERE tenant=1"), vec![]).await?;
let mut context = Context::default();
let mut access = Access::tenant(&identity, &selected, &mut context)?;
assert!(matches!(access.authorize(scope, &control, "content.article.admin.read").await, Err(Error::Forbidden)));
assert!(matches!(access.authorize(scope, &control, &key).await, Err(Error::Forbidden)));
assert!(matches!(access.register_capability(scope, &control, namespace(), resource).await, Err(Error::Forbidden)));
Ok::<_, Error>(())
}).unwrap().unwrap();
drop(first);
drop(second);
std::fs::remove_dir(directory).unwrap();
}
#[test]
#[ignore = "explicit release performance probe; real physical tenant and capability authorization"]
fn tenant_authorization_cost() {
let control_file = File::new("authorization-tenant-cost");
let directory = control_file.0.with_extension("tenants");
std::fs::create_dir(&directory).unwrap();
let tenant_file = File(directory.join("1.sqlite"));
task::run(false, 16, async |scope| {
let control = Database::sqlite(&control_file.0, true, options(), None).await?;
control.acquire().await?.migrate_group(scope, schema::CATALOG.into_iter()
.chain([("_dever_tenant_database", auth::tenant::CATALOG)])
.map(|(name, sql)| (name, sql, None)).collect()).await?;
{
let mut fixture = control.acquire().await?;
for sql in [
"INSERT INTO _dever_tenant_database VALUES (1,'ready','v1')",
"INSERT INTO _dever_tenant_component VALUES (1,'content',TRUE)",
"INSERT INTO _dever_permission VALUES ('content.article.admin.read','admin','content','article','read',TRUE,'GET','http')",
] {
fixture.execute(scope, Sql::same(sql), vec![]).await?;
}
}
let database = Database::sqlite(&tenant_file.0, true, options(), None).await?;
database.acquire().await?.migrate_group(scope, schema::ROLES.into_iter()
.map(|(name, sql)| (name, sql, None)).collect()).await?;
auth::initialize_owner(scope, &database, "admin", 7).await?;
database.acquire().await?.execute(scope, Sql::same(
"INSERT INTO _dever_auth_capability VALUES ('capability:content.article.admin.00000000-0000-0000-0000-00000000002a','content','article','admin','00000000-0000-0000-0000-00000000002a',TRUE)"
), vec![]).await?;
let pools = Directory::new(control.clone(), Backend::Sqlite { cache_size_kib: None,
directory: directory.clone(), options: options(),
}, "v1".into(), &schema::ROLES, (1, Duration::from_secs(60)))?;
let owner = verified("admin", 7, Some(1)).await;
let visitor = verified("admin", 8, Some(1)).await;
let selected = pools.select(scope, &owner).await?;
println!("case,sample,iterations,elapsed_ns,allowed");
for (name, key) in [("tenant", "content.article.admin.read"),
("capability", "capability:content.article.admin.00000000-0000-0000-0000-00000000002a")] {
for (identity, expected) in [(&owner, true), (&visitor, false)] {
let mut context = Context::default();
let mut access = Access::tenant(identity, &selected, &mut context)?;
for sample in -1..7 {
let started = std::time::Instant::now();
let mut allowed = 0;
for _ in 0..256 {
match access.authorize(scope, &control, key).await {
Ok(()) => { assert!(expected); allowed += 1; }
Err(Error::Forbidden) => assert!(!expected),
Err(error) => return Err(error),
}
}
println!("{name}_{expected},{sample},256,{},{}", started.elapsed().as_nanos(), allowed);
}
}
}
Ok::<_, Error>(())
}).unwrap().unwrap();
drop(tenant_file);
std::fs::remove_dir(directory).unwrap();
}
+144
View File
@@ -0,0 +1,144 @@
use super::database::{File, options};
use dever_runtime::{
auth::{self, Claims, Error, Identity, Provider, Verified},
database::{Context, Database, Parameter, Sql},
task,
value::secret::Secret,
};
mod access;
mod capability;
mod tenant;
fn provider() -> Provider {
Provider::new("accounts".into(), Secret::from_input(vec![42; 32]), 60).unwrap()
}
fn claims(site: &str) -> Claims {
Claims {
subject: "subject".into(),
session: "session".into(),
tenant: None,
site: site.into(),
}
}
pub(super) async fn verified(site: &str, user: i64, tenant: Option<i64>) -> Verified {
let provider = provider();
let token = provider.issue(&claims(site), 100).unwrap();
auth::authenticate(&provider, &token, site, 101, async |_| {
Ok(Identity {
id: "user".into(),
user_id: Some(user),
tenant_id: tenant,
})
})
.await
.unwrap()
}
#[test]
fn token_encoding_matches_independent_hs256_vectors() {
let provider = provider();
// Python 标准库 json/base64/hmac 生成固定向量,防止签发和验签一起改错仍自证通过。
// 只比较测试 Token 的 HMAC,不公开 Secret 字节。
for (subject, session, tenant, expected) in [
(
"subject",
"session",
None,
[
175, 58, 78, 186, 13, 221, 100, 150, 175, 147, 188, 89, 169, 12, 116, 138, 251,
137, 214, 237, 67, 159, 53, 145, 1, 23, 40, 40, 65, 230, 166, 130,
],
),
(
"用户\"甲\n\\",
"会话\\01",
Some("租户/一"),
[
51, 78, 228, 224, 50, 86, 151, 37, 25, 23, 41, 10, 208, 165, 41, 40, 125, 149, 63,
180, 237, 28, 15, 28, 78, 234, 216, 108, 178, 9, 113, 199,
],
),
] {
let claims = Claims {
subject: subject.into(),
session: session.into(),
tenant: tenant.map(str::to_owned),
site: "admin".into(),
};
let token = provider.issue(&claims, 100).unwrap();
let proof = dever_runtime::crypto::hmac_sha256(&token, b"auth-token-contract");
assert_eq!(proof.as_ref(), expected);
assert_eq!(provider.verify_token(&token, "admin", 101).unwrap(), claims);
}
}
#[test]
fn tokens_check_signature_provider_site_and_time_before_project_verify() {
task::execute(true, async {
let provider = provider();
let token = provider.issue(&claims("admin"), 100).unwrap();
assert_eq!(
provider.verify_token(&token, "admin", 101).unwrap(),
claims("admin")
);
for (site, now) in [("other", 101), ("admin", 99), ("admin", 160)] {
let result = auth::authenticate(
&provider,
&token,
site,
now,
async |_| -> Result<Identity, Error> {
panic!("invalid token cannot invoke project verifier")
},
)
.await;
assert!(matches!(result, Err(Error::Unauthorized)));
}
let wrong_key =
Provider::new("accounts".into(), Secret::from_input(vec![43; 32]), 60).unwrap();
assert!(matches!(
wrong_key.verify_token(&token, "admin", 101),
Err(Error::Unauthorized)
));
let wrong_provider =
Provider::new("other".into(), Secret::from_input(vec![42; 32]), 60).unwrap();
assert!(matches!(
wrong_provider.verify_token(&token, "admin", 101),
Err(Error::Unauthorized)
));
let invalid = auth::authenticate(&provider, &token, "admin", 101, async |_| {
Ok(Identity {
id: "user".into(),
user_id: Some(0),
tenant_id: None,
})
})
.await;
assert!(matches!(invalid, Err(Error::Unauthorized)));
})
.unwrap();
}
#[test]
fn a_valid_signature_does_not_bypass_live_session_revocation() {
let file = File::new("auth-session");
task::run(true, 16, async |scope| {
let database = Database::sqlite(&file.0,true,options(), None).await?;
let mut fixture = database.acquire().await?;
fixture.execute(scope, Sql::same("CREATE TABLE session(id TEXT PRIMARY KEY,user_id INTEGER NOT NULL,active BOOLEAN NOT NULL)"), vec![]).await?;
fixture.execute(scope, Sql::same("INSERT INTO session VALUES ('session',7,TRUE)"), vec![]).await?;
drop(fixture);
let provider = provider();
let token = provider.issue(&claims("admin"),100)?;
let verify = async |claims: &Claims| {
let rows = database.acquire().await?.query(scope,Sql::same("SELECT user_id FROM session WHERE id=$1 AND active=TRUE"),vec![Parameter::Text(claims.session.clone())],|row|row.get::<i64>(0)).await?;
let user_id = rows.into_iter().next().ok_or(Error::Unauthorized)?;
Ok(Identity { id: user_id.to_string(),user_id:Some(user_id),tenant_id:None })
};
let identity = auth::authenticate(&provider,&token,"admin",101,&verify).await?;
assert_eq!(identity.user(),Some(7));
database.acquire().await?.execute(scope,Sql::same("UPDATE session SET active=FALSE WHERE id=$1"),vec![Parameter::Text("session".into())]).await?;
assert!(matches!(auth::authenticate(&provider,&token,"admin",101,&verify).await,Err(Error::Unauthorized)));
Ok::<_,Error>(())
}).unwrap().unwrap();
}
+199
View File
@@ -0,0 +1,199 @@
use super::{IncomingRequest, tests::limits, wire};
use crate::{
auth::{
Claims, Error, Identity, Provider,
request::{self, Cookie, Origin},
},
task,
value::secret::Secret,
};
fn request(method: &str, headers: &[(&str, &str)]) -> std::io::Result<IncomingRequest> {
let (parts, body) = headers
.iter()
.fold(
hyper::Request::builder().method(method).uri("/"),
|builder, &(name, value)| builder.header(name, value),
)
.body(bytes::Bytes::new())
.unwrap()
.into_parts();
let head = wire::incoming(parts, &limits(false).check().unwrap())?;
Ok(IncomingRequest { head, body })
}
#[test]
fn cookie_writes_require_the_configured_origin_and_cannot_mix_bearer() {
task::execute(true, async {
let provider =
Provider::new("accounts".into(), Secret::from_input(vec![42; 32]), 60).unwrap();
let cookie = Cookie::new("session".into(), "https://example.test").unwrap();
let claims = Claims {
subject: "subject".into(),
session: "session".into(),
tenant: None,
site: "admin".into(),
};
let header = cookie.issue(&provider, &claims, 100).unwrap();
let value = std::str::from_utf8(&header.value).unwrap();
assert!(value.contains("HttpOnly") && value.contains("Secure"));
let value = value.split(';').next().unwrap();
let verify = async |_: &Claims| {
Ok(Identity {
id: "u".into(),
user_id: Some(7),
tenant_id: None,
})
};
assert!(request("GET", &[("cookie", value)]).is_err());
let read = request("GET", &[("host", "example.test"), ("cookie", value)]).unwrap();
assert!(
request::authenticate(&provider, Some(&cookie), &read, "admin", false, 101, verify)
.await
.unwrap()
.is_some()
);
for headers in [
vec![("host", "example.test"), ("cookie", value)],
vec![
("cookie", value),
("host", "example.test"),
("origin", "https://evil.test"),
],
vec![
("cookie", value),
("host", "example.test:garbage"),
("origin", "https://example.test"),
],
vec![
("cookie", value),
("host", "example.test"),
("origin", "https://example.test"),
("origin", "https://example.test"),
],
vec![
("host", "example.test"),
("cookie", value),
("authorization", "Bearer explicit"),
],
vec![
("host", "example.test"),
("cookie", value),
("cookie", value),
],
] {
// 畸形 Host 可以在协议入口拒绝;有效头构成的拒绝用例继续进入原认证逻辑。
let input = match request("POST", &headers) {
Ok(input) => input,
Err(error) => {
assert!(
headers.contains(&("host", "example.test:garbage")),
"{error}"
);
continue;
}
};
assert!(
request::authenticate(
&provider,
Some(&cookie),
&input,
"admin",
false,
101,
async |_| -> Result<Identity, Error> {
panic!("invalid request reached project verifier")
}
)
.await
.is_err()
);
}
let write = request(
"POST",
&[
("cookie", value),
("host", "EXAMPLE.test:443"),
("origin", "https://example.test"),
],
)
.unwrap();
assert!(
request::authenticate(
&provider,
Some(&cookie),
&write,
"admin",
false,
101,
verify
)
.await
.unwrap()
.is_some()
);
// public 不利用浏览器自动携带的 Cookie 建立身份,显式 Bearer 仍必须验证。
assert!(
request::authenticate(
&provider,
Some(&cookie),
&read,
"admin",
true,
101,
async |_| -> Result<Identity, Error> {
panic!("public cookie cannot authenticate")
}
)
.await
.unwrap()
.is_none()
);
let invalid = request(
"GET",
&[
("host", "example.test"),
("authorization", "Bearer invalid"),
],
)
.unwrap();
assert!(
request::authenticate(
&provider,
Some(&cookie),
&invalid,
"admin",
true,
101,
verify
)
.await
.is_err()
);
assert!(
std::str::from_utf8(&cookie.clear().value)
.unwrap()
.contains("Max-Age=0")
);
})
.unwrap();
for value in [
"https://example.test#fragment",
"https://example.test:bad",
"https://example.test:0",
"https://user@example.test",
"https://example.test/path",
] {
assert!(Origin::parse(value).is_err(), "{value}");
}
Origin::parse("http://[::1]:8080")
.unwrap()
.check(
&request(
"POST",
&[("origin", "http://[::1]:8080"), ("host", "[::1]:8080")],
)
.unwrap()
.head,
)
.unwrap();
}
+61
View File
@@ -0,0 +1,61 @@
use super::*;
use auth::{Access, tenant::Directory};
use dever_runtime::database::Kind;
use std::time::Duration;
const ARTICLE: Sql = Sql::same("CREATE TABLE article(id INTEGER PRIMARY KEY,title TEXT NOT NULL)");
static MODELS: [(&str, Sql); 1] = [("article", ARTICLE)];
#[test]
fn tenant_selection_never_falls_back_and_does_not_evict_active_leases() {
let control_file = File::new("tenant-control");
let directory = control_file.0.with_extension("tenants");
std::fs::create_dir(&directory).unwrap();
let first = File(directory.join("1.sqlite"));
let second = File(directory.join("2.sqlite"));
task::run(true, 16,async |scope| {
let control=Database::sqlite(&control_file.0,true,options(), None).await?;
control.acquire().await?.schema(scope,"_dever_tenant_database",auth::tenant::CATALOG).await?;
control.acquire().await?.execute(scope,Sql::same("INSERT INTO _dever_tenant_database VALUES (1,'ready','v1'),(2,'ready','v1'),(3,'ready','v1')"), vec![]).await?;
for (file,title) in [(&first,"one"),(&second,"two")] {
let database=Database::sqlite(&file.0,true,options(), None).await?;
database.acquire().await?.schema(scope,"article",ARTICLE).await?;
database.acquire().await?.execute(scope,Sql::same("INSERT INTO article VALUES (1,$1)"),vec![Parameter::Text(title.into())]).await?;
}
let config: dever_runtime::database::config::Config = serde_json::from_value(serde_json::json!({
"type":"sqlite","path":control_file.0.file_name().unwrap().to_str().unwrap(),
"tenant_directory":directory.file_name().unwrap().to_str().unwrap(),"cache_size_kib":512
})).unwrap();
let backend = config.tenant_backend(control_file.0.parent().unwrap(), scope, false, &[&config]).await?;
let pools=Directory::new(control.clone(),backend,"v1".into(),&MODELS,(1,Duration::from_secs(60)))?;
let user_one=verified("admin",7,Some(1)).await;
let user_two=verified("admin",7,Some(2)).await;
let selected=pools.select(scope,&user_one).await?;
assert_eq!(selected.database().acquire().await?.query_one(scope, Sql::same("PRAGMA cache_size"), vec![], |row|row.get::<i64>(0)).await?, Some(-512));
let mut context=Context::default();
assert!(matches!(Access::tenant(&user_two,&selected,&mut context),Err(Error::Forbidden)));
assert!(matches!(Access::global(&user_one,&control,&mut context),Err(Error::Forbidden)));
let result=context.on(scope,selected.database()).await?.query(scope,Sql::same("SELECT title FROM article WHERE id=1"),vec![],|row|row.get::<String>(0)).await?;
assert_eq!(result,["one"]);
drop(selected);
// Executor 自己持有池生命周期;调用方释放 Selection 不能让池被误判闲置。
assert!(matches!(pools.select(scope,&user_two).await,Err(Error::Database(error)) if error.kind==Kind::PoolExhausted));
drop(context);
let selected=pools.select(scope,&user_two).await?;
assert_eq!(selected.database().acquire().await?.query(scope,Sql::same("SELECT title FROM article WHERE id=1"),vec![],|row|row.get::<String>(0)).await?,["two"]);
control.acquire().await?.execute(scope,Sql::same("UPDATE _dever_tenant_database SET state='disabled' WHERE id=2"), vec![]).await?;
assert!(matches!(pools.select(scope,&user_two).await,Err(Error::Forbidden)));
drop(selected);
let missing=verified("admin",7,Some(3)).await;
assert!(matches!(pools.select(scope,&missing).await,Err(Error::Database(error)) if error.kind==Kind::Connection));
assert!(!directory.join("3.sqlite").exists());
let database=Database::sqlite(&first.0,false,options(), None).await?;
database.acquire().await?.execute(scope,Sql::same("CREATE INDEX manual_drift ON article(title)"), vec![]).await?;
drop(database);
assert!(matches!(pools.select(scope,&user_one).await,Err(Error::Database(error)) if error.kind==Kind::Migration));
Ok::<_,Error>(())
}).unwrap().unwrap();
drop(first);
drop(second);
std::fs::remove_dir(directory).unwrap();
}
+112
View File
@@ -0,0 +1,112 @@
use dever_runtime::{
value::calendar::{Date, DateTime, Duration, Time},
wire::serde_json,
};
#[test]
fn rfc3339_offsets_normalize_to_utc_at_millisecond_precision() {
assert_eq!(
DateTime::parse("2024-02-29T12:34:56.12+08:00")
.unwrap()
.format()
.unwrap(),
"2024-02-29T04:34:56.120Z"
);
for value in [
"1969-12-31T23:59:59.999Z",
"0000-01-01T00:00:00Z",
"9999-12-31T23:59:59.999Z",
] {
assert_eq!(DateTime::parse(value).unwrap().format().unwrap(), value);
}
for value in [
"2023-02-29T00:00:00Z",
"2024-02-29T00:00:00.1230Z",
"2024-02-29T00:00:00.1234Z",
"2024-12-31T23:59:60Z",
"2024-01-01T00:00:00",
"9999-12-31T23:30:00-01:00",
"0000-01-01T00:00:00+01:00",
] {
assert!(DateTime::parse(value).is_err(), "{value}");
}
}
#[test]
fn date_and_time_spellings_are_strict_and_zero_fractions_normalize() {
assert_eq!(Date::parse("2024-02-29").unwrap().format(), "2024-02-29");
for value in ["2024-2-29", "2023-02-29", "10000-01-01", "2024-01-01 "] {
assert!(Date::parse(value).is_err(), "{value}");
}
assert_eq!(Time::parse("12:34:56.000").unwrap().format(), "12:34:56");
assert_eq!(
Time::parse("12:34:56.001").unwrap().format(),
"12:34:56.001"
);
for value in [
"24:00:00",
"23:60:00",
"23:59:60",
"12:34:56.1",
"12:34:56.12",
"12:34:56.1234",
" 12:34:56",
] {
assert!(Time::parse(value).is_err(), "{value}");
}
}
#[test]
fn arithmetic_keeps_i64_values_and_checks_overflow_separately_from_formatting() {
let epoch = DateTime::parse("1970-01-01T00:00:00Z").unwrap();
assert_eq!(
epoch
.checked_sub(Duration::from_millis(1))
.unwrap()
.format()
.unwrap(),
"1969-12-31T23:59:59.999Z"
);
let maximum = epoch.checked_add(Duration::from_millis(i64::MAX)).unwrap();
let minimum = epoch.checked_add(Duration::from_millis(i64::MIN)).unwrap();
assert!(maximum.format().is_err());
assert!(maximum.checked_add(Duration::from_millis(1)).is_err());
assert!(minimum.checked_sub(Duration::from_millis(1)).is_err());
assert!(maximum.difference(minimum).is_err());
assert_eq!(epoch.difference(epoch).unwrap().millis(), 0);
}
#[test]
fn temporal_values_are_inline() {
assert_eq!(std::mem::size_of::<DateTime>(), 8);
assert_eq!(std::mem::size_of::<Date>(), 8);
assert_eq!(std::mem::size_of::<Time>(), 8);
assert_eq!(std::mem::size_of::<Duration>(), 8);
assert!(!std::mem::needs_drop::<DateTime>());
}
#[test]
fn wire_uses_canonical_strings_and_integer_durations() {
let value: DateTime = serde_json::from_str(r#""2024-02-29T12:34:56.12+08:00""#).unwrap();
assert_eq!(
serde_json::to_string(&value).unwrap(),
r#""2024-02-29T04:34:56.120Z""#
);
let escaped: Date = serde_json::from_str(r#""\u0032024-02-29""#).unwrap();
assert_eq!(serde_json::to_string(&escaped).unwrap(), r#""2024-02-29""#);
let clock: Time = serde_json::from_str(r#""12:34:56.000""#).unwrap();
assert_eq!(serde_json::to_string(&clock).unwrap(), r#""12:34:56""#);
assert!(serde_json::from_str::<DateTime>("0").is_err());
assert!(serde_json::from_str::<Duration>("1.0").is_err());
assert!(serde_json::from_str::<Duration>(r#""1""#).is_err());
let duration: Duration = serde_json::from_str("9223372036854775807").unwrap();
assert_eq!(
serde_json::to_string(&duration).unwrap(),
"9223372036854775807"
);
let far = DateTime::parse("1970-01-01T00:00:00Z")
.unwrap()
.checked_add(duration)
.unwrap();
assert!(serde_json::to_string(&far).is_err());
}
+103
View File
@@ -0,0 +1,103 @@
use dever_runtime::channel::Channel;
use std::{
future::Future,
pin::pin,
sync::Arc,
task::{Context, Poll, Waker},
};
fn pending<T>(value: std::pin::Pin<&mut impl Future<Output = T>>) {
assert!(matches!(
value.poll(&mut Context::from_waker(Waker::noop())),
Poll::Pending
));
}
#[tokio::test]
async fn channel_close_wakes_waiters_and_drains_shared_fifo() {
assert!(Channel::<i64>::new(0).is_err());
assert!(Channel::<i64>::new(65537).is_err());
let channel = Channel::new(1).unwrap();
let alias = channel.clone();
channel.send(7).await.unwrap();
let mut send = pin!(alias.send(8));
pending(send.as_mut());
channel.close();
alias.close();
assert_eq!(send.await.unwrap_err().0, 8);
assert_eq!(alias.receive().await.ok(), Some(7));
assert!(channel.receive().await.is_err());
let empty = Channel::<i64>::new(1).unwrap();
let mut receive = pin!(empty.receive());
pending(receive.as_mut());
empty.close();
assert!(receive.await.is_err());
}
#[tokio::test]
async fn channel_cancelled_send_and_receive_do_not_consume_capacity_or_messages() {
let channel = Channel::new(1).unwrap();
let payload = Arc::new(7);
channel.send(payload.clone()).await.unwrap();
{
let mut send = pin!(channel.send(payload.clone()));
pending(send.as_mut());
assert_eq!(Arc::strong_count(&payload), 3);
}
assert_eq!(Arc::strong_count(&payload), 2);
assert_eq!(*channel.receive().await.unwrap(), 7);
{
let mut receive = pin!(channel.receive());
pending(receive.as_mut());
}
channel.send(payload.clone()).await.unwrap();
assert_eq!(*channel.receive().await.unwrap(), 7);
assert_eq!(Arc::strong_count(&payload), 1);
}
#[tokio::test]
async fn channel_multiple_producers_and_receivers_deliver_each_value_once() {
let channel = Channel::new(3).unwrap();
let mut producers = Vec::new();
for producer in 0..4 {
let channel = channel.clone();
producers.push(tokio::spawn(async move {
for index in 0..1000 {
channel.send(producer * 1000 + index).await.unwrap();
}
}));
}
let mut consumers = Vec::new();
for _ in 0..3 {
let channel = channel.clone();
consumers.push(tokio::spawn(async move {
let mut values = Vec::new();
while let Ok(value) = channel.receive().await {
values.push(value);
}
values
}));
}
for producer in producers {
producer.await.unwrap();
}
channel.close();
let mut values = Vec::new();
for consumer in consumers {
values.extend(consumer.await.unwrap());
}
values.sort_unstable();
assert_eq!(values, (0..4000).collect::<Vec<_>>());
}
#[tokio::test]
async fn channel_drops_buffer_only_after_last_alias() {
let payload = Arc::new(7);
let channel = Channel::new(1).unwrap();
let alias = channel.clone();
channel.send(payload.clone()).await.unwrap();
drop(channel);
assert_eq!(Arc::strong_count(&payload), 2);
drop(alias);
assert_eq!(Arc::strong_count(&payload), 1);
}
+157
View File
@@ -0,0 +1,157 @@
//! 同一 SQLite 版本上的真实 COUNT 成本;只操作已结束负载的临时一致副本。
use deadpool_sqlite::rusqlite::{Connection, OpenFlags};
use std::{fs::OpenOptions, io::Write, path::PathBuf, time::Instant};
#[test]
#[ignore = "requires DEVER_TEST_COUNT_DATABASE and a new DEVER_TEST_COUNT_OUTPUT"]
fn large_model_count_index_cost() {
let source_path = PathBuf::from(std::env::var_os("DEVER_TEST_COUNT_DATABASE").unwrap());
let output = std::env::var_os("DEVER_TEST_COUNT_OUTPUT").unwrap();
let source =
Connection::open_with_flags(&source_path, OpenFlags::SQLITE_OPEN_READ_ONLY).unwrap();
let snapshot = tempfile::NamedTempFile::new().unwrap();
source
.execute("VACUUM INTO ?1", [snapshot.path().to_str().unwrap()])
.unwrap();
let connection = Connection::open(snapshot.path()).unwrap();
let rows: i64 = source
.query_row("SELECT COUNT(*) FROM demo_service", [], |row| row.get(0))
.unwrap();
let version: String = connection
.query_row("SELECT sqlite_version()", [], |row| row.get(0))
.unwrap();
let mut samples = serde_json::Map::new();
for (name, indexed) in [("table", false), ("narrow_index", true)] {
if indexed {
connection
.execute_batch("CREATE INDEX count_probe_id ON demo_service(id)")
.unwrap();
}
let plan = connection
.prepare("EXPLAIN QUERY PLAN SELECT COUNT(*) FROM demo_service")
.unwrap()
.query_map([], |row| row.get::<_, String>(3))
.unwrap()
.collect::<Result<Vec<_>, _>>()
.unwrap();
let mut query = connection
.prepare_cached("SELECT COUNT(*) FROM demo_service")
.unwrap();
let mut seconds = Vec::new();
for repeat in 0..8 {
let begin = Instant::now();
for _ in 0..256 {
assert_eq!(
query.query_row([], |row| row.get::<_, i64>(0)).unwrap(),
rows
);
}
if repeat != 0 {
seconds.push(begin.elapsed().as_secs_f64());
}
}
samples.insert(
name.into(),
serde_json::json!({"plan":plan,"seconds":seconds}),
);
}
drop(connection);
snapshot.close().unwrap();
let report = serde_json::json!({"sqlite_version":version,"source":source_path,"rows":rows,
"contract":"Native SQLite query only, using the application dependency version. One warmup and seven rounds of 256 exact counts on a VACUUM INTO snapshot; original opened read-only. Not an async-resource or four-way performance gate.",
"samples":samples,"source_read_only":true,"temporary_copy_removed":true});
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.open(output)
.unwrap();
serde_json::to_writer_pretty(&mut file, &report).unwrap();
file.write_all(b"\n").unwrap();
println!("{report}");
}
#[test]
#[ignore = "requires DEVER_TEST_CACHE_DIRECTORY, DEVER_TEST_CACHE_KIB and a new DEVER_TEST_CACHE_OUTPUT"]
fn large_model_native_cache_memory() {
let directory = PathBuf::from(std::env::var_os("DEVER_TEST_CACHE_DIRECTORY").unwrap());
let output = std::env::var_os("DEVER_TEST_CACHE_OUTPUT").unwrap();
let kib: i64 = std::env::var("DEVER_TEST_CACHE_KIB")
.unwrap()
.parse()
.unwrap();
assert!(kib > 0);
let rss = || {
std::fs::read_to_string("/proc/self/status")
.unwrap()
.lines()
.find(|line| line.starts_with("VmRSS:"))
.unwrap()
.split_whitespace()
.nth(1)
.unwrap()
.parse::<u64>()
.unwrap()
};
let initial = rss();
let mut paths: Vec<_> = std::fs::read_dir(&directory)
.unwrap()
.map(|entry| entry.unwrap().path())
.filter(|path| {
path.extension()
.is_some_and(|extension| extension == "sqlite")
})
.collect();
paths.sort();
assert!(!paths.is_empty());
let mut connections = Vec::new();
for path in &paths {
for _ in 0..2 {
let connection =
Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_ONLY).unwrap();
// 只调本连接的原生缓存;数据库文件以只读方式打开,不改原始结果。
connection.pragma_update(None, "cache_size", -kib).unwrap();
let actual: i64 = connection
.pragma_query_value(None, "cache_size", |row| row.get(0))
.unwrap();
assert_eq!(actual, -kib);
connections.push(connection);
}
}
let version: String = connections[0]
.query_row("SELECT sqlite_version()", [], |row| row.get(0))
.unwrap();
let mut samples = Vec::new();
for repeat in 0..8 {
let begin = Instant::now();
for connection in &connections {
for _ in 0..4 {
let rows: i64 = connection
.query_row("SELECT COUNT(*) FROM demo_service", [], |row| row.get(0))
.unwrap();
let jobs: i64 = connection
.query_row("SELECT COUNT(*) FROM _dever_job", [], |row| row.get(0))
.unwrap();
assert!(rows > 0 && jobs > 0);
}
}
let seconds = begin.elapsed().as_secs_f64();
if repeat != 0 {
samples.push(serde_json::json!({"seconds":seconds,"rss_kib":rss()}));
}
}
let populated = rss();
for connection in &connections {
connection.execute_batch("PRAGMA shrink_memory").unwrap();
}
let released = rss();
drop(connections);
let report = serde_json::json!({"sqlite_version":version,"directory":directory,"connections":paths.len()*2,"cache_kib_per_connection":kib,"initial_rss_kib":initial,"populated_rss_kib":populated,"after_native_shrink_rss_kib":released,"after_close_rss_kib":rss(),"samples":samples,"source_read_only":true,"contract":"Native SQLite on the stopped real workload files; two read-only connections per physical tenant, four exact model and queue counts each, one warmup and seven rounds. Each cache size runs in a separate test process. Native shrink_memory diagnoses retained page-cache memory; no application, async-resource or four-way performance claim."});
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.open(output)
.unwrap();
serde_json::to_writer_pretty(&mut file, &report).unwrap();
file.write_all(b"\n").unwrap();
println!("{report}");
}
+413
View File
@@ -0,0 +1,413 @@
//! 使用真实临时 SQLite 文件与池验证事务、资源退出和隔离,不复制执行逻辑。
use dever_runtime::{
database::{Context, Database, Error, Kind, Options, Parameter, Sql},
task,
};
use std::{path::PathBuf, time::Duration};
mod postgres;
mod postgres_tenant;
mod schema;
mod stream;
pub(super) struct File(pub(super) PathBuf);
impl File {
pub(super) fn new(name: &str) -> Self {
let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../target/next-database-tests");
std::fs::create_dir_all(&root).unwrap();
let path = root.join(format!("{}-{name}.sqlite", std::process::id()));
assert!(!path.exists(), "test database must be fresh");
Self(path)
}
}
impl Drop for File {
fn drop(&mut self) {
for suffix in ["", "-wal", "-shm"] {
let path = PathBuf::from(format!("{}{suffix}", self.0.display()));
if path.exists() {
std::fs::remove_file(path).unwrap();
}
}
}
}
pub(super) fn options() -> Options {
Options {
max_page_size: 100,
max_connections: 1,
wait_timeout: Duration::from_millis(100),
io_timeout: Duration::from_secs(2),
}
}
const CREATE: Sql = Sql::same(
"CREATE TABLE article(id INTEGER PRIMARY KEY, title TEXT NOT NULL UNIQUE, published BOOLEAN NOT NULL CHECK(published IN (0,1)))",
);
const INSERT: Sql = Sql::same("INSERT INTO article(title,published) VALUES ($1,$2)");
const COUNT: Sql = Sql::same("SELECT COUNT(*) FROM article");
fn values(title: &str) -> Vec<Parameter> {
vec![Parameter::Text(title.into()), Parameter::Bool(false)]
}
#[test]
fn model_text_normalization_trims_unicode_in_place_and_preserves_modes() {
use dever_runtime::value::text::{TextMode, normalize};
for (input, expected) in [
("", ""),
("plain", "plain"),
(" \t\r\n  ", ""),
("  中文 ", "中文"),
("\tleft", "left"),
("right\r\n", "right"),
(" inner space kept ", "inner space kept"),
] {
let input = input.to_owned();
let pointer = input.as_ptr();
let capacity = input.capacity();
let result = normalize(input, TextMode::Trim);
assert_eq!(result, expected);
assert_eq!(result.as_ptr(), pointer);
assert_eq!(result.capacity(), capacity);
}
assert_eq!(normalize(" 原文 ".into(), TextMode::Raw), " 原文 ");
assert_eq!(normalize(" AbCß ".into(), TextMode::Lower), "abcß");
assert_eq!(normalize(" AbCß ".into(), TextMode::Upper), "ABCSS");
}
#[test]
fn sqlite_native_cache_budget_reaches_every_pooled_connection() {
let file = File::new("cache-budget");
let value = serde_json::json!({"type":"sqlite","path":file.0.file_name().unwrap().to_str().unwrap(),"max_connections":2,"cache_size_kib":512});
let config: dever_runtime::database::config::Config =
serde_json::from_value(value.clone()).unwrap();
task::run(false, 16, async |scope| {
let database = config.open(file.0.parent().unwrap(), true).await?;
let mut first = database.acquire().await?;
let mut second = database.acquire().await?;
for executor in [&mut first, &mut second] {
assert_eq!(
executor
.query_one(scope, Sql::same("PRAGMA cache_size"), vec![], |row| row
.get::<i64>(0))
.await?,
Some(-512)
);
}
Ok::<_, Error>(())
})
.unwrap()
.unwrap();
let mut invalid = value.clone();
invalid["cache_size_kib"] = serde_json::json!(0);
assert!(serde_json::from_value::<dever_runtime::database::config::Config>(invalid).is_err());
assert!(serde_json::from_value::<dever_runtime::database::config::Config>(serde_json::json!({
"type":"postgres","url":"postgres://localhost/test","tls":"disabled","cache_size_kib":512
})).is_err());
let excessive = File::new("excessive-cache");
task::execute(false, async {
let error = Database::sqlite(
&excessive.0,
true,
options(),
std::num::NonZeroU32::new(u32::MAX),
)
.await
.err()
.unwrap();
assert_eq!(error.kind, Kind::Pool);
assert!(!excessive.0.exists());
})
.unwrap();
}
#[test]
fn sqlite_path_keeps_unicode_and_uri_delimiters_in_the_filename() {
let file = File::new("中文?mode=ro#part%20");
task::run(false, 16, async |scope| {
assert!(
Database::sqlite(&file.0, false, options(), None)
.await?
.acquire()
.await
.is_err()
);
assert!(!file.0.exists());
let database = Database::sqlite(&file.0, true, options(), None).await?;
let mut executor = database.acquire().await?;
executor.execute(scope, CREATE, vec![]).await?;
executor
.execute(scope, INSERT, values("保存实际文件"))
.await?;
drop(executor);
drop(database);
assert!(file.0.exists());
let database = Database::sqlite(&file.0, false, options(), None).await?;
assert_eq!(
database
.acquire()
.await?
.query_one(scope, COUNT, vec![], |row| row.get::<i64>(0))
.await?,
Some(1),
);
Ok::<_, Error>(())
})
.unwrap()
.unwrap();
}
#[test]
fn single_rows_preserve_absence_decode_failure_and_transaction_rollback() {
let file = File::new("single-row");
task::run(false, 16, async |scope| {
let database = Database::sqlite(&file.0, true, options(), None).await?;
let mut executor = database.acquire().await?;
executor.execute(scope, CREATE, vec![]).await?;
assert_eq!(
executor
.query_one(
scope,
Sql::same("SELECT id FROM article WHERE id=1"),
vec![],
|row| row.get::<i64>(0)
)
.await?,
None
);
let owner = executor.begin(scope).await?;
let inserted = executor
.query_one(
scope,
Sql::same("INSERT INTO article(title,published) VALUES ($1,$2) RETURNING id"),
values("created"),
|row| row.get::<i64>(0),
)
.await?;
assert_eq!(inserted, Some(1));
executor.finish(scope, owner, true).await?;
let owner = executor.begin(scope).await?;
executor.execute(scope, INSERT, values("rollback")).await?;
let error = executor
.query_one(
scope,
Sql::same("SELECT title FROM article WHERE id=1"),
vec![],
|row| row.get::<i64>(0),
)
.await
.unwrap_err();
assert_eq!(error.kind, Kind::InvalidData);
assert!(executor.finish(scope, owner, true).await.is_err());
drop(executor);
assert_eq!(
database
.acquire()
.await?
.query_one(scope, COUNT, vec![], |row| row.get::<i64>(0))
.await?,
Some(1)
);
Ok::<_, Error>(())
})
.unwrap()
.unwrap();
}
#[test]
fn sqlite_parameter_binding_typed_rows_transactions_and_reuse() {
let file = File::new("transactions");
task::run(false, 16, async |scope| {
let database = Database::sqlite(&file.0, true, options(), None).await?;
let mut executor = database.acquire().await?;
executor.execute(scope, CREATE, vec![]).await?;
let owner = executor.begin(scope).await?;
executor
.execute(scope, INSERT, values("中文'; DROP TABLE article;--"))
.await?;
executor.finish(scope, owner, true).await?;
let rows = executor
.query(
scope,
Sql::same("SELECT title,published FROM article"),
vec![],
|row| Ok((row.get::<String>(0)?, row.get::<bool>(1)?)),
)
.await?;
assert_eq!(rows, [("中文'; DROP TABLE article;--".into(), false)]);
let owner = executor.begin(scope).await?;
executor.execute(scope, INSERT, values("rollback")).await?;
executor.finish(scope, owner, false).await?;
assert_eq!(
executor
.query(scope, COUNT, vec![], |row| row.get::<i64>(0))
.await?,
[1]
);
drop(executor);
assert_eq!(
database
.acquire()
.await?
.query(scope, COUNT, vec![], |row| row.get::<i64>(0))
.await?,
[1]
);
Ok::<_, Error>(())
})
.unwrap()
.unwrap();
}
#[test]
fn nested_failure_cannot_be_caught_and_committed_and_drop_rolls_back() {
let file = File::new("nested");
task::run(false, 16, async |scope| {
let database = Database::sqlite(&file.0, true, options(), None).await?;
let mut context = Context::default();
context
.on(scope, &database)
.await?
.execute(scope, CREATE, vec![])
.await?;
let outer = context.enter();
context
.on(scope, &database)
.await?
.execute(scope, INSERT, values("first"))
.await?;
let nested = context.enter();
assert!(!nested);
let error = context
.on(scope, &database)
.await?
.execute(scope, INSERT, values("first"))
.await
.unwrap_err();
assert_eq!(error.kind, Kind::Constraint);
assert!(std::error::Error::source(&error).is_some());
context.finish(scope, nested, false).await?;
assert!(context.finish(scope, outer, true).await.is_err());
assert_eq!(
context
.on(scope, &database)
.await?
.query(scope, COUNT, vec![], |row| row.get::<i64>(0))
.await?,
[0]
);
context.enter();
context
.on(scope, &database)
.await?
.execute(scope, INSERT, values("abandoned"))
.await?;
drop(context);
assert_eq!(
database
.acquire()
.await?
.query(scope, COUNT, vec![], |row| row.get::<i64>(0))
.await?,
[0]
);
Ok::<_, Error>(())
})
.unwrap()
.unwrap();
}
#[test]
fn physical_database_boundary_rejects_cross_database_transactions() {
let one = File::new("tenant-one");
let two = File::new("tenant-two");
task::run(false, 16, async |scope| {
let one = Database::sqlite(&one.0, true, options(), None).await?;
let two = Database::sqlite(&two.0, true, options(), None).await?;
one.acquire().await?.execute(scope, CREATE, vec![]).await?;
two.acquire().await?.execute(scope, CREATE, vec![]).await?;
let mut context = Context::default();
let owner = context.enter();
context
.on(scope, &one)
.await?
.execute(scope, INSERT, values("private"))
.await?;
let error = context.on(scope, &two).await.err().unwrap();
assert!(error.message.contains("physical databases"));
assert!(context.finish(scope, owner, true).await.is_err());
for database in [&one, &two] {
assert_eq!(
database
.acquire()
.await?
.query(scope, COUNT, vec![], |row| row.get::<i64>(0))
.await?,
[0]
);
}
Ok::<_, Error>(())
})
.unwrap()
.unwrap();
}
#[test]
fn existing_database_mode_never_creates_a_missing_tenant_file() {
let file = File::new("missing");
task::execute(false, async {
let error = Database::sqlite(&file.0, false, options(), None)
.await
.unwrap()
.acquire()
.await
.err()
.unwrap();
assert_eq!(error.kind, Kind::Connection);
assert!(!file.0.exists());
})
.unwrap();
}
#[test]
fn sqlite_operation_deadline_rolls_back_before_the_pool_is_reused() {
let file = File::new("sql-deadline");
task::run(false, 16, async |scope| {
let mut settings = options();
settings.io_timeout = Duration::from_millis(100);
let database = Database::sqlite(&file.0, true, settings, None).await?;
database.acquire().await?.execute(scope, CREATE, vec![]).await?;
scope.within(async |boundary| {
let mut executor = database.acquire().await?;
executor.begin(boundary).await?;
executor.execute(boundary, INSERT, values("expired transaction")).await?;
let error = executor.query_one(boundary, Sql::same(
"WITH RECURSIVE n(value) AS (SELECT 1 UNION ALL SELECT value+1 FROM n WHERE value<1000000000) SELECT sum(value) FROM n"
), vec![], |row| row.get::<i64>(0)).await.unwrap_err();
assert_eq!(error.kind, Kind::Timeout);
Ok::<_, Error>(())
}).await?;
let mut executor = database.acquire().await?;
assert_eq!(executor.query_one(scope, COUNT, vec![], |row| row.get::<i64>(0)).await?, Some(0));
executor.execute(scope, INSERT, values("after deadline")).await?;
Ok::<_, Error>(())
}).unwrap().unwrap();
}
#[test]
fn cancelling_sql_waits_for_worker_exit_and_replaces_the_connection() {
let file = File::new("cancel");
task::run(false, 16, async |scope| {
let database = Database::sqlite(&file.0, true, options(), std::num::NonZeroU32::new(512)).await?;
database.acquire().await?.execute(scope, CREATE, vec![]).await?;
scope.within(async |boundary| {
let mut executor = database.acquire().await?;
executor.begin(boundary).await?;
executor.execute(boundary, INSERT, values("cancelled transaction")).await?;
assert_eq!(executor.query_one(boundary, COUNT, vec![], |row| row.get::<i64>(0)).await?, Some(1));
let work = executor.query(boundary, Sql::same("WITH RECURSIVE n(value) AS (SELECT 1 UNION ALL SELECT value+1 FROM n WHERE value<1000000000) SELECT sum(value) FROM n"), vec![], |row| row.get::<i64>(0));
assert!(tokio::time::timeout(Duration::from_millis(30), work).await.is_err());
assert_eq!(executor.execute(boundary, INSERT, values("discarded lease")).await.unwrap_err().kind, Kind::Cancelled);
Ok::<_, Error>(())
}).await?;
let mut executor = database.acquire().await?;
assert_eq!(executor.query_one(scope, Sql::same("PRAGMA cache_size"), vec![], |row| row.get::<i64>(0)).await?, Some(-512));
assert_eq!(executor.query_one(scope, COUNT, vec![], |row| row.get::<i64>(0)).await?, Some(0));
executor.execute(scope, INSERT, values("after cancellation")).await?;
Ok::<_, Error>(())
}).unwrap().unwrap();
}
+196
View File
@@ -0,0 +1,196 @@
//! PostgreSQL 特有行锁、失租和角色状态验收;测试库由外部 runner 独立建立。
use super::*;
use dever_runtime::{auth, job};
#[test]
#[ignore = "requires an isolated PostgreSQL database; run test/postgres.py"]
fn postgres_uuid_columns_keep_values_and_null_contract() {
use dever_runtime::value::uuid::Uuid;
let url = std::env::var("DEVER_TEST_POSTGRES").expect("isolated PostgreSQL test connection");
task::run(true, 16, async |scope| {
let database = Database::postgres(url.parse().unwrap(), None, options()).await?;
let mut executor = database.acquire().await?;
let expected = Uuid::parse("018f040a-785e-7000-8000-000000000001").unwrap();
assert_eq!(
executor
.query_one(
scope,
Sql::same("SELECT $1::uuid"),
vec![Parameter::Uuid(expected.into())],
|row| Ok((row.get::<Uuid>(0)?, row.get::<Option<Uuid>>(0)?)),
)
.await?,
Some((expected, Some(expected)))
);
assert_eq!(
executor
.query_one(scope, Sql::same("SELECT NULL::uuid"), vec![], |row| {
row.get::<Option<Uuid>>(0)
})
.await?,
Some(None)
);
let error = executor
.query_one(scope, Sql::same("SELECT NULL::uuid"), vec![], |row| {
row.get::<Uuid>(0)
})
.await
.unwrap_err();
assert_eq!(error.kind, Kind::InvalidData);
let error = executor
.query_one(scope, Sql::same("SELECT 1"), vec![], |row| {
row.get::<Uuid>(0)
})
.await
.unwrap_err();
assert!(std::error::Error::source(&error).is_some());
Ok::<_, Error>(())
})
.unwrap()
.unwrap();
}
#[test]
#[ignore = "requires an isolated PostgreSQL database; run test/postgres.py"]
fn postgres_row_locks_queue_ownership_and_live_permissions() {
let url = std::env::var("DEVER_TEST_POSTGRES").expect("isolated PostgreSQL test connection");
task::run(true, 32, async |scope| {
let mut settings = options();
settings.max_connections = 4;
settings.io_timeout = Duration::from_secs(10);
let database = Database::postgres(url.parse().unwrap(), None, settings).await?;
database
.acquire()
.await?
.migrate_group(
scope,
auth::schema::CATALOG
.into_iter()
.chain(auth::schema::ROLES)
.chain(job::schema::TABLES)
.map(|(name, sql)| (name, sql, None))
.collect(),
)
.await?;
let mut first = database.acquire().await?;
let mut second = database.acquire().await?;
let execution = job::Execution::System { tenant: None };
let submit = |key| job::Submission {
target: "demo.work.save",
schema: "one",
execution: &execution,
policy: job::Policy {
retries: 3,
timeout_ms: 100,
},
items: job::Item {
key,
payload: None,
at: 0,
},
};
let one = job::enqueue(&mut first, scope, submit("first"), 0).await?;
assert_eq!(
one,
job::enqueue(&mut second, scope, submit("first"), 0).await?
);
let two = job::enqueue(&mut second, scope, submit("second"), 0).await?;
let owner = first.begin(scope).await?;
first
.query(
scope,
Sql::same("SELECT id FROM _dever_job WHERE id=$1 FOR UPDATE"),
vec![Parameter::Text(one.clone().into_text())],
|row| row.get::<String>(0),
)
.await?;
// 第一条持有真实行锁,另一连接领取第二条,不等待第一条释放。
let claim = tokio::time::timeout(
Duration::from_secs(1),
job::claim(&mut second, scope, 0, 1000),
)
.await
.unwrap()?
.unwrap();
assert_eq!(claim.id, two.into_text());
first.finish(scope, owner, true).await?;
let old = job::claim(&mut first, scope, 0, 100).await?.unwrap();
assert_eq!(old.id, one.into_text());
let renewed = job::claim(&mut second, scope, 101, 1000).await?.unwrap();
assert_ne!(old.token, renewed.token);
assert!(
job::complete(&mut first, scope, &old, 102, false)
.await
.is_err()
);
job::complete(&mut second, scope, &renewed, 102, false).await?;
job::complete(&mut second, scope, &claim, 102, false).await?;
let owner = first.begin(scope).await?;
job::enqueue(&mut first, scope, submit("rollback"), 200).await?;
first.finish(scope, owner, false).await?;
assert!(job::claim(&mut second, scope, 200, 1000).await?.is_none());
drop(first);
drop(second);
database
.acquire()
.await?
.execute(
scope,
Sql::same(
"INSERT INTO _dever_permission VALUES ($1,$2,$3,$4,$5,TRUE,'GET','http')",
),
vec![
Parameter::Text("demo.article.admin.read".into()),
Parameter::Text("admin".into()),
Parameter::Text("demo".into()),
Parameter::Text("article".into()),
Parameter::Text("read".into()),
],
)
.await?;
auth::initialize_owner(scope, &database, "admin", 1).await?;
let identity = crate::auth::verified("admin", 2, None).await;
let mut context = Context::default();
let mut access = auth::Access::global(&identity, &database, &mut context)?;
assert!(matches!(
access
.authorize(scope, &database, "demo.article.admin.read")
.await,
Err(auth::Error::Forbidden)
));
access
.save_role(
scope,
&database,
auth::Role {
id: "reader".into(),
name: "Reader".into(),
all_permissions: false,
permissions: vec!["demo.article.admin.read".into()],
},
)
.await?;
access.grant_role(scope, 2, "reader").await?;
access
.authorize(scope, &database, "demo.article.admin.read")
.await?;
assert_eq!(
access.current_permissions(scope, &database).await?,
["demo.article.admin.read"]
);
access.revoke_role(scope, 2, "reader").await?;
assert!(matches!(
access
.authorize(scope, &database, "demo.article.admin.read")
.await,
Err(auth::Error::Forbidden)
));
assert!(matches!(
access.disable_role(scope, "owner").await,
Err(auth::Error::Forbidden)
));
Ok::<_, auth::Error>(())
})
.unwrap()
.unwrap();
}
@@ -0,0 +1,79 @@
use super::*;
use dever_runtime::auth::{
self, Access, Namespace, Role, schema,
tenant::{Backend, Directory},
};
const ARTICLE: Sql = Sql::same("CREATE TABLE article(id BIGINT PRIMARY KEY,title TEXT NOT NULL)");
static MODELS: [(&str, Sql); 5] = [
schema::ROLES[0],
schema::ROLES[1],
schema::ROLES[2],
schema::ROLES[3],
("article", ARTICLE),
];
fn namespace() -> Namespace {
Namespace {
component: "content",
domain: "article",
}
}
#[test]
#[ignore = "requires an isolated PostgreSQL database; run test/postgres.py"]
fn postgres_tenants_and_concurrent_capability_revocation_keep_isolation() {
let url = std::env::var("DEVER_TEST_POSTGRES").expect("isolated PostgreSQL test connection");
task::run(true, 32,async |scope| {
let mut options=options();options.max_connections=4;options.io_timeout=Duration::from_secs(10);
let control=Database::postgres(url.parse().unwrap(),None,options).await?;
control.acquire().await?.migrate_group(scope,schema::CATALOG.into_iter().chain([("_dever_tenant_database",auth::tenant::CATALOG)]).map(|(name,sql)|(name,sql,None)).collect()).await?;
let mut fixture=control.acquire().await?;
fixture.execute(scope,Sql::same("INSERT INTO _dever_tenant_database VALUES (1,'ready','one'),(2,'ready','one'),(3,'ready','one')"),vec![]).await?;
fixture.execute(scope,Sql::same("INSERT INTO _dever_tenant_component VALUES (1,'content',TRUE),(2,'content',TRUE)"),vec![]).await?;
drop(fixture);
let backend=Backend::Postgres {config:Box::new(url.parse().unwrap()),tls:None,prefix:"dever_tenant".into(),options};
let Backend::Postgres {config,..}=&backend else {unreachable!()};
for (name,title) in [("dever_tenant_1","one"),("dever_tenant_2","two")] {
control.acquire().await?.execute(scope,Sql::same(if name=="dever_tenant_1" {"CREATE DATABASE dever_tenant_1"} else {"CREATE DATABASE dever_tenant_2"}),vec![]).await?;
let mut config=config.as_ref().clone();config.dbname(name);
let database=Database::postgres(config,None,options).await?;
database.acquire().await?.migrate_group(scope,MODELS.into_iter().map(|(name,sql)|(name,sql,None)).collect()).await?;
database.acquire().await?.execute(scope,Sql::same("INSERT INTO article VALUES (1,$1)"),vec![Parameter::Text(title.into())]).await?;
}
let directory=Directory::new(control.clone(),backend,"one".into(),&MODELS,(2,Duration::from_secs(60)))?;
let identity=crate::auth::verified("admin",7,Some(1)).await;
let second=crate::auth::verified("admin",7,Some(2)).await;
let selected=directory.select(scope,&identity).await?;
let other=directory.select(scope,&second).await?;
for (selection,title) in [(&selected,"one"),(&other,"two")] {
assert_eq!(selection.database().acquire().await?.query(scope,Sql::same("SELECT title FROM article WHERE id=1"),vec![],|row|row.get::<String>(0)).await?,[title]);
}
let resource=dever_runtime::value::uuid::Uuid::parse("00000000-0000-0000-0000-00000000002a").unwrap();
let mut context=Context::default();
let key=Access::tenant(&identity,&selected,&mut context)?.register_capability(scope,&control,namespace(),resource).await?;
let owner=context.enter();
{
let mut access=Access::tenant(&identity,&selected,&mut context)?;
access.save_role(scope,&control,Role {id:"reader".into(),name:"Reader".into(),all_permissions:false,permissions:vec![key.clone()]}).await?;
access.grant_role(scope,7,"reader").await?;
}
let mut revoke_context=Context::default();
let mut revoke_access=Access::tenant(&identity,&selected,&mut revoke_context)?;
let mut revoke=Box::pin(revoke_access.remove_capability(scope,&control,namespace(),resource));
// 赋权事务仍持有 capability 行锁;撤销必须等到这次真实提交之后再清 grants。
assert!(tokio::time::timeout(Duration::from_millis(30),&mut revoke).await.is_err());
context.finish(scope,owner,true).await?;
revoke.await?;
let mut access=Access::tenant(&identity,&selected,&mut context)?;
access.register_capability(scope,&control,namespace(),resource).await?;
assert!(matches!(access.authorize(scope,&control,&key).await,Err(auth::Error::Forbidden)));
let mut other_context=Context::default();
assert!(matches!(Access::tenant(&second,&other,&mut other_context)?.authorize(scope,&control,&key).await,Err(auth::Error::Forbidden)));
control.acquire().await?.execute(scope,Sql::same("UPDATE _dever_tenant_database SET state='disabled' WHERE id=2"),vec![]).await?;
assert!(matches!(directory.select(scope,&second).await,Err(auth::Error::Forbidden)));
drop(other_context);drop(other);drop(revoke_context);drop(context);drop(selected);
let missing=crate::auth::verified("admin",7,Some(3)).await;
assert!(matches!(directory.select(scope,&missing).await,Err(auth::Error::Database(error)) if error.kind==Kind::Connection));
Ok::<_,auth::Error>(())
}).unwrap().unwrap();
}
+240
View File
@@ -0,0 +1,240 @@
use super::*;
use dever_runtime::database::{Migration, Plan, Statement, scalar::decimal};
use dever_runtime::value::decimal::Decimal;
const FIRST: Sql = Sql::same(
"CREATE TABLE \"article\" (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL);",
);
const SECOND: Sql = Sql::same(
"CREATE TABLE \"article\" (id INTEGER PRIMARY KEY AUTOINCREMENT, heading TEXT NOT NULL, published BOOLEAN NOT NULL DEFAULT FALSE);",
);
static SEED: [Statement; 1] = [Statement {
sql: Sql::same("INSERT INTO article(id,title) VALUES ($1,$2) ON CONFLICT(id) DO NOTHING"),
parameters: || Ok(vec![Parameter::Integer(1), Parameter::Text("seed".into())]),
}];
static INITIAL: Plan = Plan {
create: FIRST,
indexes: Sql::same(""),
postgres_columns: &[],
renames: &[],
migrations: &[],
seeds: &SEED,
seed_revision: "first",
};
static RENAMED: Plan = Plan {
create: SECOND,
indexes: Sql::same(""),
postgres_columns: &[],
renames: &[("heading", "title")],
migrations: &[],
seeds: &[],
seed_revision: "second",
};
#[test]
fn model_schema_rename_and_seeds_preserve_actual_data() {
let file = File::new("schema-rename");
task::run(false, 16, async |scope| {
let database = Database::sqlite(&file.0, true, options(), None).await?;
let mut executor = database.acquire().await?;
executor
.migrate(scope, "article", FIRST, Some(&INITIAL))
.await?;
executor
.execute(
scope,
Sql::same("UPDATE article SET title=$1 WHERE id=1"),
vec![Parameter::Text("edited".into())],
)
.await?;
executor
.migrate(scope, "article", FIRST, Some(&INITIAL))
.await?;
executor
.migrate(scope, "article", SECOND, Some(&RENAMED))
.await?;
executor
.migrate(scope, "article", SECOND, Some(&RENAMED))
.await?;
let records = executor
.query(
scope,
Sql::same("SELECT id,heading,published FROM article"),
vec![],
|row| {
Ok((
row.get::<i64>(0)?,
row.get::<String>(1)?,
row.get::<bool>(2)?,
))
},
)
.await?;
assert_eq!(records, [(1, "edited".into(), false)]);
executor
.execute(
scope,
Sql::same("CREATE INDEX unexpected ON article(heading)"),
vec![],
)
.await?;
assert_eq!(
executor
.migrate(scope, "article", SECOND, Some(&RENAMED))
.await
.unwrap_err()
.kind,
Kind::Migration
);
assert_eq!(
executor
.query(scope, COUNT, vec![], |row| row.get::<i64>(0))
.await?,
[1]
);
Ok::<_, Error>(())
})
.unwrap()
.unwrap();
}
#[test]
fn failed_constraint_migration_rolls_back_structure_and_rows() {
const STRICT: Sql = Sql::same(
"CREATE TABLE \"article\" (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL CHECK(_dever_length(title)<3));",
);
static PLAN: Plan = Plan {
create: STRICT,
indexes: Sql::same(""),
postgres_columns: &[],
renames: &[],
migrations: &[],
seeds: &[],
seed_revision: "strict",
};
let file = File::new("schema-rollback");
task::run(false, 16, async |scope| {
let database = Database::sqlite(&file.0, true, options(), None).await?;
let mut executor = database.acquire().await?;
executor
.migrate(scope, "article", FIRST, Some(&INITIAL))
.await?;
assert_eq!(
executor
.migrate(scope, "article", STRICT, Some(&PLAN))
.await
.unwrap_err()
.kind,
Kind::Constraint
);
executor
.migrate(scope, "article", FIRST, Some(&INITIAL))
.await?;
assert_eq!(
executor
.query(
scope,
Sql::same("SELECT title FROM article"),
vec![],
|row| row.get::<String>(0)
)
.await?,
["seed"]
);
assert_eq!(
executor
.query(scope, Sql::same("PRAGMA foreign_keys"), vec![], |row| row
.get::<i64>(
0
))
.await?,
[1]
);
Ok::<_, Error>(())
})
.unwrap()
.unwrap();
}
#[test]
fn column_removal_requires_explicit_immutable_migration() {
const REMOVED: Sql =
Sql::same("CREATE TABLE \"article\" (id INTEGER PRIMARY KEY AUTOINCREMENT);");
static UNSAFE: Plan = Plan {
create: REMOVED,
indexes: Sql::same(""),
postgres_columns: &[],
renames: &[],
migrations: &[],
seeds: &[],
seed_revision: "removed",
};
static SAFE: Plan = Plan {
migrations: &[Migration {
name: "remove_title",
revision: "one",
drops: &["title"],
before: &[],
after: &[],
}],
..UNSAFE
};
static REWRITTEN: Plan = Plan {
migrations: &[Migration {
name: "remove_title",
revision: "changed",
drops: &["title"],
before: &[],
after: &[],
}],
..UNSAFE
};
let file = File::new("schema-drop");
task::run(false, 16, async |scope| {
let database = Database::sqlite(&file.0, true, options(), None).await?;
let mut executor = database.acquire().await?;
executor
.migrate(scope, "article", FIRST, Some(&INITIAL))
.await?;
assert_eq!(
executor
.migrate(scope, "article", REMOVED, Some(&UNSAFE))
.await
.unwrap_err()
.kind,
Kind::Migration
);
executor
.migrate(scope, "article", REMOVED, Some(&SAFE))
.await?;
assert_eq!(
executor
.migrate(scope, "article", REMOVED, Some(&REWRITTEN))
.await
.unwrap_err()
.kind,
Kind::Migration
);
assert_eq!(
executor
.query(scope, COUNT, vec![], |row| row.get::<i64>(0))
.await?,
[1]
);
Ok::<_, Error>(())
})
.unwrap()
.unwrap();
}
#[test]
fn decimal_storage_keeps_exact_order_and_never_rounds_away_digits() {
let values = ["-99.99", "-1", "0", "0.01", "99.99"].map(|text| Decimal::parse(text).unwrap());
let encoded = values.map(|value| decimal::encode(value, 4, 2).unwrap());
assert!(encoded.windows(2).all(|pair| pair[0] < pair[1]));
for (value, encoded) in values.iter().zip(&encoded) {
assert_eq!(*value, decimal::decode(encoded, 4, 2).unwrap());
}
assert!(decimal::encode(Decimal::parse("0.001").unwrap(), 4, 2).is_err());
assert!(decimal::encode(Decimal::parse("100").unwrap(), 4, 2).is_err());
}
+110
View File
@@ -0,0 +1,110 @@
//! 用 SQLite 的真实提交钩子拒绝提交,验证 RETURNING 后的错误没有被析构吞掉。
use super::*;
use std::{
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
time::Duration,
};
#[test]
fn single_row_reports_a_commit_failure_after_returning_the_row() {
let path =
std::env::temp_dir().join(format!("dever-single-commit-{}.sqlite", std::process::id()));
assert!(!path.exists());
crate::task::run(true, 16, async |scope| {
let database = super::super::Database::sqlite(
&path,
true,
super::super::Options {
max_page_size: 100,
max_connections: 1,
wait_timeout: Duration::from_secs(1),
io_timeout: Duration::from_secs(2),
},
None,
)
.await?;
let mut executor = database.acquire().await?;
executor
.execute(
scope,
Sql::same("CREATE TABLE article(id INTEGER PRIMARY KEY)"),
vec![],
)
.await?;
let called = Arc::new(AtomicBool::new(false));
let observed = called.clone();
match &mut executor.lease {
Lease::Sqlite(lease) => {
lease
.call(scope, move |connection, _| {
connection.commit_hook(Some(move || {
observed.store(true, Ordering::SeqCst);
true
}))?;
Ok(())
})
.await?
}
#[cfg(feature = "postgres")]
Lease::Postgres(_) => unreachable!(),
};
let result = executor
.query_one(
scope,
Sql::same("INSERT INTO article DEFAULT VALUES RETURNING id"),
vec![],
|row| row.get::<i64>(0),
)
.await;
assert!(
called.load(Ordering::SeqCst),
"SQLite must attempt the commit"
);
assert!(
result.is_err(),
"uncommitted write reported success: {result:?}"
);
assert_eq!(result.unwrap_err().kind, Kind::Constraint);
assert_eq!(
executor
.query_one(
scope,
Sql::same("SELECT COUNT(*) FROM article"),
vec![],
|row| row.get::<i64>(0)
)
.await?,
Some(0)
);
Ok::<_, Error>(())
})
.unwrap()
.unwrap();
std::fs::remove_file(path).unwrap();
}
#[cfg(feature = "stored-bytes")]
#[test]
fn deferred_constraint_removes_staged_file_after_publication() {
let dir = tempfile::tempdir().unwrap();
let config: crate::upload::Config =
serde_json::from_value(serde_json::json!({"directory": dir.path()})).unwrap();
crate::task::run(true, 16, async |scope| {
let db = super::super::Database::sqlite(&dir.path().join("test.sqlite"), true, super::super::Options {
max_page_size: 10, max_connections: 1, wait_timeout: Duration::from_secs(2), io_timeout: Duration::from_secs(2)
}, None).await?;
let mut e = db.acquire().await?;
e.execute(scope,Sql::same("CREATE TABLE parent(id INTEGER PRIMARY KEY)"), vec![]).await?;
e.execute(scope,Sql::same("CREATE TABLE child(parent_id INTEGER REFERENCES parent(id) DEFERRABLE INITIALLY DEFERRED)"), vec![]).await?;
e.begin(scope).await?;
e.execute(scope,Sql::same("INSERT INTO child VALUES (1)"),vec![]).await?;
let key = e.files.stage(&config, Some(3), crate::Bytes::from_static(b"attachment")).unwrap();
assert_eq!(e.finish(scope, true, true).await.unwrap_err().kind, Kind::Constraint);
let folder = dir.path().join("tenant/3");
assert!(folder.is_dir() && !folder.join(key.to_string()).exists());
Ok::<_, Error>(())
}).unwrap().unwrap();
}
+121
View File
@@ -0,0 +1,121 @@
use super::*;
use std::sync::{
Arc,
atomic::{AtomicUsize, Ordering},
};
const ROWS: Sql = Sql::same(
"WITH RECURSIVE items(n) AS (SELECT 1 UNION ALL SELECT n+1 FROM items WHERE n<10000) SELECT n FROM items",
);
#[test]
fn sqlite_stream_has_bounded_read_ahead_and_releases_its_only_connection() {
let file = File::new("stream-close");
task::run(false, 16, async |scope| {
let database = Database::sqlite(&file.0, true, options(), None).await?;
let mut context = Context::default();
let count = Arc::new(AtomicUsize::new(0));
let observed = count.clone();
let rows = context
.stream(scope, &database, ROWS, vec![], move |row| {
observed.fetch_add(1, Ordering::SeqCst);
row.get::<i64>(0)
})
.await?;
assert_eq!(rows.next().await?, Some(1));
tokio::time::sleep(Duration::from_millis(10)).await;
assert!(
count.load(Ordering::SeqCst) <= 3,
"query was collected instead of streamed"
);
let alias = rows.clone();
rows.close();
assert_eq!(alias.next().await?, None);
let mut executor = database.acquire().await?;
assert_eq!(
executor
.query(scope, Sql::same("SELECT 7"), vec![], |row| row
.get::<i64>(0))
.await?,
[7]
);
Ok::<_, Error>(())
})
.unwrap()
.unwrap();
}
#[test]
fn sqlite_stream_delivers_decode_error_once_and_rejects_transaction_escape() {
let file = File::new("stream-errors");
task::run(false, 16, async |scope| {
let database = Database::sqlite(&file.0, true, options(), None).await?;
let mut context = Context::default();
let rows = context
.stream(
scope,
&database,
Sql::same("SELECT 1 UNION ALL SELECT 2"),
vec![],
|row| {
let value = row.get::<i64>(0)?;
if value == 2 {
return Err(Error::new(Kind::InvalidData, "invalid row"));
}
Ok(value)
},
)
.await?;
assert_eq!(rows.next().await?, Some(1));
let error = rows.next().await.unwrap_err();
assert_eq!(error.kind, Kind::InvalidData);
assert_eq!(error.message, "invalid row");
assert_eq!(rows.next().await?, None);
let owner = context.enter();
assert_eq!(
context
.stream(scope, &database, ROWS, vec![], |row| row.get::<i64>(0))
.await
.unwrap_err()
.kind,
Kind::Database
);
context.finish(scope, owner, false).await?;
Ok::<_, Error>(())
})
.unwrap()
.unwrap();
}
#[test]
fn cancelling_a_scope_unblocks_a_database_producer_with_a_live_stream_alias() {
let file = File::new("stream-scope");
task::run(false, 16, async |scope| {
let database = Database::sqlite(&file.0, true, options(), None).await?;
let worker = scope.spawn(move |scope| async move {
let rows = Context::default()
.stream(&scope, &database, ROWS, vec![], |row| row.get::<i64>(0))
.await?;
assert_eq!(rows.next().await?, Some(1));
tokio::time::sleep(Duration::from_millis(10)).await;
Ok::<_, Error>(rows)
})?;
let rows = tokio::time::timeout(Duration::from_secs(1), worker)
.await
.unwrap()??;
loop {
match rows.next().await {
Ok(Some(_)) => {}
Err(error) => {
assert_eq!(error.kind, Kind::Cancelled);
break;
}
Ok(None) => panic!("cancellation was hidden as successful EOF"),
}
}
assert_eq!(rows.next().await?, None);
Ok::<_, Error>(())
})
.unwrap()
.unwrap();
}
+101
View File
@@ -0,0 +1,101 @@
//! UUID 列使用真实 SQLite 行;性能探针只比较列解码,不代表完整 Model 成本。
use super::*;
use crate::value::uuid::Uuid;
use rusqlite::{Connection, params, types::Value};
use std::{hint::black_box, time::Instant};
#[test]
fn uuid_columns_preserve_bytes_null_and_driver_errors() {
let connection = Connection::open_in_memory().unwrap();
let bytes = *uuid::Uuid::parse_str("018f040a-785e-7000-8000-000000000001")
.unwrap()
.as_bytes();
let expected = Uuid::from(uuid::Uuid::from_bytes(bytes));
let mut statement = connection.prepare("SELECT ?1").unwrap();
for value in [
Value::Blob(bytes.to_vec()),
Value::Null,
Value::Blob(vec![]),
Value::Blob(bytes[..15].to_vec()),
Value::Blob(vec![0; 17]),
Value::Text(expected.to_string()),
Value::Integer(1),
] {
let (required, optional) = statement
.query_row(params![value], |raw| {
let row = Row::Sqlite(raw);
Ok((row.get::<Uuid>(0), row.get::<Option<Uuid>>(0)))
})
.unwrap();
match value {
Value::Blob(ref value) if value.as_slice() == bytes => {
assert_eq!(required.unwrap(), expected);
assert_eq!(optional.unwrap(), Some(expected));
}
Value::Null => {
assert_eq!(required.unwrap_err().kind, super::super::Kind::InvalidData);
assert_eq!(optional.unwrap(), None);
}
_ => {
for error in [required.unwrap_err(), optional.unwrap_err()] {
assert_eq!(error.kind, super::super::Kind::InvalidData);
assert!(std::error::Error::source(&error).is_some());
}
}
}
}
}
#[test]
#[ignore = "bounded UUID column comparison; run explicitly with --release --nocapture"]
fn uuid_column_cost() {
let mut connection = Connection::open_in_memory().unwrap();
connection
.execute_batch("CREATE TABLE sample(id INTEGER PRIMARY KEY,value BLOB)")
.unwrap();
let transaction = connection.transaction().unwrap();
{
let mut insert = transaction
.prepare("INSERT INTO sample VALUES (?1,?2)")
.unwrap();
for index in 0..65536 {
let value = uuid::Uuid::from_u128(index as u128);
insert.execute(params![index, value.as_bytes()]).unwrap();
}
}
transaction.commit().unwrap();
let mut statement = connection
.prepare("SELECT value FROM sample WHERE id < ?1 ORDER BY id")
.unwrap();
let mut samples = Vec::new();
for size in [1, 32, 1024, 65536] {
for repeat in -1..7 {
for offset in 0..2 {
let native = (repeat + 1 + offset) % 2 == 0;
let start = Instant::now();
let mut rows = statement.query([size]).unwrap();
let mut values = Vec::with_capacity(size as usize);
while let Some(row) = rows.next().unwrap() {
let value = if native {
// 独立对照只调用驱动与 uuid,不经过 Dever 的 Row/ColumnValue。
uuid::Uuid::from_bytes(row.get::<_, [u8; 16]>(0).unwrap())
} else {
Row::Sqlite(row).get::<Uuid>(0).unwrap().into()
};
values.push(value);
}
let elapsed_ns = start.elapsed().as_nanos();
assert_eq!(values.len(), size as usize);
for (index, value) in values.iter().enumerate() {
assert_eq!(value.as_u128(), index as u128);
}
black_box(&values);
samples.push(serde_json::json!({
"implementation":if native {"native"} else {"dever"},
"size":size,"repeat":repeat,"elapsed_ns":elapsed_ns,"checked":true
}));
}
}
}
println!("UUID_COLUMN {}", serde_json::to_string(&samples).unwrap());
}
+57
View File
@@ -0,0 +1,57 @@
use dever_runtime::io::File;
fn fixture(name: &str) -> std::path::PathBuf {
let path = std::env::temp_dir().join(format!("dever-stream-{}-{name}", std::process::id()));
let mut output = std::fs::OpenOptions::new()
.create_new(true)
.write(true)
.open(&path)
.unwrap();
std::io::Write::write_all(&mut output, b"abc123").unwrap();
path
}
#[test]
fn file_streams_are_lazy_share_one_cursor_and_preserve_external_files() {
let path = fixture("cursor");
let file = File::open(path.to_str().unwrap()).unwrap();
let stream = file.chunks(2, std::convert::identity).unwrap();
let alias = stream.clone();
assert_eq!(file.read(1).unwrap().unwrap().as_ref(), b"a");
assert_eq!(stream.next().unwrap().unwrap().as_ref(), b"bc");
assert_eq!(alias.next().unwrap().unwrap().as_ref(), b"12");
stream.close();
assert!(alias.next().is_none());
assert_eq!(file.read(1).unwrap().unwrap().as_ref(), b"3");
file.close().unwrap();
std::fs::remove_file(path).unwrap();
}
#[test]
fn file_stream_failure_is_delivered_once_and_guards_close_every_alias() {
let path = fixture("failure");
let file = File::open(path.to_str().unwrap()).unwrap();
assert!(file.chunks(0, std::convert::identity).is_err());
let stream = file.chunks(2, std::convert::identity).unwrap();
file.close().unwrap();
assert!(file.chunks(2, std::convert::identity).is_err());
assert_eq!(
stream.next().unwrap().unwrap_err().kind(),
std::io::ErrorKind::BrokenPipe
);
assert!(stream.next().is_none());
let file = File::open(path.to_str().unwrap()).unwrap();
let stream = file.chunks(2, std::convert::identity).unwrap();
let alias = stream.clone();
let fault = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let _close = stream.close_on_drop();
assert!(stream.next().unwrap().is_ok());
std::panic::panic_any(42u32);
}))
.unwrap_err();
assert_eq!(fault.downcast_ref::<u32>(), Some(&42));
assert!(alias.next().is_none());
assert_eq!(file.read(4).unwrap().unwrap().as_ref(), b"c123");
file.close().unwrap();
std::fs::remove_file(path).unwrap();
}
+138
View File
@@ -0,0 +1,138 @@
//! 在同一 SQLite 版本和真实历史快照上对照队列索引;原始负载数据只读。
use crate::{
database::{Database, Error, Options},
job, task,
};
use deadpool_sqlite::rusqlite::{Connection, OpenFlags};
use std::{
fs::OpenOptions,
io::Write,
path::PathBuf,
time::{Duration, Instant},
};
const ORIGINAL: &str = "CREATE INDEX _dever_job_ready ON _dever_job(state,available_at,id); CREATE INDEX _dever_job_lease ON _dever_job(state,lease_until);";
#[test]
#[ignore = "requires DEVER_TEST_JOB_DATABASE and a new DEVER_TEST_JOB_OUTPUT"]
fn completed_history_index_cost() {
let path = PathBuf::from(std::env::var_os("DEVER_TEST_JOB_DATABASE").unwrap());
let output = std::env::var_os("DEVER_TEST_JOB_OUTPUT").unwrap();
let source = Connection::open_with_flags(&path, OpenFlags::SQLITE_OPEN_READ_ONLY).unwrap();
let version: String = source
.query_row("SELECT sqlite_version()", [], |row| row.get(0))
.unwrap();
// 候选索引取自正式 DDL,不能在探针中另维护一份看起来相同的实现。
let schema = Connection::open_in_memory().unwrap();
schema.execute_batch(super::SQL.sqlite).unwrap();
let current = schema.prepare("SELECT sql FROM sqlite_master WHERE name IN ('_dever_job_ready','_dever_job_lease') ORDER BY name").unwrap()
.query_map([], |row| row.get::<_, String>(0)).unwrap().collect::<Result<Vec<_>, _>>().unwrap().join(";");
let mut samples = serde_json::Map::new();
for (name, indexes) in [("original", ORIGINAL), ("active", current.as_str())] {
let snapshot = tempfile::NamedTempFile::new().unwrap();
source
.execute("VACUUM INTO ?1", [snapshot.path().to_str().unwrap()])
.unwrap();
let connection = Connection::open(snapshot.path()).unwrap();
connection
.execute_batch("DROP INDEX _dever_job_ready; DROP INDEX _dever_job_lease;")
.unwrap();
connection.execute_batch(indexes).unwrap();
let queries = [
"SELECT id FROM _dever_job WHERE state='running' AND lease_until <= ?1 ORDER BY lease_until,id LIMIT 256",
"SELECT id,available_at FROM _dever_job WHERE state='pending' AND attempt < retries AND available_at <= ?1 UNION ALL SELECT id,available_at FROM _dever_job WHERE state='running' AND attempt < retries AND lease_until <= ?1 AND available_at <= ?1 ORDER BY available_at,id LIMIT 1",
];
let plans = queries.map(|sql| {
connection
.prepare(&format!("EXPLAIN QUERY PLAN {sql}"))
.unwrap()
.query_map([i64::MAX / 2], |row| row.get::<_, String>(3))
.unwrap()
.collect::<Result<Vec<_>, _>>()
.unwrap()
});
if name == "active" {
assert!(
plans[0]
.iter()
.any(|plan| plan.contains("COVERING INDEX _dever_job_lease"))
);
assert!(plans[0].iter().all(|plan| !plan.contains("TEMP B-TREE")));
assert!(
plans[1]
.iter()
.any(|plan| plan.contains("INDEX _dever_job_ready"))
);
}
let sizes: Vec<(String, i64)> = connection.prepare("SELECT name,sum(pgsize) FROM dbstat WHERE name IN ('_dever_job_ready','_dever_job_lease') GROUP BY name").unwrap()
.query_map([], |row| Ok((row.get(0)?,row.get(1)?))).unwrap().collect::<Result<_, _>>().unwrap();
drop(connection);
let seconds = task::run(false, 8, async |scope| {
let database = Database::sqlite(
snapshot.path(),
false,
Options {
max_page_size: 100,
max_connections: 2,
wait_timeout: Duration::from_secs(5),
io_timeout: Duration::from_secs(30),
},
None,
)
.await?;
let mut executor = database.acquire().await?;
let execution = job::Execution::System { tenant: None };
for index in 0..2048 {
job::enqueue(
&mut executor,
scope,
job::Submission {
target: "probe.save",
schema: "probe",
execution: &execution,
policy: job::Policy {
retries: 1,
timeout_ms: 1000,
},
items: job::Item {
key: format!("probe/{index}").as_str(),
payload: None,
at: 0,
},
},
0,
)
.await?;
}
let mut seconds = Vec::new();
for repeat in 0..8 {
let begin = Instant::now();
for _ in 0..256 {
let now = job::worker::now()?;
let claim = job::claim(&mut executor, scope, now, 10000).await?.unwrap();
job::complete(&mut executor, scope, &claim, now, false).await?;
}
if repeat != 0 {
seconds.push(begin.elapsed().as_secs_f64());
}
}
Ok::<_, Error>(seconds)
})
.unwrap()
.unwrap();
snapshot.close().unwrap();
samples.insert(
name.into(),
serde_json::json!({"plans":plans,"index_bytes":sizes,"seconds":seconds}),
);
}
let report = serde_json::json!({"sqlite_version":version,"source":path,"samples":samples,"source_read_only":true,"temporary_copies_removed":true,"contract":"Same real queue snapshot, application SQLite and job::claim/complete. Each variant seeds 2048 extra jobs through enqueue; one warmup and seven rounds of 256 claims/completions. No handler or independent Rust/Go comparison; index-cost diagnostic only."});
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.open(output)
.unwrap();
serde_json::to_writer_pretty(&mut file, &report).unwrap();
file.write_all(b"\n").unwrap();
println!("{report}");
}
+148
View File
@@ -0,0 +1,148 @@
use super::*;
use dever_runtime::{
auth::{self, Claims, Identity, Provider},
job::Failure,
value::secret::Secret,
};
#[test]
fn persisted_identity_rejects_malformed_duplicate_and_oversized_input_without_leaking_it() {
let file = File::new("job-identity-input");
task::run(true, 32, async |scope| {
let database = prepare(scope, &file).await;
let mut executor = database.acquire().await?;
job::enqueue(&mut executor, scope, submission("identity", 0), 0).await?;
let mut claim =
std::sync::Arc::try_unwrap(job::claim(&mut executor, scope, 0, 10000).await?.unwrap())
.unwrap();
assert!(
claim
.revalidate(None, async |_, _| panic!("System does not verify a user"))
.await
.is_ok()
);
let secret = "identity-value-must-not-leak";
let inputs = [
format!(r#"{{"kind":"System","tenant":"{secret}"}}"#),
r#"{"kind":"System","tenant":null,"tenant":1}"#.into(),
format!(r#"{{"kind":"System","tenant":null,"extra":"{secret}"}}"#),
r#"{"kind":"System","kind":"User"}"#.into(),
r#"{"kind":"System","tenant":null} {}"#.into(),
format!(
r#"{{"kind":"System","tenant":null,"extra":"{}"}}"#,
"x".repeat(dever_runtime::wire::MAX_BYTES)
),
];
for input in inputs {
claim.execution = input;
let Err(error) = claim
.revalidate(None, async |_, _| {
panic!("invalid identity must not invoke a Provider")
})
.await
else {
panic!("invalid persisted identity was accepted");
};
assert!(matches!(error, Failure::Blocked(_)));
assert!(!error.to_string().contains(secret));
}
Ok::<_, Error>(())
})
.unwrap()
.unwrap();
}
#[test]
fn queued_user_is_verified_again_and_tenant_changes_are_blocked() {
let file = File::new("job-identity");
task::run(true, 32, async |scope| {
let database = prepare(scope, &file).await;
let provider =
Provider::new("accounts".into(), Secret::from_input(vec![42; 32]), 60).unwrap();
let claims = Claims {
subject: "u".into(),
session: "s".into(),
tenant: Some("tenant".into()),
site: "admin".into(),
};
let token = provider.issue(&claims, 100).unwrap();
let user = auth::authenticate(&provider, &token, "admin", 101, async |_| {
Ok(Identity {
id: "u".into(),
user_id: Some(7),
tenant_id: Some(1),
})
})
.await
.unwrap();
let execution = Execution::user(&user, "content.article.admin.publish".into());
let mut input = submission("verify", 0);
input.execution = &execution;
let mut executor = database.acquire().await?;
job::enqueue(&mut executor, scope, input, 0).await?;
let mut claim =
std::sync::Arc::try_unwrap(job::claim(&mut executor, scope, 0, 10000).await?.unwrap())
.unwrap();
assert_eq!(
serde_json::from_str::<serde_json::Value>(&claim.execution).unwrap(),
serde_json::json!({
"kind":"User", "provider":"accounts", "subject":"u", "session":"s",
"site":"admin", "tenant":"tenant", "tenant_id":1,
"permission":"content.article.admin.publish"
})
);
let (verified, permission) = claim
.revalidate(Some(1), async |provider, claims| {
assert_eq!(provider, "accounts");
assert_eq!(claims.session, "s");
Ok(Identity {
id: "u".into(),
user_id: Some(7),
tenant_id: Some(1),
})
})
.await
.unwrap();
assert_eq!(verified.unwrap().user(), Some(7));
assert_eq!(permission.as_deref(), Some("content.article.admin.publish"));
assert!(matches!(
claim
.revalidate(Some(1), async |_, _| Err(auth::Error::Unauthorized))
.await,
Err(Failure::Blocked(_))
));
assert!(matches!(
claim
.revalidate(Some(1), async |_, _| Ok(Identity {
id: "u".into(),
user_id: Some(7),
tenant_id: Some(2)
}))
.await,
Err(Failure::Blocked(_))
));
assert!(matches!(
claim
.revalidate(Some(2), async |_, _| panic!(
"wrong physical tenant cannot invoke verifier"
))
.await,
Err(Failure::Blocked(_))
));
let prefix = claim.execution.strip_suffix('}').unwrap().to_owned();
for extra in [r#","extra":true}"#, r#","subject":"other"}"#] {
claim.execution = format!("{prefix}{extra}");
assert!(matches!(
claim
.revalidate(Some(1), async |_, _| panic!(
"invalid user record must not invoke a Provider"
))
.await,
Err(Failure::Blocked(_))
));
}
Ok::<_, Error>(())
})
.unwrap()
.unwrap();
}
+263
View File
@@ -0,0 +1,263 @@
//! 队列验收直接使用真实 SQLite,不用内存队列或复制实现来替代。
use super::database::{File, options};
use dever_runtime::{
database::{Database, Error, Parameter, Sql},
job::{self, Config, Execution, Item, Policy, Submission},
task,
};
mod identity;
mod worker;
const POLICY: Policy = Policy {
retries: 3,
timeout_ms: 500,
};
const SYSTEM: Execution = Execution::System { tenant: None };
#[test]
fn retry_delay_follows_declared_backoff_and_caps_large_attempts() {
let config = Config {
retry_base_ms: 3,
retry_max_ms: 50,
..Config::default()
};
for (attempt, expected) in [
(1, 3),
(2, 6),
(5, 48),
(6, 50),
(63, 50),
(64, 50),
(100, 50),
] {
assert_eq!(config.delay(attempt), expected, "attempt {attempt}");
}
}
async fn prepare(scope: &task::Scope, file: &File) -> Database {
let mut settings = options();
settings.max_connections = 4;
let database = Database::sqlite(&file.0, true, settings, None)
.await
.unwrap();
database
.acquire()
.await
.unwrap()
.migrate_group(
scope,
job::schema::TABLES
.into_iter()
.map(|(table, sql)| (table, sql, None))
.collect(),
)
.await
.unwrap();
database
}
fn submission(key: &str, at: i64) -> Submission<'_, Item<&str>> {
Submission {
target: "content.article.publish",
schema: "v1",
execution: &SYSTEM,
policy: POLICY,
items: Item {
key,
payload: None,
at,
},
}
}
async fn state(database: &Database, scope: &task::Scope) -> Vec<(String, i64)> {
database
.acquire()
.await
.unwrap()
.query(
scope,
Sql::same("SELECT state,attempt FROM _dever_job ORDER BY created_at,id"),
vec![],
|row| Ok((row.get(0)?, row.get(1)?)),
)
.await
.unwrap()
}
#[test]
fn enqueue_is_transactional_and_active_keys_are_idempotent() {
let file = File::new("job-enqueue");
task::run(true, 32, async |scope| {
let database = prepare(scope, &file).await;
let mut executor = database.acquire().await?;
let owner = executor.begin(scope).await?;
job::enqueue(&mut executor, scope, submission("rollback", 0), 0).await?;
executor.finish(scope, owner, false).await?;
assert!(state(&database, scope).await.is_empty());
let payload = r#"{"label":"中文 \"text\"","values":[1,2,3]}"#;
let mut input = submission("same", 1000);
input.items.payload =
Some(dever_runtime::wire::json::Json::from_text(payload.into()).unwrap());
let one = job::enqueue(&mut executor, scope, input, 0).await?;
let two = job::enqueue(&mut executor, scope, submission("same", 2000), 0).await?;
assert_eq!(one, two);
assert!(job::claim(&mut executor, scope, 0, 10000).await?.is_none());
let claim = job::claim(&mut executor, scope, 1000, 10000)
.await?
.unwrap();
assert_eq!(claim.payload, payload);
job::complete(&mut executor, scope, &claim, 1001, false).await?;
let next = job::enqueue(&mut executor, scope, submission("same", 1002), 1002).await?;
assert_ne!(one, next);
Ok::<_, Error>(())
})
.unwrap()
.unwrap();
}
#[test]
fn expired_claim_cannot_acknowledge_a_new_owner_and_retry_limit_is_enforced() {
let file = File::new("job-lease");
task::run(true, 32, async |scope| {
let database = prepare(scope, &file).await;
let mut executor = database.acquire().await?;
job::enqueue(&mut executor, scope, submission("lease", 0), 0).await?;
let first = job::claim(&mut executor, scope, 0, 100).await?.unwrap();
let second = job::claim(&mut executor, scope, first.lease_until + 1, 1000)
.await?
.unwrap();
assert_ne!(first.token, second.token);
assert_eq!(second.attempt, 2);
let owner = executor.begin(scope).await?;
job::enqueue(
&mut executor,
scope,
submission("rollback-on-lost-lease", 0),
0,
)
.await?;
assert!(
job::complete(&mut executor, scope, &first, first.lease_until + 1, owner)
.await
.is_err()
);
assert_eq!(
state(&database, scope).await,
[("running".into(), second.attempt)]
);
let config = Config {
retry_base_ms: 10,
retry_max_ms: 100,
..Config::default()
};
job::fail(
&mut executor,
scope,
&second,
first.lease_until + 2,
&config,
"attempt failed",
)
.await?;
let third = job::claim(&mut executor, scope, second.lease_until + 1000, 10000)
.await?
.unwrap();
assert_eq!(third.attempt, 3);
job::fail(
&mut executor,
scope,
&third,
second.lease_until + 1001,
&config,
"attempt failed again",
)
.await?;
assert_eq!(state(&database, scope).await, [("dead".into(), 3)]);
Ok::<_, Error>(())
})
.unwrap()
.unwrap();
}
#[test]
fn claim_orders_pending_and_expired_jobs_beyond_the_recovery_batch() {
let file = File::new("job-claim-order");
task::run(true, 32, async |scope| {
let database = prepare(scope, &file).await;
let mut executor = database.acquire().await?;
let owner = executor.begin(scope).await?;
for index in 0..258 {
job::enqueue(&mut executor, scope, submission(&index.to_string(), 0), 0).await?;
}
// 前 256 项占满恢复批次;更早到期的最后两项仍须参与领取,并按 id 打破平局。
for sql in [
"UPDATE _dever_job SET state='running',attempt=1,lease_until=1,token='expired',available_at=20",
"UPDATE _dever_job SET lease_until=2,available_at=-20 WHERE task_key IN ('256','257')",
] {
executor.execute(scope, Sql::same(sql), vec![]).await?;
}
let expected = executor.query(scope, Sql::same(
"SELECT id FROM _dever_job WHERE task_key IN ('256','257') ORDER BY id"
), vec![], |row| row.get::<String>(0)).await?;
job::enqueue(&mut executor, scope, submission("pending", -10), 0).await?;
job::enqueue(&mut executor, scope, submission("future", 2000000), 0).await?;
job::enqueue(&mut executor, scope, submission("exhausted", -30), 0).await?;
executor.execute(scope, Sql::same(
"UPDATE _dever_job SET state='running',attempt=retries,lease_until=2,token='expired' WHERE task_key='exhausted'"
), vec![]).await?;
executor.finish(scope, owner, true).await?;
for id in expected {
let claim = job::claim(&mut executor, scope, 1000000, 10000).await?.unwrap();
assert_eq!(claim.id, id);
assert_eq!(claim.attempt, 2);
job::complete(&mut executor, scope, &claim, 1000001, false).await?;
}
let claim = job::claim(&mut executor, scope, 1000000, 10000).await?.unwrap();
assert_eq!(claim.attempt, 1);
let key = executor.query_one(scope, Sql::same(
"SELECT task_key FROM _dever_job WHERE id=?1"
), vec![Parameter::Text(claim.id.clone())], |row| row.get::<String>(0)).await?;
assert_eq!(key.as_deref(), Some("pending"));
Ok::<_, Error>(())
}).unwrap().unwrap();
}
#[test]
fn schedules_deduplicate_occurrences_and_reject_implicit_cron_changes() {
let file = File::new("job-schedule");
task::run(true, 32, async |scope| {
let database = prepare(scope, &file).await;
let mut executor = database.acquire().await?;
let schedule = job::Schedule::new("content.article.publish", "v1", "* * * * *", POLICY)?;
assert_eq!(
job::tick(&mut executor, scope, &schedule, None, 60000).await?,
1
);
assert_eq!(
job::tick(&mut executor, scope, &schedule, None, 60000).await?,
0
);
assert_eq!(
job::tick(&mut executor, scope, &schedule, None, 60000 * 300).await?,
256
);
assert_eq!(
job::tick(&mut executor, scope, &schedule, None, 60000 * 300).await?,
43
);
assert_eq!(state(&database, scope).await.len(), 300);
let changed = job::Schedule::new("content.article.publish", "v1", "*/2 * * * *", POLICY)?;
assert!(
job::tick(&mut executor, scope, &changed, None, 60000 * 301)
.await
.is_err()
);
for pattern in [
"0 0 0 * * *",
"@daily",
"0 0 * * MON",
"0 0 * * 7",
"*/0 * * * *",
] {
assert!(
job::Schedule::new("target", "v1", pattern, POLICY).is_err(),
"{pattern}"
);
}
Ok::<_, Error>(())
})
.unwrap()
.unwrap();
}
+589
View File
@@ -0,0 +1,589 @@
use super::*;
use dever_runtime::job::{Entry, Failure};
use std::{
sync::{
Arc,
atomic::{AtomicUsize, Ordering},
},
time::Duration,
};
static ENTRIES: [Entry; 1] = [Entry {
target: "content.article.publish",
schema: "v1",
policy: POLICY,
long: false,
}];
#[test]
#[ignore = "requires an isolated PostgreSQL database; run test/postgres.py"]
fn postgres_worker_rejects_success_returned_after_the_handler_deadline() {
static ENTRY: [Entry; 1] = [Entry {
target: "content.article.publish",
schema: "v1",
policy: Policy {
retries: 1,
timeout_ms: 100,
},
long: false,
}];
let url = std::env::var("DEVER_TEST_POSTGRES").expect("isolated PostgreSQL test connection");
task::run(true, 32, async |scope| {
let mut settings = options();
settings.max_connections = 4;
settings.wait_timeout = Duration::from_secs(2);
let database = Database::postgres(url.parse().unwrap(), None, settings).await?;
let mut executor = database.acquire().await?;
executor
.migrate_group(
scope,
job::schema::TABLES
.into_iter()
.map(|(name, sql)| (name, sql, None))
.collect(),
)
.await?;
executor
.execute(
scope,
Sql::same("CREATE TABLE effects(value BIGINT)"),
vec![],
)
.await?;
let mut input = submission("late-success", 0);
input.policy = ENTRY[0].policy;
job::enqueue(&mut executor, scope, input, 0).await?;
drop(executor);
let worker = job::start(
scope,
database.clone(),
None,
config(),
&ENTRY,
vec![],
|_, mut executor, scope| async move {
executor
.execute(&scope, Sql::same("INSERT INTO effects VALUES (1)"), vec![])
.await
.map_err(Failure::handler)?;
// 模拟一次不让出调度的业务计算:返回时结果和截止计时器同时就绪。
std::thread::sleep(Duration::from_millis(200));
Ok(executor)
},
)?;
let final_state = tokio::time::timeout(Duration::from_secs(5), async {
loop {
let rows = state(&database, scope).await;
if rows
.iter()
.any(|(state, _)| state == "completed" || state == "dead")
{
break rows;
}
task::sleep(2).await.unwrap();
}
})
.await
.unwrap();
worker.stop(1000).await?;
assert_eq!(final_state, [("dead".into(), 1)]);
let mut executor = database.acquire().await?;
assert_eq!(
executor
.query_one(
scope,
Sql::same("SELECT COUNT(*) FROM effects"),
vec![],
|row| row.get::<i64>(0)
)
.await?,
Some(0)
);
let cause = executor
.query_one(
scope,
Sql::same("SELECT error FROM _dever_job"),
vec![],
|row| row.get::<String>(0),
)
.await?
.unwrap();
assert!(cause.contains("handler deadline expired"), "{cause}");
Ok::<_, Error>(())
})
.unwrap()
.unwrap();
}
#[test]
#[ignore = "requires an isolated PostgreSQL database; run test/postgres.py"]
fn postgres_worker_resumes_after_disconnect_while_claiming() {
let url = std::env::var("DEVER_TEST_POSTGRES").expect("isolated PostgreSQL test connection");
task::run(true, 32, async |scope| {
let mut options = options();
options.max_connections = 4;
let admin = Database::postgres(url.parse().unwrap(), None, options).await?;
let database = Database::postgres(
format!("{url} application_name=dever_worker_disconnect")
.parse()
.unwrap(),
None,
options,
)
.await?;
let mut gate = admin.acquire().await?;
gate.migrate_group(
scope,
job::schema::TABLES
.into_iter()
.map(|(name, sql)| (name, sql, None))
.collect(),
)
.await?;
let owner = gate.begin(scope).await?;
gate.execute(
scope,
Sql::same("LOCK TABLE _dever_job IN ACCESS EXCLUSIVE MODE"),
vec![],
)
.await?;
let worker = job::start(
scope,
database,
None,
config(),
&ENTRIES,
vec![],
|_, executor, _| async move { Ok(executor) },
)?;
let mut observer = admin.acquire().await?;
tokio::time::timeout(Duration::from_secs(5), async {
loop {
let killed = observer
.query_one(
scope,
Sql::same(
"SELECT pg_terminate_backend(pid, 1000) FROM pg_stat_activity
WHERE datname=current_database() AND application_name='dever_worker_disconnect'
AND wait_event_type='Lock'",
),
vec![],
|row| row.get::<bool>(0),
)
.await?;
if killed == Some(true) {
return Ok::<_, Error>(());
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("worker did not reach a blocked claim")?;
gate.finish(scope, owner, true).await?;
job::enqueue(&mut gate, scope, submission("after-disconnect", 0), 0).await?;
tokio::time::timeout(Duration::from_secs(5), async {
while state(&admin, scope).await != [("completed".into(), 1)] {
tokio::time::sleep(Duration::from_millis(10)).await;
}
Ok::<_, Error>(())
})
.await
.expect("worker did not resume after disconnect")?;
worker.stop(1000).await
})
.unwrap()
.unwrap();
}
fn config() -> Config {
Config {
workers: 1,
shutdown_ms: 30000,
poll_ms: 1,
lease_ms: 10000,
retry_base_ms: 1,
retry_max_ms: 5,
}
}
#[test]
fn tenant_worker_checks_the_next_queue_before_waiting() {
use dever_runtime::auth::tenant::{Schema, Settings, Storage};
static SCHEMAS: [Schema; 1] = [Schema {
all: &[],
all_plans: &[],
global: &[],
global_plans: &[],
tenant: &job::schema::TABLES,
tenant_plans: &[None; job::schema::TABLES.len()],
}];
let root = tempfile::tempdir().unwrap();
let database = serde_json::from_value(serde_json::json!({
"type":"sqlite","path":"control.sqlite","tenant_directory":"tenants","max_connections":2
}))
.unwrap();
let tenants = Settings {
database: "default".into(),
max_pools: 1,
idle_timeout_ms: 1000,
};
task::run(true, 16, async |scope| {
let storage = Storage::open(
scope,
root.path(),
&[("default", &database)],
&SCHEMAS,
Some(&tenants),
false,
true,
)
.await?;
storage.migrate_tenant(scope, 1).await?;
storage.migrate_tenant(scope, 2).await?;
let selected = storage.select_id(scope, 2).await.unwrap();
let mut input = submission("second-only", 0);
input.execution = &Execution::System { tenant: Some(2) };
job::enqueue(&mut selected.model(0)?.acquire().await?, scope, input, 0).await?;
drop(selected);
let done = Arc::new(tokio::sync::Notify::new());
let completed = done.clone();
let worker = job::start_tenants(
scope,
storage.clone(),
0,
Config {
poll_ms: 10_000,
..config()
},
&ENTRIES,
vec![],
move |claim, executor, _| {
let completed = completed.clone();
async move {
assert_eq!(claim.execution_tenant, 2);
completed.notify_one();
Ok(executor)
}
},
)?;
tokio::time::timeout(Duration::from_secs(4), done.notified())
.await
.expect("the first tenant is empty; the second must be checked before waiting");
worker.stop(1000).await?;
let selected = storage.select_id(scope, 2).await.unwrap();
assert_eq!(
state(selected.model(0)?, scope).await,
[("completed".into(), 1)]
);
Ok::<_, Error>(())
})
.unwrap()
.unwrap();
}
#[test]
fn worker_commits_success_rolls_back_failure_and_rechecks_declarations() {
let file = File::new("job-worker");
let other = File::new("job-worker-other");
task::run(true, 64, async |scope| {
let database = prepare(scope, &file).await;
let other = prepare(scope, &other).await;
database
.acquire()
.await?
.execute(
scope,
Sql::same("CREATE TABLE effects(id TEXT PRIMARY KEY)"),
vec![],
)
.await?;
for key in [
"success",
"failure",
"blocked",
"panic",
"literal-panic",
"wrong-database",
] {
job::enqueue(&mut database.acquire().await?, scope, submission(key, 0), 0).await?;
}
database
.acquire()
.await?
.execute(
scope,
Sql::same("UPDATE _dever_job SET schema='old' WHERE task_key='blocked'"),
vec![],
)
.await?;
let calls = Arc::new(AtomicUsize::new(0));
let called = calls.clone();
let worker = job::start(
scope,
database.clone(),
None,
config(),
&ENTRIES,
vec![],
move |claim, mut executor, scope| {
let calls = called.clone();
let other = other.clone();
async move {
calls.fetch_add(1, Ordering::SeqCst);
let keys = executor
.query(
&scope,
Sql::same("SELECT task_key FROM _dever_job WHERE id=$1"),
vec![Parameter::Text(claim.id.clone())],
|row| row.get::<String>(0),
)
.await
.map_err(Failure::handler)?;
executor
.execute(
&scope,
Sql::same("INSERT INTO effects VALUES ($1)"),
vec![Parameter::Text(claim.id.clone())],
)
.await
.map_err(Failure::handler)?;
if keys[0] == "failure" {
return Err(Failure::handler("actual business failure"));
}
if keys[0] == "wrong-database" {
// 业务写入仍在原事务中;错误归属必须阻止确认并回滚该写入。
drop(executor);
return other.acquire().await.map_err(Failure::handler);
}
if keys[0] == "literal-panic" {
panic!("actual literal handler fault");
}
assert_ne!(keys[0], "panic", "actual handler fault");
Ok(executor)
}
},
)?;
tokio::time::timeout(Duration::from_secs(5), async {
loop {
let rows = state(&database, scope).await;
if rows
.iter()
.all(|(state, _)| matches!(state.as_str(), "completed" | "dead" | "blocked"))
{
break;
}
task::sleep(2).await.unwrap();
}
})
.await
.unwrap();
worker.stop(1000).await?;
assert_eq!(calls.load(Ordering::SeqCst), 11);
let counts = database
.acquire()
.await?
.query(
scope,
Sql::same("SELECT COUNT(*) FROM effects"),
vec![],
|row| row.get::<i64>(0),
)
.await?;
assert_eq!(counts, [1]);
let mut states = state(&database, scope).await;
states.sort();
assert_eq!(
states,
[
("blocked".into(), 1),
("blocked".into(), 1),
("completed".into(), 1),
("dead".into(), 3),
("dead".into(), 3),
("dead".into(), 3)
]
);
let causes = database
.acquire()
.await?
.query(
scope,
Sql::same("SELECT task_key,error FROM _dever_job WHERE task_key<>'success' ORDER BY task_key"),
vec![],
|row| Ok((row.get::<String>(0)?, row.get::<String>(1)?)),
)
.await?;
for ((key, cause), (expected, message)) in causes.iter().zip([
("blocked", "queued Job no longer matches"),
("failure", "actual business failure"),
("literal-panic", "actual literal handler fault"),
("panic", "actual handler fault"),
("wrong-database", "handler returned a different database"),
]) {
assert_eq!(key, expected);
assert!(cause.contains(message), "{cause}");
}
Ok::<_, Error>(())
})
.unwrap()
.unwrap();
}
#[test]
fn shutdown_cancels_and_joins_a_running_handler_before_returning() {
let file = File::new("job-stop");
task::run(true, 32, async |scope| {
let database = prepare(scope, &file).await;
job::enqueue(
&mut database.acquire().await?,
scope,
submission("stop", 0),
0,
)
.await?;
let entered = Arc::new(tokio::sync::Notify::new());
let signal = entered.clone();
let active = Arc::new(AtomicUsize::new(0));
let used = active.clone();
struct Guard(Arc<AtomicUsize>);
impl Drop for Guard {
fn drop(&mut self) {
self.0.fetch_sub(1, Ordering::SeqCst);
}
}
let worker = job::start(
scope,
database.clone(),
None,
config(),
&ENTRIES,
vec![],
move |_, executor, scope| {
let (signal, used) = (signal.clone(), used.clone());
async move {
used.fetch_add(1, Ordering::SeqCst);
let _guard = Guard(used.clone());
let (started, ready) = tokio::sync::oneshot::channel();
let _child = scope
.spawn_blocking(move || {
used.fetch_add(1, Ordering::SeqCst);
let _guard = Guard(used);
started.send(()).unwrap();
std::thread::sleep(Duration::from_millis(60));
})
.unwrap();
ready.await.unwrap();
signal.notify_one();
std::future::pending::<()>().await;
Ok(executor)
}
},
)?;
tokio::time::timeout(Duration::from_secs(2), entered.notified())
.await
.unwrap();
assert!(worker.stop(10).await.is_err());
assert_eq!(active.load(Ordering::SeqCst), 0);
// 未确认的任务仍为 running,下一次租约到期后才可以重领。
assert_eq!(state(&database, scope).await, [("running".into(), 1)]);
Ok::<_, Error>(())
})
.unwrap()
.unwrap();
}
#[test]
fn handler_deadline_drains_blocking_descendants_before_retrying() {
static SHORT: [Entry; 1] = [Entry {
target: "content.article.publish",
schema: "v1",
policy: Policy {
retries: 2,
timeout_ms: 100,
},
long: false,
}];
for completes in [false, true] {
let file = File::new(if completes {
"job-deadline-cleanup"
} else {
"job-deadline-descendants"
});
task::run(true, 32, async |scope| {
let database = prepare(scope, &file).await;
database
.acquire()
.await?
.execute(
scope,
Sql::same("CREATE TABLE effects(value INTEGER)"),
vec![],
)
.await?;
let mut input = submission("timeout", 0);
input.policy = SHORT[0].policy;
job::enqueue(&mut database.acquire().await?, scope, input, 0).await?;
let active = Arc::new(AtomicUsize::new(0));
let calls = Arc::new(AtomicUsize::new(0));
let (used, called) = (active.clone(), calls.clone());
let worker = job::start(
scope,
database.clone(),
None,
config(),
&SHORT,
vec![],
move |_, mut executor, scope| {
let (used, called) = (used.clone(), called.clone());
async move {
// 下一次处理必须发生在前次真实阻塞工作退出之后。
assert_eq!(used.load(Ordering::SeqCst), 0);
called.fetch_add(1, Ordering::SeqCst);
executor
.execute(&scope, Sql::same("INSERT INTO effects VALUES (1)"), vec![])
.await
.map_err(Failure::handler)?;
let (started, ready) = tokio::sync::oneshot::channel();
let _child = scope
.spawn_blocking(move || {
used.fetch_add(1, Ordering::SeqCst);
started.send(()).unwrap();
std::thread::sleep(Duration::from_millis(180));
used.fetch_sub(1, Ordering::SeqCst);
})
.unwrap();
ready.await.unwrap();
if !completes {
std::future::pending::<()>().await;
}
Ok(executor)
}
},
)?;
tokio::time::timeout(Duration::from_secs(3), async {
while state(&database, scope).await != [("dead".into(), 2)] {
task::sleep(2).await.unwrap();
}
})
.await
.unwrap();
worker.stop(1000).await?;
assert_eq!(active.load(Ordering::SeqCst), 0);
assert_eq!(calls.load(Ordering::SeqCst), 2);
assert_eq!(
database
.acquire()
.await?
.query_one(
scope,
Sql::same("SELECT COUNT(*) FROM effects"),
vec![],
|row| row.get::<i64>(0)
)
.await?,
Some(0)
);
Ok::<_, Error>(())
})
.unwrap()
.unwrap();
}
}
+244
View File
@@ -0,0 +1,244 @@
use dever_runtime::{
collection::Map,
wire::{
self,
document::{self, Value},
json::Json,
},
};
#[test]
fn document_keeps_numbers_order_and_postorder_ids() {
let source = r#"{"z":1e9999,"雪":[null,true,"\u96ea",1e+03]}"#;
let (root, nodes) = document::parse(source).unwrap();
assert_eq!(root, 6);
assert_eq!(nodes[0], Value::Number("1e9999".into()));
assert_eq!(nodes[3], Value::String("雪".into()));
assert_eq!(nodes[5], Value::Array(vec![1, 2, 3, 4]));
assert_eq!(
document::stringify(root, &nodes).unwrap(),
r#"{"z":1e9999,"雪":[null,true,"雪",1e+03]}"#
);
for source in [
"null",
"false",
"[]",
"{}",
"-0",
"1e+03",
r#""\u0000\n\t雪""#,
] {
let (root, nodes) = document::parse(source).unwrap();
assert_eq!(
document::parse(&document::stringify(root, &nodes).unwrap()).unwrap(),
(root, nodes)
);
}
}
#[test]
fn invalid_json_reports_errors_without_panicking_on_unicode() {
for source in [
"",
" ",
"[",
"[1,]",
"{}{}",
"01",
"NaN",
"1e",
r#""\uD800""#,
r#"{"x":0,"x":1}"#,
r#"{"雪":0,"\u96ea":1}"#,
"[雪]",
"[\"雪\",雪]",
] {
let error = document::parse(source).unwrap_err();
assert!(
error.position >= 0 && error.position <= source.chars().count() as i64,
"{source}: {error:?}"
);
assert!(Json::from_text(source.into()).is_err(), "{source}");
}
for source in [r#""\雪""#, r#""\u0雪雪""#, "\"雪🙂", "{\"雪🙂"] {
assert!(document::parse(source).is_err());
}
assert_eq!(document::parse("[\"雪\",]").unwrap_err().position, 5);
let duplicate = r#"{"雪":0,"\u96ea":[}"#;
let error = document::parse(duplicate).unwrap_err();
assert_eq!(error.message, "duplicate JSON object key");
assert_eq!(
error.position,
duplicate[..duplicate.rfind(':').unwrap()].chars().count() as i64
);
}
#[test]
fn document_strings_match_serde_for_unicode_and_control_characters() {
let text: String = (0..=u32::from(char::MAX))
.filter_map(char::from_u32)
.collect();
let expected = wire::serde_json::to_string(&text).unwrap();
let nodes = vec![Value::String(text)];
assert_eq!(document::stringify(0, &nodes).unwrap(), expected);
assert_eq!(document::parse(&expected).unwrap().1, nodes);
}
#[test]
fn documents_validate_all_nodes_and_expansion_before_writing() {
for children in [vec![-1], vec![1], vec![2]] {
assert_eq!(
document::stringify(0, &[Value::Array(children)])
.unwrap_err()
.node,
0
);
}
assert!(document::stringify(-1, &[Value::Null]).is_err());
assert!(document::stringify(1, &[Value::Null]).is_err());
for raw in ["", "01", "1 ", " 1", "true", "1e", "[1]"] {
assert_eq!(
document::stringify(0, &[Value::Null, Value::Number(raw.into())])
.unwrap_err()
.node,
1
);
}
let mut nodes = vec![Value::Null];
for index in 0..16 {
nodes.push(Value::Array(vec![index, index]));
}
assert!(
document::stringify(16, &nodes)
.unwrap_err()
.message
.contains("value limit")
);
assert!(document::stringify(0, &[Value::String("x".repeat(wire::MAX_BYTES))]).is_err());
}
#[test]
fn json_limits_accept_boundary_and_reject_next_value() {
for (depth, valid) in [(64, true), (65, false)] {
let text = format!("{}0{}", "[".repeat(depth), "]".repeat(depth));
assert_eq!(Json::from_text(text).is_ok(), valid);
}
for (depth, valid) in [(256, true), (257, false)] {
let text = format!("{}0{}", "[".repeat(depth), "]".repeat(depth));
let parsed = document::parse(&text);
assert_eq!(parsed.is_ok(), valid);
if let Ok((root, nodes)) = parsed {
assert_eq!(document::stringify(root, &nodes).unwrap(), text);
}
}
for (values, valid) in [(wire::MAX_VALUES - 1, true), (wire::MAX_VALUES, false)] {
let text = format!("[{}0]", "0,".repeat(values - 1));
assert_eq!(document::parse(&text).is_ok(), valid);
}
let text = format!("\"{}\"", "x".repeat(wire::MAX_BYTES - 2));
assert!(Json::from_text(text.clone()).is_ok());
assert!(Json::from_text(format!("{text} ")).is_err());
}
#[test]
fn json_response_counts_the_outer_object_in_each_budget() {
let body = wire::json::response_body(|output| output.value("雪\"")).unwrap();
assert_eq!(
serde_json::from_slice::<serde_json::Value>(&body).unwrap(),
serde_json::json!({"code":0,"message":"ok","data":"雪\""})
);
let mut values = vec![0; wire::MAX_VALUES - 4];
assert!(wire::response(&values).is_ok());
values.push(0);
assert!(wire::response(&values).unwrap_err().contains("value limit"));
let mut nested = serde_json::json!(0);
for _ in 1..wire::MAX_DEPTH {
nested = serde_json::json!([nested]);
}
assert!(wire::response(&nested).is_ok());
assert!(
wire::response(&serde_json::json!([nested]))
.unwrap_err()
.contains("nesting")
);
let overhead = br#"{"code":0,"message":"ok","data":""}"#.len();
let maximum = "x".repeat(wire::MAX_BYTES - overhead);
assert_eq!(wire::response(&maximum).unwrap().len(), wire::MAX_BYTES);
assert!(
wire::response(&(maximum + "x"))
.unwrap_err()
.contains("16 MiB")
);
}
#[test]
fn opaque_json_moves_text_and_composes_validated_values() {
let source = String::from(" {\"z\":1e9999,\"雪\":\"白\"} ");
let pointer = source.as_ptr();
let value = Json::from_text(source).unwrap();
assert_eq!(value.as_str().as_ptr(), pointer);
assert_eq!(value.property("z").unwrap().unwrap().as_str(), "1e9999");
assert_eq!(
value.property("雪").unwrap().unwrap().as_text().unwrap(),
"白"
);
assert!(value.property("missing").unwrap().is_none());
assert!(Json::null().property("x").is_err());
let replaced = value
.set_property("雪", &Json::integer(42).unwrap())
.unwrap();
assert_eq!(replaced.as_str(), "{\"z\":1e9999,\"雪\":42}");
assert_eq!(
replaced
.property("雪")
.unwrap()
.unwrap()
.as_integer()
.unwrap(),
42
);
assert!(value.property("z").unwrap().unwrap().as_integer().is_err());
let source = value.into_text();
assert_eq!(source.as_ptr(), pointer);
let mut fields = Map::with_capacity(1);
fields.put("a".into(), Json::boolean(true).unwrap());
let object = Json::object(&fields).unwrap();
assert_eq!(
Json::array(&[object, Json::string("雪").unwrap()])
.unwrap()
.as_str(),
"[{\"a\":true},\"雪\"]"
);
assert_eq!(
Json::from_text("{}".into())
.unwrap()
.set_property("a", &Json::null())
.unwrap()
.as_str(),
"{\"a\":null}"
);
}
#[test]
fn dynamic_wire_counts_all_raw_siblings_once_at_the_input_boundary() {
#[derive(wire::serde::Deserialize)]
#[serde(crate = "wire::serde", deny_unknown_fields)]
struct Pair {
left: Json,
right: Json,
}
let input = r#"{"left":{"n":1e9999},"right":null}"#;
let pair: Pair = wire::decode_dynamic(input, false).unwrap();
assert_eq!(pair.left.as_str(), r#"{"n":1e9999}"#);
assert_eq!(pair.right.as_str(), "null");
let array = format!("[{}0]", "0,".repeat(32767));
let input = format!(r#"{{"left":{array},"right":{array}}}"#);
assert!(
wire::decode_dynamic::<Pair>(&input, false)
.err()
.unwrap()
.contains("value limit")
);
}
+246
View File
@@ -0,0 +1,246 @@
use dever_runtime::{
net::{self, Socket},
task::{self, Scope},
};
#[path = "net/tls.rs"]
mod tls;
use std::{
future::{Future, poll_fn},
io::ErrorKind,
task::Poll,
};
async fn pair(scope: &Scope) -> (Socket, Socket) {
let listener = net::listen("127.0.0.1", 0, scope).await.unwrap();
let client = net::connect_timeout("127.0.0.1", listener.port().unwrap(), 1000)
.await
.unwrap();
let server = listener.accept().await.unwrap();
(client, server)
}
async fn pending(mut future: std::pin::Pin<&mut impl Future>) {
poll_fn(|cx| {
assert!(future.as_mut().poll(cx).is_pending());
Poll::Ready(())
})
.await;
}
async fn waiting<T: Send + 'static>(
future: impl Future<Output = T> + Send + 'static,
) -> tokio::task::JoinHandle<T> {
let (started, ready) = tokio::sync::oneshot::channel();
let task = tokio::spawn(async move {
let mut future = std::pin::pin!(future);
pending(future.as_mut()).await;
started.send(()).unwrap();
future.await
});
ready.await.unwrap();
task
}
#[test]
fn dns_bidirectional_io_and_shared_close() {
task::run(true, 8, async |scope| {
let listener = net::listen("127.0.0.1", 0, scope).await.unwrap();
let client = net::connect("localhost", listener.port().unwrap(), scope)
.await
.unwrap();
let server = listener.accept().await.unwrap();
client.write(b"abc").await.unwrap();
assert_eq!(server.read(2).await.unwrap().unwrap().as_ref(), b"ab");
assert_eq!(server.read(2).await.unwrap().unwrap().as_ref(), b"c");
server.write(b"reply").await.unwrap();
assert_eq!(client.read(5).await.unwrap().unwrap().as_ref(), b"reply");
client.clone().close().unwrap();
assert_eq!(
client.write(b"x").await.unwrap_err().kind(),
ErrorKind::NotConnected
);
assert!(client.read(1).await.is_err());
assert!(client.close().is_err());
assert_eq!(server.read(1).await.unwrap(), None);
listener.close().unwrap();
assert!(listener.port().is_err());
for port in [-1, 65536] {
assert_eq!(
net::listen("127.0.0.1", port, scope)
.await
.unwrap_err()
.kind(),
ErrorKind::InvalidInput
);
}
assert!(net::connect_timeout("localhost", 1, 10).await.is_err());
assert!(net::connect_timeout("127.0.0.1", 1, 0).await.is_err());
assert!(server.read(0).await.is_err());
assert!(server.timeout(-1).is_err());
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
#[test]
fn ready_reads_yield_to_other_tasks() {
task::run(true, 8, async |scope| {
let (client, server) = pair(scope).await;
client.write(&[7; 4096]).await.unwrap();
// 首次读取等到就绪;随后缓冲充足,不能依赖 WouldBlock 让出执行权。
assert_eq!(server.read(1).await.unwrap().unwrap().as_ref(), &[7]);
let observer = tokio::spawn(async {});
for _ in 1..4096 {
assert_eq!(server.read(1).await.unwrap().unwrap().as_ref(), &[7]);
}
assert!(observer.is_finished(), "ready reads starved another task");
observer.await.unwrap();
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
#[test]
fn close_wakes_read_lock_waiters_and_accept() {
task::run(true, 8, async |scope| {
let (client, _server) = pair(scope).await;
let first_socket = client.clone();
let first = waiting(async move { first_socket.read(1).await }).await;
let second_socket = client.clone();
let second = waiting(async move { second_socket.read(1).await }).await;
std::thread::spawn(move || client.close().unwrap())
.join()
.unwrap();
let deadline = std::time::Duration::from_secs(1);
assert_eq!(
tokio::time::timeout(deadline, second)
.await
.unwrap()
.unwrap()
.unwrap_err()
.kind(),
ErrorKind::NotConnected
);
assert_eq!(
tokio::time::timeout(deadline, first)
.await
.unwrap()
.unwrap()
.unwrap_err()
.kind(),
ErrorKind::NotConnected
);
let listener = net::listen("127.0.0.1", 0, scope).await.unwrap();
let first_listener = listener.clone();
let accept = waiting(async move { first_listener.accept().await }).await;
let second_listener = listener.clone();
let queued = waiting(async move { second_listener.accept().await }).await;
std::thread::spawn(move || listener.close().unwrap())
.join()
.unwrap();
assert_eq!(
tokio::time::timeout(deadline, queued)
.await
.unwrap()
.unwrap()
.unwrap_err()
.kind(),
ErrorKind::NotConnected
);
assert_eq!(
tokio::time::timeout(deadline, accept)
.await
.unwrap()
.unwrap()
.unwrap_err()
.kind(),
ErrorKind::NotConnected
);
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
#[test]
fn read_timeout_includes_lock_wait_and_cancel_preserves_future_data() {
task::run(true, 8, async |scope| {
let (client, server) = pair(scope).await;
{
let mut first = std::pin::pin!(client.read(1));
pending(first.as_mut()).await;
client.timeout(10).unwrap();
assert_eq!(
client.read(1).await.unwrap_err().kind(),
ErrorKind::TimedOut
);
}
server.write(b"next").await.unwrap();
assert_eq!(client.read(4).await.unwrap().unwrap().as_ref(), b"next");
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
#[test]
fn cancelling_partial_write_revokes_every_socket_alias() {
task::run(true, 8, async |scope| {
let (client, server) = pair(scope).await;
let bytes = vec![7; 64 * 1024 * 1024];
let queued;
{
let mut write = std::pin::pin!(client.write(&bytes));
tokio::select! {
result = &mut write => panic!("large write completed before peer consumed data: {result:?}"),
received = server.read(1) => assert_eq!(received.unwrap().unwrap().as_ref(), &[7]),
}
let next = client.clone();
queued = waiting(async move { next.write(b"later").await }).await;
}
assert_eq!(tokio::time::timeout(std::time::Duration::from_secs(1), queued).await.unwrap().unwrap().unwrap_err().kind(), ErrorKind::NotConnected);
assert_eq!(client.write(b"later").await.unwrap_err().kind(), ErrorKind::NotConnected);
let mut count = 1;
while let Some(chunk) = server.read(65536).await.unwrap() {
assert!(chunk.iter().all(|byte| *byte == 7));
count += chunk.len();
}
assert!(count > 1 && count < bytes.len());
Ok::<_, ()>(())
}).unwrap().unwrap();
}
#[test]
fn streams_are_lazy_terminal_and_preserve_external_resources() {
task::run(true, 8, async |scope| {
let (client, server) = pair(scope).await;
let chunks = server.chunks(2, |value| value).unwrap();
assert!(server.chunks(0, |value| value).is_err());
client.write(b"abc").await.unwrap();
client.close().unwrap();
let mut bytes = Vec::new();
while let Some(chunk) = chunks.next().await.unwrap() {
bytes.extend_from_slice(&chunk.unwrap());
}
assert_eq!(bytes, b"abc");
assert_eq!(server.read(1).await.unwrap(), None);
let failed = server.chunks(1, |value| value).unwrap();
server.close().unwrap();
assert!(failed.next().await.unwrap().unwrap().is_err());
assert!(failed.next().await.unwrap().is_none());
let listener = net::listen("127.0.0.1", 0, scope).await.unwrap();
let stream = listener.connections(|value| value);
stream.clone().close();
assert!(stream.next().await.unwrap().is_none());
assert!(listener.port().is_ok());
let failed = listener.connections(|value| value);
listener.close().unwrap();
assert!(failed.next().await.unwrap().unwrap().is_err());
assert!(failed.next().await.unwrap().is_none());
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
+444
View File
@@ -0,0 +1,444 @@
use super::*;
use crate::task;
use http_body_util::{BodyExt, Full};
use hyper::service::service_fn;
use std::{
convert::Infallible,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
time::Duration,
};
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::TcpListener,
};
pub(super) fn limits(http2: bool) -> Limits {
Limits {
header_bytes: 8192,
body_bytes: 200_000,
timeout_ms: 1000,
connections: 32,
http2: http2.then_some(Http2Limits {
streams: 16,
stream_window_bytes: 65535,
connection_window_bytes: 262144,
}),
}
}
pub(super) fn request() -> Request {
Request {
method: "POST".into(),
target: "/test?q=1".into(),
headers: vec![Header {
name: "host".into(),
value: Bytes::from_static(b"localhost"),
}],
body: Bytes::from_static(b"hello"),
}
}
#[test]
fn http2_incoming_reuses_authority_without_weakening_host_rules() {
let limits = limits(true).check().unwrap();
for (uri, hosts, valid) in [
("http://localhost/test?q=1", vec![], true),
("http://localhost/test?q=1", vec!["LOCALHOST"], true),
(
"http://localhost/test?q=1",
vec!["localhost", "localhost"],
false,
),
("http://localhost/test?q=1", vec!["other"], false),
("http://user@localhost/test?q=1", vec![], false),
(
"http://user@localhost/test?q=1",
vec!["user@localhost"],
false,
),
("/test?q=1", vec!["localhost"], false),
] {
let mut request = hyper::Request::builder()
.uri(uri)
.version(hyper::Version::HTTP_2);
for host in hosts {
request = request.header("Host", host);
}
let (parts, ()) = request.body(()).unwrap().into_parts();
let result = wire::incoming(parts, &limits);
assert_eq!(result.is_ok(), valid, "{uri}: {:?}", result.as_ref().err());
if let Ok(head) = result {
assert_eq!(head.target.as_str(), "/test?q=1");
#[cfg(feature = "auth")]
assert_eq!(head.authority.as_str(), "localhost");
assert!(
head.headers["host"]
.as_bytes()
.eq_ignore_ascii_case(b"localhost")
);
}
}
}
#[test]
fn http2_library_rejects_connection_headers_and_runtime_rejects_response_te() {
task::execute(true, async {
for (name, value, valid) in [
("x-test", "yes", true),
("connection", "close", false),
("keep-alive", "timeout=5", false),
("te", "trailers", false),
] {
let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
let port = i64::from(listener.local_addr().unwrap().port());
let (done, wait) = tokio::sync::oneshot::channel();
let peer = tokio::spawn(async move {
let (mut stream, _) = listener.accept().await.unwrap();
let mut preface = [0; 24];
stream.read_exact(&mut preface).await.unwrap();
assert_eq!(&preface, b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n");
stream
.write_all(&[0, 0, 0, 4, 0, 0, 0, 0, 0])
.await
.unwrap();
// 读取真实请求后再回复;手写非法帧避免发送库先剔除待测协议头。
loop {
let mut frame = [0; 9];
stream.read_exact(&mut frame).await.unwrap();
let len = u32::from_be_bytes([0, frame[0], frame[1], frame[2]]);
let mut payload = vec![0; len as usize];
stream.read_exact(&mut payload).await.unwrap();
if frame[3] == 1 {
break;
}
}
// HPACK: 索引 :status=200,后接一个不索引的字面量字段。
let mut headers = vec![0x88, 0, name.len() as u8];
headers.extend_from_slice(name.as_bytes());
headers.push(value.len() as u8);
headers.extend_from_slice(value.as_bytes());
let mut reply = vec![0, 0, headers.len() as u8, 1, 5, 0, 0, 0, 1];
reply.extend(headers);
stream.write_all(&reply).await.unwrap();
// 保持连接,不能把对端提前断开造成的失败误当协议校验成功。
wait.await.unwrap();
});
let result = send("127.0.0.1", port, request(), &limits(true)).await;
done.send(()).unwrap();
peer.await.unwrap();
if valid {
assert_eq!(result.unwrap().status, 200);
} else {
let error = result.unwrap_err();
assert_ne!(error.kind(), io::ErrorKind::TimedOut);
if name == "te" {
assert_eq!(error.to_string(), "invalid HTTP/2 connection header");
}
}
}
})
.unwrap();
}
#[test]
fn http_round_trips_both_protocols_and_preserves_headers_and_bytes() {
task::execute(true, async {
for http2 in [false, true] {
let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
let port = listener.local_addr().unwrap().port();
let peer = tokio::spawn(async move {
let (stream, _) = listener.accept().await.unwrap();
let service = service_fn(
|request: hyper::Request<hyper::body::Incoming>| async move {
assert_eq!(request.method(), "POST");
assert_eq!(
request.uri().path_and_query().unwrap().as_str(),
"/test?q=1"
);
let body = request.into_body().collect().await.unwrap().to_bytes();
assert_eq!(body, Bytes::from(vec![42; 100_000]));
let response = hyper::Response::builder()
.status(202)
.header("x-repeat", "one")
.header("x-repeat", "two")
.header("x-binary", &[128u8][..])
.body(Full::new(body))
.unwrap();
Ok::<_, Infallible>(response)
},
);
if http2 {
hyper::server::conn::http2::Builder::new(TokioExecutor::new())
.serve_connection(TokioIo::new(stream), service)
.await
.unwrap();
} else {
hyper::server::conn::http1::Builder::new()
.serve_connection(TokioIo::new(stream), service)
.await
.unwrap();
}
});
let mut input = request();
input.body = Bytes::from(vec![42; 100_000]);
let response = send("127.0.0.1", i64::from(port), input, &limits(http2))
.await
.unwrap();
assert_eq!(response.status, 202);
assert_eq!(response.body, Bytes::from(vec![42; 100_000]));
let repeated: Vec<_> = response
.headers
.iter()
.filter(|h| h.name == "x-repeat")
.map(|h| h.value.as_ref())
.collect();
assert_eq!(repeated, [b"one".as_slice(), b"two".as_slice()]);
assert!(
response
.headers
.iter()
.any(|h| h.name == "x-binary" && h.value.as_ref() == [128])
);
tokio::time::timeout(Duration::from_secs(1), peer)
.await
.unwrap()
.unwrap();
}
})
.unwrap();
}
#[test]
fn http_cancelling_a_pending_call_closes_the_real_connection() {
task::execute(true, async {
for http2 in [false, true] {
let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
let port = i64::from(listener.local_addr().unwrap().port());
let (started, waiting) = tokio::sync::oneshot::channel();
let peer = tokio::spawn(async move {
let (mut stream, _) = listener.accept().await.unwrap();
let mut bytes = [0; 8192];
assert!(stream.read(&mut bytes).await.unwrap() > 0);
started.send(()).unwrap();
let mut remaining = Vec::new();
stream.read_to_end(&mut remaining).await.unwrap();
});
let limits = limits(http2);
let mut call = Box::pin(send("127.0.0.1", port, request(), &limits));
tokio::select! {
result = &mut call => panic!("peer has not responded: {result:?}"),
ready = waiting => ready.unwrap(),
}
drop(call);
tokio::time::timeout(Duration::from_secs(1), peer)
.await
.unwrap()
.unwrap();
}
})
.unwrap();
}
#[test]
fn http_rejects_invalid_requests_and_limits_before_connecting() {
task::execute(true, async {
let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
let port = i64::from(listener.local_addr().unwrap().port());
let base = request();
let mut cases = Vec::new();
for target in [
"/test#fragment",
"http://localhost/test",
"localhost:80",
"*",
] {
cases.push(Request {
target: target.into(),
..base.clone()
});
}
cases.push(Request {
method: "CONNECT".into(),
..base.clone()
});
cases.push(Request {
method: "G ET".into(),
..base.clone()
});
cases.push(Request {
headers: vec![],
..base.clone()
});
let mut repeated = base.clone();
repeated.headers.push(repeated.headers[0].clone());
cases.push(repeated);
for (name, value) in [
("content-length", "5"),
("upgrade", "websocket"),
("x", "a\r\nb"),
("x bad", "a"),
("host", "a@b"),
] {
let mut input = base.clone();
input.headers.push(Header {
name: name.into(),
value: Bytes::copy_from_slice(value.as_bytes()),
});
cases.push(input);
}
for input in cases {
assert!(
send("127.0.0.1", port, input, &limits(false))
.await
.is_err()
);
}
for invalid in [
Limits {
body_bytes: 4,
..limits(false)
},
Limits {
header_bytes: 8191,
..limits(false)
},
Limits {
timeout_ms: 0,
..limits(false)
},
Limits {
connections: 0,
..limits(false)
},
Limits {
body_bytes: -1,
..limits(false)
},
Limits {
http2: Some(Http2Limits {
streams: 65536,
stream_window_bytes: 1,
connection_window_bytes: 65535,
}),
..limits(true)
},
] {
assert!(
send("127.0.0.1", port, base.clone(), &invalid)
.await
.is_err()
);
}
let mut h2 = base.clone();
h2.headers.push(Header {
name: "connection".into(),
value: Bytes::from_static(b"close"),
});
assert!(send("127.0.0.1", port, h2, &limits(true)).await.is_err());
assert!(
send("localhost", port, base.clone(), &limits(false))
.await
.is_err()
);
assert!(send("127.0.0.1", -1, base, &limits(false)).await.is_err());
assert!(
tokio::time::timeout(Duration::from_millis(10), listener.accept())
.await
.is_err()
);
})
.unwrap();
}
#[test]
fn http_truncation_limits_and_timeout_are_failures_and_release_the_connection() {
task::execute(true, async {
for reply in [
b"HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nshort".to_vec(),
b"HTTP/1.1 200 OK\r\nContent-Length: 9\r\n\r\n123456789".to_vec(),
b"HTTP/1.1 205 Reset Content\r\nContent-Length: 1\r\n\r\nx".to_vec(),
format!(
"HTTP/1.1 200 OK\r\nX-Large: {}\r\nContent-Length: 0\r\n\r\n",
"x".repeat(9000)
)
.into_bytes(),
] {
let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
let port = i64::from(listener.local_addr().unwrap().port());
let peer = tokio::spawn(async move {
let (mut stream, _) = listener.accept().await.unwrap();
let mut received = vec![0; 8192];
assert!(stream.read(&mut received).await.unwrap() > 0);
stream.write_all(&reply).await.unwrap();
});
assert!(
send(
"127.0.0.1",
port,
request(),
&Limits {
body_bytes: 8,
..limits(false)
}
)
.await
.is_err()
);
peer.await.unwrap();
}
for http2 in [false, true] {
let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
let port = i64::from(listener.local_addr().unwrap().port());
let released = Arc::new(AtomicBool::new(false));
let flag = released.clone();
let peer = tokio::spawn(async move {
let (stream, _) = listener.accept().await.unwrap();
struct Active(Arc<AtomicBool>);
impl Drop for Active {
fn drop(&mut self) {
self.0.store(true, Ordering::SeqCst);
}
}
let service = service_fn(move |_request| {
let active = Active(flag.clone());
async move {
let _active = active;
std::future::pending::<Result<hyper::Response<Full<Bytes>>, Infallible>>()
.await
}
});
if http2 {
let _ = hyper::server::conn::http2::Builder::new(TokioExecutor::new())
.serve_connection(TokioIo::new(stream), service)
.await;
} else {
let _ = hyper::server::conn::http1::Builder::new()
.serve_connection(TokioIo::new(stream), service)
.await;
}
});
let error = send(
"127.0.0.1",
port,
request(),
&Limits {
timeout_ms: 30,
..limits(http2)
},
)
.await
.unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::TimedOut);
tokio::time::timeout(Duration::from_secs(1), peer)
.await
.unwrap()
.unwrap();
// HTTP/2 的协议任务由 Hyper 派生;真实连接结束后,取消必须传播到路由。
tokio::task::yield_now().await;
assert!(released.load(Ordering::SeqCst));
}
})
.unwrap();
}
+373
View File
@@ -0,0 +1,373 @@
use super::{
tests::{limits, request},
*,
};
use crate::{net, stream::AsyncStream, task, tls};
use std::{sync::Arc, time::Duration};
fn live() -> LiveLimits {
LiveLimits {
chunk_bytes: 128,
idle_ms: 80,
heartbeat_ms: 20,
}
}
#[test]
fn live_preserves_stream_errors_and_sse_heartbeat_on_both_protocols() {
task::run(true, 32, async |scope| {
for http2 in [false, true] {
let listener = net::listen("127.0.0.1", 0, scope).await.unwrap();
let port = listener.port().unwrap();
let active = listener.clone();
let server = scope.spawn(move |child| async move {
serve_live(&child, |request, reply, _| async move {
match request.target.as_str() {
"/panic" => panic!("live original panic"),
"/missing" => return Ok(()),
"/sse" => {
reply.start_sse(vec![]).await.map_err(|e| e.to_string())?;
// SSE 使用心跳,不受普通流 idle 限制。
tokio::time::sleep(Duration::from_millis(160)).await;
reply.send_event(Event { event: "message".into(), data: "one\r\ntwo\rthree\nfour".into(), id: Some("7".into()), retry_ms: Some(500) }).await.map_err(|e| e.to_string())?;
}
target => {
reply.start(200, vec![]).await.map_err(|e| e.to_string())?;
reply.write(Bytes::from_static(b"part")).await.map_err(|e| e.to_string())?;
match target {
"/failure" => return Err("original stream failure".into()),
"/unfinished" => return Ok(()),
"/idle" => std::future::pending::<()>().await,
_ => {},
}
}
}
reply.finish().await.map_err(|e| e.to_string())
}, &active, &limits(http2), &live(), None).await
}).unwrap();
for target in ["/panic", "/missing"] {
let response = send("127.0.0.1", port, Request { target: target.into(), ..request() }, &limits(http2)).await.unwrap();
assert_eq!(response.status, 500);
assert!(response.body.is_empty());
}
for target in ["/failure", "/unfinished", "/idle"] {
let response = send("127.0.0.1", port, Request { target: target.into(), ..request() }, &limits(http2)).await;
assert!(response.is_err(), "{http2} {target}: {response:?}");
}
let response = send("127.0.0.1", port, Request { target: "/sse".into(), ..request() }, &limits(http2)).await.unwrap();
let body = std::str::from_utf8(&response.body).unwrap();
assert!(body.contains(": heartbeat\n\n"));
assert!(body.ends_with("event: message\nid: 7\nretry: 500\ndata: one\ndata: two\ndata: three\ndata: four\n\n"), "{body}");
listener.close().unwrap();
tokio::time::timeout(Duration::from_secs(2), server).await.unwrap().unwrap().unwrap();
}
Ok::<_, ()>(())
}).unwrap().unwrap();
}
#[test]
fn upload_streams_chunks_and_closes_failed_sources() {
task::run(true, 32, async |scope| {
for http2 in [false, true] {
let listener = net::listen("127.0.0.1", 0, scope).await.unwrap();
let port = listener.port().unwrap();
let active = listener.clone();
let server = scope
.spawn(move |child| async move {
serve::<false, _, _>(
&child,
|request, _| async move {
Ok(Response {
status: 200,
headers: vec![],
body: request.body,
})
},
&active,
&limits(http2),
None,
)
.await
})
.unwrap();
let client = client(
&format!("http://127.0.0.1:{port}"),
&tls::system(),
&limits(http2),
&PoolLimits {
idle_ms: 1000,
chunk_bytes: 3,
read_ms: 100,
},
scope,
)
.await
.unwrap();
let source = AsyncStream::values([
Ok(Bytes::new()),
Ok(Bytes::from_static(b"abc")),
Ok(Bytes::from_static(b"def")),
]);
let alias = source.clone();
let response = client
.open_stream(
StreamRequest {
method: "POST".into(),
target: "/upload".into(),
headers: vec![],
body: source,
},
|value| value,
|value| value,
)
.await
.unwrap();
let mut received = Vec::new();
while let Some(value) = response.body.next().await.unwrap() {
received.extend_from_slice(&value.unwrap());
}
assert_eq!(received, b"abcdef");
assert!(alias.next().await.unwrap().is_none());
for error in [false, true] {
let source = AsyncStream::values([if error {
Err(io::Error::other("original upload error"))
} else {
Ok(Bytes::from_static(b"over-limit"))
}]);
let alias = source.clone();
let response = client
.open_stream(
StreamRequest {
method: "POST".into(),
target: "/upload".into(),
headers: vec![],
body: source,
},
|value| value,
|value| value,
)
.await;
assert!(response.is_err(), "{http2}: {response:?}");
assert!(alias.next().await.unwrap().is_none());
}
client.close().await.unwrap();
listener.close().unwrap();
server.await.unwrap().unwrap();
}
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
#[test]
fn upload_early_response_and_disconnection_release_pending_sources() {
use http_body_util::{BodyExt, Full};
use hyper::service::service_fn;
use hyper_util::rt::{TokioExecutor, TokioIo};
use tokio::sync::Notify;
task::run(true, 32, async |scope| {
for http2 in [false, true] {
for disconnect in [false, true] {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let server = tokio::spawn(async move {
let (socket, _) = listener.accept().await.unwrap();
let read = Arc::new(Notify::new());
let received = read.clone();
let service =
service_fn(move |mut request: hyper::Request<hyper::body::Incoming>| {
let received = received.clone();
async move {
assert_eq!(
request
.body_mut()
.frame()
.await
.unwrap()
.unwrap()
.into_data()
.unwrap(),
b"abc"[..]
);
received.notify_one();
Ok::<_, std::convert::Infallible>(hyper::Response::new(Full::new(
Bytes::from_static(b"early"),
)))
}
});
let connection = async {
if http2 {
hyper::server::conn::http2::Builder::new(TokioExecutor::new())
.serve_connection(TokioIo::new(socket), service)
.await
} else {
hyper::server::conn::http1::Builder::new()
.serve_connection(TokioIo::new(socket), service)
.await
}
};
tokio::select! {
result = connection => { let _ = result; }
() = read.notified(), if disconnect => {}
}
});
let client = client(
&format!("http://127.0.0.1:{port}"),
&tls::system(),
&limits(http2),
&PoolLimits {
idle_ms: 1000,
chunk_bytes: 128,
read_ms: 5000,
},
scope,
)
.await
.unwrap();
let (released, release) = tokio::sync::oneshot::channel::<()>();
let source = AsyncStream::new(futures_util::stream::unfold(
(false, released),
|(sent, released)| async move {
if sent {
std::future::pending::<()>().await;
}
Some((
Ok(Ok::<_, io::Error>(Bytes::from_static(b"abc"))),
(true, released),
))
},
));
let alias = source.clone();
let response = client
.open_stream(
StreamRequest {
method: "POST".into(),
target: "/".into(),
headers: vec![],
body: source,
},
|v| v,
|v| v,
)
.await;
if disconnect {
// 对端关闭与已写响应可能同时发生;两条合法路径都必须释放上传源。
if let Ok(response) = response {
while let Some(value) = response.body.next().await.unwrap() {
if value.is_err() {
break;
}
}
}
} else {
let response = response.unwrap();
let mut body = Vec::new();
while let Some(value) = response.body.next().await.unwrap() {
body.extend_from_slice(&value.unwrap());
}
assert_eq!(body, b"early");
}
// sender 析构证明 pending 来源被释放,不能只验证响应返回。
assert!(
tokio::time::timeout(Duration::from_secs(2), release)
.await
.unwrap()
.is_err()
);
assert!(alias.next().await.unwrap().is_none());
let other = client.clone();
let (first, second) = tokio::join!(client.close(), other.close());
assert!(first.is_ok());
assert_eq!(second.unwrap_err().kind(), io::ErrorKind::NotConnected);
tokio::time::timeout(Duration::from_secs(2), server)
.await
.unwrap()
.unwrap();
}
}
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
#[test]
fn live_disconnect_cancels_handler_before_listener_finishes() {
task::run(true, 32, async |scope| {
for http2 in [false, true] {
let listener = net::listen("127.0.0.1", 0, scope).await.unwrap();
let port = listener.port().unwrap();
let active = listener.clone();
let (released, release) = tokio::sync::oneshot::channel::<()>();
let signal = Arc::new(std::sync::Mutex::new(Some(released)));
let server = scope
.spawn(move |child| async move {
serve_live(
&child,
move |_, reply, _| {
let released = signal.lock().unwrap().take().unwrap();
async move {
reply.start(200, vec![]).await.unwrap();
reply.write(Bytes::from_static(b"part")).await.unwrap();
std::future::pending::<()>().await;
drop(released);
Ok(())
}
},
&active,
&limits(http2),
&live(),
None,
)
.await
})
.unwrap();
let client = client(
&format!("http://127.0.0.1:{port}"),
&tls::system(),
&limits(http2),
&PoolLimits {
idle_ms: 1000,
chunk_bytes: 128,
read_ms: 1000,
},
scope,
)
.await
.unwrap();
let response = client
.open(
Request {
headers: vec![],
..request()
},
|v| v,
)
.await
.unwrap();
assert_eq!(
response.body.next().await.unwrap().unwrap().unwrap(),
b"part"[..]
);
response.body.close();
client.close().await.unwrap();
assert!(
tokio::time::timeout(Duration::from_secs(2), release)
.await
.unwrap()
.is_err()
);
listener.close().unwrap();
tokio::time::timeout(Duration::from_secs(2), server)
.await
.unwrap()
.unwrap()
.unwrap();
}
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
+410
View File
@@ -0,0 +1,410 @@
use super::{
tests::{limits, request},
*,
};
use crate::{task, tls};
use http_body_util::BodyExt;
use hyper::service::service_fn;
use std::{convert::Infallible, time::Duration};
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::TcpListener,
};
fn input() -> Request {
Request {
headers: vec![],
..request()
}
}
fn pool() -> PoolLimits {
PoolLimits {
idle_ms: 1000,
chunk_bytes: 65536,
read_ms: 1000,
}
}
#[test]
fn pool_idle_timeout_releases_socket_and_next_call_reconnects() {
task::run(true, 16, async |scope| {
let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
let origin = format!("http://{}", listener.local_addr().unwrap());
let (closed, idle_closed) = tokio::sync::oneshot::channel();
let peer = tokio::spawn(async move {
let mut closed = Some(closed);
for _ in 0..2 {
let (mut stream, _) = listener.accept().await.unwrap();
let mut bytes = [0; 8192];
assert!(stream.read(&mut bytes).await.unwrap() > 0);
stream
.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n")
.await
.unwrap();
stream.read_to_end(&mut Vec::new()).await.unwrap();
if let Some(closed) = closed.take() {
closed.send(()).unwrap();
}
}
});
let client = client(
&origin,
&tls::system(),
&limits(false),
&PoolLimits {
idle_ms: 20,
..pool()
},
scope,
)
.await
.unwrap();
client.request(input()).await.unwrap();
tokio::time::timeout(Duration::from_secs(2), idle_closed)
.await
.unwrap()
.unwrap();
client.request(input()).await.unwrap();
client.close().await.unwrap();
tokio::time::timeout(Duration::from_secs(2), peer)
.await
.unwrap()
.unwrap();
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
#[test]
fn pool_tls_does_not_fall_back_when_the_ca_is_untrusted() {
task::run(true, 16, async |scope| {
let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
let origin = format!(
"https://localhost:{}",
listener.local_addr().unwrap().port()
);
let peer = tokio::spawn(async move {
let (stream, _) = listener.accept().await.unwrap();
let config = tls::server(
include_bytes!("../../../fixtures/tls/server.pem"),
include_bytes!("../../../fixtures/tls/server-key.pem"),
)
.unwrap();
assert!(config.acceptor(false).accept(stream).await.is_err());
});
let client = client(&origin, &tls::system(), &limits(false), &pool(), scope)
.await
.unwrap();
assert!(
client
.request(input())
.await
.unwrap_err()
.to_string()
.contains("UnknownIssuer")
);
client.close().await.unwrap();
tokio::time::timeout(Duration::from_secs(2), peer)
.await
.unwrap()
.unwrap();
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
#[test]
fn pool_bounds_parallel_requests_and_reuses_after_timeout() {
use std::sync::{
Arc,
atomic::{AtomicUsize, Ordering},
};
task::run(true, 32, async |scope| {
for http2 in [false, true] {
let listener = crate::net::listen("127.0.0.1", 0, scope).await.unwrap();
let origin = format!("http://127.0.0.1:{}", listener.port().unwrap());
let listening = listener.clone();
let active = Arc::new(AtomicUsize::new(0));
let peak = Arc::new(AtomicUsize::new(0));
let (count, maximum) = (active.clone(), peak.clone());
let server = scope
.spawn(move |child| async move {
serve::<false, _, _>(
&child,
move |request, _| {
let (active, peak) = (count.clone(), maximum.clone());
async move {
struct Active(Arc<AtomicUsize>);
impl Drop for Active {
fn drop(&mut self) {
self.0.fetch_sub(1, Ordering::SeqCst);
}
}
let current = active.fetch_add(1, Ordering::SeqCst) + 1;
peak.fetch_max(current, Ordering::SeqCst);
let _guard = Active(active);
if request.target == "/wait" {
std::future::pending::<()>().await;
}
tokio::time::sleep(Duration::from_millis(20)).await;
Ok(Response {
status: 200,
headers: vec![],
body: request.body,
})
}
},
&listening,
&limits(http2),
None,
)
.await
})
.unwrap();
let mut options = limits(http2);
options.connections = 1;
if let Some(h2) = &mut options.http2 {
h2.streams = 2;
}
let client = client(&origin, &tls::system(), &options, &pool(), scope)
.await
.unwrap();
let (a, b, c) = tokio::join!(
client.request(input()),
client.request(input()),
client.request(input())
);
for response in [a, b, c] {
assert_eq!(response.unwrap().body, b"hello"[..]);
}
assert_eq!(active.load(Ordering::SeqCst), 0);
assert!(peak.load(Ordering::SeqCst) <= if http2 { 2 } else { 1 });
client.close().await.unwrap();
options.timeout_ms = 50;
let client = super::client(&origin, &tls::system(), &options, &pool(), scope)
.await
.unwrap();
let error = client
.request(Request {
target: "/wait".into(),
..input()
})
.await
.unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::TimedOut);
assert_eq!(client.request(input()).await.unwrap().body, b"hello"[..]);
client.close().await.unwrap();
listener.close().unwrap();
server.await.unwrap().unwrap();
assert_eq!(active.load(Ordering::SeqCst), 0);
}
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
#[test]
fn pool_reuses_one_connection_in_http1_http2_and_verified_tls() {
task::run(true, 32, async |scope| {
for secure in [false, true] {
for http2 in [false, true] {
let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
let port = listener.local_addr().unwrap().port();
let origin = format!(
"{}://localhost:{port}",
if secure { "https" } else { "http" }
);
let peer = tokio::spawn(async move {
// 只接受一条连接:三次调用成功才能证明真实复用。
let (stream, _) = listener.accept().await.unwrap();
let service = service_fn(
move |request: hyper::Request<hyper::body::Incoming>| async move {
assert_eq!(request.headers()["host"], format!("localhost:{port}"));
assert_eq!(
request.uri().path_and_query().unwrap().as_str(),
"/test?q=1"
);
let body = request.into_body().collect().await.unwrap().to_bytes();
Ok::<_, Infallible>(
hyper::Response::builder()
.status(201)
.header("x-repeat", "one")
.header("x-repeat", "two")
.body(http_body_util::Full::new(body))
.unwrap(),
)
},
);
if secure {
let config = tls::server(
include_bytes!("../../../fixtures/tls/server.pem"),
include_bytes!("../../../fixtures/tls/server-key.pem"),
)
.unwrap();
let stream =
TokioIo::new(config.acceptor(http2).accept(stream).await.unwrap());
if http2 {
hyper::server::conn::http2::Builder::new(TokioExecutor::new())
.serve_connection(stream, service)
.await
.unwrap();
} else {
hyper::server::conn::http1::Builder::new()
.serve_connection(stream, service)
.await
.unwrap();
}
} else {
let stream = TokioIo::new(stream);
if http2 {
hyper::server::conn::http2::Builder::new(TokioExecutor::new())
.serve_connection(stream, service)
.await
.unwrap();
} else {
hyper::server::conn::http1::Builder::new()
.serve_connection(stream, service)
.await
.unwrap();
}
}
});
let tls = tls::client(include_bytes!("../../../fixtures/tls/root.pem")).unwrap();
let client = client(&origin, &tls, &limits(http2), &pool(), scope)
.await
.unwrap();
for value in ["first", "第二次", "last"] {
let response = client
.request(Request {
body: Bytes::copy_from_slice(value.as_bytes()),
..input()
})
.await
.unwrap();
assert_eq!(response.status, 201);
assert_eq!(response.body, value.as_bytes());
assert_eq!(
response
.headers
.iter()
.filter(|h| h.name == "x-repeat")
.count(),
2
);
}
client.close().await.unwrap();
assert!(client.close().await.is_err());
assert_eq!(
client.request(input()).await.unwrap_err().kind(),
io::ErrorKind::NotConnected
);
tokio::time::timeout(Duration::from_secs(2), peer)
.await
.unwrap()
.unwrap();
}
}
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
#[test]
fn pool_rejects_origin_host_and_limits_and_obeys_owner_scope() {
task::run(true, 16, async |scope| {
for origin in [
"ftp://localhost",
"http://user@localhost",
"http://localhost/path",
"http://localhost?q=1",
"http://localhost#hidden",
"http://localhost:65536",
"http://localhost:",
] {
assert!(
client(origin, &tls::system(), &limits(false), &pool(), scope)
.await
.is_err(),
"{origin}"
);
}
assert!(
client(
"http://localhost",
&tls::system(),
&limits(false),
&PoolLimits {
idle_ms: 0,
..pool()
},
scope
)
.await
.is_err()
);
let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
let origin = format!("http://{}", listener.local_addr().unwrap());
let client = client(&origin, &tls::system(), &limits(false), &pool(), scope)
.await
.unwrap();
assert!(client.request(request()).await.is_err());
assert!(
tokio::time::timeout(Duration::from_millis(20), listener.accept())
.await
.is_err()
);
client.close().await.unwrap();
let escaped = scope
.within(async |child| {
super::client(&origin, &tls::system(), &limits(false), &pool(), child)
.await
.unwrap()
})
.await;
assert_eq!(
escaped.request(input()).await.unwrap_err().kind(),
io::ErrorKind::NotConnected
);
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
#[test]
fn pool_close_cancels_inflight_and_last_alias_drop_closes_idle_socket() {
task::run(true, 16, async |scope| {
for close_pending in [false, true] {
let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
let origin = format!("http://{}", listener.local_addr().unwrap());
let (started, ready) = tokio::sync::oneshot::channel();
let peer = tokio::spawn(async move {
let (mut stream, _) = listener.accept().await.unwrap();
let mut buffer = [0; 8192];
assert!(stream.read(&mut buffer).await.unwrap() > 0);
if !close_pending { stream.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n").await.unwrap(); }
started.send(()).unwrap();
let mut rest = Vec::new();
stream.read_to_end(&mut rest).await.unwrap();
});
let client = client(&origin, &tls::system(), &limits(false), &pool(), scope).await.unwrap();
if close_pending {
let mut pending = Box::pin(client.request(input()));
tokio::select! { result = &mut pending => panic!("response must wait: {result:?}"), _ = ready => {} }
let alias = client.clone();
alias.close().await.unwrap();
assert_eq!(pending.await.unwrap_err().kind(), io::ErrorKind::NotConnected);
} else {
client.request(input()).await.unwrap();
ready.await.unwrap();
drop(client);
}
tokio::time::timeout(Duration::from_secs(2), peer).await.unwrap().unwrap();
}
Ok::<_, ()>(())
}).unwrap().unwrap();
}
+454
View File
@@ -0,0 +1,454 @@
use super::{
tests::{limits, request},
*,
};
use crate::{net, task, tls};
use std::{
sync::{
Arc,
atomic::{AtomicUsize, Ordering},
},
time::Duration,
};
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::TcpStream,
};
fn echo(request: Request) -> Response {
Response {
status: 202,
headers: vec![Header {
name: "x-test".into(),
value: Bytes::from_static(b"yes"),
}],
body: request.body,
}
}
#[test]
fn server_round_trip_tls_and_plain_both_protocols() {
task::run(true, 32, async |scope| {
for encrypted in [false, true] {
for http2 in [false, true] {
let listener = net::listen("127.0.0.1", 0, scope).await.unwrap();
let port = listener.port().unwrap();
let listening = listener.clone();
let server = scope
.spawn(move |child| async move {
let tls = encrypted.then(|| {
tls::server(
include_bytes!("../../../fixtures/tls/server.pem"),
include_bytes!("../../../fixtures/tls/server-key.pem"),
)
.unwrap()
});
serve::<false, _, _>(
&child,
|request, _| async move { Ok(echo(request)) },
&listening,
&limits(http2),
tls.as_ref(),
)
.await
})
.unwrap();
let response = if encrypted {
let stream = TcpStream::connect(("127.0.0.1", port as u16))
.await
.unwrap();
let client =
tls::client(include_bytes!("../../../fixtures/tls/root.pem")).unwrap();
let stream =
TokioIo::new(client.connect("localhost", stream, http2).await.unwrap());
let input =
wire::request(request(), &limits(http2).check().unwrap(), None).unwrap();
if http2 {
let (mut sender, connection) =
hyper::client::conn::http2::handshake(TokioExecutor::new(), stream)
.await
.unwrap();
drive(connection, async {
receive(
sender.send_request(input).await.unwrap(),
&limits(true).check().unwrap(),
)
.await
})
.await
.unwrap()
} else {
let (mut sender, connection) =
hyper::client::conn::http1::handshake(stream).await.unwrap();
drive(connection, async {
receive(
sender.send_request(input).await.unwrap(),
&limits(false).check().unwrap(),
)
.await
})
.await
.unwrap()
}
} else {
send("127.0.0.1", port, request(), &limits(http2))
.await
.unwrap()
};
assert_eq!(response.status, 202);
assert_eq!(response.body, b"hello"[..]);
assert!(
response
.headers
.iter()
.any(|header| header.name == "x-test" && header.value == b"yes"[..])
);
listener.close().unwrap();
tokio::time::timeout(Duration::from_secs(2), server)
.await
.unwrap()
.unwrap()
.unwrap();
}
}
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
#[test]
fn server_isolates_failures_panics_timeouts_and_invalid_responses() {
task::run(true, 32, async |scope| {
for http2 in [false, true] {
let listener = net::listen("127.0.0.1", 0, scope).await.unwrap();
let port = listener.port().unwrap();
let listening = listener.clone();
let server = scope
.spawn(move |child| async move {
serve::<false, _, _>(
&child,
|request, _| async move {
match request.target.as_str() {
"/fail" => Err("private failure".into()),
"/panic" => panic!("original panic"),
"/timeout" => std::future::pending().await,
"/invalid" => Ok(Response {
status: 700,
..echo(request)
}),
_ => Ok(echo(request)),
}
},
&listening,
&Limits {
timeout_ms: 30,
..limits(http2)
},
None,
)
.await
})
.unwrap();
for (target, status) in [
("/fail", 500),
("/panic", 500),
("/timeout", 504),
("/invalid", 500),
("/ok", 202),
] {
let response = send(
"127.0.0.1",
port,
Request {
target: target.into(),
..request()
},
&limits(http2),
)
.await
.unwrap();
assert_eq!(response.status, status, "{target}");
if status != 202 {
assert!(response.body.is_empty());
}
}
listener.close().unwrap();
server.await.unwrap().unwrap();
}
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
struct Active(Arc<AtomicUsize>);
impl Drop for Active {
fn drop(&mut self) {
self.0.fetch_sub(1, Ordering::SeqCst);
}
}
#[test]
fn server_scheduled_timeout_and_cancellation_drain_descendants() {
task::run(true, 32, async |scope| {
for http2 in [false, true] {
for cancel_server in [false, true] {
let listener = net::listen("127.0.0.1", 0, scope).await.unwrap();
let port = listener.port().unwrap();
let listening = listener.clone();
let active = Arc::new(AtomicUsize::new(0));
let counter = active.clone();
let server = scope
.spawn(move |child| async move {
serve::<true, _, _>(
&child,
move |_, child| {
let active = counter.clone();
async move {
active.fetch_add(1, Ordering::SeqCst);
let guard = Active(active);
let task = child
.spawn_leaf(async move {
let _guard = guard;
std::future::pending::<()>().await;
})
.unwrap();
task.await.unwrap();
unreachable!()
}
},
&listening,
&Limits {
timeout_ms: if cancel_server { 1000 } else { 30 },
..limits(http2)
},
None,
)
.await
})
.unwrap();
let client = tokio::spawn(async move {
send("127.0.0.1", port, request(), &limits(http2)).await
});
tokio::time::timeout(Duration::from_secs(1), async {
while active.load(Ordering::SeqCst) == 0 {
tokio::task::yield_now().await;
}
})
.await
.unwrap();
if cancel_server {
server.stop().await.unwrap();
assert!(client.await.unwrap().is_err());
} else {
assert_eq!(client.await.unwrap().unwrap().status, 504);
assert_eq!(active.load(Ordering::SeqCst), 0);
listener.close().unwrap();
server.await.unwrap().unwrap();
}
assert_eq!(active.load(Ordering::SeqCst), 0);
}
}
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
#[test]
fn server_listener_close_finishes_inflight_and_rejects_new_connections() {
task::run(true, 16, async |scope| {
for http2 in [false, true] {
let listener = net::listen("127.0.0.1", 0, scope).await.unwrap();
let port = listener.port().unwrap();
let listening = listener.clone();
let closing = listener.clone();
let server = scope
.spawn(move |child| async move {
serve::<false, _, _>(
&child,
move |request, _| {
let closing = closing.clone();
async move {
closing.close().unwrap();
tokio::time::sleep(Duration::from_millis(10)).await;
Ok(echo(request))
}
},
&listening,
&limits(http2),
None,
)
.await
})
.unwrap();
assert_eq!(
send("127.0.0.1", port, request(), &limits(http2))
.await
.unwrap()
.body,
b"hello"[..]
);
tokio::time::timeout(Duration::from_secs(1), server)
.await
.unwrap()
.unwrap()
.unwrap();
assert!(
TcpStream::connect(("127.0.0.1", port as u16))
.await
.is_err()
);
}
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
#[test]
fn server_validates_real_request_headers_body_and_deadlines() {
task::run(true, 16, async |scope| {
let listener = net::listen("127.0.0.1", 0, scope).await.unwrap();
let port = listener.port().unwrap();
let listening = listener.clone();
let server = scope
.spawn(move |child| async move {
serve::<false, _, _>(
&child,
|request, _| async move { Ok(echo(request)) },
&listening,
&Limits {
body_bytes: 4,
timeout_ms: 30,
..limits(false)
},
None,
)
.await
})
.unwrap();
for (request, expected) in [
("GET / HTTP/1.1\r\nConnection: close\r\n\r\n", 400),
(
"GET / HTTP/1.1\r\nHost: a\r\nHost: b\r\nConnection: close\r\n\r\n",
400,
),
(
"POST / HTTP/1.1\r\nHost: a\r\nContent-Length: 5\r\nConnection: close\r\n\r\n12345",
413,
),
(
"POST / HTTP/1.1\r\nHost: a\r\nContent-Length: 4\r\nConnection: close\r\n\r\n12",
408,
),
] {
let mut stream = TcpStream::connect(("127.0.0.1", port as u16))
.await
.unwrap();
stream.write_all(request.as_bytes()).await.unwrap();
let mut response = String::new();
tokio::time::timeout(Duration::from_secs(1), stream.read_to_string(&mut response))
.await
.unwrap()
.unwrap();
assert!(
response.starts_with(&format!("HTTP/1.1 {expected}")),
"{response}"
);
}
listener.close().unwrap();
server.await.unwrap().unwrap();
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
#[test]
fn server_task_capacity_is_503_and_connection_limit_applies_before_accept() {
task::run(true, 2, async |scope| {
let listener = net::listen("127.0.0.1", 0, scope).await.unwrap();
let port = listener.port().unwrap();
let active = listener.clone();
let server = scope
.spawn(move |child| async move {
serve::<true, _, _>(
&child,
|_, _| async { panic!("capacity must reject before calling handler") },
&active,
&limits(true),
None,
)
.await
})
.unwrap();
assert_eq!(
send("127.0.0.1", port, request(), &limits(true))
.await
.unwrap()
.status,
503
);
listener.close().unwrap();
server.await.unwrap().unwrap();
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
task::run(true, 16, async |scope| {
let listener = net::listen("127.0.0.1", 0, scope).await.unwrap();
let port = listener.port().unwrap();
let active = listener.clone();
let calls = Arc::new(AtomicUsize::new(0));
let counter = calls.clone();
let gate = Arc::new(tokio::sync::Notify::new());
let release = gate.clone();
let server = scope
.spawn(move |child| async move {
serve::<false, _, _>(
&child,
move |request, _| {
let (counter, gate) = (counter.clone(), gate.clone());
async move {
if counter.fetch_add(1, Ordering::SeqCst) == 0 {
gate.notified().await;
}
Ok(echo(request))
}
},
&active,
&Limits {
connections: 1,
..limits(false)
},
None,
)
.await
})
.unwrap();
let first =
tokio::spawn(async move { send("127.0.0.1", port, request(), &limits(false)).await });
tokio::time::timeout(Duration::from_secs(1), async {
while calls.load(Ordering::SeqCst) == 0 {
tokio::task::yield_now().await;
}
})
.await
.unwrap();
let second =
tokio::spawn(async move { send("127.0.0.1", port, request(), &limits(false)).await });
tokio::time::sleep(Duration::from_millis(20)).await;
assert_eq!(calls.load(Ordering::SeqCst), 1);
release.notify_one();
assert_eq!(first.await.unwrap().unwrap().status, 202);
assert_eq!(second.await.unwrap().unwrap().status, 202);
assert_eq!(calls.load(Ordering::SeqCst), 2);
listener.close().unwrap();
server.await.unwrap().unwrap();
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
+170
View File
@@ -0,0 +1,170 @@
use super::{tests::limits, *};
use crate::{task, tls};
use http_body_util::Full;
use hyper::service::service_fn;
use std::{convert::Infallible, time::Duration};
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::TcpListener,
};
fn request() -> Request {
Request {
method: "GET".into(),
target: "/stream".into(),
headers: vec![],
body: Bytes::new(),
}
}
fn pool() -> PoolLimits {
PoolLimits {
idle_ms: 1000,
chunk_bytes: 3,
read_ms: 200,
}
}
#[test]
fn stream_bounds_chunks_and_eof_returns_capacity_for_connection_reuse() {
task::run(true, 16, async |scope| {
for http2 in [false, true] {
let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
let origin = format!("http://{}", listener.local_addr().unwrap());
let peer = tokio::spawn(async move {
// 只接收一个连接;后续请求成功说明 EOF 后真实归还了容量和连接。
let (stream, _) = listener.accept().await.unwrap();
let service = service_fn(|_| async {
Ok::<_, Infallible>(hyper::Response::new(Full::new(Bytes::from_static(
b"abcdefghij",
))))
});
let stream = TokioIo::new(stream);
if http2 {
hyper::server::conn::http2::Builder::new(TokioExecutor::new())
.serve_connection(stream, service)
.await
.unwrap();
} else {
hyper::server::conn::http1::Builder::new()
.serve_connection(stream, service)
.await
.unwrap();
}
});
let mut limits = limits(http2);
limits.connections = 1;
limits.body_bytes = 2; // 流式下载不收集整个正文,允许超过完整响应的收集限额。
let client = client(&origin, &tls::system(), &limits, &pool(), scope)
.await
.unwrap();
for _ in 0..2 {
let response = client.open(request(), |item| item).await.unwrap();
assert_eq!(response.status, 200);
let mut bytes = Vec::new();
let mut chunks = 0;
while let Some(chunk) = response.body.next().await.unwrap() {
let chunk = chunk.unwrap();
assert!(!chunk.is_empty() && chunk.len() <= 3);
bytes.extend_from_slice(&chunk);
chunks += 1;
}
assert_eq!(bytes, b"abcdefghij");
assert!(chunks >= 4);
assert!(response.body.next().await.unwrap().is_none());
}
client.close().await.unwrap();
tokio::time::timeout(Duration::from_secs(2), peer)
.await
.unwrap()
.unwrap();
}
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
#[test]
fn stream_delivers_headers_and_partial_data_before_one_terminal_error() {
task::run(true, 16, async |scope| {
for mode in ["truncated", "timeout", "client_close", "stream_close"] {
let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
let origin = format!("http://{}", listener.local_addr().unwrap());
let (continue_body, continuation) = tokio::sync::oneshot::channel();
let peer = tokio::spawn(async move {
let (mut stream, _) = listener.accept().await.unwrap();
let mut buffer = [0; 8192];
assert!(stream.read(&mut buffer).await.unwrap() > 0);
stream
.write_all(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n")
.await
.unwrap();
// 客户端必须先取得响应头,服务端才开始发送正文。
continuation.await.unwrap();
stream.write_all(b"3\r\nabc\r\n").await.unwrap();
if mode == "truncated" {
stream.write_all(b"5\r\nx").await.unwrap();
} else {
stream.read_to_end(&mut Vec::new()).await.unwrap();
}
});
let client = client(&origin, &tls::system(), &limits(false), &pool(), scope)
.await
.unwrap();
let response = client.open(request(), |item| item).await.unwrap();
assert_eq!(response.status, 200);
continue_body.send(()).unwrap();
assert_eq!(
response.body.next().await.unwrap().unwrap().unwrap(),
b"abc"[..]
);
if mode == "stream_close" {
let mut pending = Box::pin(response.body.next());
tokio::select! {
result = &mut pending => panic!("body must wait: {result:?}"),
() = tokio::time::sleep(Duration::from_millis(10)) => {},
}
response.body.close();
assert!(pending.await.unwrap().is_none());
} else if mode == "client_close" {
let mut pending = Box::pin(response.body.next());
tokio::select! {
result = &mut pending => panic!("body must wait: {result:?}"),
() = tokio::time::sleep(Duration::from_millis(10)) => {},
}
client.close().await.unwrap();
assert_eq!(
pending.await.unwrap().unwrap().unwrap_err().kind(),
io::ErrorKind::NotConnected
);
} else {
let error = loop {
match response
.body
.next()
.await
.unwrap()
.expect("terminal failure must be delivered")
{
Ok(bytes) => assert_eq!(bytes, b"x"[..]),
Err(error) => break error,
}
};
if mode == "timeout" {
assert_eq!(error.kind(), io::ErrorKind::TimedOut);
}
}
assert!(response.body.next().await.unwrap().is_none());
if mode != "client_close" {
client.close().await.unwrap();
}
tokio::time::timeout(Duration::from_secs(2), peer)
.await
.unwrap()
.unwrap();
}
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
+185
View File
@@ -0,0 +1,185 @@
use super::{tests::limits, websocket::*, *};
use crate::{net, task, tls};
use futures_util::{SinkExt, StreamExt};
use std::{
sync::{Arc, Mutex},
time::Duration,
};
use tokio::net::TcpListener;
use tokio_tungstenite::tungstenite::Message as Frame;
fn ws_limits() -> websocket::Limits {
websocket::Limits {
message_bytes: 16,
idle_ms: 1000,
write_ms: 1000,
}
}
fn live_limits() -> LiveLimits {
LiveLimits {
chunk_bytes: 1024,
idle_ms: 1000,
heartbeat_ms: 100,
}
}
#[test]
fn websocket_client_uses_library_frames_pong_and_close() {
task::run(true, 16, async |scope| {
let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
let port = listener.local_addr().unwrap().port();
let peer = tokio::spawn(async move {
let (stream, _) = listener.accept().await.unwrap();
let mut socket = tokio_tungstenite::accept_async(stream).await.unwrap();
assert_eq!(
socket.next().await.unwrap().unwrap(),
Frame::Text("hello".into())
);
for frame in [
Frame::Text("world".into()),
Frame::Binary(Bytes::from_static(b"bytes")),
Frame::Ping(Bytes::from_static(b"ping")),
] {
socket.send(frame).await.unwrap();
}
assert_eq!(
socket.next().await.unwrap().unwrap(),
Frame::Pong(Bytes::from_static(b"ping"))
);
assert!(matches!(
socket.next().await.unwrap().unwrap(),
Frame::Close(_)
));
socket.flush().await.unwrap();
});
let socket = connect("127.0.0.1", port.into(), "/chat", &ws_limits(), scope)
.await
.unwrap();
assert!(socket.send(Message::Text("x".repeat(17))).await.is_err());
socket.send(Message::Text("hello".into())).await.unwrap();
assert_eq!(
socket.receive().await.unwrap(),
Some(Message::Text("world".into()))
);
assert_eq!(
socket.receive().await.unwrap(),
Some(Message::Binary(Bytes::from_static(b"bytes")))
);
assert_eq!(
socket.receive().await.unwrap(),
Some(Message::Ping(Bytes::from_static(b"ping")))
);
socket.close(1000, "done").await.unwrap();
assert!(socket.receive().await.unwrap().is_none());
peer.await.unwrap();
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
#[test]
fn upgraded_socket_cannot_outlive_cancelled_handler_even_through_an_alias() {
task::run(true, 16, async |scope| {
let listener = net::listen("127.0.0.1", 0, scope).await.unwrap();
let port = listener.port().unwrap();
let active = listener.clone();
let (send, receive) = tokio::sync::oneshot::channel();
let send = Arc::new(Mutex::new(Some(send)));
let server = scope
.spawn(move |child| async move {
serve_live(
&child,
move |_, reply, _| {
let send = send.clone();
async move {
let socket = accept(&reply, &ws_limits())
.await
.map_err(|e| e.to_string())?;
send.lock().unwrap().take().unwrap().send(socket).unwrap();
std::future::pending().await
}
},
&active,
&limits(false),
&live_limits(),
None,
)
.await
})
.unwrap();
let client = connect("127.0.0.1", port, "/chat", &ws_limits(), scope)
.await
.unwrap();
let alias = receive.await.unwrap();
assert!(
tokio::time::timeout(Duration::from_secs(2), server.stop())
.await
.unwrap()
.unwrap()
.is_none()
);
assert!(alias.receive().await.is_err());
assert!(client.receive().await.is_err());
listener.close().unwrap();
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
#[test]
fn websocket_verifies_tls_and_preserves_upgrade_after_http_finishes() {
task::run(true, 16, async |scope| {
let listener = net::listen("127.0.0.1", 0, scope).await.unwrap();
let port = listener.port().unwrap();
let active = listener.clone();
let server = scope
.spawn(move |child| async move {
let tls = tls::server(
include_bytes!("../../../fixtures/tls/server.pem"),
include_bytes!("../../../fixtures/tls/server-key.pem"),
)
.unwrap();
serve_live(
&child,
|_, reply, _| async move {
let socket = accept(&reply, &ws_limits())
.await
.map_err(|e| e.to_string())?;
tokio::time::sleep(Duration::from_millis(30)).await;
socket
.send(Message::Text("upgraded".into()))
.await
.map_err(|e| e.to_string())?;
assert!(socket.receive().await.map_err(|e| e.to_string())?.is_none());
Ok(())
},
&active,
&limits(false),
&live_limits(),
Some(&tls),
)
.await
})
.unwrap();
let trust = tls::client(include_bytes!("../../../fixtures/tls/root.pem")).unwrap();
let url = format!("wss://localhost:{port}/chat");
assert!(
open(&url, &tls::system(), &ws_limits(), scope)
.await
.is_err()
);
let client = open(&url, &trust, &ws_limits(), scope).await.unwrap();
assert_eq!(
client.receive().await.unwrap(),
Some(Message::Text("upgraded".into()))
);
client.close(1000, "done").await.unwrap();
listener.close().unwrap();
server.await.unwrap().unwrap();
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
+90
View File
@@ -0,0 +1,90 @@
use dever_runtime::{task, tls};
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::{TcpListener, TcpStream},
};
const ROOT: &[u8] = include_bytes!("../../../fixtures/tls/root.pem");
const CERT: &[u8] = include_bytes!("../../../fixtures/tls/server.pem");
const KEY: &[u8] = include_bytes!("../../../fixtures/tls/server-key.pem");
#[test]
fn certificates_hostname_and_protocol_are_verified_on_real_connections() {
task::execute(true, async {
let server = tls::server(CERT, KEY).unwrap();
let client = tls::client(ROOT).unwrap();
for http2 in [false, true] {
for (config, name, requested, valid) in [
(client.clone(), "localhost", http2, true),
(client.clone(), "wrong.test", http2, false),
(tls::system(), "localhost", http2, false),
(client.clone(), "localhost", !http2, false),
(client.clone(), "localhost", http2, true),
] {
let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
let address = listener.local_addr().unwrap();
let acceptor = server.acceptor(http2);
let peer = tokio::spawn(async move {
let (socket, _) = listener.accept().await.unwrap();
if let Ok(mut stream) = acceptor.accept(socket).await {
let mut data = [0; 4];
if stream.read_exact(&mut data).await.is_ok() {
assert_eq!(&data, b"ping");
stream.write_all(b"pong").await.unwrap();
}
}
});
let socket = TcpStream::connect(address).await.unwrap();
let connection = config.connect(name, socket, requested).await;
assert_eq!(connection.is_ok(), valid, "{name}: {connection:?}");
if let Ok(mut stream) = connection {
stream.write_all(b"ping").await.unwrap();
let mut data = [0; 4];
stream.read_exact(&mut data).await.unwrap();
assert_eq!(&data, b"pong");
}
peer.await.unwrap();
}
}
})
.unwrap();
}
#[test]
fn configuration_errors_preserve_causes_without_echoing_key_material() {
assert!(
tls::client(b"private-input")
.unwrap_err()
.to_string()
.contains("empty")
);
let missing = tls::server(CERT, b"private-key-input")
.unwrap_err()
.to_string();
assert!(missing.contains("missing"));
assert!(!missing.contains("private-key-input"));
for key in [
"-----BEGIN PRIVATE_DO_NOT_ECHO",
"-----BEGIN PRIVATE_DO_NOT_ECHO-----\n",
] {
let message = tls::server(CERT, key.as_bytes()).unwrap_err().to_string();
assert!(message.contains("section"), "{message}");
assert!(!message.contains("PRIVATE_DO_NOT_ECHO"), "{message}");
}
assert!(tls::server(ROOT, KEY).is_err());
assert!(tls::server(b"", KEY).is_err());
let mut duplicate = KEY.to_vec();
duplicate.extend_from_slice(KEY);
assert!(
tls::server(CERT, &duplicate)
.unwrap_err()
.to_string()
.contains("one private key")
);
assert!(tls::client(b"-----BEGIN CERTIFICATE-----\n%%%%\n-----END CERTIFICATE-----").is_err());
assert_eq!(
format!("{:?}", tls::server(CERT, KEY).unwrap()),
"ServerTls"
);
assert_eq!(format!("{:?}", tls::client(ROOT).unwrap()), "ClientTls");
}
+42
View File
@@ -0,0 +1,42 @@
use dever_runtime::{crypto, value::secret::Secret};
#[test]
fn passwords_use_the_existing_profile_and_distinguish_mismatch_from_invalid_hash() {
let password = Secret::from_input(b"test-only-password".to_vec());
let wrong = Secret::from_input(b"other-test-password".to_vec());
let encoded = crypto::password_hash(&password).unwrap();
assert!(encoded.starts_with("$argon2id$v=19$m=19456,t=2,p=1$"));
assert_eq!(crypto::password_verify(&password, &encoded), Ok(true));
assert_eq!(crypto::password_verify(&wrong, &encoded), Ok(false));
assert!(crypto::password_verify(&password, "not a hash").is_err());
let other = crypto::password_hash(&password).unwrap();
assert_ne!(encoded, other, "each hash must use a fresh salt");
}
#[test]
fn password_costs_and_missing_parameters_fail_before_expensive_work() {
let password = Secret::from_input(b"test-only-password".to_vec());
let encoded =
"$argon2id$v=19$m=19456,t=2,p=1$c29tZXNhbHQ$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
for invalid in [
encoded.replace("m=19456", "m=19457"),
encoded.replace("t=2", "t=3"),
encoded.replace("p=1", "p=2"),
encoded.replace("p=1", "p=536870912"),
encoded.replace("p=1", "p=0"),
encoded.replace("p=1", "p=invalid"),
encoded.replace("m=19456,", ""),
encoded.replace("t=2,", ""),
encoded.replace(",p=1", ""),
encoded.replace("$v=19$", "$v=16$"),
encoded.replace("argon2id", "argon2i"),
encoded.replace("p=1", "p=1,data=YQ"),
encoded.replace("p=1", "p=1,keyid=YQ"),
"x".repeat(257),
] {
assert!(
crypto::password_verify(&password, &invalid).is_err(),
"{invalid}"
);
}
}
+176
View File
@@ -0,0 +1,176 @@
//! 真实子进程覆盖管道背压、退出、输出预算与取消;不使用替身进程。
use dever_runtime::{
Bytes,
process::{self, Limits},
task,
};
use std::{
io,
path::Path,
time::{Duration, Instant},
};
fn limits() -> Limits {
Limits {
timeout_ms: 3000,
output_limit: 1_048_576,
}
}
#[test]
fn command_drains_stdin_and_both_outputs_and_preserves_nonzero_exit() {
task::run(true, 8, async |scope| {
let input = Bytes::from(vec![0x85; 512 * 1024]);
let output = process::run(
scope,
&Path::new("/bin/cat").into(),
&[],
Some(&input),
limits(),
)
.await?;
assert_eq!(output.code, 0);
assert_eq!(output.stdout, input);
assert!(output.stderr.is_empty());
let output = process::run(
scope,
&Path::new("/bin/sh").into(),
&["-c".into(), "printf out; printf err >&2; exit 9".into()],
None,
limits(),
)
.await?;
assert_eq!(output.code, 9);
assert_eq!(output.stdout.as_ref(), b"out");
assert_eq!(output.stderr.as_ref(), b"err");
Ok::<_, io::Error>(())
})
.unwrap()
.unwrap();
}
#[test]
fn command_limits_and_spawn_errors_retain_real_failures() {
task::run(true, 8, async |scope| {
let result = process::run(
scope,
&Path::new("/nonexistent-dever-command").into(),
&[],
None,
limits(),
)
.await;
assert_eq!(result.unwrap_err().kind(), io::ErrorKind::NotFound);
let result = process::run(
scope,
&Path::new("/bin/echo").into(),
&["bad\0arg".into()],
None,
limits(),
)
.await;
assert_eq!(result.unwrap_err().kind(), io::ErrorKind::InvalidInput);
let result = process::run(
scope,
&Path::new("/bin/sh").into(),
&["-c".into(), "printf 12345; printf 67890 >&2".into()],
None,
Limits {
output_limit: 8,
..limits()
},
)
.await;
assert_eq!(result.unwrap_err().kind(), io::ErrorKind::FileTooLarge);
let start = Instant::now();
let result = process::run(
scope,
&Path::new("/bin/sleep").into(),
&["30".into()],
None,
Limits {
timeout_ms: 20,
..limits()
},
)
.await;
assert_eq!(result.unwrap_err().kind(), io::ErrorKind::TimedOut);
assert!(start.elapsed() < Duration::from_secs(2));
Ok::<_, io::Error>(())
})
.unwrap()
.unwrap();
}
#[test]
fn cancelled_command_is_reaped_before_scope_returns() {
let start = Instant::now();
task::run(true, 8, async |scope| {
let arguments = ["30".into()];
let executable = Path::new("/bin/sleep").into();
let call = process::run(scope, &executable, &arguments, None, limits());
assert!(
tokio::time::timeout(Duration::from_millis(20), call)
.await
.is_err()
);
Ok::<_, io::Error>(())
})
.unwrap()
.unwrap();
assert!(start.elapsed() < Duration::from_secs(2));
}
#[test]
fn command_exit_and_cancellation_stop_descendants_holding_the_pipes() {
for wait in [false, true] {
let file =
std::env::temp_dir().join(format!("dever-process-{}-{wait}.pid", std::process::id()));
let script = format!(
"sleep 30 & echo $! >\"$1\"; {}",
if wait { "wait" } else { "exit 4" }
);
let start = Instant::now();
task::run(true, 8, async |scope| {
let args = [
"-c".into(),
script,
"test".into(),
file.to_str().unwrap().into(),
];
let executable = Path::new("/bin/sh").into();
let call = process::run(scope, &executable, &args, None, limits());
if wait {
assert!(
tokio::time::timeout(Duration::from_millis(100), call)
.await
.is_err()
);
} else {
assert_eq!(call.await?.code, 4);
}
Ok::<_, io::Error>(())
})
.unwrap()
.unwrap();
assert!(start.elapsed() < Duration::from_secs(2));
let pid = std::fs::read_to_string(&file).unwrap();
// 后代由系统的 reaper 回收。KILL 只保证信号已送达,进程可能仍在退出路径上,
// 所以在期限内等待它变成僵尸或消失;超时仍存活才算清理失败。
let deadline = Instant::now() + Duration::from_secs(1);
loop {
match std::fs::read_to_string(format!("/proc/{}/stat", pid.trim())) {
Ok(stat) if stat.rsplit_once(") ").unwrap().1.starts_with('Z') => break,
Ok(stat) => {
assert!(Instant::now() < deadline, "descendant still alive: {stat}");
std::thread::sleep(Duration::from_millis(5));
}
Err(error) => {
assert_eq!(error.kind(), io::ErrorKind::NotFound);
break;
}
}
}
std::fs::remove_file(file).unwrap();
}
}
+192
View File
@@ -0,0 +1,192 @@
use dever_runtime::{
channel::Channel,
stream::{AsyncStream, Error},
};
use std::{
future::Future,
pin::pin,
sync::{
Arc,
atomic::{AtomicUsize, Ordering},
},
task::{Context, Poll, Waker},
};
fn pending<T>(value: std::pin::Pin<&mut impl Future<Output = T>>) {
assert!(matches!(
value.poll(&mut Context::from_waker(Waker::noop())),
Poll::Pending
));
}
#[tokio::test]
async fn streams_are_lazy_share_cursor_and_close_without_replaying() {
let calls = Arc::new(AtomicUsize::new(0));
let observed = calls.clone();
let values = AsyncStream::<_>::values((1..=3).inspect(move |_| {
observed.fetch_add(1, Ordering::SeqCst);
}));
assert_eq!(calls.load(Ordering::SeqCst), 0);
let alias = values.clone();
assert_eq!(values.next().await, Ok(Some(1)));
assert_eq!(alias.next().await, Ok(Some(2)));
alias.close();
assert_eq!(values.next().await, Ok(None));
assert_eq!(calls.load(Ordering::SeqCst), 2);
}
#[tokio::test]
async fn stream_close_preserves_null_messages_and_external_channel() {
let channel = Channel::new(2).unwrap();
channel.send(None).await.unwrap();
channel.send(Some(2)).await.unwrap();
let values = AsyncStream::<_>::channel(channel.clone());
assert_eq!(values.next().await, Ok(Some(None)));
values.close();
assert_eq!(values.next().await, Ok(None));
assert_eq!(channel.receive().await.unwrap(), Some(2));
channel.send(Some(3)).await.unwrap();
channel.close();
let remaining = AsyncStream::<_>::channel(channel);
assert_eq!(remaining.next().await, Ok(Some(Some(3))));
assert_eq!(remaining.next().await, Ok(None));
}
#[tokio::test]
async fn closing_stream_wakes_active_and_queued_pulls() {
let values = AsyncStream::<_>::channel(Channel::<i64>::new(1).unwrap());
let mut first = pin!(values.next());
let mut second = pin!(values.next());
pending(first.as_mut());
pending(second.as_mut());
values.close();
assert_eq!(first.await, Ok(None));
assert_eq!(second.await, Ok(None));
}
#[tokio::test]
async fn close_wakes_a_scheduled_consumer_without_another_source_event() {
let (entered, ready) = tokio::sync::oneshot::channel();
let values = AsyncStream::<i64>::new(futures_util::stream::once(async move {
entered.send(()).unwrap();
std::future::pending().await
}));
let alias = values.clone();
let consumer = tokio::spawn(async move { alias.next().await });
ready.await.unwrap();
values.close();
assert_eq!(
tokio::time::timeout(std::time::Duration::from_secs(1), consumer)
.await
.unwrap()
.unwrap(),
Ok(None)
);
}
#[tokio::test]
async fn closing_then_dropping_pending_pull_releases_source_without_another_poll() {
let owner = Arc::new(7);
let values = AsyncStream::<_>::new(futures_util::stream::unfold(
owner.clone(),
|owner| async move {
std::future::pending::<()>().await;
Some((Ok(1), owner))
},
));
{
let mut next = pin!(values.next());
pending(next.as_mut());
values.close();
assert_eq!(Arc::strong_count(&owner), 1);
}
assert_eq!(Arc::strong_count(&owner), 1);
assert_eq!(values.next().await, Ok(None));
}
#[tokio::test]
async fn stream_fault_and_consumption_guard_release_source_before_return() {
let owner = Arc::new(7);
let values = AsyncStream::<i64>::new(futures_util::stream::unfold(
owner.clone(),
|owner| async move { Some((Err(Error::Overflow), owner)) },
));
assert_eq!(values.next().await, Err(Error::Overflow));
assert_eq!(Arc::strong_count(&owner), 1);
assert_eq!(values.next().await, Ok(None));
let values = AsyncStream::<_>::values(vec![owner.clone()]);
{
let _consume = values.close_on_drop();
}
assert_eq!(Arc::strong_count(&owner), 1);
assert_eq!(values.next().await, Ok(None));
}
#[test]
fn ticks_start_on_first_pull_and_close_without_waiting_for_deadline() {
assert!(matches!(AsyncStream::ticks(0), Err(Error::Period)));
assert!(matches!(AsyncStream::ticks(-1), Err(Error::Period)));
let values = AsyncStream::ticks(60000).unwrap();
tokio::runtime::Builder::new_current_thread()
.enable_time()
.build()
.unwrap()
.block_on(async {
let mut next = pin!(values.next());
pending(next.as_mut());
values.close();
assert_eq!(next.await, Ok(None));
let values = AsyncStream::ticks(1).unwrap();
assert_eq!(values.next().await, Ok(Some(1)));
assert_eq!(values.next().await, Ok(Some(2)));
});
}
#[test]
fn concurrent_close_and_pull_cancellation_release_source_with_live_alias() {
for _ in 0..256 {
let owner = Arc::new(7);
let values = AsyncStream::<i64>::new(futures_util::stream::unfold(
owner.clone(),
|owner| async move {
std::future::pending::<()>().await;
Some((Ok(1), owner))
},
));
let ready = std::sync::Barrier::new(2);
std::thread::scope(|scope| {
scope.spawn(|| {
let mut next = pin!(values.next());
pending(next.as_mut());
ready.wait();
// 取消和另一个线程的关闭竞争,之后不再轮询 next。
});
ready.wait();
values.close();
});
assert_eq!(Arc::strong_count(&owner), 1);
}
}
#[test]
fn producer_panic_preserves_original_fault_and_releases_source() {
let owner = Arc::new(7);
let held = owner.clone();
let values = AsyncStream::<i64>::new(futures_util::stream::poll_fn(move |_| {
std::hint::black_box(&held);
std::panic::panic_any(42u32);
}));
let fault = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let _consume = values.close_on_drop();
let mut next = pin!(values.next());
pending(next.as_mut());
}))
.unwrap_err();
assert_eq!(fault.downcast_ref::<u32>(), Some(&42));
assert_eq!(Arc::strong_count(&owner), 1);
let mut next = pin!(values.next());
assert_eq!(
next.as_mut().poll(&mut Context::from_waker(Waker::noop())),
Poll::Ready(Ok(None))
);
}
+65
View File
@@ -0,0 +1,65 @@
//! 真实计时器的完成、输入错误和取消析构,不用 sleep 阻塞执行线程。
use dever_runtime::task;
#[path = "task/boundary.rs"]
mod boundary;
#[path = "task/combinations.rs"]
mod combinations;
#[path = "task/ordered.rs"]
mod ordered;
#[path = "task/scope.rs"]
mod scope;
#[path = "task/worker.rs"]
mod worker;
use std::{
cell::Cell,
future::{Future, poll_fn},
pin::pin,
task::Poll,
time::{Duration, Instant},
};
#[test]
fn timer_completes_and_rejects_invalid_duration() {
task::execute(false, async {
assert_eq!(
task::sleep(-1).await.unwrap_err(),
"sleep duration must be nonnegative"
);
let start = Instant::now();
task::sleep(5).await.unwrap();
assert!(start.elapsed() >= Duration::from_millis(5));
task::sleep(0).await.unwrap();
})
.unwrap();
}
#[test]
fn dropping_pending_timer_releases_its_owned_scope_without_running_later_steps() {
struct Released<'a>(&'a Cell<bool>);
impl Drop for Released<'_> {
fn drop(&mut self) {
self.0.set(true);
}
}
let released = Cell::new(false);
let completed = Cell::new(false);
task::execute(false, async {
{
let mut pending = pin!(async {
let _owned = Released(&released);
task::sleep(60_000).await.unwrap();
completed.set(true);
});
poll_fn(|context| {
assert!(pending.as_mut().poll(context).is_pending());
Poll::Ready(())
})
.await;
}
assert!(released.get());
assert!(!completed.get());
task::sleep(1).await.unwrap();
assert!(!completed.get());
})
.unwrap();
}
+143
View File
@@ -0,0 +1,143 @@
use dever_runtime::{
task::{self, RunError},
value::{FaultInfo, fault},
};
use std::{
future::{Future, pending, poll_fn},
sync::{
Arc,
atomic::{AtomicUsize, Ordering},
},
task::Poll,
};
struct Released(Arc<AtomicUsize>);
impl Drop for Released {
fn drop(&mut self) {
self.0.fetch_add(1, Ordering::SeqCst);
}
}
static PARENT: FaultInfo = FaultInfo {
message: "captured fault",
source: "app.dever",
line: 8,
column: 2,
};
#[test]
fn captured_boundary_releases_tasks_before_continuing() {
let released = Arc::new(AtomicUsize::new(0));
task::run(true, 1, async |scope| {
for expected in 1..=2 {
let result = scope
.within(async |child| {
let held = Released(released.clone());
let _task = child
.spawn_leaf(async move {
let _held = held;
pending::<()>().await
})
.unwrap();
Err::<(), _>("business failure")
})
.await;
assert_eq!(result, Err("business failure"));
assert_eq!(released.load(Ordering::SeqCst), expected);
}
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
#[test]
fn cancelled_nested_boundary_transfers_cleanup_to_the_parent() {
let released = Arc::new(AtomicUsize::new(0));
task::run(true, 1, async |root| {
root.within(async |parent| {
let mut nested = Box::pin(parent.within(async |child| {
let held = Released(released.clone());
let _task = child
.spawn_leaf(async move {
let _held = held;
pending::<()>().await
})
.unwrap();
pending::<()>().await;
}));
poll_fn(|cx| {
assert!(nested.as_mut().poll(cx).is_pending());
Poll::Ready(())
})
.await;
drop(nested);
})
.await;
assert_eq!(released.load(Ordering::SeqCst), 1);
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
#[test]
fn captured_boundary_preserves_original_panic_and_cleans_descendants() {
let released = Arc::new(AtomicUsize::new(0));
let result = task::run::<(), ()>(true, 1, async |root| {
root.within(async |child| {
let held = Released(released.clone());
let _task = child
.spawn_leaf(async move {
let _held = held;
pending::<()>().await
})
.unwrap();
fault(&PARENT);
})
.await;
Ok(())
})
.unwrap();
let RunError::Fault {
primary,
additional,
} = result.unwrap_err()
else {
panic!("original fault required")
};
assert!(std::ptr::eq(
*primary.downcast_ref::<&'static FaultInfo>().unwrap(),
&PARENT
));
assert!(additional.is_empty());
assert_eq!(released.load(Ordering::SeqCst), 1);
}
#[test]
fn database_cleanup_failure_preserves_the_primary_business_error() {
use dever_runtime::database::{Error, Kind};
let result = task::run(true, 1, async |scope| {
scope.record_cleanup(
Error::new(Kind::Connection, "rollback failed")
.caused_by(std::io::Error::other("driver failure")),
);
Err::<(), _>("original business failure")
})
.unwrap();
let Err(RunError::Business { error, additional }) = result else {
panic!("business error with cleanup")
};
assert_eq!(error, "original business failure");
assert_eq!(additional.len(), 1);
let cleanup = additional[0].downcast_ref::<Error>().unwrap();
assert_eq!(cleanup.kind, Kind::Connection);
assert_eq!(
std::error::Error::source(cleanup).unwrap().to_string(),
"driver failure"
);
let result = task::run(true, 1, async |scope| {
scope.record_cleanup(Error::new(Kind::Connection, "rollback failed"));
Ok::<_, ()>(())
})
.unwrap();
assert!(matches!(result, Err(RunError::Fault { .. })));
}
+210
View File
@@ -0,0 +1,210 @@
use dever_runtime::task::{self, Error, Group, RunError, Selection, Timed};
use std::{
future::pending,
sync::{
Arc,
atomic::{AtomicUsize, Ordering},
},
};
struct Released(Arc<AtomicUsize>);
impl Drop for Released {
fn drop(&mut self) {
self.0.fetch_add(1, Ordering::SeqCst);
}
}
#[test]
fn timeout_releases_descendants_before_returning_and_preserves_ready_failures() {
let released = Arc::new(AtomicUsize::new(0));
task::run(true, 2, async |scope| {
let held = Released(released.clone());
let task = scope
.spawn(move |child| async move {
let task = child
.spawn_leaf(async move {
let _held = held;
pending::<()>().await
})
.unwrap();
task.wait().await.unwrap();
})
.unwrap();
assert!(matches!(task.timeout(5).await, Ok(Timed::Expired(None))));
assert_eq!(released.load(Ordering::SeqCst), 1);
let task = scope
.spawn_leaf(async { Err::<(), _>("original failure") })
.unwrap();
task::sleep(1).await.unwrap();
assert!(matches!(
task.timeout(1).await,
Ok(Timed::Ready(Err("original failure")))
));
for millis in [0, -1, i64::MIN] {
let task = scope.spawn_leaf(pending::<()>()).unwrap();
assert!(matches!(
task.timeout(millis).await,
Err(Error::InvalidTimeout)
));
task::sleep(1).await.unwrap();
}
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
#[test]
fn group_limits_real_admission_and_waits_for_every_member() {
let completed = Arc::new(AtomicUsize::new(0));
task::run(true, 1, async |scope| {
Group::<()>::new(scope, 1)
.unwrap()
.wait()
.await
.unwrap()
.unwrap();
Group::<()>::new(scope, 1)
.unwrap()
.stop()
.await
.unwrap()
.unwrap();
for limit in [0, -1, 65537] {
assert!(matches!(
Group::<()>::new(scope, limit),
Err(Error::InvalidGroupLimit)
));
}
let mut group = Group::new(scope, 1).unwrap();
for index in 0..8 {
let completed = completed.clone();
group
.run(|| {
// 工厂启动时前一成员已经完成;容量只有 1,也不能提前派生。
assert_eq!(completed.load(Ordering::SeqCst), index);
scope.spawn_leaf(async move {
task::sleep(1).await.unwrap();
completed.fetch_add(1, Ordering::SeqCst);
Ok::<_, ()>(())
})
})
.await
.unwrap()
.unwrap();
}
group.wait().await.unwrap().unwrap();
assert_eq!(completed.load(Ordering::SeqCst), 8);
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
#[test]
fn group_failure_closes_admission_and_drains_before_capture_continues() {
let released = Arc::new(AtomicUsize::new(0));
task::run(true, 3, async |scope| {
let mut group = Group::new(scope, 3).unwrap();
let held = Released(released.clone());
group
.run(|| {
scope.spawn_leaf(async move {
let _held = held;
pending::<Result<(), &str>>().await
})
})
.await
.unwrap()
.unwrap();
group
.run(|| scope.spawn_leaf(async { Err("member failed") }))
.await
.unwrap()
.unwrap();
task::sleep(1).await.unwrap();
let result = group
.run(|| panic!("must not start after member failure"))
.await;
assert_eq!(result, Ok(Err("member failed")));
assert_eq!(released.load(Ordering::SeqCst), 1);
assert_eq!(
group.run(|| panic!("closed group")).await,
Err(Error::GroupClosed)
);
group.stop().await.unwrap().unwrap();
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
#[test]
fn group_stop_preserves_completed_business_failure() {
task::run(true, 1, async |scope| {
let mut group = Group::new(scope, 1).unwrap();
group
.run(|| scope.spawn_leaf(async { Err("completed before stop") }))
.await
.unwrap()
.unwrap();
task::sleep(1).await.unwrap();
assert_eq!(group.stop().await, Ok(Err("completed before stop")));
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
#[test]
fn selection_keeps_primary_business_error_and_original_loser_fault_once() {
let result = task::run(true, 2, async |scope| {
let mut first = scope.spawn_leaf(async { Err::<(), _>("primary") }).unwrap();
let mut second = scope
.spawn_leaf(async { std::panic::panic_any(73usize) })
.unwrap();
task::sleep(1).await.unwrap();
let result = task::select! {
biased;
value = &mut first => value.unwrap(),
_ = &mut second => panic!("first ready argument must win"),
};
let mut selection = Selection::new(scope);
second.cancel();
selection.join(second).await;
selection.finish(result.is_ok());
result
})
.unwrap();
let Err(RunError::Business { error, additional }) = result else {
panic!("business primary")
};
assert_eq!(error, "primary");
assert_eq!(additional.len(), 1);
assert_eq!(*additional[0].downcast_ref::<usize>().unwrap(), 73);
}
#[test]
fn selection_cannot_turn_loser_fault_into_success() {
let result = task::run(true, 1, async |scope| {
let task = scope
.spawn_leaf(async { std::panic::panic_any(91usize) })
.unwrap();
task::sleep(1).await.unwrap();
let mut selection = Selection::new(scope);
task.cancel();
selection.join(task).await;
selection.finish(true);
Ok::<_, ()>(())
})
.unwrap();
let Err(RunError::Fault {
primary,
additional,
}) = result
else {
panic!("must retain fault")
};
assert_eq!(*primary.downcast_ref::<usize>().unwrap(), 91);
assert!(additional.is_empty());
}
+208
View File
@@ -0,0 +1,208 @@
use super::*;
use futures_util::FutureExt;
use std::{
panic::AssertUnwindSafe,
sync::atomic::{AtomicUsize, Ordering},
};
use tokio::sync::Notify;
#[test]
fn ordered_limits_pending_plus_buffered_results_and_preserves_input_order() {
task::execute(true, async {
let pulled = AtomicUsize::new(0);
let accepted = AtomicUsize::new(0);
let completed = Notify::new();
let release = Notify::new();
let mut output = Vec::new();
let run = dever_runtime::ordered_loop!(
(),
3,
async || {
let next = pulled.fetch_add(1, Ordering::SeqCst);
assert!(next - accepted.load(Ordering::SeqCst) < 3);
Ok::<_, ()>((next < 20).then_some(next))
},
async |value| {
if value == 0 {
release.notified().await;
}
if value == 2 {
completed.notify_one();
}
Ok(value)
},
|value| {
output.push(value);
accepted.fetch_add(1, Ordering::SeqCst);
},
);
let verify = async {
completed.notified().await;
tokio::task::yield_now().await;
assert_eq!(pulled.load(Ordering::SeqCst), 3);
assert_eq!(accepted.load(Ordering::SeqCst), 0);
release.notify_one();
};
let (result, ()) = tokio::join!(run, verify);
result.unwrap();
assert_eq!(output, (0..20).collect::<Vec<_>>());
})
.unwrap();
}
struct Released<'a>(&'a Cell<usize>);
impl Drop for Released<'_> {
fn drop(&mut self) {
self.0.set(self.0.get() + 1);
}
}
#[test]
fn ordered_observes_later_failure_without_waiting_for_the_first_item() {
task::execute(true, async {
let released = Cell::new(0);
let mut pulled = 0;
let result = dever_runtime::ordered_loop!(
&str,
2,
async || {
let item = pulled;
pulled += 1;
Ok::<_, &str>(Some(item))
},
async |item| {
let _owned = Released(&released);
if item == 0 {
std::future::pending::<()>().await;
}
Err::<(), _>("second failed")
},
|_| panic!("failed work cannot deliver success"),
)
.await;
assert_eq!(result, Err("second failed"));
assert_eq!(pulled, 2);
assert_eq!(released.get(), 2);
})
.unwrap();
}
#[test]
fn ordered_keeps_one_pending_pull_while_other_work_completes() {
task::execute(true, async {
let calls = Cell::new(0);
let pulled = Notify::new();
let release = Notify::new();
let mut out = Vec::new();
let run = dever_runtime::ordered_loop!(
(),
3,
async || {
let call = calls.get();
calls.set(call + 1);
if call == 2 {
pulled.notify_one();
release.notified().await;
}
Ok::<_, ()>((call < 3).then_some(call))
},
async |item| {
tokio::task::yield_now().await;
Ok(item)
},
|item| out.push(item),
);
let verify = async {
pulled.notified().await;
for _ in 0..3 {
tokio::task::yield_now().await;
}
assert_eq!(calls.get(), 3);
release.notify_one();
};
let (result, ()) = tokio::join!(run, verify);
result.unwrap();
assert_eq!(out, [0, 1, 2]);
assert_eq!(calls.get(), 4);
})
.unwrap();
}
#[test]
fn ordered_source_failure_fault_and_cancellation_release_pending_work() {
task::execute(true, async {
for fault in [false, true] {
let released = Cell::new(0);
let mut pulled = false;
let work = dever_runtime::ordered_loop!(
&str,
2,
async || {
if pulled {
if fault {
std::panic::panic_any(71u32);
}
return Err("source failed");
}
pulled = true;
Ok(Some(Released(&released)))
},
async |owned| {
let _owned = owned;
std::future::pending::<Result<(), &str>>().await
},
|_| (),
);
let result = AssertUnwindSafe(work).catch_unwind().await;
if fault {
assert_eq!(*result.unwrap_err().downcast::<u32>().unwrap(), 71);
} else {
assert_eq!(result.unwrap(), Err("source failed"));
}
assert_eq!(released.get(), 1);
}
let released = Cell::new(0);
{
let mut work = pin!(dever_runtime::ordered_loop!(
(),
2,
async || Ok::<_, ()>(Some(())),
async |()| {
let _owned = Released(&released);
std::future::pending::<Result<(), ()>>().await
},
|_| ()
));
poll_fn(|cx| {
assert!(work.as_mut().poll(cx).is_pending());
Poll::Ready(())
})
.await;
}
assert_eq!(released.get(), 2);
})
.unwrap();
}
#[test]
fn ordered_delivery_keeps_gaps_and_wrapping_sequence_numbers() {
for initial in [0usize, usize::MAX - 1] {
for order in [[0, 1, 2, 3], [3, 2, 1, 0], [2, 0, 3, 1], [1, 0, 3, 2]] {
let mut head = initial;
let mut ready = std::collections::VecDeque::new();
let mut output = Vec::new();
for offset in order {
dever_runtime::task::ordered::deliver(
initial.wrapping_add(offset),
offset,
&mut head,
&mut ready,
&mut |value| output.push(value),
);
}
assert_eq!(output, [0, 1, 2, 3]);
assert_eq!(head, initial.wrapping_add(4));
assert!(ready.is_empty());
}
}
}
+403
View File
@@ -0,0 +1,403 @@
//! 真正派生 Tokio 任务,检查领取、取消、后代清理和原始故障身份。
use dever_runtime::{
task::{self, Error, RunError},
value::{FaultInfo, fault},
};
use std::{
future::{Future, pending, poll_fn},
sync::{
Arc,
atomic::{AtomicBool, AtomicUsize, Ordering},
},
task::Poll,
time::{Duration, Instant},
};
struct Released(Arc<AtomicUsize>);
impl Drop for Released {
fn drop(&mut self) {
self.0.fetch_add(1, Ordering::SeqCst);
}
}
async fn started(flag: &AtomicBool) {
let begin = Instant::now();
while !flag.load(Ordering::SeqCst) {
assert!(
begin.elapsed() < Duration::from_secs(5),
"task did not start"
);
task::sleep(1).await.unwrap();
}
}
static CHILD: FaultInfo = FaultInfo {
message: "child arithmetic fault",
source: "worker.dever",
line: 4,
column: 7,
};
static PARENT: FaultInfo = FaultInfo {
message: "parent arithmetic fault",
source: "app.dever",
line: 8,
column: 2,
};
#[test]
fn scope_bounds_admission_reuses_capacity_and_moves_results() {
for capacity in [0, 65537] {
let called = AtomicBool::new(false);
let result = task::run(true, capacity, async |_| {
called.store(true, Ordering::SeqCst);
Ok::<_, ()>(())
});
assert_eq!(result.unwrap_err().kind(), std::io::ErrorKind::InvalidInput);
assert!(!called.load(Ordering::SeqCst));
}
let released = Arc::new(AtomicUsize::new(0));
task::run(true, 1, async |scope| {
let value = Released(released.clone());
let first = scope
.spawn_leaf(async move {
let _value = value;
pending::<()>().await
})
.unwrap();
let rejected = Released(released.clone());
let second = scope.spawn_leaf(async move {
drop(rejected);
});
assert!(matches!(second, Err(Error::Capacity)));
assert_eq!(released.load(Ordering::SeqCst), 1);
assert_eq!(first.stop().await, Ok(None));
assert_eq!(released.load(Ordering::SeqCst), 2);
let text = "owned result".repeat(1000);
let pointer = text.as_ptr();
let result = scope
.spawn_leaf(async move { text })
.unwrap()
.wait()
.await
.unwrap();
assert_eq!(result.as_ptr(), pointer);
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
#[test]
fn stop_preserves_already_completed_business_failure() {
task::run(true, 1, async |scope| {
let finished = Arc::new(AtomicBool::new(false));
let flag = finished.clone();
let task = scope
.spawn_leaf(async move {
flag.store(true, Ordering::SeqCst);
Err::<i64, _>("business rejected")
})
.unwrap();
started(&finished).await;
assert_eq!(task.stop().await, Ok(Some(Err("business rejected"))));
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
#[test]
fn stopping_parent_waits_for_real_descendant_destruction() {
let released = Arc::new(AtomicUsize::new(0));
let began = Arc::new(AtomicBool::new(false));
task::run(true, 2, async |scope| {
let value = Released(released.clone());
let flag = began.clone();
let parent = scope
.spawn(async move |child| {
let task = child
.spawn_leaf(async move {
let _value = value;
flag.store(true, Ordering::SeqCst);
pending::<()>().await;
})
.unwrap();
task.wait().await.unwrap();
})
.unwrap();
started(&began).await;
assert_eq!(released.load(Ordering::SeqCst), 0);
assert!(matches!(scope.spawn_leaf(async {}), Err(Error::Capacity)));
assert_eq!(parent.stop().await, Ok(None));
assert_eq!(released.load(Ordering::SeqCst), 1);
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
#[test]
fn stop_requests_cancellation_on_first_poll_not_construction() {
task::run(true, 1, async |scope| {
let began = Arc::new(AtomicBool::new(false));
let flag = began.clone();
let task = scope
.spawn_leaf(async move {
flag.store(true, Ordering::SeqCst);
42
})
.unwrap();
let stopping = task.stop();
started(&began).await;
assert_eq!(stopping.await, Ok(Some(42)));
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
#[test]
fn dropping_wait_or_stop_and_entry_fault_drain_pending_tasks() {
for (panic_at_entry, stop) in [(false, false), (true, false), (false, true), (true, true)] {
let released = Arc::new(AtomicUsize::new(0));
let began = Arc::new(AtomicBool::new(false));
let result = task::run::<(), ()>(true, 2, async |scope| {
let value = Released(released.clone());
let flag = began.clone();
let task = scope
.spawn_leaf(async move {
let _value = value;
flag.store(true, Ordering::SeqCst);
pending::<()>().await;
})
.unwrap();
started(&began).await;
let mut waiting = Box::pin(async move {
if stop {
task.stop().await.unwrap();
} else {
task.wait().await.unwrap();
}
});
poll_fn(|context| {
assert!(waiting.as_mut().poll(context).is_pending());
Poll::Ready(())
})
.await;
if panic_at_entry {
fault(&PARENT);
}
drop(waiting);
Ok(())
})
.unwrap();
assert_eq!(released.load(Ordering::SeqCst), 1);
if panic_at_entry {
let RunError::Fault {
primary,
additional,
} = result.unwrap_err()
else {
panic!("expected entry fault");
};
assert!(std::ptr::eq(
*primary.downcast_ref::<&'static FaultInfo>().unwrap(),
&PARENT
));
assert!(additional.is_empty());
} else {
result.unwrap();
}
}
}
#[test]
fn awaited_fault_keeps_source_identity_without_duplicate_reports() {
let result = task::run::<(), ()>(true, 2, async |scope| {
let task = scope
.spawn(async |child| {
let task = child
.spawn_leaf(async {
fault(&CHILD);
})
.unwrap();
task.wait().await.unwrap();
})
.unwrap();
task.wait().await.unwrap();
Ok(())
})
.unwrap();
let RunError::Fault {
primary,
additional,
} = result.unwrap_err()
else {
panic!("expected task fault");
};
assert!(std::ptr::eq(
*primary.downcast_ref::<&'static FaultInfo>().unwrap(),
&CHILD
));
assert!(additional.is_empty());
}
#[test]
fn unclaimed_faults_are_reported_without_overwriting_the_primary_error() {
for business_failure in [false, true] {
let began = Arc::new(AtomicBool::new(false));
let result = task::run(true, 1, async |scope| {
let flag = began.clone();
let task = scope
.spawn_leaf(async move {
flag.store(true, Ordering::SeqCst);
fault(&CHILD);
})
.unwrap();
started(&began).await;
drop(task);
if business_failure {
Err("primary business failure")
} else {
Ok(())
}
})
.unwrap();
let payload = match result.unwrap_err() {
RunError::Business {
error,
mut additional,
} => {
assert!(business_failure);
assert_eq!(error, "primary business failure");
assert_eq!(additional.len(), 1);
additional.remove(0)
}
RunError::Fault {
primary,
additional,
} => {
assert!(!business_failure);
assert!(additional.is_empty());
primary
}
};
assert!(std::ptr::eq(
*payload.downcast_ref::<&'static FaultInfo>().unwrap(),
&CHILD
));
}
}
#[test]
fn cancelling_before_first_poll_does_not_start_scoped_work() {
let began = Arc::new(AtomicBool::new(false));
task::run(true, 1, async |scope| {
let flag = began.clone();
let task = scope
.spawn(async move |_| {
flag.store(true, Ordering::SeqCst);
})
.unwrap();
assert_eq!(task.stop().await, Ok(None));
assert!(!began.load(Ordering::SeqCst));
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
#[test]
fn unclaimed_outputs_and_faults_are_released_before_entry_returns() {
let released = Arc::new(AtomicUsize::new(0));
let began = Arc::new(AtomicBool::new(false));
let result = task::run::<(), ()>(true, 2, async |scope| {
let value = Released(released.clone());
let flag = began.clone();
let output = scope
.spawn_leaf(async move {
flag.store(true, Ordering::SeqCst);
value
})
.unwrap();
started(&began).await;
began.store(false, Ordering::SeqCst);
let flag = began.clone();
let failed = scope
.spawn_leaf(async move {
flag.store(true, Ordering::SeqCst);
fault(&CHILD);
})
.unwrap();
started(&began).await;
drop((output, failed));
fault(&PARENT);
})
.unwrap();
assert_eq!(released.load(Ordering::SeqCst), 1);
let RunError::Fault {
primary,
additional,
} = result.unwrap_err()
else {
panic!("expected entry fault");
};
assert!(std::ptr::eq(
*primary.downcast_ref::<&'static FaultInfo>().unwrap(),
&PARENT
));
assert_eq!(additional.len(), 1);
assert!(std::ptr::eq(
*additional[0].downcast_ref::<&'static FaultInfo>().unwrap(),
&CHILD
));
}
#[test]
fn abandoned_parent_collects_its_own_fault_and_the_child_fault_once() {
let result = task::run::<(), ()>(true, 2, async |scope| {
let parent_began = Arc::new(AtomicBool::new(false));
let flag = parent_began.clone();
let parent = scope
.spawn(async move |child| {
let child_began = Arc::new(AtomicBool::new(false));
let child_flag = child_began.clone();
let task = child
.spawn_leaf(async move {
child_flag.store(true, Ordering::SeqCst);
fault(&CHILD);
})
.unwrap();
started(&child_began).await;
drop(task);
flag.store(true, Ordering::SeqCst);
fault(&PARENT);
})
.unwrap();
started(&parent_began).await;
drop(parent);
Ok(())
})
.unwrap();
let RunError::Fault {
primary,
mut additional,
} = result.unwrap_err()
else {
panic!("expected abandoned task faults");
};
additional.push(primary);
assert_eq!(additional.len(), 2);
for expected in [&PARENT, &CHILD] {
assert_eq!(
additional
.iter()
.filter(|value| std::ptr::eq(
*value.downcast_ref::<&'static FaultInfo>().unwrap(),
expected,
))
.count(),
1
);
}
}
+292
View File
@@ -0,0 +1,292 @@
//! 用握手控制真实工作线程,验证排队取消与已启动计算的收尾边界。
use dever_runtime::task::{self, DEFAULT_WORKERS, RunError};
use dever_runtime::value::{FaultInfo, fault};
use std::{
collections::HashSet,
future::{Future, poll_fn},
pin::pin,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
mpsc,
},
task::Poll,
time::Duration,
};
use tokio::sync::oneshot;
#[test]
fn workers_are_bounded_move_values_and_cancel_before_admission() {
task::run(true, DEFAULT_WORKERS + 1, async |scope| {
let mut tasks = Vec::new();
let mut releases = Vec::new();
let mut threads = HashSet::new();
for _ in 0..DEFAULT_WORKERS {
let (started, ready) = oneshot::channel();
let (release, gate) = mpsc::channel();
let text = String::from("owned worker input");
let address = text.as_ptr() as usize;
let task = scope
.spawn(async move |child| {
child
.parallel(move || {
started.send(std::thread::current().id()).unwrap();
gate.recv_timeout(Duration::from_secs(10)).unwrap();
assert_eq!(text.as_ptr() as usize, address);
(text, address)
})
.await
.unwrap()
})
.unwrap();
threads.insert(ready.await.unwrap());
tasks.push(task);
releases.push(release);
}
assert_eq!(threads.len(), DEFAULT_WORKERS);
assert!(!threads.contains(&std::thread::current().id()));
let executed = Arc::new(AtomicBool::new(false));
let flag = executed.clone();
let (entered, queued) = oneshot::channel();
let queued_task = scope
.spawn(async move |child| {
entered.send(()).unwrap();
child
.parallel(move || flag.store(true, Ordering::SeqCst))
.await
.unwrap();
})
.unwrap();
queued.await.unwrap();
// 工作线程仍全部占用,排队任务也必须立即停止。
assert_eq!(
tokio::time::timeout(Duration::from_secs(1), queued_task.stop())
.await
.unwrap(),
Ok(None)
);
assert!(!executed.load(Ordering::SeqCst));
let flag = executed.clone();
let queued_task = scope
.spawn_blocking(move || flag.store(true, Ordering::SeqCst))
.unwrap();
tokio::task::yield_now().await;
assert_eq!(
tokio::time::timeout(Duration::from_secs(1), queued_task.stop())
.await
.unwrap(),
Ok(None)
);
assert!(!executed.load(Ordering::SeqCst));
for release in releases {
release.send(()).unwrap();
}
for task in tasks {
let (text, address) = task.await.unwrap();
assert_eq!(text.as_ptr() as usize, address);
}
assert!(!executed.load(Ordering::SeqCst));
assert_eq!(
scope.parallel(|| Err::<(), _>("business")).await.unwrap(),
Err("business")
);
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
#[test]
fn stopping_or_timing_out_started_blocking_tasks_preserves_late_business_failure() {
for timed in [false, true] {
task::run(true, 1, async |scope| {
let (started, ready) = oneshot::channel();
let (release, gate) = mpsc::channel();
let task = scope
.spawn_blocking(move || {
started.send(()).unwrap();
gate.recv_timeout(Duration::from_secs(10)).unwrap();
Err::<(), _>("late business failure")
})
.unwrap();
ready.await.unwrap();
let mut ending = pin!(async move {
if timed {
let task::Timed::Expired(value) = task.timeout(1).await.unwrap() else {
panic!("must expire")
};
value
} else {
task.stop().await.unwrap()
}
});
poll_fn(|context| {
assert!(ending.as_mut().poll(context).is_pending());
Poll::Ready(())
})
.await;
task::sleep(5).await.unwrap();
poll_fn(|context| {
assert!(ending.as_mut().poll(context).is_pending());
Poll::Ready(())
})
.await;
release.send(()).unwrap();
assert_eq!(ending.await, Some(Err("late business failure")));
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
}
#[test]
fn group_stop_preserves_late_blocking_failure_and_releases_owned_output() {
let released = Arc::new(AtomicBool::new(false));
task::run(true, 1, async |scope| {
let (started, ready) = oneshot::channel();
let (release, gate) = mpsc::channel();
let mut group = task::Group::new(scope, 1).unwrap();
group
.run(|| {
scope.spawn_blocking(move || {
started.send(()).unwrap();
gate.recv_timeout(Duration::from_secs(10)).unwrap();
Err::<(), _>("late group failure")
})
})
.await
.unwrap()
.unwrap();
ready.await.unwrap();
let mut stopping = pin!(group.stop());
poll_fn(|context| {
assert!(stopping.as_mut().poll(context).is_pending());
Poll::Ready(())
})
.await;
release.send(()).unwrap();
assert_eq!(stopping.await, Ok(Err("late group failure")));
let owned = Released(released.clone());
let (started, ready) = oneshot::channel();
let work = scope
.spawn_blocking(move || {
started.send(()).unwrap();
owned
})
.unwrap();
ready.await.unwrap();
drop(work);
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
assert!(released.load(Ordering::SeqCst));
}
struct Released(Arc<AtomicBool>);
impl Drop for Released {
fn drop(&mut self) {
self.0.store(true, Ordering::SeqCst);
}
}
#[test]
fn cancellation_waits_for_running_worker_and_skips_later_steps() {
let released = Arc::new(AtomicBool::new(false));
let continued = Arc::new(AtomicBool::new(false));
task::run(true, 1, async |scope| {
let held = Released(released.clone());
let flag = continued.clone();
let (started, ready) = oneshot::channel();
let (release, gate) = mpsc::channel();
let task = scope
.spawn(async move |child| {
child
.parallel(move || {
let _held = held;
started.send(()).unwrap();
gate.recv_timeout(Duration::from_secs(10)).unwrap();
})
.await
.unwrap();
flag.store(true, Ordering::SeqCst);
})
.unwrap();
ready.await.unwrap();
let mut stopping = pin!(task.stop());
poll_fn(|context| {
assert!(stopping.as_mut().poll(context).is_pending());
Poll::Ready(())
})
.await;
assert!(!released.load(Ordering::SeqCst));
release.send(()).unwrap();
assert_eq!(stopping.await, Ok(None));
assert!(released.load(Ordering::SeqCst));
assert!(!continued.load(Ordering::SeqCst));
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
#[test]
fn worker_fault_keeps_original_payload_and_does_not_replace_business_error() {
static ORIGINAL: FaultInfo = FaultInfo {
message: "original worker fault",
source: "worker.dever",
line: 1,
column: 1,
};
let result = task::run::<(), ()>(true, 1, async |scope| {
scope.parallel(|| fault(&ORIGINAL)).await.unwrap();
Ok(())
})
.unwrap();
let Err(RunError::Fault {
primary,
additional,
}) = result
else {
panic!("expected fault")
};
assert!(std::ptr::eq(
*primary.downcast_ref::<&'static FaultInfo>().unwrap(),
&ORIGINAL
));
assert!(additional.is_empty());
let result = task::run::<(), _>(true, 1, async |scope| {
let (started, ready) = oneshot::channel();
let (release, gate) = mpsc::channel();
let task = scope
.spawn(async move |child| {
child
.parallel(move || {
started.send(()).unwrap();
gate.recv_timeout(Duration::from_secs(10)).unwrap();
fault(&ORIGINAL);
})
.await
.unwrap();
})
.unwrap();
ready.await.unwrap();
// 取消父任务后仍要保留工作线程实际发生的故障。
drop(task);
tokio::task::yield_now().await;
release.send(()).unwrap();
Err("primary business error")
})
.unwrap();
let Err(RunError::Business { error, additional }) = result else {
panic!("expected business error")
};
assert_eq!(error, "primary business error");
assert_eq!(additional.len(), 1);
assert!(std::ptr::eq(
*additional[0].downcast_ref::<&'static FaultInfo>().unwrap(),
&ORIGINAL
));
}
+52
View File
@@ -0,0 +1,52 @@
#!/usr/bin/python3
"""协议故障与半帧 fixture;不代替 SDK 验收。"""
import json
import os
import pathlib
import struct
import sys
def read():
size = struct.unpack('>I', sys.stdin.buffer.read(4))[0]
return json.loads(sys.stdin.buffer.read(size))
def write(value):
body = json.dumps(value).encode()
sys.stdout.buffer.write(struct.pack('>I', len(body)) + body)
sys.stdout.buffer.flush()
hello = read()
root = pathlib.Path(hello.pop('setting')['directory'])
hello['kind'] = 'ready'
write(hello)
remaining = None
while True:
frame = read()
kind = frame['kind']
if kind == 'health':
write(frame)
elif kind == 'shutdown':
(root / 'shutdown').touch()
write(frame)
break
elif kind == 'cancel':
(root / 'cancelled').touch()
if remaining is not None:
sys.stdout.buffer.write(remaining)
sys.stdout.buffer.flush()
remaining = None
else:
write(dict(kind='error', id=frame['id'], error='dever.cancelled', payload=None))
elif kind == 'call':
operation = frame['operation']
if operation in ('hang', 'partial'):
(root / 'started').touch()
if operation == 'partial':
body = json.dumps(dict(kind='result', id=frame['id'], payload={})).encode()
sys.stdout.buffer.write(struct.pack('>I', len(body)) + body[:5])
sys.stdout.buffer.flush()
remaining = body[5:]
elif operation == 'invalid':
write(dict(kind='result', id=frame['id'] + 1, payload={}))
else:
write(dict(kind='result', id=frame['id'], payload=dict(value=frame['payload']['value'], pid=os.getpid())))
+203
View File
@@ -0,0 +1,203 @@
use dever_runtime::{
task,
wire::json::Json,
worker::{self, Contract, Reply},
};
use std::{fs, io, os::unix::fs::PermissionsExt, sync::Arc};
mod performance;
static CONTRACT: Contract = Contract {
port: "demo.test",
schema: "runtime-worker-test",
adapter: "default",
capabilities: &[],
operations: &["echo", "hang", "partial", "invalid"],
};
struct Fixture {
directory: tempfile::TempDir,
path: Arc<dever_runtime::process::Executable>,
}
impl Fixture {
fn new() -> Self {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("worker");
fs::write(&path, include_str!("fixture.py")).unwrap();
fs::set_permissions(&path, fs::Permissions::from_mode(0o700)).unwrap();
Self {
directory,
path: Arc::new(path.as_path().into()),
}
}
fn setting(&self) -> Result<Json, String> {
Json::encode(&serde_json::json!({"directory":self.directory.path()}))
}
}
async fn finish(response: worker::Response) -> Result<serde_json::Value, String> {
let decoded = match &response.reply {
Reply::Result(payload) => serde_json::from_str(payload).map_err(|e| e.to_string()),
_ => Err("unexpected error".into()),
};
response.finish(decoded).await
}
async fn call(
scope: &task::Scope,
fixture: &Fixture,
operation: &'static str,
payload: serde_json::Value,
) -> io::Result<worker::Response> {
worker::call(
scope,
&fixture.path,
&CONTRACT,
|| fixture.setting(),
operation,
Json::encode(&payload).unwrap(),
)
.await
}
async fn marked(path: &std::path::Path) {
tokio::time::timeout(std::time::Duration::from_secs(2), async {
while !path.exists() {
tokio::time::sleep(std::time::Duration::from_millis(2)).await
}
})
.await
.unwrap();
}
#[test]
fn worker_cancel_drains_partial_frames_and_reuses_session() {
for operation in ["hang", "partial"] {
let fixture = Fixture::new();
let marker = fixture.directory.path().join("started");
let result = task::run(true, 16, async |scope| {
let before = finish(
call(scope, &fixture, "echo", serde_json::json!({"value":1}))
.await
.unwrap(),
)
.await
.unwrap();
let path = fixture.path.clone();
let setting = fixture.setting().unwrap();
let pending = scope
.spawn(move |child| async move {
worker::call(
&child,
&path,
&CONTRACT,
|| Ok(setting),
operation,
Json::encode(&serde_json::json!({})).unwrap(),
)
.await
})
.unwrap();
marked(&marker).await;
pending.stop().await.unwrap();
assert!(fixture.directory.path().join("cancelled").exists());
let after = finish(
call(scope, &fixture, "echo", serde_json::json!({"value":2}))
.await
.unwrap(),
)
.await
.unwrap();
assert_eq!(before["pid"], after["pid"]);
assert_eq!(after["value"], 2);
Ok::<_, String>(after["pid"].as_u64().unwrap())
})
.unwrap()
.unwrap();
assert!(!std::path::Path::new(&format!("/proc/{result}")).exists());
assert!(fixture.directory.path().join("shutdown").exists());
}
}
#[test]
fn worker_protocol_or_output_rejection_reaps_before_return() {
for invalid in [true, false] {
let fixture = Fixture::new();
task::run(true, 16, async |scope| {
let value = finish(
call(scope, &fixture, "echo", serde_json::json!({"value":1}))
.await
.unwrap(),
)
.await
.unwrap();
let pid = value["pid"].as_u64().unwrap();
if invalid {
assert!(
call(scope, &fixture, "invalid", serde_json::json!({}))
.await
.is_err()
);
} else {
assert!(
call(scope, &fixture, "echo", serde_json::json!({"value":2}))
.await
.unwrap()
.finish::<()>(Err("bad typed output".into()))
.await
.is_err()
);
}
assert!(!std::path::Path::new(&format!("/proc/{pid}")).exists());
let restarted = finish(
call(scope, &fixture, "echo", serde_json::json!({"value":3}))
.await
.unwrap(),
)
.await
.unwrap();
assert_ne!(restarted["pid"].as_u64().unwrap(), pid);
assert_eq!(restarted["value"], 3);
Ok::<_, String>(())
})
.unwrap()
.unwrap();
}
}
#[test]
fn worker_failure_invalidates_queued_calls_and_limits_restarts() {
let fixture = Fixture::new();
task::run(true, 16, async |scope| {
let response = call(scope, &fixture, "echo", serde_json::json!({"value":1}))
.await
.unwrap();
// 已持有响应直到类型验证,后续调用必定还在等待同一会话许可。
let queued = call(scope, &fixture, "echo", serde_json::json!({"value":2}));
tokio::pin!(queued);
tokio::select! {
biased;
_ = &mut queued => panic!("queued call crossed validation boundary"),
_ = tokio::task::yield_now() => {},
}
assert!(
response
.finish::<()>(Err("bad typed output".into()))
.await
.is_err()
);
assert!(queued.await.err().unwrap().to_string().contains("queued"));
for _ in 0..2 {
assert!(
call(scope, &fixture, "invalid", serde_json::json!({}))
.await
.err()
.unwrap()
.to_string()
.contains("out of order")
);
}
let error = call(scope, &fixture, "echo", serde_json::json!({"value":3}))
.await
.err()
.unwrap();
assert!(error.to_string().contains("restart budget"), "{error}");
Ok::<_, String>(())
})
.unwrap()
.unwrap();
}
+77
View File
@@ -0,0 +1,77 @@
//! 固定轮次的真实 Worker 回包对照;启动和输入准备在计时外,原始样本全部输出。
use super::*;
use std::{path::PathBuf, time::Instant};
static BENCH: Contract = Contract {
port: "demo.bench",
schema: "worker-reply-bench",
adapter: "default",
capabilities: &[],
operations: &["echo"],
};
#[derive(serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct Echo {
out: String,
}
async fn echo(
scope: &task::Scope,
executable: &Arc<dever_runtime::process::Executable>,
input: Json,
) -> String {
let response = worker::call(
scope,
executable,
&BENCH,
|| Ok(Json::null()),
"echo",
input,
)
.await
.unwrap();
let decoded = match &response.reply {
Reply::Result(payload) => {
serde_json::from_slice::<Echo>(payload.as_ref()).map_err(|e| e.to_string())
}
_ => Err("expected echo result".into()),
};
response.finish(decoded).await.unwrap().out
}
#[test]
#[ignore = "explicit release performance probe; requires precompiled worker fixture"]
fn worker_reply_cost() {
let fixture = PathBuf::from(
std::env::var_os("DEVER_WORKER_BENCH_FIXTURE")
.expect("precompiled Worker fixture is required"),
);
let executable = Arc::new(fixture.as_path().into());
task::run(true, 32, async |scope| {
println!("case,sample,iterations,elapsed_ns,checksum");
for (size, iterations) in [(64, 512), (65_536, 64), (1_048_576, 8)] {
let text = "雪🙂".repeat(size / 7);
let input = Json::encode(&serde_json::json!({"value": text})).unwrap();
assert_eq!(echo(scope, &executable, input.clone()).await, text);
// 一次预热和七次测量;响应内容核对在计时后进行,保留所有响应到本轮结束。
for sample in -1..7 {
let inputs = vec![input.clone(); iterations];
let mut results = Vec::with_capacity(iterations);
let started = Instant::now();
for input in inputs {
results.push(echo(scope, &executable, input).await);
}
let elapsed = started.elapsed().as_nanos();
assert!(results.iter().all(|value| *value == text));
println!(
"worker_reply_{size},{sample},{iterations},{elapsed},{}",
text.len() * iterations
);
}
}
Ok::<_, String>(())
})
.unwrap()
.unwrap();
}