Dever v0.0.2
This commit is contained in:
commit
e6e175ebcf
816 files changed
+120349
No files matched your search
@@ -0,0 +1,163 @@
|
||||
//! 独立 Job 对端的 SQL 业务;两种资源调度共用同一队列合同。
|
||||
use deadpool_sqlite::rusqlite::{Connection, OptionalExtension, TransactionBehavior, params};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
error::Error,
|
||||
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
|
||||
pub(crate) type Result<T> = std::result::Result<T, Box<dyn Error + Send + Sync>>;
|
||||
#[cfg(not(feature = "contract"))]
|
||||
pub(crate) const TARGET: &str = "benchmark.queue.publish";
|
||||
#[cfg(not(feature = "contract"))]
|
||||
pub(crate) const SCHEMA: &str = "Payload{name:Text,amount:Int}";
|
||||
// 完整合同对照保留与实际 Dever fixture 相同的持久声明,避免行宽差异改变 B-tree 成本。
|
||||
#[cfg(feature = "contract")]
|
||||
pub(crate) const TARGET: &str = "benchmark.queue.job.publish";
|
||||
#[cfg(feature = "contract")]
|
||||
pub(crate) const SCHEMA: &str = "550a5abbd4954e48b26bf2d51a821e0ce6b143622a82373344ded0ee8aef124a";
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Payload {
|
||||
pub(crate) name: String,
|
||||
pub(crate) amount: i64,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Batch {
|
||||
pub(crate) inputs: Vec<Payload>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Submit {
|
||||
pub(crate) input: Payload,
|
||||
pub(crate) key: String,
|
||||
}
|
||||
pub(crate) struct Claim {
|
||||
pub(crate) id: String,
|
||||
pub(crate) token: String,
|
||||
pub(crate) payload: String,
|
||||
pub(crate) attempt: i64,
|
||||
}
|
||||
|
||||
pub(crate) fn now() -> i64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_millis()
|
||||
.try_into()
|
||||
.unwrap()
|
||||
}
|
||||
pub(crate) fn identifier() -> Result<String> {
|
||||
let mut bytes = [0; 16];
|
||||
getrandom::getrandom(&mut bytes).map_err(|e| e.to_string())?;
|
||||
Ok(format!("{:032x}", u128::from_be_bytes(bytes)))
|
||||
}
|
||||
|
||||
pub(crate) fn submit(connection: &mut Connection, inputs: Vec<Submit>) -> Result<Vec<String>> {
|
||||
let tx = connection.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
let mut ids = Vec::with_capacity(inputs.len());
|
||||
for value in inputs {
|
||||
ids.push(enqueue(&tx, value)?);
|
||||
}
|
||||
tx.commit()?;
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
pub(crate) fn enqueue(connection: &Connection, value: Submit) -> Result<String> {
|
||||
if value.key.is_empty() || value.key.len() > 1024 {
|
||||
return Err("invalid key".into());
|
||||
}
|
||||
let id = identifier()?;
|
||||
let payload = serde_json::to_string(&value.input)?;
|
||||
let inserted = connection.prepare_cached("INSERT INTO _dever_job(id,target,payload,schema,execution,execution_tenant,task_key,state,retries,timeout_ms,available_at,created_at) VALUES (?1,?2,?3,?4,'{\"kind\":\"System\",\"tenant\":null}',0,?5,'pending',2,1000,?6,?6) ON CONFLICT(execution_tenant,target,task_key) WHERE state IN ('pending','running') DO NOTHING")?
|
||||
.execute(params![id, TARGET, payload, SCHEMA, value.key, now()])?;
|
||||
Ok(if inserted == 1 {
|
||||
id
|
||||
} else {
|
||||
connection.prepare_cached("SELECT id FROM _dever_job WHERE execution_tenant=0 AND target=?1 AND task_key=?2 AND state IN ('pending','running')")?
|
||||
.query_row(params![TARGET, value.key], |row| row.get(0))?
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn claim(connection: &mut Connection) -> Result<Option<Claim>> {
|
||||
let tx = connection.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
let clock = now();
|
||||
tx.prepare_cached("UPDATE _dever_job SET state=CASE WHEN attempt >= retries THEN 'dead' ELSE 'pending' END,token=NULL,lease_until=NULL,error='lease expired' WHERE id IN (SELECT id FROM _dever_job WHERE state='running' AND lease_until<=?1 ORDER BY lease_until,id LIMIT 256)")?.execute([clock])?;
|
||||
let token = identifier()?;
|
||||
let value = tx.prepare_cached("SELECT id,payload,attempt FROM _dever_job WHERE state='pending' AND available_at<=?1 AND attempt<retries ORDER BY available_at,id LIMIT 1")?
|
||||
.query_row([clock], |row| Ok(Claim { id:row.get(0)?, payload:row.get(1)?, attempt:row.get::<_,i64>(2)?+1, token })).optional()?;
|
||||
if let Some(value) = &value {
|
||||
tx.prepare_cached(
|
||||
"UPDATE _dever_job SET state='running',attempt=?1,token=?2,lease_until=?3 WHERE id=?4",
|
||||
)?
|
||||
.execute(params![value.attempt, value.token, clock + 10000, value.id])?;
|
||||
}
|
||||
tx.commit()?;
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
pub(crate) fn transition(
|
||||
connection: &Connection,
|
||||
claim: &Claim,
|
||||
state: &str,
|
||||
error: Option<&str>,
|
||||
) -> Result<()> {
|
||||
let clock = now();
|
||||
let changed = connection.prepare_cached("UPDATE _dever_job SET state=?1,available_at=?2,error=?3,token=NULL,lease_until=NULL WHERE id=?4 AND state='running' AND token=?5 AND lease_until>?6")?
|
||||
.execute(params![state, clock+1, error, claim.id, claim.token, clock])?;
|
||||
if changed != 1 {
|
||||
return Err("lease ownership lost".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn apply(connection: &mut Connection, claim: Claim) -> Result<()> {
|
||||
let input: Payload = serde_json::from_str(&claim.payload)?;
|
||||
let deadline = Instant::now() + Duration::from_millis(1000);
|
||||
connection.progress_handler(1000, Some(move || Instant::now() >= deadline))?;
|
||||
let outcome = (|| -> Result<bool> {
|
||||
let tx = connection.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
let saved = insert(&tx, input)?;
|
||||
if saved.3 < 0 {
|
||||
return Ok(false);
|
||||
}
|
||||
transition(&tx, &claim, "completed", None)?;
|
||||
if Instant::now() >= deadline {
|
||||
return Err("handler deadline expired".into());
|
||||
}
|
||||
tx.commit()?;
|
||||
Ok(true)
|
||||
})();
|
||||
connection.progress_handler(0, None::<fn() -> bool>)?;
|
||||
if !outcome? {
|
||||
let tx = connection.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
transition(
|
||||
&tx,
|
||||
&claim,
|
||||
if claim.attempt >= 2 {
|
||||
"dead"
|
||||
} else {
|
||||
"pending"
|
||||
},
|
||||
Some("handler failed"),
|
||||
)?;
|
||||
tx.commit()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn insert(connection: &Connection, input: Payload) -> Result<(i64, i64, String, i64)> {
|
||||
let amount = input
|
||||
.amount
|
||||
.checked_mul(3)
|
||||
.and_then(|n| n.checked_add(7))
|
||||
.ok_or("amount overflow")?;
|
||||
let mut statement = connection.prepare_cached("INSERT INTO benchmark_queue(created_at,name,amount) VALUES (?1,?2,?3) RETURNING id,created_at,name,amount")?;
|
||||
let mut rows = statement.query(params![now(), input.name.trim(), amount])?;
|
||||
let row = rows.next()?.ok_or("missing inserted row")?;
|
||||
let saved = (row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?);
|
||||
rows.next()?;
|
||||
Ok(saved)
|
||||
}
|
||||
Reference in new issue
Block a user