Dever v0.0.2
This commit is contained in:
commit
e6e175ebcf
816 files changed
+120349
No files matched your search
@@ -0,0 +1,148 @@
|
||||
//! 独立权限查询对端;复用官方 SQLite 资源模块,不链接 Dever 运行库。
|
||||
mod sqlite_resource;
|
||||
use deadpool_sqlite::{Pool, rusqlite::Connection};
|
||||
use sqlite_resource::{Lease, Result, Work, pool};
|
||||
use std::{
|
||||
path::Path,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
const ROLE: &str = "SELECT EXISTS(SELECT 1 FROM _dever_user_role u JOIN _dever_role r ON r.site=u.site AND r.id=u.role_id WHERE u.site=$1 AND u.user_id=$2 AND r.enabled=TRUE AND (r.all_permissions=TRUE OR EXISTS(SELECT 1 FROM _dever_role_permission g WHERE g.site=r.site AND g.role_id=r.id AND g.permission_key=$3)))";
|
||||
const LOCAL: &str = "SELECT EXISTS(SELECT 1 FROM _dever_user_role u JOIN _dever_role r ON r.site=u.site AND r.id=u.role_id WHERE u.site=$1 AND u.user_id=$2 AND r.enabled=TRUE AND (r.all_permissions=TRUE OR EXISTS(SELECT 1 FROM _dever_role_permission g WHERE g.site=r.site AND g.role_id=r.id AND g.permission_key=$3)) AND EXISTS(SELECT 1 FROM _dever_permission p WHERE p.site=u.site AND p.key=$3 AND p.active=TRUE))";
|
||||
const CAPABILITY: &str = "capability:content.article.admin.00000000-0000-0000-0000-00000000002a";
|
||||
|
||||
fn prepare(path: &Path) -> Result<()> {
|
||||
drop(
|
||||
std::fs::OpenOptions::new()
|
||||
.create_new(true)
|
||||
.write(true)
|
||||
.open(path)?,
|
||||
);
|
||||
let connection = Connection::open(path)?;
|
||||
connection.execute_batch(
|
||||
"CREATE TABLE _dever_permission(key TEXT PRIMARY KEY,site TEXT NOT NULL,component TEXT NOT NULL,domain TEXT NOT NULL,action TEXT NOT NULL,active BOOLEAN NOT NULL CHECK(active IN (0,1)),method TEXT NOT NULL,kind TEXT NOT NULL);
|
||||
CREATE TABLE _dever_role(site TEXT NOT NULL,id TEXT NOT NULL,name TEXT NOT NULL,all_permissions BOOLEAN NOT NULL CHECK(all_permissions IN (0,1)),enabled BOOLEAN NOT NULL CHECK(enabled IN (0,1)),protected BOOLEAN NOT NULL CHECK(protected IN (0,1)),PRIMARY KEY(site,id));
|
||||
CREATE TABLE _dever_user_role(site TEXT NOT NULL,user_id INTEGER NOT NULL CHECK(user_id>0),role_id TEXT NOT NULL,PRIMARY KEY(site,user_id,role_id),FOREIGN KEY(site,role_id) REFERENCES _dever_role(site,id) ON DELETE CASCADE);
|
||||
CREATE TABLE _dever_role_permission(site TEXT NOT NULL,role_id TEXT NOT NULL,permission_key TEXT NOT NULL,PRIMARY KEY(site,role_id,permission_key),FOREIGN KEY(site,role_id) REFERENCES _dever_role(site,id) ON DELETE CASCADE);
|
||||
CREATE TABLE _dever_tenant_component(tenant INTEGER NOT NULL,component TEXT NOT NULL,enabled BOOLEAN NOT NULL,PRIMARY KEY(tenant,component));
|
||||
CREATE TABLE _dever_auth_capability(key TEXT PRIMARY KEY,component TEXT NOT NULL,domain TEXT NOT NULL,site TEXT NOT NULL,action TEXT NOT NULL,active BOOLEAN NOT NULL);
|
||||
INSERT INTO _dever_permission VALUES ('content.article.admin.read','admin','content','article','read',TRUE,'GET','http');
|
||||
INSERT INTO _dever_tenant_component VALUES (1,'content',TRUE);
|
||||
INSERT INTO _dever_auth_capability VALUES ('capability:content.article.admin.00000000-0000-0000-0000-00000000002a','content','article','admin','00000000-0000-0000-0000-00000000002a',TRUE);
|
||||
INSERT INTO _dever_role VALUES ('admin','owner','Owner',TRUE,TRUE,TRUE);
|
||||
INSERT INTO _dever_user_role VALUES ('admin',7,'owner');",
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn authorize(
|
||||
work: &Work,
|
||||
lease: &mut Option<Lease>,
|
||||
catalog: Option<&Pool>,
|
||||
user: i64,
|
||||
) -> Result<bool> {
|
||||
let sql = if let Some(catalog) = catalog {
|
||||
let mut catalog_lease = Some(Lease {
|
||||
object: Some(catalog.get().await?),
|
||||
reusable: true,
|
||||
});
|
||||
let exists = work.call(&mut catalog_lease, Duration::from_secs(2), |connection| {
|
||||
Ok(connection.prepare_cached("SELECT EXISTS(SELECT 1 FROM _dever_permission WHERE site=$1 AND key=$2 AND active=TRUE)")?
|
||||
.query_row(["admin", "content.article.admin.read"], |row| row.get::<_,bool>(0))?)
|
||||
}).await?;
|
||||
if !exists {
|
||||
return Ok(false);
|
||||
}
|
||||
ROLE
|
||||
} else {
|
||||
LOCAL
|
||||
};
|
||||
work.call(lease, Duration::from_secs(2), move |connection| {
|
||||
Ok(connection.prepare_cached(sql)?.query_row(
|
||||
deadpool_sqlite::rusqlite::params!["admin", user, "content.article.admin.read"],
|
||||
|row| row.get(0),
|
||||
)?)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
async fn authorize_tenant(
|
||||
work: &Work, lease: &mut Option<Lease>, catalog: &Pool, user: i64, key: &'static str,
|
||||
) -> Result<bool> {
|
||||
let mut control = Some(Lease { object: Some(catalog.get().await?), reusable: true });
|
||||
if key.starts_with("capability:") {
|
||||
use deadpool_sqlite::rusqlite::OptionalExtension;
|
||||
let permission = work.call(lease, Duration::from_secs(2), move |connection| {
|
||||
Ok(connection.prepare_cached("SELECT c.component,EXISTS(SELECT 1 FROM _dever_user_role u JOIN _dever_role r ON r.site=u.site AND r.id=u.role_id WHERE u.site=$1 AND (r.all_permissions=TRUE OR EXISTS(SELECT 1 FROM _dever_role_permission g WHERE g.site=r.site AND g.role_id=r.id AND g.permission_key=$2)) AND u.user_id=$3 AND r.enabled=TRUE) FROM _dever_auth_capability c WHERE c.site=$1 AND c.key=$2 AND c.active=TRUE")?
|
||||
.query_row(deadpool_sqlite::rusqlite::params!["admin",key,user], |row| Ok((row.get::<_,String>(0)?, row.get::<_,bool>(1)?))).optional()?)
|
||||
}).await?;
|
||||
let Some((component, allowed)) = permission else { return Ok(false) };
|
||||
let enabled = work.call(&mut control, Duration::from_secs(2), move |connection| {
|
||||
Ok(connection.prepare_cached("SELECT EXISTS(SELECT 1 FROM _dever_tenant_component WHERE tenant=$1 AND component=$2 AND enabled=TRUE)")?
|
||||
.query_row(deadpool_sqlite::rusqlite::params![1,component], |row| row.get::<_,bool>(0))?)
|
||||
}).await?;
|
||||
return Ok(enabled && allowed);
|
||||
} else {
|
||||
let enabled = work.call(&mut control, Duration::from_secs(2), move |connection| {
|
||||
Ok(connection.prepare_cached("SELECT EXISTS(SELECT 1 FROM _dever_permission p WHERE site=$1 AND key=$2 AND active=TRUE AND EXISTS(SELECT 1 FROM _dever_tenant_component c WHERE c.tenant=$3 AND c.component=p.component AND c.enabled=TRUE))")?
|
||||
.query_row(deadpool_sqlite::rusqlite::params!["admin", key, 1], |row| row.get::<_,bool>(0))?)
|
||||
}).await?;
|
||||
if !enabled { return Ok(false) }
|
||||
}
|
||||
work.call(lease, Duration::from_secs(2), move |connection| {
|
||||
Ok(connection.prepare_cached(ROLE)?.query_row(
|
||||
deadpool_sqlite::rusqlite::params!["admin",user,key], |row| row.get(0))?)
|
||||
}).await
|
||||
}
|
||||
|
||||
async fn measure(first: &str, second: &str, tenant: bool) -> Result<()> {
|
||||
let database = pool(first, 1).await?;
|
||||
let separate = pool(second, 1).await?;
|
||||
let work = Work::new();
|
||||
println!("case,sample,iterations,elapsed_ns,allowed");
|
||||
let cases = if tenant { [("tenant",Some(&separate)), ("capability",Some(&separate))] }
|
||||
else { [("same",None), ("separate",Some(&separate))] };
|
||||
for (name, catalog) in cases {
|
||||
for (user, expected) in [(7, true), (8, false)] {
|
||||
let mut lease = Some(Lease {
|
||||
object: Some(database.get().await?),
|
||||
reusable: true,
|
||||
});
|
||||
for sample in -1..7 {
|
||||
let started = Instant::now();
|
||||
let mut allowed = 0;
|
||||
for _ in 0..256 {
|
||||
let result = if tenant {
|
||||
let key = if name == "tenant" { "content.article.admin.read" } else { CAPABILITY };
|
||||
authorize_tenant(&work, &mut lease, &separate, user, key).await?
|
||||
} else { authorize(&work, &mut lease, catalog, user).await? };
|
||||
assert_eq!(result, expected);
|
||||
allowed += usize::from(result);
|
||||
}
|
||||
println!(
|
||||
"{name}_{expected},{sample},256,{},{}",
|
||||
started.elapsed().as_nanos(),
|
||||
allowed
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
work.finish().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let directory = std::env::args()
|
||||
.nth(1)
|
||||
.ok_or("provide a new fixture directory")?;
|
||||
let directory = Path::new(&directory);
|
||||
std::fs::create_dir(directory)?;
|
||||
let first = directory.join("roles.sqlite");
|
||||
let second = directory.join("catalog.sqlite");
|
||||
prepare(&first)?;
|
||||
prepare(&second)?;
|
||||
tokio::runtime::Builder::new_current_thread()
|
||||
.enable_time()
|
||||
.build()?
|
||||
.block_on(measure(first.to_str().unwrap(), second.to_str().unwrap(), std::env::args().nth(2).as_deref()==Some("--tenant")))
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
cmd submit = app.submit
|
||||
cmd submitAll = app.submitAll
|
||||
job publish(input: app.Payload) retry(2) timeout(1000) = app.apply
|
||||
@@ -0,0 +1,21 @@
|
||||
type Payload { name: Text, amount: Int }
|
||||
|
||||
flow submit(input: Payload, key: Text) (id: Id)
|
||||
| step | kind | do |
|
||||
| id | calc | enqueue(job.publish, input, key) |
|
||||
|
||||
type Submission { key: Text, payload: Payload }
|
||||
|
||||
loop submissions(inputs: List<Payload>) (result: List<Submission>)
|
||||
| each input in inputs | result |
|
||||
| result | list Submission { key = input.name, payload = input } |
|
||||
|
||||
flow submitAll(inputs: List<Payload>) (ids: List<Id>)
|
||||
| step | kind | do |
|
||||
| ids | calc | enqueueMany(job.publish, submissions(inputs)) |
|
||||
|
||||
flow apply(input: Payload) ()
|
||||
| step | kind | do |
|
||||
| amount | calc | input.amount * 3 + 7 |
|
||||
| saved | data | data.create({ name = input.name, amount = amount }) |
|
||||
| - | check | saved.amount >= 0 else Conflict |
|
||||
@@ -0,0 +1,103 @@
|
||||
//! System Job 的完整持久合同参考;共用基础队列操作,不链接 Dever 运行库。
|
||||
use crate::base_queue;
|
||||
pub(crate) use base_queue::{Batch, Payload, Submit, enqueue, insert, transition};
|
||||
use base_queue::{Result, SCHEMA, TARGET, identifier, now};
|
||||
use deadpool_sqlite::rusqlite::{Connection, OptionalExtension, TransactionBehavior, params};
|
||||
use serde::Deserialize;
|
||||
|
||||
pub(crate) struct Claim {
|
||||
value: base_queue::Claim,
|
||||
target: String,
|
||||
schema: String,
|
||||
execution: String,
|
||||
tenant: i64,
|
||||
retries: i64,
|
||||
timeout_ms: i64,
|
||||
}
|
||||
impl std::ops::Deref for Claim {
|
||||
type Target = base_queue::Claim;
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.value
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Rejected(String);
|
||||
impl std::fmt::Display for Rejected {
|
||||
fn fmt(&self, out: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
out.write_str(&self.0)
|
||||
}
|
||||
}
|
||||
impl std::error::Error for Rejected {}
|
||||
fn rejected(cause: impl std::fmt::Display) -> Box<dyn std::error::Error + Send + Sync> {
|
||||
Box::new(Rejected(cause.to_string()))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(tag = "kind", deny_unknown_fields)]
|
||||
enum Execution {
|
||||
System { tenant: Option<i64> },
|
||||
}
|
||||
|
||||
pub(crate) fn decode(claim: &Claim) -> Result<Payload> {
|
||||
if claim.target != TARGET
|
||||
|| claim.schema != SCHEMA
|
||||
|| claim.tenant != 0
|
||||
|| claim.retries != 2
|
||||
|| claim.timeout_ms != 1000
|
||||
{
|
||||
return Err(rejected(
|
||||
"queued Job differs from its declaration or physical queue",
|
||||
));
|
||||
}
|
||||
if claim.execution.len() > 16 * 1024 * 1024 || claim.payload.len() > 16 * 1024 * 1024 {
|
||||
return Err(rejected("Job JSON exceeds 16 MiB"));
|
||||
}
|
||||
let Execution::System { tenant } = serde_json::from_str(&claim.execution).map_err(rejected)?;
|
||||
if tenant.is_some() {
|
||||
return Err(rejected(
|
||||
"Job execution tenant differs from its physical queue",
|
||||
));
|
||||
}
|
||||
// Serde 的结构体默认也接受位置数组;Dever 的具名载荷合同只接受对象。
|
||||
struct Object;
|
||||
impl<'de> serde::de::Visitor<'de> for Object {
|
||||
type Value = Payload;
|
||||
fn expecting(&self, out: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
out.write_str("Job payload object")
|
||||
}
|
||||
fn visit_map<A: serde::de::MapAccess<'de>>(self, fields: A) -> std::result::Result<Payload, A::Error> {
|
||||
Payload::deserialize(serde::de::value::MapAccessDeserializer::new(fields))
|
||||
}
|
||||
}
|
||||
let mut decoder = serde_json::Deserializer::from_str(&claim.payload);
|
||||
let value = serde::Deserializer::deserialize_map(&mut decoder, Object).map_err(rejected)?;
|
||||
decoder.end().map_err(rejected)?;
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
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,target,substr(payload,1,16777217),schema,substr(execution,1,16777217),retries,timeout_ms,attempt,execution_tenant FROM _dever_job
|
||||
WHERE id=(SELECT id FROM (
|
||||
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
|
||||
))"
|
||||
)?.query_row([clock], |row| Ok(Claim {
|
||||
value: base_queue::Claim { id: row.get(0)?, payload: row.get(2)?, attempt: row.get::<_,i64>(7)?+1, token },
|
||||
target: row.get(1)?, schema: row.get(3)?, execution: row.get(4)?,
|
||||
retries: row.get(5)?, timeout_ms: row.get(6)?, tenant: row.get(8)?,
|
||||
})).optional()?;
|
||||
if let Some(value) = &value {
|
||||
tx.prepare_cached("UPDATE _dever_job SET state='running',attempt=?1,token=?2,lease_until=?3,error=CASE WHEN state='running' THEN 'lease expired' ELSE error END WHERE id=?4")?
|
||||
.execute(params![value.attempt,value.token,clock+10000,value.id])?;
|
||||
}
|
||||
tx.commit()?;
|
||||
Ok(value)
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
type Queue { name: Text, amount: Int }
|
||||
@@ -0,0 +1,22 @@
|
||||
type Payload { name: Text, amount: Int }
|
||||
|
||||
submit(input: Payload, key: Text) (id: Id) {
|
||||
id = dever.job.enqueue(job.publish, input, key)
|
||||
}
|
||||
|
||||
submitOne(input: Payload) (id: Id) {
|
||||
id = submit(input, input.name)
|
||||
}
|
||||
|
||||
submitAll(inputs: List<Payload>) (ids: List<Id>) {
|
||||
ids = each(submitOne, inputs)
|
||||
}
|
||||
|
||||
apply(input: Payload) () {
|
||||
amount = input.amount * 3 + 7
|
||||
saved = model.create({ name = input.name, amount = amount })
|
||||
reject(saved.amount < 0)
|
||||
}
|
||||
|
||||
reject(failed: true) () { fail(dever.api.Error.Conflict) }
|
||||
reject(failed: false) () {}
|
||||
@@ -0,0 +1,284 @@
|
||||
// 独立 database/sql 队列参考;事务和取消交给驱动,信号后等待在途事务完成。
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
_ "github.com/mattn/go-sqlite3"
|
||||
"io"
|
||||
"math"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
const target = "benchmark.queue.publish"
|
||||
const schema = "Payload{name:Text,amount:Int}"
|
||||
|
||||
type Payload struct {
|
||||
Name string "json:\"name\""
|
||||
Amount int64 "json:\"amount\""
|
||||
}
|
||||
type Submit struct {
|
||||
Input Payload "json:\"input\""
|
||||
Key string "json:\"key\""
|
||||
}
|
||||
type Batch struct {
|
||||
Inputs []Payload "json:\"inputs\""
|
||||
}
|
||||
type Claim struct {
|
||||
ID, Payload, Token string
|
||||
Attempt int64
|
||||
}
|
||||
|
||||
func identifier() (string, error) {
|
||||
var value [16]byte
|
||||
_, err := rand.Read(value[:])
|
||||
return hex.EncodeToString(value[:]), err
|
||||
}
|
||||
|
||||
func decode(raw string, out any) error {
|
||||
decoder := json.NewDecoder(bytes.NewBufferString(raw))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(out); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := decoder.Decode(new(any)); err != io.EOF {
|
||||
return fmt.Errorf("trailing JSON: %v", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func submit(db *sql.DB, inputs []Submit) ([]string, error) {
|
||||
tx, err := db.Begin()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
insert, err := tx.Prepare("INSERT INTO _dever_job(id,target,payload,schema,execution,execution_tenant,task_key,state,retries,timeout_ms,available_at,created_at) VALUES (?,?,?,?,'{\"kind\":\"System\",\"tenant\":null}',0,?,'pending',2,1000,?,?) ON CONFLICT(execution_tenant,target,task_key) WHERE state IN ('pending','running') DO NOTHING")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer insert.Close()
|
||||
find, err := tx.Prepare("SELECT id FROM _dever_job WHERE execution_tenant=0 AND target=? AND task_key=? AND state IN ('pending','running')")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer find.Close()
|
||||
ids := make([]string, 0, len(inputs))
|
||||
for _, value := range inputs {
|
||||
if len(value.Key) == 0 || len(value.Key) > 1024 {
|
||||
return nil, errors.New("invalid key")
|
||||
}
|
||||
id, err := identifier()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
payload, err := json.Marshal(value.Input)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
clock := time.Now().UnixMilli()
|
||||
result, err := insert.Exec(id, target, string(payload), schema, value.Key, clock, clock)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
changed, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if changed == 0 {
|
||||
if err = find.QueryRow(target, value.Key).Scan(&id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
return ids, tx.Commit()
|
||||
}
|
||||
|
||||
func claim(db *sql.DB) (*Claim, error) {
|
||||
tx, err := db.Begin()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
clock := time.Now().UnixMilli()
|
||||
_, err = tx.Exec("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<=? ORDER BY lease_until,id LIMIT 256)", clock)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var value Claim
|
||||
value.Token, err = identifier()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = tx.QueryRow("SELECT id,payload,attempt FROM _dever_job WHERE state='pending' AND available_at<=? AND attempt<retries ORDER BY available_at,id LIMIT 1", clock).Scan(&value.ID, &value.Payload, &value.Attempt)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, tx.Commit()
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
value.Attempt++
|
||||
_, err = tx.Exec("UPDATE _dever_job SET state='running',attempt=?,token=?,lease_until=? WHERE id=?", value.Attempt, value.Token, clock+10000, value.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &value, tx.Commit()
|
||||
}
|
||||
|
||||
func transition(ctx context.Context, tx *sql.Tx, value *Claim, state string, failure any) error {
|
||||
clock := time.Now().UnixMilli()
|
||||
result, err := tx.ExecContext(ctx, "UPDATE _dever_job SET state=?,available_at=?,error=?,token=NULL,lease_until=NULL WHERE id=? AND state='running' AND token=? AND lease_until>?", state, clock+1, failure, value.ID, value.Token, clock)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
changed, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if changed != 1 {
|
||||
return errors.New("lease ownership lost")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func apply(db *sql.DB, value *Claim) (bool, error) {
|
||||
var input Payload
|
||||
if err := decode(value.Payload, &input); err != nil {
|
||||
return false, err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
tx, err := db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if input.Amount > math.MaxInt64/3 || input.Amount < math.MinInt64/3 {
|
||||
return false, errors.New("amount overflow")
|
||||
}
|
||||
amount := input.Amount * 3
|
||||
if amount > math.MaxInt64-7 {
|
||||
return false, errors.New("amount overflow")
|
||||
}
|
||||
amount += 7
|
||||
var id, created, stored int64
|
||||
var name string
|
||||
err = tx.QueryRowContext(ctx, "INSERT INTO benchmark_queue(created_at,name,amount) VALUES (?,?,?) RETURNING id,created_at,name,amount", time.Now().UnixMilli(), strings.TrimSpace(input.Name), amount).Scan(&id, &created, &name, &stored)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if stored < 0 {
|
||||
return false, nil
|
||||
}
|
||||
if err = transition(ctx, tx, value, "completed", nil); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, tx.Commit()
|
||||
}
|
||||
|
||||
func work(db *sql.DB, value *Claim) error {
|
||||
accepted, err := apply(db, value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if accepted {
|
||||
return nil
|
||||
}
|
||||
tx, err := db.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
state := "pending"
|
||||
if value.Attempt >= 2 {
|
||||
state = "dead"
|
||||
}
|
||||
if err = transition(context.Background(), tx, value, state, "handler failed"); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func run() error {
|
||||
db, err := sql.Open("sqlite3", "file:"+os.Args[1]+"?mode=rw&_journal_mode=WAL&_foreign_keys=on&_synchronous=NORMAL&_busy_timeout=30000&_txlock=immediate")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer db.Close()
|
||||
db.SetMaxOpenConns(2)
|
||||
if os.Args[2] == "worker" {
|
||||
stop := make(chan os.Signal, 1)
|
||||
signal.Notify(stop, syscall.SIGTERM)
|
||||
defer signal.Stop(stop)
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
return nil
|
||||
default:
|
||||
}
|
||||
value, err := claim(db)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if value != nil {
|
||||
if err = work(db, value); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
select {
|
||||
case <-stop:
|
||||
return nil
|
||||
case <-time.After(time.Millisecond):
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
var inputs []Submit
|
||||
switch os.Args[2] {
|
||||
case "submitAll":
|
||||
var batch Batch
|
||||
if err = decode(os.Args[3], &batch); err != nil {
|
||||
return err
|
||||
}
|
||||
if batch.Inputs == nil {
|
||||
return errors.New("inputs required")
|
||||
}
|
||||
for _, input := range batch.Inputs {
|
||||
inputs = append(inputs, Submit{Input: input, Key: input.Name})
|
||||
}
|
||||
case "submit":
|
||||
var input Submit
|
||||
if err = decode(os.Args[3], &input); err != nil {
|
||||
return err
|
||||
}
|
||||
inputs = []Submit{input}
|
||||
default:
|
||||
return errors.New("unknown command")
|
||||
}
|
||||
ids, err := submit(db, inputs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if os.Args[2] == "submit" {
|
||||
return json.NewEncoder(os.Stdout).Encode(ids[0])
|
||||
}
|
||||
return json.NewEncoder(os.Stdout).Encode(ids)
|
||||
}
|
||||
|
||||
func main() {
|
||||
if err := run(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
//! 独立队列参考:官方 SQLite 事务、deadpool 阻塞交接及 Tokio 信号,不链接 Dever。
|
||||
mod queue;
|
||||
use deadpool_sqlite::{Object, Runtime, rusqlite::Connection};
|
||||
use queue::*;
|
||||
use std::time::Duration;
|
||||
|
||||
async fn call<T: Send + 'static>(
|
||||
object: &Object,
|
||||
action: impl FnOnce(&mut Connection) -> Result<T> + Send + 'static,
|
||||
) -> Result<T> {
|
||||
// 每次阻塞操作都等待真实结束,终止信号不丢弃正在提交或回滚的任务。
|
||||
object
|
||||
.interact(action)
|
||||
.await
|
||||
.map_err(|error| error.to_string())?
|
||||
}
|
||||
|
||||
async fn run() -> Result<()> {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let pool = deadpool_sqlite::Config::new(&args[1])
|
||||
.builder(Runtime::Tokio1)?
|
||||
.max_size(2)
|
||||
.build()?;
|
||||
let object = pool.get().await?;
|
||||
call(&object, |connection| {
|
||||
connection.execute_batch(
|
||||
"PRAGMA journal_mode=WAL;PRAGMA synchronous=NORMAL;PRAGMA foreign_keys=ON;",
|
||||
)?;
|
||||
connection.busy_timeout(Duration::from_secs(30))?;
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
if args[2] == "worker" {
|
||||
let mut stop = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?;
|
||||
loop {
|
||||
// 仅在领取间隙停止;已经领取的工作在上方期限内完成事务收尾。
|
||||
let stopping = tokio::select! { biased;
|
||||
_ = stop.recv() => true,
|
||||
_ = std::future::ready(()) => false,
|
||||
};
|
||||
if stopping {
|
||||
break;
|
||||
}
|
||||
match call(&object, claim).await? {
|
||||
Some(value) => call(&object, move |connection| apply(connection, value)).await?,
|
||||
None => tokio::select! {
|
||||
_ = stop.recv() => break,
|
||||
_ = tokio::time::sleep(Duration::from_millis(1)) => {},
|
||||
},
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let inputs = match args[2].as_str() {
|
||||
"submitAll" => serde_json::from_str::<Batch>(&args[3])?
|
||||
.inputs
|
||||
.into_iter()
|
||||
.map(|input| Submit {
|
||||
key: input.name.clone(),
|
||||
input,
|
||||
})
|
||||
.collect(),
|
||||
"submit" => vec![serde_json::from_str::<Submit>(&args[3])?],
|
||||
_ => return Err("unknown command".into()),
|
||||
};
|
||||
let ids = call(&object, move |connection| submit(connection, inputs)).await?;
|
||||
let out = if args[2] == "submit" {
|
||||
serde_json::to_value(&ids[0])?
|
||||
} else {
|
||||
serde_json::to_value(ids)?
|
||||
};
|
||||
println!("{out}");
|
||||
}
|
||||
drop(object);
|
||||
pool.close();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap();
|
||||
if let Err(error) = runtime.block_on(run()) {
|
||||
eprintln!("{error}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -0,0 +1,391 @@
|
||||
//! 逐操作交接的独立 Job 对端;保留轻量队列参考,不用较慢参考覆盖它。
|
||||
#[allow(dead_code)]
|
||||
#[cfg(not(feature = "contract"))]
|
||||
mod queue;
|
||||
#[cfg(feature = "contract")]
|
||||
#[allow(dead_code)]
|
||||
#[path = "queue.rs"]
|
||||
mod base_queue;
|
||||
#[cfg(feature = "contract")]
|
||||
#[path = "contract.rs"]
|
||||
mod queue;
|
||||
mod sqlite_resource;
|
||||
use deadpool_sqlite::rusqlite::TransactionBehavior;
|
||||
use futures_util::FutureExt;
|
||||
use queue::{Batch, Claim, Payload, Submit};
|
||||
use sqlite_resource::{Lease, Result, Work, panic_message, pool};
|
||||
use std::{future::Future, panic::AssertUnwindSafe, sync::Arc, time::Duration};
|
||||
use tokio::time::Instant;
|
||||
|
||||
const IO_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
async fn submit(
|
||||
work: &Work,
|
||||
lease: &mut Option<Lease>,
|
||||
inputs: Vec<Submit>,
|
||||
) -> Result<Vec<String>> {
|
||||
work.call(lease, IO_TIMEOUT, |connection| {
|
||||
connection.execute_batch("BEGIN IMMEDIATE")?;
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
let mut ids = Vec::with_capacity(inputs.len());
|
||||
for value in inputs {
|
||||
ids.push(
|
||||
work.call(lease, IO_TIMEOUT, move |connection| {
|
||||
queue::enqueue(connection, value)
|
||||
})
|
||||
.await?,
|
||||
);
|
||||
}
|
||||
work.call(lease, IO_TIMEOUT, |connection| {
|
||||
connection.execute_batch("COMMIT")?;
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
async fn handle(work: &Work, lease: &mut Option<Lease>, input: Payload) -> Result<()> {
|
||||
work.call(lease, IO_TIMEOUT, |connection| {
|
||||
connection.execute_batch("BEGIN IMMEDIATE")?;
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
let saved = work
|
||||
.call(lease, IO_TIMEOUT, move |connection| {
|
||||
queue::insert(connection, input)
|
||||
})
|
||||
.await?;
|
||||
if saved.3 < 0 {
|
||||
return Err("negative amount".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn wait<T>(
|
||||
work: &Work,
|
||||
deadline: Instant,
|
||||
handler: impl Future<Output = Result<T>>,
|
||||
) -> Result<T> {
|
||||
let outcome = AssertUnwindSafe(tokio::time::timeout_at(deadline, handler))
|
||||
.catch_unwind()
|
||||
.await
|
||||
.map_err(|panic| panic_message(panic).into())
|
||||
.and_then(|value| value.map_err(Into::into))
|
||||
.and_then(|value| value);
|
||||
// 单 worker 没有并行的其他 Job;复用其 tracker,每次确认前等待真实后代退出。
|
||||
let cleanup = work.finish().await;
|
||||
match (outcome, cleanup) {
|
||||
(Ok(value), Ok(())) if Instant::now() < deadline => Ok(value),
|
||||
(Ok(_), Ok(())) => Err("handler deadline expired during cleanup".into()),
|
||||
(Err(cause), Ok(())) | (Ok(_), Err(cause)) => Err(cause),
|
||||
(Err(cause), Err(cleanup)) => Err(format!("{cause}; cleanup: {cleanup}").into()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn process(
|
||||
work: &Work,
|
||||
lease: &mut Option<Lease>,
|
||||
database: &deadpool_sqlite::Pool,
|
||||
claim: Claim,
|
||||
) -> Result<()> {
|
||||
let claim = Arc::new(claim);
|
||||
let deadline = Instant::now() + Duration::from_secs(1);
|
||||
let outcome = wait(work, deadline, async {
|
||||
#[cfg(not(feature = "contract"))]
|
||||
let input = serde_json::from_str(&claim.payload)?;
|
||||
#[cfg(feature = "contract")]
|
||||
let input = queue::decode(&claim)?;
|
||||
handle(work, lease, input).await
|
||||
})
|
||||
.await;
|
||||
match outcome {
|
||||
Ok(()) => {
|
||||
let value = claim.clone();
|
||||
work.call(lease, IO_TIMEOUT, move |connection| {
|
||||
queue::transition(connection, &value, "completed", None)
|
||||
})
|
||||
.await?;
|
||||
work.call(lease, IO_TIMEOUT, |connection| {
|
||||
connection.execute_batch("COMMIT")?;
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
Err(error) => {
|
||||
eprintln!("Job handler: {error}");
|
||||
#[cfg(feature = "contract")]
|
||||
let rejected = error.is::<queue::Rejected>();
|
||||
#[cfg(not(feature = "contract"))]
|
||||
let rejected = false;
|
||||
if lease.is_none() {
|
||||
// wait 已等待取消的阻塞操作释放连接;此处重新借用,不能复用未提交租约。
|
||||
*lease = Some(Lease {
|
||||
object: Some(database.get().await?),
|
||||
reusable: true,
|
||||
});
|
||||
} else {
|
||||
work.call(lease, IO_TIMEOUT, |connection| {
|
||||
if !connection.is_autocommit() {
|
||||
connection.execute_batch("ROLLBACK")?;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
work.call(lease, IO_TIMEOUT, move |connection| {
|
||||
let tx = connection.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
queue::transition(
|
||||
&tx,
|
||||
&claim,
|
||||
if rejected {
|
||||
"blocked"
|
||||
} else if claim.attempt >= 2 {
|
||||
"dead"
|
||||
} else {
|
||||
"pending"
|
||||
},
|
||||
Some("handler failed"),
|
||||
)?;
|
||||
tx.commit()?;
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn worker(
|
||||
work: &Work,
|
||||
lease: &mut Option<Lease>,
|
||||
database: &deadpool_sqlite::Pool,
|
||||
) -> Result<()> {
|
||||
let mut stop = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?;
|
||||
loop {
|
||||
let stopping = tokio::select! { biased;
|
||||
_ = stop.recv() => true,
|
||||
_ = std::future::ready(()) => false,
|
||||
};
|
||||
if stopping {
|
||||
break;
|
||||
}
|
||||
match work.call(lease, IO_TIMEOUT, queue::claim).await? {
|
||||
Some(claim) => process(work, lease, database, claim).await?,
|
||||
None => tokio::select! {
|
||||
_ = stop.recv() => break,
|
||||
_ = tokio::time::sleep(Duration::from_millis(1)) => {},
|
||||
},
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn run(args: &[String]) -> Result<()> {
|
||||
let database = pool(&args[1], 2).await?;
|
||||
let work = Work::new();
|
||||
let mut lease = Some(Lease {
|
||||
object: Some(database.get().await?),
|
||||
reusable: true,
|
||||
});
|
||||
let result = async {
|
||||
if args[2] == "worker" {
|
||||
worker(&work, &mut lease, &database).await?;
|
||||
} else {
|
||||
let inputs = match args[2].as_str() {
|
||||
"submitAll" => serde_json::from_str::<Batch>(&args[3])?
|
||||
.inputs
|
||||
.into_iter()
|
||||
.map(|input| Submit {
|
||||
key: input.name.clone(),
|
||||
input,
|
||||
})
|
||||
.collect(),
|
||||
"submit" => vec![serde_json::from_str::<Submit>(&args[3])?],
|
||||
_ => return Err("unknown command".into()),
|
||||
};
|
||||
let ids = submit(&work, &mut lease, inputs).await?;
|
||||
let out = if args[2] == "submit" {
|
||||
serde_json::to_value(&ids[0])?
|
||||
} else {
|
||||
serde_json::to_value(ids)?
|
||||
};
|
||||
println!("{out}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
.await;
|
||||
// 未提交的连接直接丢弃,SQLite 回滚;等待后台析构,保留清理中的原始错误。
|
||||
drop(lease);
|
||||
let cleanup = work.finish().await;
|
||||
drop(database);
|
||||
if let Err(cause) = cleanup {
|
||||
if result.is_ok() {
|
||||
return Err(cause);
|
||||
}
|
||||
eprintln!("cleanup: {cause}");
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let args = std::env::args().collect::<Vec<_>>();
|
||||
tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()?
|
||||
.block_on(run(&args))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use deadpool_sqlite::rusqlite::Connection;
|
||||
|
||||
struct File(std::path::PathBuf);
|
||||
impl File {
|
||||
fn new() -> Self {
|
||||
let mut id = [0; 16];
|
||||
getrandom::getrandom(&mut id).unwrap();
|
||||
let directory =
|
||||
std::env::temp_dir().join(format!("job-boundary-{:032x}", u128::from_ne_bytes(id)));
|
||||
std::fs::create_dir(&directory).unwrap();
|
||||
Connection::open(directory.join("queue.db"))
|
||||
.unwrap()
|
||||
.execute_batch("CREATE TABLE effects(value INTEGER)")
|
||||
.unwrap();
|
||||
Self(directory)
|
||||
}
|
||||
}
|
||||
impl Drop for File {
|
||||
fn drop(&mut self) {
|
||||
std::fs::remove_dir_all(&self.0).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
async fn scenario(
|
||||
handler_pending: bool,
|
||||
expired: bool,
|
||||
late_panic: bool,
|
||||
handler_panic: bool,
|
||||
) -> Result<()> {
|
||||
let file = File::new();
|
||||
let path = file.0.join("queue.db");
|
||||
let database = pool(path.to_str().unwrap(), 2).await?;
|
||||
let work = Work::new();
|
||||
let mut lease = Some(Lease {
|
||||
object: Some(database.get().await?),
|
||||
reusable: true,
|
||||
});
|
||||
let (release, released) = std::sync::mpsc::channel();
|
||||
let (entered, ready) = tokio::sync::oneshot::channel();
|
||||
let deadline = Instant::now()
|
||||
+ if expired {
|
||||
Duration::from_millis(50)
|
||||
} else {
|
||||
IO_TIMEOUT
|
||||
};
|
||||
let handler = async {
|
||||
let (started, blocking) = tokio::sync::oneshot::channel();
|
||||
{
|
||||
let operation = work.call(&mut lease, IO_TIMEOUT, move |connection| {
|
||||
connection.execute_batch("BEGIN IMMEDIATE; INSERT INTO effects VALUES(1)")?;
|
||||
started.send(()).unwrap();
|
||||
released.recv()?;
|
||||
assert!(!late_panic, "late SQLite panic");
|
||||
Ok(())
|
||||
});
|
||||
tokio::pin!(operation);
|
||||
tokio::select! {
|
||||
result = &mut operation => panic!("operation finished before release: {result:?}"),
|
||||
result = blocking => result.unwrap(),
|
||||
}
|
||||
}
|
||||
// 丢弃 SQL future 后真实阻塞工作仍在运行,持有未提交的连接。
|
||||
entered.send(()).unwrap();
|
||||
assert!(!handler_panic, "handler panic");
|
||||
if handler_pending {
|
||||
std::future::pending::<()>().await;
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
{
|
||||
let result = wait(&work, deadline, handler);
|
||||
tokio::pin!(result);
|
||||
tokio::select! {
|
||||
result = &mut result => panic!("boundary returned before descendant exit: {result:?}"),
|
||||
result = ready => result.unwrap(),
|
||||
}
|
||||
if expired {
|
||||
tokio::time::sleep_until(deadline).await;
|
||||
}
|
||||
assert!(futures_util::poll!(&mut result).is_pending());
|
||||
release.send(()).unwrap();
|
||||
let result = result.await;
|
||||
if expired || late_panic || handler_panic {
|
||||
let message = result.unwrap_err().to_string();
|
||||
if late_panic {
|
||||
assert!(message.contains("late SQLite panic"), "{message}");
|
||||
}
|
||||
if handler_panic {
|
||||
assert!(message.contains("handler panic"), "{message}");
|
||||
}
|
||||
if expired && handler_pending {
|
||||
assert!(message.contains("deadline"), "{message}");
|
||||
}
|
||||
} else {
|
||||
result?;
|
||||
}
|
||||
}
|
||||
assert!(lease.is_none());
|
||||
assert_eq!(
|
||||
Connection::open(&path)?.query_row("SELECT count(*) FROM effects", [], |row| row
|
||||
.get::<_, i64>(0))?,
|
||||
0
|
||||
);
|
||||
// tracker 在首个边界后仍可跟踪下一项工作;事务回滚完成后才允许重试。
|
||||
let mut lease = Some(Lease {
|
||||
object: Some(database.get().await?),
|
||||
reusable: true,
|
||||
});
|
||||
wait(
|
||||
&work,
|
||||
Instant::now() + IO_TIMEOUT,
|
||||
work.call(&mut lease, IO_TIMEOUT, |connection| {
|
||||
connection.execute("INSERT INTO effects VALUES(2)", [])?;
|
||||
Ok(())
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
Connection::open(&path)?
|
||||
.query_row("SELECT sum(value) FROM effects", [], |row| row
|
||||
.get::<_, i64>(0))?,
|
||||
2
|
||||
);
|
||||
drop(lease);
|
||||
work.finish().await?;
|
||||
drop(database);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn waits_for_cancelled_sql_and_rolls_back_before_next_job() -> Result<()> {
|
||||
scenario(false, false, false, false).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_success_when_descendant_cleanup_exceeds_deadline() -> Result<()> {
|
||||
scenario(false, true, false, false).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn timeout_drains_and_preserves_late_panic() -> Result<()> {
|
||||
scenario(true, true, true, false).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn handler_panic_still_drains_and_preserves_late_panic() -> Result<()> {
|
||||
scenario(false, false, true, true).await
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
long cmd integer = app.integer
|
||||
|
||||
long cmd continuous_integer = app.continuousInteger
|
||||
|
||||
long cmd float = app.float
|
||||
|
||||
long cmd continuous_float = app.continuousFloat
|
||||
|
||||
long cmd list = app.list
|
||||
|
||||
long cmd continuous_list = app.continuousList
|
||||
|
||||
long cmd map = app.map
|
||||
|
||||
long cmd continuous_map = app.continuousMap
|
||||
|
||||
long cmd list_read = app.listRead
|
||||
|
||||
long cmd continuous_list_read = app.continuousListRead
|
||||
|
||||
long cmd map_read = app.mapRead
|
||||
|
||||
long cmd continuous_map_read = app.continuousMapRead
|
||||
|
||||
long cmd list_record = app.listRecord
|
||||
|
||||
long cmd continuous_list_record = app.continuousListRecord
|
||||
|
||||
long cmd list_record_read = app.listRecordRead
|
||||
|
||||
long cmd continuous_list_record_read = app.continuousListRecordRead
|
||||
|
||||
long cmd call_read = app.callRead
|
||||
|
||||
long cmd continuous_call_read = app.continuousCallRead
|
||||
|
||||
long cmd record_update = app.recordUpdate
|
||||
|
||||
long cmd continuous_record_update = app.continuousRecordUpdate
|
||||
|
||||
long cmd record_inspect = app.recordInspect
|
||||
|
||||
long cmd continuous_record_inspect = app.continuousRecordInspect
|
||||
|
||||
long cmd map_lookup = app.mapLookup
|
||||
|
||||
long cmd continuous_map_lookup = app.continuousMapLookup
|
||||
|
||||
long cmd map_text_lookup = app.mapTextLookup
|
||||
|
||||
long cmd continuous_map_text_lookup = app.continuousMapTextLookup
|
||||
|
||||
long cmd text_equal = app.textEqual
|
||||
|
||||
long cmd continuous_text_equal = app.continuousTextEqual
|
||||
|
||||
long cmd text_contains = app.textContains
|
||||
|
||||
long cmd continuous_text_contains = app.continuousTextContains
|
||||
|
||||
long cmd bytes_concat = app.bytesConcat
|
||||
|
||||
long cmd continuous_bytes_concat = app.continuousBytesConcat
|
||||
|
||||
long cmd text_concat = app.textConcat
|
||||
|
||||
long cmd continuous_text_concat = app.continuousTextConcat
|
||||
@@ -0,0 +1,410 @@
|
||||
type Sample {
|
||||
elapsed_ns: Int
|
||||
checksum: Int
|
||||
}
|
||||
|
||||
type FloatSample {
|
||||
elapsed_ns: Int
|
||||
checksum: Float
|
||||
}
|
||||
|
||||
type Record {
|
||||
first: Int
|
||||
second: Int
|
||||
third: Int
|
||||
}
|
||||
|
||||
type OwnedRecord {
|
||||
name: Text
|
||||
tags: List<Text>
|
||||
count: Int
|
||||
}
|
||||
|
||||
type Accumulator {
|
||||
values: List<Int>
|
||||
count: Int
|
||||
}
|
||||
|
||||
type Lookup {
|
||||
values: Map<Int, Int>
|
||||
index: Int
|
||||
total: Int
|
||||
}
|
||||
|
||||
type TextLookup {
|
||||
values: Map<Text, Int>
|
||||
total: Int
|
||||
}
|
||||
|
||||
type TextPair {
|
||||
left: Text
|
||||
right: Text
|
||||
}
|
||||
|
||||
rule selected(value: Int?) (out: Int)
|
||||
| value | out |
|
||||
| null | 0 |
|
||||
| other | value |
|
||||
|
||||
loop total(values: List<Int>) (out: Int)
|
||||
| each value in values | result |
|
||||
| out | sum value |
|
||||
|
||||
loop byteTotal(values: Bytes) (out: Int)
|
||||
| each value in values | result |
|
||||
| out | sum value |
|
||||
|
||||
loop floatTotal(values: Bytes) (out: Float)
|
||||
| each value in values | result |
|
||||
| out | sum float.fromInt(value) |
|
||||
|
||||
loop buildList(values: Bytes) (out: List<Int>)
|
||||
| each value in values | result |
|
||||
| out | list value |
|
||||
|
||||
loop buildMap(values: Bytes) (out: Map<Int, Int>)
|
||||
| each value in values | result |
|
||||
| out | fold(acc = {}, putValue(value, acc)) |
|
||||
|
||||
loop mapTotal(values: Map<Int, Int>) (out: Int)
|
||||
| each entry in entries(values) | result |
|
||||
| out | sum entry.value |
|
||||
|
||||
loop buildRecords(values: Bytes) (out: List<Record>)
|
||||
| each value in values | result |
|
||||
| out | list Record { first = value, second = 0, third = 0 } |
|
||||
|
||||
loop recordTotal(values: List<Record>) (out: Int)
|
||||
| each row in values | result |
|
||||
| out | sum row.first + row.second + row.third |
|
||||
|
||||
ownedRecord(value: Int) (row: OwnedRecord) {
|
||||
name = "row-value-" + int.toText(value)
|
||||
row = OwnedRecord { name = name, tags = [name], count = value - length(name) - 1 }
|
||||
}
|
||||
|
||||
inspectOwned(row: OwnedRecord) (value: Int) {
|
||||
value = row.count + length(row.name) + length(row.tags)
|
||||
}
|
||||
|
||||
forwardOwned(row: OwnedRecord) (value: Int) {
|
||||
value = inspectOwned(row)
|
||||
}
|
||||
|
||||
loop ownedRecords(values: Bytes) (out: List<OwnedRecord>)
|
||||
| each value in values | result |
|
||||
| out | list ownedRecord(value) |
|
||||
|
||||
loop inspectRecords(values: List<OwnedRecord>) (out: Int)
|
||||
| each row in values | result |
|
||||
| out | sum forwardOwned(row) |
|
||||
|
||||
appendField(value: Int, state: Accumulator) (next: Accumulator) {
|
||||
next = Accumulator { values = append(state.values, value), count = state.count + 1 }
|
||||
}
|
||||
|
||||
appendInspected(value: Int, state: Accumulator) (next: Accumulator) {
|
||||
count = length(state.values) + 1
|
||||
next = Accumulator { values = append(state.values, value), count = count }
|
||||
}
|
||||
|
||||
loop updateRecords(values: Bytes) (out: Accumulator)
|
||||
| each value in values | result |
|
||||
| out | fold(acc = Accumulator { values = [], count = 0 }, appendField(value, acc)) |
|
||||
|
||||
loop inspectUpdates(values: Bytes) (out: Accumulator)
|
||||
| each value in values | result |
|
||||
| out | fold(acc = Accumulator { values = [], count = 0 }, appendInspected(value, acc)) |
|
||||
|
||||
lookup(value: Int, state: Lookup) (next: Lookup) {
|
||||
found = selected(get(state.values, state.index))
|
||||
next = Lookup { values = state.values, index = state.index + 1, total = state.total + found }
|
||||
}
|
||||
|
||||
loop lookupValues(input: Bytes, initial: Lookup) (out: Lookup)
|
||||
| each value in input | result |
|
||||
| out | fold(acc = initial, lookup(value, acc)) |
|
||||
|
||||
loop textEntries(values: List<MapEntry<Int, Int>>) (out: Map<Text, Int>)
|
||||
| each entry in values | result |
|
||||
| out | fold(acc = {}, textEntry(entry, acc)) |
|
||||
|
||||
loop textKeys(values: List<MapEntry<Text, Int>>) (out: List<Text>)
|
||||
| each entry in values | result |
|
||||
| out | list entry.key |
|
||||
|
||||
textLookup(key: Text, state: TextLookup) (next: TextLookup) {
|
||||
found = selected(get(state.values, key))
|
||||
next = TextLookup { values = state.values, total = state.total + found }
|
||||
}
|
||||
|
||||
loop lookupText(keys: List<Text>, initial: TextLookup) (out: TextLookup)
|
||||
| each key in keys | result |
|
||||
| out | fold(acc = initial, textLookup(key, acc)) |
|
||||
|
||||
textPair(value: Int) (pair: TextPair) {
|
||||
left = "compare-value-" + int.toText(value)
|
||||
pair = TextPair { left = left, right = text.lower(text.upper(left)) }
|
||||
}
|
||||
|
||||
rule matchedValue(matched: Bool) (value: Int)
|
||||
| matched | value |
|
||||
| true | 120 |
|
||||
| false | 0 |
|
||||
|
||||
loop textPairs(values: Bytes) (out: List<TextPair>)
|
||||
| each value in values | result |
|
||||
| out | list textPair(value) |
|
||||
|
||||
loop equalPairs(rows: List<TextPair>) (out: Int)
|
||||
| each row in rows | result |
|
||||
| out | sum matchedValue(row.left == row.right) |
|
||||
|
||||
loop containsPairs(rows: List<TextPair>) (out: Int)
|
||||
| each row in rows | result |
|
||||
| out | sum matchedValue(text.contains(row.left, row.right)) |
|
||||
|
||||
loop joinText(chunks: List<Text>) (out: Text)
|
||||
| each value in chunks | result |
|
||||
| out | fold(acc = "", appendText(value, acc)) |
|
||||
|
||||
loop byteChunks(chunks: List<Text>) (out: List<Bytes>)
|
||||
| each value in chunks | result |
|
||||
| out | list dever.bytes.fromText(value) |
|
||||
|
||||
loop joinBytes(chunks: List<Bytes>) (out: Bytes)
|
||||
| each value in chunks | result |
|
||||
| out | fold(acc = dever.bytes.fromText(""), appendBytes(value, acc)) |
|
||||
|
||||
flow integer(ticks: Text) (sample: Sample)
|
||||
| step | kind | do |
|
||||
| input | calc | dever.bytes.fromText(ticks) |
|
||||
| begin | flow | dever.time.monotonicNanos() |
|
||||
| value | loop | byteTotal(input) |
|
||||
| end | flow | dever.time.monotonicNanos() |
|
||||
| sample | calc | Sample { elapsed_ns = end - begin, checksum = value } |
|
||||
|
||||
loop continuousInteger(ticks: Text) (samples: List<Sample>)
|
||||
| each value in range(0, 10) | result |
|
||||
| samples | list integer(ticks) |
|
||||
|
||||
flow float(ticks: Text) (sample: FloatSample)
|
||||
| step | kind | do |
|
||||
| input | calc | dever.bytes.fromText(ticks) |
|
||||
| begin | flow | dever.time.monotonicNanos() |
|
||||
| value | loop | floatTotal(input) |
|
||||
| end | flow | dever.time.monotonicNanos() |
|
||||
| sample | calc | FloatSample { elapsed_ns = end - begin, checksum = value } |
|
||||
|
||||
loop continuousFloat(ticks: Text) (samples: List<FloatSample>)
|
||||
| each value in range(0, 10) | result |
|
||||
| samples | list float(ticks) |
|
||||
|
||||
flow list(ticks: Text) (sample: Sample)
|
||||
| step | kind | do |
|
||||
| input | calc | dever.bytes.fromText(ticks) |
|
||||
| begin | flow | dever.time.monotonicNanos() |
|
||||
| values | loop | buildList(input) |
|
||||
| end | flow | dever.time.monotonicNanos() |
|
||||
| sample | calc | Sample { elapsed_ns = end - begin, checksum = total(values) } |
|
||||
|
||||
loop continuousList(ticks: Text) (samples: List<Sample>)
|
||||
| each value in range(0, 10) | result |
|
||||
| samples | list list(ticks) |
|
||||
|
||||
flow map(ticks: Text) (sample: Sample)
|
||||
| step | kind | do |
|
||||
| input | calc | dever.bytes.fromText(ticks) |
|
||||
| begin | flow | dever.time.monotonicNanos() |
|
||||
| values | loop | buildMap(input) |
|
||||
| end | flow | dever.time.monotonicNanos() |
|
||||
| sample | calc | Sample { elapsed_ns = end - begin, checksum = mapTotal(values) } |
|
||||
|
||||
loop continuousMap(ticks: Text) (samples: List<Sample>)
|
||||
| each value in range(0, 10) | result |
|
||||
| samples | list map(ticks) |
|
||||
|
||||
flow listRead(ticks: Text) (sample: Sample)
|
||||
| step | kind | do |
|
||||
| values | loop | buildList(dever.bytes.fromText(ticks)) |
|
||||
| begin | flow | dever.time.monotonicNanos() |
|
||||
| value | loop | total(values) |
|
||||
| end | flow | dever.time.monotonicNanos() |
|
||||
| sample | calc | Sample { elapsed_ns = end - begin, checksum = value } |
|
||||
|
||||
loop continuousListRead(ticks: Text) (samples: List<Sample>)
|
||||
| each value in range(0, 10) | result |
|
||||
| samples | list listRead(ticks) |
|
||||
|
||||
flow mapRead(ticks: Text) (sample: Sample)
|
||||
| step | kind | do |
|
||||
| values | loop | buildMap(dever.bytes.fromText(ticks)) |
|
||||
| begin | flow | dever.time.monotonicNanos() |
|
||||
| value | loop | mapTotal(values) |
|
||||
| end | flow | dever.time.monotonicNanos() |
|
||||
| sample | calc | Sample { elapsed_ns = end - begin, checksum = value } |
|
||||
|
||||
loop continuousMapRead(ticks: Text) (samples: List<Sample>)
|
||||
| each value in range(0, 10) | result |
|
||||
| samples | list mapRead(ticks) |
|
||||
|
||||
flow listRecord(ticks: Text) (sample: Sample)
|
||||
| step | kind | do |
|
||||
| input | calc | dever.bytes.fromText(ticks) |
|
||||
| begin | flow | dever.time.monotonicNanos() |
|
||||
| values | loop | buildRecords(input) |
|
||||
| end | flow | dever.time.monotonicNanos() |
|
||||
| sample | calc | Sample { elapsed_ns = end - begin, checksum = recordTotal(values) } |
|
||||
|
||||
loop continuousListRecord(ticks: Text) (samples: List<Sample>)
|
||||
| each value in range(0, 10) | result |
|
||||
| samples | list listRecord(ticks) |
|
||||
|
||||
flow listRecordRead(ticks: Text) (sample: Sample)
|
||||
| step | kind | do |
|
||||
| values | loop | buildRecords(dever.bytes.fromText(ticks)) |
|
||||
| begin | flow | dever.time.monotonicNanos() |
|
||||
| value | loop | recordTotal(values) |
|
||||
| end | flow | dever.time.monotonicNanos() |
|
||||
| sample | calc | Sample { elapsed_ns = end - begin, checksum = value } |
|
||||
|
||||
loop continuousListRecordRead(ticks: Text) (samples: List<Sample>)
|
||||
| each value in range(0, 10) | result |
|
||||
| samples | list listRecordRead(ticks) |
|
||||
|
||||
flow callRead(ticks: Text) (sample: Sample)
|
||||
| step | kind | do |
|
||||
| rows | loop | ownedRecords(dever.bytes.fromText(ticks)) |
|
||||
| begin | flow | dever.time.monotonicNanos() |
|
||||
| value | loop | inspectRecords(rows) |
|
||||
| end | flow | dever.time.monotonicNanos() |
|
||||
| sample | calc | Sample { elapsed_ns = end - begin, checksum = value + length(rows) - length(rows) } |
|
||||
|
||||
loop continuousCallRead(ticks: Text) (samples: List<Sample>)
|
||||
| each value in range(0, 10) | result |
|
||||
| samples | list callRead(ticks) |
|
||||
|
||||
flow recordUpdate(ticks: Text) (sample: Sample)
|
||||
| step | kind | do |
|
||||
| input | calc | dever.bytes.fromText(ticks) |
|
||||
| begin | flow | dever.time.monotonicNanos() |
|
||||
| state | loop | updateRecords(input) |
|
||||
| end | flow | dever.time.monotonicNanos() |
|
||||
| sample | calc | Sample {
|
||||
elapsed_ns = end - begin
|
||||
checksum = total(state.values) + state.count - length(state.values)
|
||||
} |
|
||||
|
||||
loop continuousRecordUpdate(ticks: Text) (samples: List<Sample>)
|
||||
| each value in range(0, 10) | result |
|
||||
| samples | list recordUpdate(ticks) |
|
||||
|
||||
flow recordInspect(ticks: Text) (sample: Sample)
|
||||
| step | kind | do |
|
||||
| input | calc | dever.bytes.fromText(ticks) |
|
||||
| begin | flow | dever.time.monotonicNanos() |
|
||||
| state | loop | inspectUpdates(input) |
|
||||
| end | flow | dever.time.monotonicNanos() |
|
||||
| sample | calc | Sample {
|
||||
elapsed_ns = end - begin
|
||||
checksum = total(state.values) + state.count - length(state.values)
|
||||
} |
|
||||
|
||||
loop continuousRecordInspect(ticks: Text) (samples: List<Sample>)
|
||||
| each value in range(0, 10) | result |
|
||||
| samples | list recordInspect(ticks) |
|
||||
|
||||
flow mapLookup(ticks: Text) (sample: Sample)
|
||||
| step | kind | do |
|
||||
| input | calc | dever.bytes.fromText(ticks) |
|
||||
| values | loop | buildMap(input) |
|
||||
| initial | calc | Lookup { values = values, index = 0, total = 0 } |
|
||||
| begin | flow | dever.time.monotonicNanos() |
|
||||
| state | loop | lookupValues(input, initial) |
|
||||
| end | flow | dever.time.monotonicNanos() |
|
||||
| sample | calc | Sample { elapsed_ns = end - begin, checksum = state.total } |
|
||||
|
||||
loop continuousMapLookup(ticks: Text) (samples: List<Sample>)
|
||||
| each value in range(0, 10) | result |
|
||||
| samples | list mapLookup(ticks) |
|
||||
|
||||
flow mapTextLookup(ticks: Text) (sample: Sample)
|
||||
| step | kind | do |
|
||||
| input | calc | dever.bytes.fromText(ticks) |
|
||||
| values | loop | textEntries(entries(buildMap(input))) |
|
||||
| keys | loop | textKeys(entries(values)) |
|
||||
| initial | calc | TextLookup { values = values, total = 0 } |
|
||||
| begin | flow | dever.time.monotonicNanos() |
|
||||
| state | loop | lookupText(keys, initial) |
|
||||
| end | flow | dever.time.monotonicNanos() |
|
||||
| sample | calc | Sample { elapsed_ns = end - begin, checksum = state.total + length(keys) - length(input) } |
|
||||
|
||||
loop continuousMapTextLookup(ticks: Text) (samples: List<Sample>)
|
||||
| each value in range(0, 10) | result |
|
||||
| samples | list mapTextLookup(ticks) |
|
||||
|
||||
flow textEqual(ticks: Text) (sample: Sample)
|
||||
| step | kind | do |
|
||||
| input | calc | dever.bytes.fromText(ticks) |
|
||||
| rows | loop | textPairs(input) |
|
||||
| begin | flow | dever.time.monotonicNanos() |
|
||||
| value | loop | equalPairs(rows) |
|
||||
| end | flow | dever.time.monotonicNanos() |
|
||||
| sample | calc | Sample { elapsed_ns = end - begin, checksum = value + length(rows) - length(input) } |
|
||||
|
||||
loop continuousTextEqual(ticks: Text) (samples: List<Sample>)
|
||||
| each value in range(0, 10) | result |
|
||||
| samples | list textEqual(ticks) |
|
||||
|
||||
flow textContains(ticks: Text) (sample: Sample)
|
||||
| step | kind | do |
|
||||
| input | calc | dever.bytes.fromText(ticks) |
|
||||
| rows | loop | textPairs(input) |
|
||||
| begin | flow | dever.time.monotonicNanos() |
|
||||
| value | loop | containsPairs(rows) |
|
||||
| end | flow | dever.time.monotonicNanos() |
|
||||
| sample | calc | Sample { elapsed_ns = end - begin, checksum = value + length(rows) - length(input) } |
|
||||
|
||||
loop continuousTextContains(ticks: Text) (samples: List<Sample>)
|
||||
| each value in range(0, 10) | result |
|
||||
| samples | list textContains(ticks) |
|
||||
|
||||
flow bytesConcat(ticks: Text) (sample: Sample)
|
||||
| step | kind | do |
|
||||
| chunks | loop | byteChunks(text.split(ticks, "")) |
|
||||
| begin | flow | dever.time.monotonicNanos() |
|
||||
| value | loop | joinBytes(chunks) |
|
||||
| end | flow | dever.time.monotonicNanos() |
|
||||
| sample | calc | Sample { elapsed_ns = end - begin, checksum = byteTotal(value) } |
|
||||
|
||||
loop continuousBytesConcat(ticks: Text) (samples: List<Sample>)
|
||||
| each value in range(0, 10) | result |
|
||||
| samples | list bytesConcat(ticks) |
|
||||
|
||||
flow textConcat(ticks: Text) (sample: Sample)
|
||||
| step | kind | do |
|
||||
| chunks | calc | text.split(ticks, ",") |
|
||||
| begin | flow | dever.time.monotonicNanos() |
|
||||
| value | loop | joinText(chunks) |
|
||||
| end | flow | dever.time.monotonicNanos() |
|
||||
| sample | calc | Sample { elapsed_ns = end - begin, checksum = byteTotal(dever.bytes.fromText(value)) } |
|
||||
|
||||
loop continuousTextConcat(ticks: Text) (samples: List<Sample>)
|
||||
| each value in range(0, 10) | result |
|
||||
| samples | list textConcat(ticks) |
|
||||
|
||||
putValue(value: Int, state: Map<Int, Int>) (out: Map<Int, Int>) {
|
||||
out = put(state, length(state), value)
|
||||
}
|
||||
|
||||
textEntry(entry: MapEntry<Int, Int>, state: Map<Text, Int>) (out: Map<Text, Int>) {
|
||||
out = put(state, "lookup-key-" + int.toText(entry.key), entry.value)
|
||||
}
|
||||
|
||||
appendText(value: Text, state: Text) (out: Text) {
|
||||
out = state + value
|
||||
}
|
||||
|
||||
appendBytes(value: Bytes, state: Bytes) (out: Bytes) {
|
||||
out = dever.bytes.concat(state, value)
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
cmd batch = app.batch
|
||||
|
||||
cmd count = app.count
|
||||
@@ -0,0 +1,20 @@
|
||||
flow change(number: Int, title: Text) (out: Int)
|
||||
| step | kind | do |
|
||||
| created | data | data.create({ number = number, title = title, amount = number }) |
|
||||
| found | data | data.get(created.id) |
|
||||
| updated | data | data.update(found.id, { amount = found.amount + 1 }) |
|
||||
| out | calc | updated.amount |
|
||||
|
||||
loop changes(numbers: List<Int>, title: Text) (out: Int)
|
||||
| each number in numbers | result |
|
||||
| out | sum change(number, title) |
|
||||
|
||||
flow batch(numbers: List<Int>, title: Text) (checksum: Int, count: Int)
|
||||
| step | kind | do |
|
||||
| removed | data | data.delete({ where = number >= 0 }) |
|
||||
| checksum | loop | changes(numbers, title) |
|
||||
| count | data | data.count() |
|
||||
|
||||
flow count() (out: Int)
|
||||
| step | kind | do |
|
||||
| out | data | data.count() |
|
||||
@@ -0,0 +1,5 @@
|
||||
module model-peer
|
||||
|
||||
go 1.25.0
|
||||
|
||||
require github.com/mattn/go-sqlite3 v1.14.47
|
||||
@@ -0,0 +1,2 @@
|
||||
github.com/mattn/go-sqlite3 v1.14.47 h1:jOBI62gS7nKeZv+as1oGEy0+1qISgXwH/QBlR6KbfIo=
|
||||
github.com/mattn/go-sqlite3 v1.14.47/go.mod h1:6JTjA44L93a0QCyJef5YvlPoKXntQPjzWv5gtm9sB6w=
|
||||
@@ -0,0 +1,6 @@
|
||||
type Article {
|
||||
number: Int unique
|
||||
title: Text(1, 120)
|
||||
amount: Int default 0
|
||||
note: Text? raw
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
change(number: Int, title: Text) (out: Int) {
|
||||
created = model.create({ number = number, title = title, amount = number })
|
||||
found = model.get(created.id)
|
||||
updated = model.update(found.id, { amount = found.amount + 1 })
|
||||
out = updated.amount
|
||||
}
|
||||
|
||||
batch(numbers: List<Int>, title: Text) (checksum: Int, count: Int) {
|
||||
removed = model.delete({ where = number >= 0 })
|
||||
checksum = sum(each(change, numbers, title))
|
||||
count = model.count()
|
||||
}
|
||||
|
||||
count() (out: Int) {
|
||||
out = model.count()
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
// 独立 database/sql CMD 对端;事务出错回滚,成功编码后提交。
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
sqlite3 "github.com/mattn/go-sqlite3"
|
||||
)
|
||||
|
||||
type Input struct {
|
||||
Numbers []int64 "json:\"numbers\""
|
||||
Title string "json:\"title\""
|
||||
}
|
||||
type Output struct {
|
||||
Checksum int64 "json:\"checksum\""
|
||||
Count int64 "json:\"count\""
|
||||
}
|
||||
type Article struct {
|
||||
ID, CreatedAt, Number int64
|
||||
Title string
|
||||
Amount int64
|
||||
Note sql.NullString
|
||||
}
|
||||
|
||||
func article(row *sql.Row) (value Article, err error) {
|
||||
err = row.Scan(&value.ID, &value.CreatedAt, &value.Number, &value.Title, &value.Amount, &value.Note)
|
||||
return
|
||||
}
|
||||
|
||||
func run() error {
|
||||
if os.Args[1] == "--sqlite-version" {
|
||||
version, _, _ := sqlite3.Version()
|
||||
fmt.Println(version)
|
||||
return nil
|
||||
}
|
||||
var input Input
|
||||
decoder := json.NewDecoder(bytes.NewBufferString(os.Args[2]))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&input); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := decoder.Decode(new(any)); err != io.EOF {
|
||||
return fmt.Errorf("unexpected trailing JSON: %v", err)
|
||||
}
|
||||
if input.Numbers == nil {
|
||||
return fmt.Errorf("numbers is required")
|
||||
}
|
||||
input.Title = strings.TrimSpace(input.Title)
|
||||
if n := utf8.RuneCountInString(input.Title); n < 1 || n > 120 {
|
||||
return fmt.Errorf("title range")
|
||||
}
|
||||
sql.Register("model-sqlite", &sqlite3.SQLiteDriver{ConnectHook: func(conn *sqlite3.SQLiteConn) error {
|
||||
return conn.RegisterFunc("_dever_length", utf8.RuneCountInString, true)
|
||||
}})
|
||||
db, err := sql.Open("model-sqlite", "file:"+os.Args[1]+"?mode=rw&_journal_mode=WAL&_foreign_keys=on&_synchronous=NORMAL&_busy_timeout=30000&_txlock=immediate")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer db.Close()
|
||||
db.SetMaxOpenConns(1)
|
||||
tx, err := db.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if _, err = tx.Exec("DELETE FROM benchmark_article WHERE number >= ?", 0); err != nil {
|
||||
return err
|
||||
}
|
||||
create, err := tx.Prepare("INSERT INTO benchmark_article (created_at,number,title,amount,note) VALUES (?,?,?,?,NULL) RETURNING id,created_at,number,title,amount,note")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer create.Close()
|
||||
read, err := tx.Prepare("SELECT id,created_at,number,title,amount,note FROM benchmark_article WHERE id = ?")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer read.Close()
|
||||
update, err := tx.Prepare("UPDATE benchmark_article SET amount = ? WHERE id = ? RETURNING id,created_at,number,title,amount,note")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer update.Close()
|
||||
var out Output
|
||||
for _, number := range input.Numbers {
|
||||
created, err := article(create.QueryRow(time.Now().UnixMilli(), number, input.Title, number))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
found, err := article(read.QueryRow(created.ID))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if found.Amount == math.MaxInt64 {
|
||||
return fmt.Errorf("amount overflow")
|
||||
}
|
||||
updated, err := article(update.QueryRow(found.Amount+1, found.ID))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if (updated.Amount > 0 && out.Checksum > math.MaxInt64-updated.Amount) || (updated.Amount < 0 && out.Checksum < math.MinInt64-updated.Amount) {
|
||||
return fmt.Errorf("checksum overflow")
|
||||
}
|
||||
out.Checksum += updated.Amount
|
||||
}
|
||||
if err = tx.QueryRow("SELECT COUNT(*) FROM benchmark_article").Scan(&out.Count); err != nil {
|
||||
return err
|
||||
}
|
||||
encoded, err := json.Marshal(out)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err = tx.Commit(); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = fmt.Println(string(encoded))
|
||||
return err
|
||||
}
|
||||
|
||||
func main() {
|
||||
if err := run(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
//! 独立同步 SQLite CMD 对端;不链接 Dever,不模拟其异步任务调度。
|
||||
use rusqlite::{Connection, OpenFlags, Row, params};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
error::Error,
|
||||
time::{Duration, SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Input {
|
||||
numbers: Vec<i64>,
|
||||
title: String,
|
||||
}
|
||||
|
||||
struct Article {
|
||||
id: i64,
|
||||
_created_at: i64,
|
||||
_number: i64,
|
||||
_title: String,
|
||||
amount: i64,
|
||||
_note: Option<String>,
|
||||
}
|
||||
|
||||
fn article(row: &Row<'_>) -> rusqlite::Result<Article> {
|
||||
Ok(Article {
|
||||
id: row.get(0)?,
|
||||
_created_at: row.get(1)?,
|
||||
_number: row.get(2)?,
|
||||
_title: row.get(3)?,
|
||||
amount: row.get(4)?,
|
||||
_note: row.get(5)?,
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct Output {
|
||||
checksum: i64,
|
||||
count: i64,
|
||||
}
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
let args: Vec<_> = std::env::args().collect();
|
||||
if args[1] == "--sqlite-version" {
|
||||
println!("{}", rusqlite::version());
|
||||
return Ok(());
|
||||
}
|
||||
let mut input: Input = serde_json::from_str(&args[2])?;
|
||||
input.title = input.title.trim().into();
|
||||
if !(1..=120).contains(&input.title.chars().count()) {
|
||||
return Err("title range".into());
|
||||
}
|
||||
let mut connection = Connection::open_with_flags(&args[1], OpenFlags::SQLITE_OPEN_READ_WRITE)?;
|
||||
connection.create_scalar_function(
|
||||
"_dever_length",
|
||||
1,
|
||||
rusqlite::functions::FunctionFlags::SQLITE_UTF8
|
||||
| rusqlite::functions::FunctionFlags::SQLITE_DETERMINISTIC
|
||||
| rusqlite::functions::FunctionFlags::SQLITE_INNOCUOUS,
|
||||
|ctx| {
|
||||
Ok(ctx
|
||||
.get_raw(0)
|
||||
.as_str()
|
||||
.map_err(|error| rusqlite::Error::UserFunctionError(Box::new(error)))?
|
||||
.chars()
|
||||
.count() as i64)
|
||||
},
|
||||
)?;
|
||||
connection.busy_timeout(Duration::from_secs(30))?;
|
||||
connection.execute_batch(
|
||||
"PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA synchronous=NORMAL;",
|
||||
)?;
|
||||
let transaction =
|
||||
connection.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
|
||||
transaction
|
||||
.prepare_cached("DELETE FROM benchmark_article WHERE number >= ?1")?
|
||||
.execute([0])?;
|
||||
let mut checksum = 0i64;
|
||||
for number in input.numbers {
|
||||
let now = i64::try_from(SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis())?;
|
||||
let created = transaction.prepare_cached("INSERT INTO benchmark_article (created_at,number,title,amount,note) VALUES (?1,?2,?3,?4,NULL) RETURNING id,created_at,number,title,amount,note")?
|
||||
.query_row(params![now,number,input.title,number], article)?;
|
||||
let found = transaction.prepare_cached("SELECT id,created_at,number,title,amount,note FROM benchmark_article WHERE id = ?1")?
|
||||
.query_row([created.id], article)?;
|
||||
let updated = transaction.prepare_cached("UPDATE benchmark_article SET amount = ?2 WHERE id = ?1 RETURNING id,created_at,number,title,amount,note")?
|
||||
.query_row(params![found.id,found.amount.checked_add(1).ok_or("amount overflow")?], article)?;
|
||||
checksum = checksum
|
||||
.checked_add(updated.amount)
|
||||
.ok_or("checksum overflow")?;
|
||||
}
|
||||
let count = transaction
|
||||
.prepare_cached("SELECT COUNT(*) FROM benchmark_article")?
|
||||
.query_row([], |row| row.get(0))?;
|
||||
let encoded = serde_json::to_string(&Output { checksum, count })?;
|
||||
transaction.commit()?;
|
||||
println!("{encoded}");
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
flow page(page: Int, size: Int) (out: data.Page)
|
||||
| step | kind | do |
|
||||
| out | data | data.page(order = [number.asc, id.asc], page = page, size = size) |
|
||||
|
||||
flow cursor(after: data.Article?, size: Int) (out: data.Cursor)
|
||||
| step | kind | do |
|
||||
| out | data | data.cursor(order = [number.asc, id.asc], after = after, size = size) |
|
||||
@@ -0,0 +1,338 @@
|
||||
//! 独立分页、游标和批量关系参考;不链接 Dever,复用同一 SQLite 资源责任。
|
||||
#[cfg(feature = "read-boundary")]
|
||||
mod boundary;
|
||||
mod sqlite_resource;
|
||||
#[cfg(feature = "read-boundary")]
|
||||
use boundary::{decode, encode};
|
||||
use deadpool_sqlite::rusqlite::{self, Row, params};
|
||||
use serde::{Deserialize, Serialize};
|
||||
#[cfg(not(feature = "read-boundary"))]
|
||||
use serde_json::{from_str as decode, to_string as encode};
|
||||
use sqlite_resource::{Lease, Result, Work, pool};
|
||||
use std::{collections::HashMap, time::Duration};
|
||||
const TIMEOUT: Duration = Duration::from_secs(30);
|
||||
const MAX_PAGE: i64 = 1024;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Moment(i64);
|
||||
impl Serialize for Moment {
|
||||
fn serialize<S: serde::Serializer>(&self, output: S) -> std::result::Result<S::Ok, S::Error> {
|
||||
let value = chrono::DateTime::from_timestamp_millis(self.0)
|
||||
.ok_or_else(|| serde::ser::Error::custom("timestamp out of range"))?;
|
||||
let pattern = if self.0 % 1000 == 0 {
|
||||
"%Y-%m-%dT%H:%M:%SZ"
|
||||
} else {
|
||||
"%Y-%m-%dT%H:%M:%S%.3fZ"
|
||||
};
|
||||
output.collect_str(&value.format(pattern))
|
||||
}
|
||||
}
|
||||
impl<'de> Deserialize<'de> for Moment {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(input: D) -> std::result::Result<Self, D::Error> {
|
||||
let value = String::deserialize(input)?;
|
||||
let parsed =
|
||||
chrono::DateTime::parse_from_rfc3339(&value).map_err(serde::de::Error::custom)?;
|
||||
#[cfg(feature = "read-boundary")]
|
||||
boundary::moment(&value, parsed).map_err(serde::de::Error::custom)?;
|
||||
Ok(Moment(parsed.timestamp_millis()))
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Article {
|
||||
id: i64,
|
||||
created_at: Moment,
|
||||
number: i64,
|
||||
title: String,
|
||||
#[cfg_attr(feature = "read-boundary", serde(default))]
|
||||
amount: i64,
|
||||
note: Option<String>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct PageInput {
|
||||
page: i64,
|
||||
size: i64,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct CursorInput {
|
||||
#[cfg_attr(
|
||||
feature = "read-boundary",
|
||||
serde(default, deserialize_with = "boundary::after")
|
||||
)]
|
||||
after: Option<Article>,
|
||||
size: i64,
|
||||
}
|
||||
#[derive(Serialize)]
|
||||
struct Page<T> {
|
||||
items: Vec<T>,
|
||||
page: i64,
|
||||
size: i64,
|
||||
total: i64,
|
||||
pages: i64,
|
||||
}
|
||||
#[derive(Serialize)]
|
||||
struct Cursor {
|
||||
items: Vec<Article>,
|
||||
next: Option<Article>,
|
||||
has_more: bool,
|
||||
}
|
||||
#[derive(Serialize)]
|
||||
struct Post {
|
||||
id: i64,
|
||||
created_at: Moment,
|
||||
title: String,
|
||||
author_id: i64,
|
||||
note: Option<String>,
|
||||
}
|
||||
#[derive(Serialize)]
|
||||
struct Author {
|
||||
id: i64,
|
||||
created_at: Moment,
|
||||
name: String,
|
||||
note: Option<String>,
|
||||
posts: Vec<Post>,
|
||||
}
|
||||
fn article(row: &Row<'_>) -> rusqlite::Result<Article> {
|
||||
Ok(Article {
|
||||
id: row.get(0)?,
|
||||
created_at: Moment(row.get(1)?),
|
||||
number: row.get(2)?,
|
||||
title: row.get(3)?,
|
||||
amount: row.get(4)?,
|
||||
note: row.get(5)?,
|
||||
})
|
||||
}
|
||||
fn page_offset(input: &PageInput) -> Result<i64> {
|
||||
if input.page < 1 || !(1..=MAX_PAGE).contains(&input.size) {
|
||||
return Err("invalid page or size".into());
|
||||
}
|
||||
input
|
||||
.page
|
||||
.checked_sub(1)
|
||||
.and_then(|page| page.checked_mul(input.size))
|
||||
.ok_or_else(|| "page offset overflow".into())
|
||||
}
|
||||
async fn page(work: &Work, lease: &mut Option<Lease>, input: PageInput) -> Result<Page<Article>> {
|
||||
let offset = page_offset(&input)?;
|
||||
let total: i64 = work
|
||||
.call(lease, TIMEOUT, |db| {
|
||||
Ok(db
|
||||
.prepare_cached("SELECT COUNT(*) FROM benchmark_article")?
|
||||
.query_row([], |row| row.get(0))?)
|
||||
})
|
||||
.await?;
|
||||
let size = input.size;
|
||||
let items = work.call(lease, TIMEOUT, move |db| {
|
||||
Ok(db.prepare_cached("SELECT id,created_at,number,title,amount,note FROM benchmark_article ORDER BY number ASC,id ASC LIMIT ?1 OFFSET ?2")?
|
||||
.query_map(params![size, offset], article)?.collect::<rusqlite::Result<Vec<_>>>()?)
|
||||
}).await?;
|
||||
Ok(Page {
|
||||
items,
|
||||
page: input.page,
|
||||
size,
|
||||
total,
|
||||
pages: total / size + i64::from(total % size != 0),
|
||||
})
|
||||
}
|
||||
async fn cursor(work: &Work, lease: &mut Option<Lease>, input: CursorInput) -> Result<Cursor> {
|
||||
if !(1..=MAX_PAGE).contains(&input.size) {
|
||||
return Err("invalid cursor size".into());
|
||||
}
|
||||
if input.after.as_ref().is_some_and(|row| row.id <= 0) {
|
||||
return Err("invalid cursor record".into());
|
||||
}
|
||||
let size = input.size;
|
||||
let mut items = work.call(lease, TIMEOUT, move |db| {
|
||||
let rows = match input.after {
|
||||
Some(after) => db.prepare_cached("SELECT id,created_at,number,title,amount,note FROM benchmark_article WHERE (number > ?1 OR (number = ?1 AND id > ?2)) ORDER BY number ASC,id ASC LIMIT ?3")?
|
||||
.query_map(params![after.number, after.id, size + 1], article)?.collect::<rusqlite::Result<Vec<_>>>()?,
|
||||
None => db.prepare_cached("SELECT id,created_at,number,title,amount,note FROM benchmark_article ORDER BY number ASC,id ASC LIMIT ?1")?
|
||||
.query_map([size + 1], article)?.collect::<rusqlite::Result<Vec<_>>>()?,
|
||||
};
|
||||
Ok(rows)
|
||||
}).await?;
|
||||
let has_more = items.len() > size as usize;
|
||||
if has_more {
|
||||
items.pop();
|
||||
}
|
||||
let next = if has_more {
|
||||
items.last().cloned()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(Cursor {
|
||||
items,
|
||||
next,
|
||||
has_more,
|
||||
})
|
||||
}
|
||||
async fn relations(
|
||||
work: &Work,
|
||||
lease: &mut Option<Lease>,
|
||||
input: PageInput,
|
||||
) -> Result<Page<Author>> {
|
||||
let offset = page_offset(&input)?;
|
||||
let total: i64 = work
|
||||
.call(lease, TIMEOUT, |db| {
|
||||
Ok(db
|
||||
.prepare_cached("SELECT COUNT(*) FROM benchmark_read_author")?
|
||||
.query_row([], |row| row.get(0))?)
|
||||
})
|
||||
.await?;
|
||||
let size = input.size;
|
||||
let mut items = work.call(lease, TIMEOUT, move |db| {
|
||||
Ok(db.prepare_cached("SELECT id,created_at,name,note FROM benchmark_read_author ORDER BY id ASC LIMIT ?1 OFFSET ?2")?
|
||||
.query_map(params![size, offset], |row| Ok(Author { id: row.get(0)?, created_at: Moment(row.get(1)?),
|
||||
name: row.get(2)?, note: row.get(3)?, posts: Vec::new() }))?.collect::<rusqlite::Result<Vec<_>>>()?)
|
||||
}).await?;
|
||||
let mut ids: Vec<_> = items.iter().map(|row| row.id).collect();
|
||||
ids.sort_unstable();
|
||||
ids.dedup();
|
||||
let mut related: HashMap<i64, Vec<Post>> = HashMap::with_capacity(ids.len());
|
||||
if !ids.is_empty() {
|
||||
let placeholders = (1..=ids.len())
|
||||
.map(|i| format!("?{i}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(",");
|
||||
let sql = format!(
|
||||
"SELECT id,created_at,title,author_id,note FROM (SELECT *,ROW_NUMBER() OVER(PARTITION BY author_id ORDER BY id DESC) AS __dever_rank FROM benchmark_read_post WHERE author_id IN ({placeholders})) AS related WHERE __dever_rank <= {} ORDER BY id DESC",
|
||||
MAX_PAGE + 1
|
||||
);
|
||||
let values = work
|
||||
.call(lease, TIMEOUT, move |db| {
|
||||
Ok(db
|
||||
.prepare_cached(&sql)?
|
||||
.query_map(rusqlite::params_from_iter(ids), |row| {
|
||||
Ok(Post {
|
||||
id: row.get(0)?,
|
||||
created_at: Moment(row.get(1)?),
|
||||
title: row.get(2)?,
|
||||
author_id: row.get(3)?,
|
||||
note: row.get(4)?,
|
||||
})
|
||||
})?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?)
|
||||
})
|
||||
.await?;
|
||||
for value in values {
|
||||
let group = related.entry(value.author_id).or_default();
|
||||
group.push(value);
|
||||
if group.len() > MAX_PAGE as usize {
|
||||
return Err("relation exceeds max_page_size".into());
|
||||
}
|
||||
}
|
||||
}
|
||||
for row in &mut items {
|
||||
row.posts = related.remove(&row.id).unwrap_or_default();
|
||||
}
|
||||
Ok(Page {
|
||||
items,
|
||||
page: input.page,
|
||||
size,
|
||||
total,
|
||||
pages: total / size + i64::from(total % size != 0),
|
||||
})
|
||||
}
|
||||
async fn execute(path: &str, operation: &str, input: &str) -> Result<String> {
|
||||
enum Input {
|
||||
Page(PageInput),
|
||||
Cursor(CursorInput),
|
||||
Relations(PageInput),
|
||||
}
|
||||
let input = match operation {
|
||||
"page" => Input::Page(decode(input)?),
|
||||
"cursor" => Input::Cursor(decode(input)?),
|
||||
"relations" => Input::Relations(decode(input)?),
|
||||
_ => return Err("unknown read operation".into()),
|
||||
};
|
||||
let pool = pool(path, 1).await?;
|
||||
let work = Work::new();
|
||||
let mut lease = Some(Lease {
|
||||
object: Some(pool.get().await?),
|
||||
reusable: true,
|
||||
});
|
||||
let result = async {
|
||||
#[cfg(feature = "read-boundary")]
|
||||
boundary::verify(&work, &mut lease).await?;
|
||||
Ok(match input {
|
||||
Input::Page(input) => encode(&page(&work, &mut lease, input).await?)?,
|
||||
Input::Cursor(input) => encode(&cursor(&work, &mut lease, input).await?)?,
|
||||
Input::Relations(input) => encode(&relations(&work, &mut lease, input).await?)?,
|
||||
})
|
||||
}
|
||||
.await;
|
||||
drop(lease);
|
||||
let cleanup = work.finish().await;
|
||||
drop(pool);
|
||||
match (result, cleanup) {
|
||||
(Ok(value), Ok(())) => Ok(value),
|
||||
(Err(error), Ok(())) | (Ok(_), Err(error)) => Err(error),
|
||||
(Err(primary), Err(cleanup)) => {
|
||||
eprintln!("cleanup: {cleanup}");
|
||||
Err(primary)
|
||||
}
|
||||
}
|
||||
}
|
||||
fn plans(path: &str) -> Result<()> {
|
||||
let db =
|
||||
rusqlite::Connection::open_with_flags(path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)?;
|
||||
let prefix = "SELECT id,created_at,number,title,amount,note FROM benchmark_article";
|
||||
let cases = [
|
||||
(
|
||||
"flag_or",
|
||||
format!(
|
||||
"{prefix} WHERE (?1 = 0 OR (number > ?2 OR (number = ?2 AND id > ?3))) ORDER BY number ASC,id ASC LIMIT ?4"
|
||||
),
|
||||
vec![1i64, 196605, 65535, 2],
|
||||
),
|
||||
(
|
||||
"lexicographic",
|
||||
format!(
|
||||
"{prefix} WHERE (number > ?1 OR (number = ?1 AND id > ?2)) ORDER BY number ASC,id ASC LIMIT ?3"
|
||||
),
|
||||
vec![196605, 65535, 2],
|
||||
),
|
||||
(
|
||||
"tuple",
|
||||
format!("{prefix} WHERE (number,id) > (?1,?2) ORDER BY number ASC,id ASC LIMIT ?3"),
|
||||
vec![196605, 65535, 2],
|
||||
),
|
||||
];
|
||||
let mut report = Vec::new();
|
||||
for (case, sql, parameters) in cases {
|
||||
let steps = db
|
||||
.prepare(&format!("EXPLAIN QUERY PLAN {sql}"))?
|
||||
.query_map(rusqlite::params_from_iter(parameters), |row| {
|
||||
row.get::<_, String>(3)
|
||||
})?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
report.push(serde_json::json!({"case":case,"sql":sql,"plan":steps}));
|
||||
}
|
||||
println!("{}", serde_json::to_string(&report)?);
|
||||
Ok(())
|
||||
}
|
||||
fn main() -> Result<()> {
|
||||
let args: Vec<_> = std::env::args().collect();
|
||||
if args[1] == "--sqlite-version" {
|
||||
println!("{}", rusqlite::version());
|
||||
return Ok(());
|
||||
}
|
||||
if args[1] == "--plans" {
|
||||
return plans(&args[2]);
|
||||
}
|
||||
#[cfg(feature = "read-boundary")]
|
||||
if args[1] == "--self-test" {
|
||||
return boundary::self_test();
|
||||
}
|
||||
#[cfg(feature = "read-boundary")]
|
||||
let (path, operation, input) = boundary::command(&args)?;
|
||||
#[cfg(not(feature = "read-boundary"))]
|
||||
let (path, operation, input) = (&args[1], args[2].as_str(), args[3].as_str());
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()?;
|
||||
println!("{}", runtime.block_on(execute(&path, operation, input))?);
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
//! 独立参考的真实入口责任:配置、Model 结构与具名 JSON 的单次编解码预算。
|
||||
use super::*;
|
||||
use rusqlite::OptionalExtension;
|
||||
use serde::de::{MapAccess, Visitor, value::MapAccessDeserializer};
|
||||
use serde_json::ser::{CompactFormatter, Formatter};
|
||||
use std::{
|
||||
fmt,
|
||||
io::{self, Write},
|
||||
marker::PhantomData,
|
||||
path::{Component, Path},
|
||||
};
|
||||
include!("schemas.rs");
|
||||
const MAX_BYTES: usize = 16 * 1024 * 1024;
|
||||
const MAX_VALUES: usize = 65536;
|
||||
const MAX_DEPTH: usize = 64;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Setting {
|
||||
database: Databases,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Databases {
|
||||
default: Sqlite,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Sqlite {
|
||||
#[serde(rename = "type")]
|
||||
kind: String,
|
||||
path: String,
|
||||
max_connections: usize,
|
||||
max_page_size: usize,
|
||||
}
|
||||
pub(super) fn command(args: &[String]) -> Result<(String, &str, &str)> {
|
||||
if args.len() != 5 || args[1] != "--config" {
|
||||
return Err("expected --config FILE CMD JSON".into());
|
||||
}
|
||||
let path = Path::new(&args[2]).canonicalize()?;
|
||||
let setting: Setting = serde_json::from_str(&std::fs::read_to_string(&path)?)?;
|
||||
let setting = setting.database.default;
|
||||
if setting.kind != "sqlite"
|
||||
|| setting.max_connections != 1
|
||||
|| setting.max_page_size != MAX_PAGE as usize
|
||||
{
|
||||
return Err("this reference requires SQLite, one connection and max_page_size=1024".into());
|
||||
}
|
||||
let relative = Path::new(&setting.path);
|
||||
if relative.as_os_str().is_empty()
|
||||
|| relative
|
||||
.components()
|
||||
.any(|c| !matches!(c, Component::Normal(_)))
|
||||
{
|
||||
return Err("database path must be relative to the application directory".into());
|
||||
}
|
||||
let database = path
|
||||
.parent()
|
||||
.and_then(Path::parent)
|
||||
.ok_or("missing project root")?
|
||||
.join(relative);
|
||||
let operation = match args[3].as_str() {
|
||||
"benchmark.article.page" => "page",
|
||||
"benchmark.article.cursor" => "cursor",
|
||||
"benchmark.read.page" => "relations",
|
||||
_ => return Err("unknown Model command".into()),
|
||||
};
|
||||
Ok((
|
||||
database
|
||||
.to_str()
|
||||
.ok_or("database path is not UTF-8")?
|
||||
.into(),
|
||||
operation,
|
||||
&args[4],
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) async fn verify(work: &Work, lease: &mut Option<Lease>) -> Result<()> {
|
||||
work.call(lease, TIMEOUT, |db| {
|
||||
for &(table, expected) in SCHEMAS {
|
||||
let recorded: Option<(String,String)> = db.query_row(
|
||||
"SELECT definition,catalog FROM _dever_history WHERE name=?1", [table],
|
||||
|row| Ok((row.get(0)?,row.get(1)?))).optional()?;
|
||||
let (definition, catalog) = recorded.ok_or("Model schema is missing")?;
|
||||
let mut query = db.prepare("SELECT type,name,sql FROM sqlite_schema WHERE tbl_name=?1 AND sql IS NOT NULL ORDER BY type,name")?;
|
||||
let actual = query.query_map([table], |row| Ok((row.get::<_,String>(0)?,row.get::<_,String>(1)?,row.get::<_,String>(2)?)))?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
if definition != expected || catalog != serde_json::to_string(&actual)? {
|
||||
return Err("Model schema is outdated or changed".into());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}).await
|
||||
}
|
||||
|
||||
fn object<'de, T: Deserialize<'de>, D: serde::Deserializer<'de>>(
|
||||
input: D,
|
||||
) -> std::result::Result<T, D::Error> {
|
||||
struct Named<T>(PhantomData<T>);
|
||||
impl<'de, T: Deserialize<'de>> Visitor<'de> for Named<T> {
|
||||
type Value = T;
|
||||
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
f.write_str("a named JSON object")
|
||||
}
|
||||
fn visit_map<M: MapAccess<'de>>(self, map: M) -> std::result::Result<T, M::Error> {
|
||||
T::deserialize(MapAccessDeserializer::new(map))
|
||||
}
|
||||
}
|
||||
input.deserialize_map(Named(PhantomData))
|
||||
}
|
||||
pub(super) fn decode<T: serde::de::DeserializeOwned>(input: &str) -> Result<T> {
|
||||
// 本夹具的输入类型最多三层、十一个值;只须在具名解码边界检查字节数。
|
||||
if input.len() > MAX_BYTES {
|
||||
return Err("JSON exceeds 16 MiB".into());
|
||||
}
|
||||
let mut decoder = serde_json::Deserializer::from_str(input);
|
||||
let value = object(&mut decoder)?;
|
||||
decoder.end()?;
|
||||
Ok(value)
|
||||
}
|
||||
pub(super) fn after<'de, D: serde::Deserializer<'de>>(
|
||||
input: D,
|
||||
) -> std::result::Result<Option<Article>, D::Error> {
|
||||
struct OptionalRecord;
|
||||
impl<'de> Visitor<'de> for OptionalRecord {
|
||||
type Value = Option<Article>;
|
||||
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
f.write_str("null or a Model object")
|
||||
}
|
||||
fn visit_none<E: serde::de::Error>(self) -> std::result::Result<Self::Value, E> {
|
||||
Ok(None)
|
||||
}
|
||||
fn visit_unit<E: serde::de::Error>(self) -> std::result::Result<Self::Value, E> {
|
||||
Ok(None)
|
||||
}
|
||||
fn visit_some<D: serde::Deserializer<'de>>(
|
||||
self,
|
||||
input: D,
|
||||
) -> std::result::Result<Self::Value, D::Error> {
|
||||
object(input).map(Some)
|
||||
}
|
||||
}
|
||||
input.deserialize_option(OptionalRecord)
|
||||
}
|
||||
pub(super) fn moment(text: &str, value: chrono::DateTime<chrono::FixedOffset>) -> Result<()> {
|
||||
use chrono::{Datelike, Timelike};
|
||||
let fraction = text.get(19..).and_then(|part| part.strip_prefix('.'));
|
||||
if fraction.is_some_and(|part| part.bytes().take_while(u8::is_ascii_digit).count() > 3)
|
||||
|| value.nanosecond() >= 1_000_000_000
|
||||
|| !value.nanosecond().is_multiple_of(1_000_000)
|
||||
|| !(0..=9999).contains(&value.with_timezone(&chrono::Utc).year())
|
||||
{
|
||||
return Err(
|
||||
"DateTime requires four-digit UTC year, milliseconds and no leap seconds".into(),
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct Output(Vec<u8>);
|
||||
impl Write for Output {
|
||||
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
|
||||
if bytes.len() > MAX_BYTES - self.0.len() {
|
||||
return Err(io::Error::other("JSON exceeds 16 MiB"));
|
||||
}
|
||||
self.0.extend_from_slice(bytes);
|
||||
Ok(bytes.len())
|
||||
}
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
struct Limit {
|
||||
depth: usize,
|
||||
values: usize,
|
||||
}
|
||||
impl Limit {
|
||||
fn open(&mut self) -> io::Result<()> {
|
||||
if self.depth == MAX_DEPTH {
|
||||
return Err(io::Error::other("JSON depth limit"));
|
||||
}
|
||||
self.depth += 1;
|
||||
Ok(())
|
||||
}
|
||||
fn value(&mut self) -> io::Result<()> {
|
||||
if self.values == MAX_VALUES {
|
||||
return Err(io::Error::other("JSON value limit"));
|
||||
}
|
||||
self.values += 1;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl Formatter for Limit {
|
||||
fn begin_array<W: Write + ?Sized>(&mut self, out: &mut W) -> io::Result<()> {
|
||||
self.open()?;
|
||||
CompactFormatter.begin_array(out)
|
||||
}
|
||||
fn end_array<W: Write + ?Sized>(&mut self, out: &mut W) -> io::Result<()> {
|
||||
self.depth -= 1;
|
||||
CompactFormatter.end_array(out)
|
||||
}
|
||||
fn begin_array_value<W: Write + ?Sized>(&mut self, out: &mut W, first: bool) -> io::Result<()> {
|
||||
self.value()?;
|
||||
CompactFormatter.begin_array_value(out, first)
|
||||
}
|
||||
fn begin_object<W: Write + ?Sized>(&mut self, out: &mut W) -> io::Result<()> {
|
||||
self.open()?;
|
||||
CompactFormatter.begin_object(out)
|
||||
}
|
||||
fn end_object<W: Write + ?Sized>(&mut self, out: &mut W) -> io::Result<()> {
|
||||
self.depth -= 1;
|
||||
CompactFormatter.end_object(out)
|
||||
}
|
||||
fn begin_object_value<W: Write + ?Sized>(&mut self, out: &mut W) -> io::Result<()> {
|
||||
self.value()?;
|
||||
CompactFormatter.begin_object_value(out)
|
||||
}
|
||||
}
|
||||
pub(super) fn encode<T: Serialize + ?Sized>(data: &T) -> Result<String> {
|
||||
#[derive(Serialize)]
|
||||
struct Response<'a, T: ?Sized> {
|
||||
code: u16,
|
||||
message: &'static str,
|
||||
data: &'a T,
|
||||
}
|
||||
let mut out = Output(Vec::with_capacity(128));
|
||||
Response {
|
||||
code: 0,
|
||||
message: "ok",
|
||||
data,
|
||||
}
|
||||
.serialize(&mut serde_json::Serializer::with_formatter(
|
||||
&mut out,
|
||||
Limit {
|
||||
depth: 0,
|
||||
values: 1,
|
||||
},
|
||||
))?;
|
||||
Ok(String::from_utf8(out.0)?)
|
||||
}
|
||||
pub(super) fn self_test() -> Result<()> {
|
||||
assert!(encode(&vec![0u8; MAX_VALUES - 4]).is_ok());
|
||||
assert!(encode(&vec![0u8; MAX_VALUES - 3]).is_err());
|
||||
let mut value = serde_json::Value::Null;
|
||||
for _ in 0..MAX_DEPTH - 1 {
|
||||
value = serde_json::json!([value]);
|
||||
}
|
||||
assert!(encode(&value).is_ok());
|
||||
assert!(encode(&serde_json::json!([value])).is_err());
|
||||
let overhead = encode("")?.len();
|
||||
assert_eq!(encode(&"x".repeat(MAX_BYTES - overhead))?.len(), MAX_BYTES);
|
||||
assert!(encode(&"x".repeat(MAX_BYTES - overhead + 1)).is_err());
|
||||
println!("byte/value/depth boundaries passed");
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
type PostRow { id: data.post.id, created_at: DateTime, title: Text, author_id: data.author.id, note: Text? }
|
||||
type AuthorRow { id: data.author.id, created_at: DateTime, name: Text, note: Text?, posts: List<PostRow> }
|
||||
type Page { items: List<AuthorRow>, page: Int, size: Int, total: Int, pages: Int }
|
||||
type Error { error NotLoaded }
|
||||
|
||||
loop posts(rows: List<data.post.Post>) (out: List<PostRow>)
|
||||
| each row in rows | result |
|
||||
| out | list PostRow { id = row.id, created_at = row.created_at, title = row.title, author_id = row.author_id, note = row.note } |
|
||||
|
||||
rule loaded(value: Related<List<data.post.Post>>) (out: List<PostRow>)
|
||||
| value | out |
|
||||
| Loaded(rows) | posts(rows) |
|
||||
| Unloaded | fail(Error.NotLoaded) |
|
||||
|
||||
loop authors(rows: List<data.author.Author>) (out: List<AuthorRow>)
|
||||
| each row in rows | result |
|
||||
| out | list AuthorRow { id = row.id, created_at = row.created_at, name = row.name, note = row.note, posts = loaded(row.posts) } |
|
||||
|
||||
flow page(page: Int, size: Int) (out: Page)
|
||||
| step | kind | do |
|
||||
| found | data | data.author.page(order = id.asc, with = [posts], page = page, size = size) |
|
||||
| items | loop | authors(found.items) |
|
||||
| out | calc | Page { items = items, page = found.page, size = found.size, total = found.total, pages = found.pages } |
|
||||
@@ -0,0 +1,239 @@
|
||||
//! 独立 Tokio/deadpool SQLite 对端;每条 SQL 有期限,取消后排空阻塞工作。
|
||||
mod sqlite_resource;
|
||||
use deadpool_sqlite::rusqlite::{self, Connection, Row, params};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sqlite_resource::{Lease, Result, Work, pool};
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Input {
|
||||
numbers: Vec<i64>,
|
||||
title: String,
|
||||
}
|
||||
#[derive(Serialize)]
|
||||
struct Output {
|
||||
checksum: i64,
|
||||
count: i64,
|
||||
}
|
||||
struct Article {
|
||||
id: i64,
|
||||
_created_at: i64,
|
||||
_number: i64,
|
||||
_title: String,
|
||||
amount: i64,
|
||||
_note: Option<String>,
|
||||
}
|
||||
|
||||
fn article(row: &Row<'_>) -> rusqlite::Result<Article> {
|
||||
// 和 Model 一样把完整记录交付给调用方,字段由持有记录的一方释放。
|
||||
Ok(Article {
|
||||
id: row.get(0)?,
|
||||
_created_at: row.get(1)?,
|
||||
_number: row.get(2)?,
|
||||
_title: row.get(3)?,
|
||||
amount: row.get(4)?,
|
||||
_note: row.get(5)?,
|
||||
})
|
||||
}
|
||||
|
||||
async fn batch(work: &Work, lease: &mut Option<Lease>, input: Input) -> Result<String> {
|
||||
let timeout = Duration::from_secs(30);
|
||||
work.call(lease, timeout, |connection| {
|
||||
connection.execute_batch("BEGIN IMMEDIATE")?;
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
work.call(lease, timeout, |connection| {
|
||||
connection
|
||||
.prepare_cached("DELETE FROM benchmark_article WHERE number >= ?1")?
|
||||
.execute([0])?;
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
let mut checksum = 0i64;
|
||||
for number in input.numbers {
|
||||
let title = input.title.clone();
|
||||
let created = work.call(lease, timeout, move |connection| {
|
||||
let now = i64::try_from(SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis())?;
|
||||
let mut statement = connection.prepare_cached("INSERT INTO benchmark_article (created_at,number,title,amount,note) VALUES (?1,?2,?3,?4,NULL) RETURNING id,created_at,number,title,amount,note")?;
|
||||
let mut rows = statement.query(params![now, number, title, number])?;
|
||||
let value = article(rows.next()?.ok_or("missing inserted row")?)?;
|
||||
rows.next()?;
|
||||
Ok(value)
|
||||
}).await?;
|
||||
let found = work.call(lease, timeout, move |connection| {
|
||||
Ok(connection.prepare_cached("SELECT id,created_at,number,title,amount,note FROM benchmark_article WHERE id = ?1")?
|
||||
.query_row([created.id], article)?)
|
||||
}).await?;
|
||||
let amount = found.amount.checked_add(1).ok_or("amount overflow")?;
|
||||
let updated = work.call(lease, timeout, move |connection| {
|
||||
let mut statement = connection.prepare_cached("UPDATE benchmark_article SET amount = ?2 WHERE id = ?1 RETURNING id,created_at,number,title,amount,note")?;
|
||||
let mut rows = statement.query(params![found.id, amount])?;
|
||||
let value = article(rows.next()?.ok_or("missing updated row")?)?;
|
||||
rows.next()?;
|
||||
Ok(value)
|
||||
}).await?;
|
||||
checksum = checksum
|
||||
.checked_add(updated.amount)
|
||||
.ok_or("checksum overflow")?;
|
||||
}
|
||||
let count = work
|
||||
.call(lease, timeout, |connection| {
|
||||
Ok(connection
|
||||
.prepare_cached("SELECT COUNT(*) FROM benchmark_article")?
|
||||
.query_row([], |row| row.get(0))?)
|
||||
})
|
||||
.await?;
|
||||
let encoded = serde_json::to_string(&Output { checksum, count })?;
|
||||
work.call(lease, timeout, |connection| {
|
||||
connection.execute_batch("COMMIT")?;
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
Ok(encoded)
|
||||
}
|
||||
|
||||
async fn execute(path: &str, input: Input) -> Result<String> {
|
||||
let pool = pool(path, 1).await?;
|
||||
let work = Work::new();
|
||||
let mut lease = Some(Lease {
|
||||
object: Some(pool.get().await?),
|
||||
reusable: true,
|
||||
});
|
||||
let result = batch(&work, &mut lease, input).await;
|
||||
if result.is_err() && lease.is_some() {
|
||||
let rollback = work
|
||||
.call(&mut lease, Duration::from_secs(30), |connection| {
|
||||
if !connection.is_autocommit() {
|
||||
connection.execute_batch("ROLLBACK")?;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.await;
|
||||
if let Err(error) = rollback {
|
||||
eprintln!("rollback: {error}");
|
||||
}
|
||||
}
|
||||
drop(lease);
|
||||
let cleanup = work.finish().await;
|
||||
drop(pool);
|
||||
if let Err(error) = cleanup {
|
||||
if result.is_ok() {
|
||||
return Err(error);
|
||||
}
|
||||
eprintln!("cleanup: {error}");
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
async fn self_test(path: &str) -> Result<()> {
|
||||
let pool = pool(path, 1).await?;
|
||||
for cancel in [false, true] {
|
||||
let work = Work::new();
|
||||
let mut lease = Some(Lease {
|
||||
object: Some(pool.get().await?),
|
||||
reusable: true,
|
||||
});
|
||||
let (started, ready) = tokio::sync::oneshot::channel();
|
||||
{
|
||||
let call = work.call(&mut lease, Duration::from_millis(50), move |connection| {
|
||||
connection.execute_batch("BEGIN IMMEDIATE; INSERT INTO cancellation VALUES (1)")?;
|
||||
started.send(()).unwrap();
|
||||
connection.query_row("WITH RECURSIVE counter(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM counter WHERE x < 1000000000) SELECT sum(x) FROM counter", [], |row| row.get::<_, i64>(0))?;
|
||||
Ok(())
|
||||
});
|
||||
tokio::pin!(call);
|
||||
if cancel {
|
||||
tokio::select! {
|
||||
result = &mut call => panic!("work ended before cancellation: {result:?}"),
|
||||
result = ready => result?,
|
||||
}
|
||||
} else {
|
||||
assert!(call.await.is_err());
|
||||
ready.await?;
|
||||
}
|
||||
}
|
||||
drop(lease);
|
||||
work.finish().await?;
|
||||
assert_eq!(work.slots.available_permits(), 8);
|
||||
let object = pool.get().await?;
|
||||
let connection = object.lock().map_err(|_| "poisoned connection")?;
|
||||
assert_eq!(
|
||||
connection.query_row("SELECT COUNT(*) FROM cancellation", [], |row| row
|
||||
.get::<_, i64>(0))?,
|
||||
0
|
||||
);
|
||||
}
|
||||
let work = Work::new();
|
||||
let mut lease = Some(Lease {
|
||||
object: Some(pool.get().await?),
|
||||
reusable: true,
|
||||
});
|
||||
let (started, ready) = tokio::sync::oneshot::channel();
|
||||
{
|
||||
let call = work.call::<()>(&mut lease, Duration::from_secs(30), move |connection| {
|
||||
connection.execute_batch("BEGIN IMMEDIATE; INSERT INTO cancellation VALUES (2)")?;
|
||||
started.send(()).unwrap();
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
panic!("cancelled SQL panic");
|
||||
});
|
||||
tokio::pin!(call);
|
||||
tokio::select! {
|
||||
result = &mut call => panic!("work ended before cancellation: {result:?}"),
|
||||
result = ready => result?,
|
||||
}
|
||||
}
|
||||
drop(lease);
|
||||
assert!(
|
||||
work.finish()
|
||||
.await
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("cancelled SQL panic")
|
||||
);
|
||||
assert_eq!(work.slots.available_permits(), 8);
|
||||
let object = pool.get().await?;
|
||||
assert_eq!(
|
||||
object
|
||||
.lock()
|
||||
.map_err(|_| "poisoned connection")?
|
||||
.query_row("SELECT COUNT(*) FROM cancellation", [], |row| row
|
||||
.get::<_, i64>(0))?,
|
||||
0
|
||||
);
|
||||
drop(object);
|
||||
drop(pool);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let args: Vec<_> = std::env::args().collect();
|
||||
if args[1] == "--sqlite-version" {
|
||||
println!("{}", rusqlite::version());
|
||||
return Ok(());
|
||||
}
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()?;
|
||||
if args[1] == "--self-test" {
|
||||
let file = std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&args[2])?;
|
||||
drop(file);
|
||||
let connection = Connection::open(&args[2])?;
|
||||
connection.execute_batch("CREATE TABLE cancellation (value INTEGER NOT NULL)")?;
|
||||
drop(connection);
|
||||
runtime.block_on(self_test(&args[2]))?;
|
||||
println!("deadline, cancellation, rollback and drain passed");
|
||||
return Ok(());
|
||||
}
|
||||
let mut input: Input = serde_json::from_str(&args[2])?;
|
||||
input.title = input.title.trim().into();
|
||||
if !(1..=120).contains(&input.title.chars().count()) {
|
||||
return Err("title range".into());
|
||||
}
|
||||
println!("{}", runtime.block_on(execute(&args[1], input))?);
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
//! 独立性能参考共用的 SQLite 资源责任;仅依赖官方库,不链接 Dever。
|
||||
use deadpool_sqlite::{
|
||||
Object, Pool, Runtime,
|
||||
rusqlite::{self, Connection},
|
||||
};
|
||||
use std::{
|
||||
error::Error,
|
||||
panic::{AssertUnwindSafe, catch_unwind},
|
||||
sync::{Arc, Mutex},
|
||||
time::Duration,
|
||||
};
|
||||
use tokio::{sync::Semaphore, time::Instant};
|
||||
use tokio_util::{sync::CancellationToken, task::TaskTracker};
|
||||
pub(crate) type Result<T> = std::result::Result<T, Box<dyn Error + Send + Sync>>;
|
||||
|
||||
pub(crate) struct Lease {
|
||||
pub(crate) object: Option<Object>,
|
||||
pub(crate) reusable: bool,
|
||||
}
|
||||
impl Drop for Lease {
|
||||
fn drop(&mut self) {
|
||||
if !self.reusable {
|
||||
drop(Object::take(self.object.take().unwrap()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Work {
|
||||
tasks: TaskTracker,
|
||||
pub(crate) slots: Arc<Semaphore>,
|
||||
faults: Arc<Mutex<Vec<String>>>,
|
||||
}
|
||||
impl Work {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
tasks: TaskTracker::new(),
|
||||
slots: Arc::new(Semaphore::new(8)),
|
||||
faults: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn call<T: Send + 'static>(
|
||||
&self,
|
||||
lease: &mut Option<Lease>,
|
||||
timeout: Duration,
|
||||
run: impl FnOnce(&mut Connection) -> Result<T> + Send + 'static,
|
||||
) -> Result<T> {
|
||||
let deadline = Instant::now() + timeout;
|
||||
let cancelled = CancellationToken::new();
|
||||
let _cancel = cancelled.clone().drop_guard();
|
||||
let slot = tokio::time::timeout_at(deadline, self.slots.clone().acquire_owned()).await??;
|
||||
let mut owned = lease.take().ok_or("discarded connection")?;
|
||||
owned.reusable = false;
|
||||
let faults = self.faults.clone();
|
||||
// 令牌随结果释放,调用取消时也等到连接被归还或丢弃后才算排空。
|
||||
let tracking = self.tasks.token();
|
||||
let job = tokio::task::spawn_blocking(move || {
|
||||
let result = catch_unwind(AssertUnwindSafe(|| -> Result<T> {
|
||||
let mut connection = owned
|
||||
.object
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.lock()
|
||||
.map_err(|_| "poisoned SQLite connection")?;
|
||||
if cancelled.is_cancelled() || Instant::now() >= deadline {
|
||||
return Err("SQLite operation cancelled or expired".into());
|
||||
}
|
||||
let signal = cancelled.clone();
|
||||
connection.progress_handler(
|
||||
1000,
|
||||
Some(move || signal.is_cancelled() || Instant::now() >= deadline),
|
||||
)?;
|
||||
let value = run(&mut connection);
|
||||
connection.progress_handler(0, None::<fn() -> bool>)?;
|
||||
if cancelled.is_cancelled() || Instant::now() >= deadline {
|
||||
return Err("SQLite operation cancelled or expired".into());
|
||||
}
|
||||
owned.reusable = connection.is_autocommit();
|
||||
value
|
||||
}));
|
||||
let result = result.unwrap_or_else(|panic| {
|
||||
let message = panic_message(panic);
|
||||
faults.lock().unwrap().push(message.clone());
|
||||
Err(message.into())
|
||||
});
|
||||
drop(slot);
|
||||
(owned, result, tracking)
|
||||
});
|
||||
let (owned, result, _tracking) = tokio::time::timeout_at(deadline, job).await??;
|
||||
*lease = Some(owned);
|
||||
result
|
||||
}
|
||||
|
||||
pub(crate) async fn finish(&self) -> Result<()> {
|
||||
self.tasks.close();
|
||||
self.tasks.wait().await;
|
||||
let faults = std::mem::take(&mut *self.faults.lock().unwrap());
|
||||
if !faults.is_empty() {
|
||||
return Err(faults.join("; ").into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn panic_message(panic: Box<dyn std::any::Any + Send>) -> String {
|
||||
panic
|
||||
.downcast_ref::<&str>()
|
||||
.copied()
|
||||
.or_else(|| panic.downcast_ref::<String>().map(String::as_str))
|
||||
.unwrap_or("non-text Rust panic")
|
||||
.to_owned()
|
||||
}
|
||||
|
||||
pub(crate) async fn pool(path: &str, connections: usize) -> Result<Pool> {
|
||||
use deadpool_sqlite::{Hook, HookError, Timeouts};
|
||||
// 输入是测量驱动创建的实际路径;URI 编码避免路径中的 '?' 改写打开模式。
|
||||
const URI_PATH: &percent_encoding::AsciiSet =
|
||||
&percent_encoding::CONTROLS.add(b'%').add(b'?').add(b'#');
|
||||
let uri = format!(
|
||||
"file:{}?mode=rw",
|
||||
percent_encoding::utf8_percent_encode(path, URI_PATH)
|
||||
);
|
||||
let timeout = Duration::from_secs(30);
|
||||
Ok(deadpool_sqlite::Config::new(uri).builder(Runtime::Tokio1)?
|
||||
.max_size(connections)
|
||||
.timeouts(Timeouts { wait: Some(Duration::from_secs(5)), create: Some(timeout), recycle: Some(timeout) })
|
||||
.post_create(Hook::async_fn(move |object, _| Box::pin(async move {
|
||||
object.interact(move |connection| {
|
||||
connection.busy_timeout(timeout)?;
|
||||
connection.create_scalar_function("_dever_length", 1,
|
||||
rusqlite::functions::FunctionFlags::SQLITE_UTF8
|
||||
| rusqlite::functions::FunctionFlags::SQLITE_DETERMINISTIC
|
||||
| rusqlite::functions::FunctionFlags::SQLITE_INNOCUOUS,
|
||||
|ctx| Ok(ctx.get_raw(0).as_str()
|
||||
.map_err(|error| rusqlite::Error::UserFunctionError(Box::new(error)))?
|
||||
.chars().count() as i64))?;
|
||||
connection.execute_batch("PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA synchronous=NORMAL;")
|
||||
}).await.map_err(|error| HookError::message(error.to_string()))?
|
||||
.map_err(HookError::Backend)
|
||||
})))
|
||||
.build()?)
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
flow echo(value: Text) (out: Text)
|
||||
| step | kind | do |
|
||||
| out | port | port.echo(value) |
|
||||
|
||||
loop echoes(values: List<Text>) (out: List<Text>)
|
||||
| each value in values | result |
|
||||
| out | list echo(value) |
|
||||
|
||||
flow batch(values: List<Text>) (out: List<Text>)
|
||||
| step | kind | do |
|
||||
| - | port | port.unit() |
|
||||
| out | loop | echoes(values) |
|
||||
@@ -0,0 +1,8 @@
|
||||
echo(value: Text) (out: Text) {
|
||||
out = port.echo(value)
|
||||
}
|
||||
|
||||
batch(values: List<Text>) (out: List<Text>) {
|
||||
port.unit()
|
||||
out = each(echo, values)
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
// 独立客户端使用标准库的管道、长度帧和进程等待,不导入 Dever。
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
)
|
||||
|
||||
const limit = 16 * 1024 * 1024
|
||||
|
||||
type worker struct { command *exec.Cmd; input io.WriteCloser; output io.ReadCloser; next uint64; waited bool }
|
||||
func (w *worker) send(value any) error {
|
||||
body, err := json.Marshal(value)
|
||||
if err != nil { return err }
|
||||
if len(body) > limit { return errors.New("Worker frame exceeds byte limit") }
|
||||
var prefix [4]byte
|
||||
binary.BigEndian.PutUint32(prefix[:],uint32(len(body)))
|
||||
_, err = io.Copy(w.input, io.MultiReader(bytes.NewReader(prefix[:]), bytes.NewReader(body)))
|
||||
return err
|
||||
}
|
||||
func (w *worker) read(target any) error {
|
||||
var prefix [4]byte
|
||||
if _,err:=io.ReadFull(w.output,prefix[:]); err!=nil { return err }
|
||||
length:=binary.BigEndian.Uint32(prefix[:])
|
||||
if length==0 || length>limit { return errors.New("invalid Worker frame length") }
|
||||
body:=make([]byte,length)
|
||||
if _,err:=io.ReadFull(w.output,body); err!=nil { return err }
|
||||
decoder:=json.NewDecoder(bytes.NewReader(body))
|
||||
decoder.DisallowUnknownFields()
|
||||
return decoder.Decode(target)
|
||||
}
|
||||
func (w *worker) identity(kind string) error {
|
||||
message:=map[string]any{"kind":kind,"id":0}
|
||||
if err:=w.send(message); err!=nil { return err }
|
||||
var reply struct {Kind string `json:"kind"`; ID uint64 `json:"id"`}
|
||||
if err:=w.read(&reply); err!=nil { return err }
|
||||
if reply.Kind!=kind || reply.ID!=0 { return errors.New("Worker identity mismatch") }
|
||||
return nil
|
||||
}
|
||||
func (w *worker) call(operation string,payload any,target any) error {
|
||||
id:=w.next
|
||||
w.next++
|
||||
if err:=w.send(map[string]any{"kind":"call","id":id,"operation":operation,"payload":payload}); err!=nil { return err }
|
||||
var reply struct {Kind string `json:"kind"`; ID uint64 `json:"id"`; Payload json.RawMessage `json:"payload"`}
|
||||
if err:=w.read(&reply); err!=nil { return err }
|
||||
if reply.Kind!="result" || reply.ID!=id { return errors.New("Worker response identity mismatch") }
|
||||
decoder:=json.NewDecoder(bytes.NewReader(reply.Payload))
|
||||
decoder.DisallowUnknownFields()
|
||||
return decoder.Decode(target)
|
||||
}
|
||||
func run(path string, values []string) (results []string, failure error) {
|
||||
command:=exec.Command(path)
|
||||
input,err:=command.StdinPipe()
|
||||
if err!=nil { return nil,err }
|
||||
output,err:=command.StdoutPipe()
|
||||
if err!=nil { return nil,err }
|
||||
command.Stderr=os.Stderr
|
||||
if err=command.Start(); err!=nil { return nil,err }
|
||||
w:=worker{command:command,input:input,output:output,next:1}
|
||||
defer func(){
|
||||
if !w.waited {
|
||||
failure=errors.Join(failure,command.Process.Kill(),command.Wait())
|
||||
}
|
||||
}()
|
||||
hello:=map[string]any{"kind":"hello","version":"dever-component-1","port":"benchmark.echo","schema":"independent-reference","adapter":"default","capabilities":[]string{},"operations":[]string{"echo","unit"},"setting":nil}
|
||||
if err=w.send(hello); err!=nil { return nil,err }
|
||||
delete(hello,"setting")
|
||||
hello["kind"]="ready"
|
||||
expected,_:=json.Marshal(hello)
|
||||
var ready map[string]json.RawMessage
|
||||
if err=w.read(&ready); err!=nil { return nil,err }
|
||||
actual,_:=json.Marshal(ready)
|
||||
if !bytes.Equal(actual,expected) { return nil,errors.New("Worker handshake mismatch") }
|
||||
if err=w.identity("health"); err!=nil { return nil,err }
|
||||
var unit struct{}
|
||||
if err=w.call("unit",struct{}{},&unit); err!=nil { return nil,err }
|
||||
results=make([]string,0,len(values))
|
||||
for _,value:=range values {
|
||||
var reply struct{Out string `json:"out"`}
|
||||
if err=w.call("echo",map[string]string{"value":value},&reply); err!=nil { return nil,err }
|
||||
results=append(results,reply.Out)
|
||||
}
|
||||
if err=w.identity("shutdown"); err!=nil { return nil,err }
|
||||
failure=command.Wait()
|
||||
w.waited=true
|
||||
return results,failure
|
||||
}
|
||||
func main(){
|
||||
if len(os.Args)!=3 { fmt.Fprintln(os.Stderr,"expected Worker and input");os.Exit(1) }
|
||||
// 输入只有一个必填字段,Token/Decode 直接拒绝未知、重复、缺失与尾随内容。
|
||||
decoder:=json.NewDecoder(bytes.NewBufferString(os.Args[2]))
|
||||
begin,err:=decoder.Token()
|
||||
if err!=nil || begin!=json.Delim('{') { fmt.Fprintln(os.Stderr,"invalid input object");os.Exit(1) }
|
||||
field,err:=decoder.Token()
|
||||
if err!=nil || field!="values" { fmt.Fprintln(os.Stderr,"expected values");os.Exit(1) }
|
||||
start,err:=decoder.Token()
|
||||
if err!=nil || start!=json.Delim('[') { fmt.Fprintln(os.Stderr,"expected text list");os.Exit(1) }
|
||||
values:=[]string{}
|
||||
for decoder.More() {
|
||||
token,err:=decoder.Token()
|
||||
value,ok:=token.(string)
|
||||
if err!=nil || !ok { fmt.Fprintln(os.Stderr,"expected text element",err);os.Exit(1) }
|
||||
values=append(values,value)
|
||||
}
|
||||
if _,err=decoder.Token(); err!=nil { fmt.Fprintln(os.Stderr,err);os.Exit(1) }
|
||||
end,err:=decoder.Token()
|
||||
if err!=nil || end!=json.Delim('}') { fmt.Fprintln(os.Stderr,"unexpected input field");os.Exit(1) }
|
||||
if _,err=decoder.Token(); !errors.Is(err,io.EOF) { fmt.Fprintln(os.Stderr,"unexpected trailing input");os.Exit(1) }
|
||||
result,err:=run(os.Args[1],values)
|
||||
if err==nil { err=json.NewEncoder(os.Stdout).Encode(result) }
|
||||
if err!=nil { fmt.Fprintln(os.Stderr,err);os.Exit(1) }
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
//! 独立 Worker 客户端;帧、异步管道和期限直接使用 Tokio/tokio-util。
|
||||
use bytes::Bytes;
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use std::{error::Error, process::Stdio, time::Duration};
|
||||
use tokio::{process::{Child, ChildStdin, ChildStdout, Command}, time::timeout};
|
||||
use tokio_util::codec::{FramedRead, FramedWrite, LengthDelimitedCodec};
|
||||
type Result<T> = std::result::Result<T, Box<dyn Error + Send + Sync>>;
|
||||
const LIMIT: usize = 16 * 1024 * 1024;
|
||||
const DEADLINE: Duration = Duration::from_secs(2);
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Input { values: Vec<String> }
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Reply { kind: String, id: u64, payload: Value }
|
||||
struct Worker {
|
||||
child: Child,
|
||||
input: FramedWrite<ChildStdin, LengthDelimitedCodec>,
|
||||
output: FramedRead<ChildStdout, LengthDelimitedCodec>,
|
||||
next: u64,
|
||||
}
|
||||
impl Worker {
|
||||
async fn start(path: &str) -> Result<Self> {
|
||||
let mut child = Command::new(path).stdin(Stdio::piped()).stdout(Stdio::piped())
|
||||
.stderr(Stdio::inherit()).kill_on_drop(true).spawn()?;
|
||||
let mut worker = Self {
|
||||
input: LengthDelimitedCodec::builder().max_frame_length(LIMIT).new_write(child.stdin.take().unwrap()),
|
||||
output: LengthDelimitedCodec::builder().max_frame_length(LIMIT).new_read(child.stdout.take().unwrap()),
|
||||
child, next: 1,
|
||||
};
|
||||
let hello = json!({"kind":"hello","version":"dever-component-1","port":"benchmark.echo","schema":"independent-reference","adapter":"default","capabilities":[],"operations":["echo","unit"],"setting":null});
|
||||
worker.send(&hello).await?;
|
||||
let mut ready = hello;
|
||||
ready.as_object_mut().unwrap().remove("setting");
|
||||
ready["kind"] = "ready".into();
|
||||
if worker.read().await? != ready { return Err("Worker handshake mismatch".into()); }
|
||||
let health = json!({"kind":"health","id":0});
|
||||
worker.send(&health).await?;
|
||||
if worker.read().await? != health { return Err("Worker health mismatch".into()); }
|
||||
Ok(worker)
|
||||
}
|
||||
async fn send(&mut self, value: &Value) -> Result<()> {
|
||||
timeout(DEADLINE, self.input.send(Bytes::from(serde_json::to_vec(value)?))).await??;
|
||||
Ok(())
|
||||
}
|
||||
async fn read(&mut self) -> Result<Value> {
|
||||
let bytes = timeout(DEADLINE, self.output.next()).await?
|
||||
.ok_or("Worker closed its output")??;
|
||||
Ok(serde_json::from_slice(&bytes)?)
|
||||
}
|
||||
async fn call(&mut self, operation: &str, payload: Value) -> Result<Value> {
|
||||
let id = self.next;
|
||||
self.next += 1;
|
||||
self.send(&json!({"kind":"call","id":id,"operation":operation,"payload":payload})).await?;
|
||||
let reply: Reply = serde_json::from_value(self.read().await?)?;
|
||||
if reply.kind != "result" || reply.id != id { return Err("Worker response identity mismatch".into()); }
|
||||
Ok(reply.payload)
|
||||
}
|
||||
async fn stop(&mut self) -> Result<()> {
|
||||
let shutdown = json!({"kind":"shutdown","id":0});
|
||||
self.send(&shutdown).await?;
|
||||
if self.read().await? != shutdown { return Err("Worker shutdown mismatch".into()); }
|
||||
if !timeout(DEADLINE, self.child.wait()).await??.success() { return Err("Worker exited unsuccessfully".into()); }
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
async fn execute(path: &str, input: Input) -> Result<Vec<String>> {
|
||||
let mut worker = Worker::start(path).await?;
|
||||
let result = async {
|
||||
if worker.call("unit", json!({})).await? != json!({}) { return Err("invalid unit output".into()); }
|
||||
let mut results = Vec::with_capacity(input.values.len());
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Echo { out: String }
|
||||
for value in input.values {
|
||||
let output: Echo = serde_json::from_value(worker.call("echo", json!({"value":value})).await?)?;
|
||||
results.push(output.out);
|
||||
}
|
||||
Ok(results)
|
||||
}.await;
|
||||
match result {
|
||||
Ok(values) => { worker.stop().await?; Ok(values) }
|
||||
Err(error) => {
|
||||
worker.child.kill().await?;
|
||||
worker.child.wait().await?;
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
fn main() -> Result<()> {
|
||||
let mut args = std::env::args().skip(1);
|
||||
let worker = args.next().ok_or("Worker path is required")?;
|
||||
let input: Input = serde_json::from_str(&args.next().ok_or("input is required")?)?;
|
||||
let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build()?;
|
||||
let values = runtime.block_on(execute(&worker, input))?;
|
||||
println!("{}", serde_json::to_string(&values)?);
|
||||
Ok(())
|
||||
}
|
||||
Reference in new issue
Block a user