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

+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();
}