129 lines
6.1 KiB
Rust
129 lines
6.1 KiB
Rust
//! Durable desktop-operation journal: the same id with the same arguments returns the
|
|
//! stored receipt and never re-executes; changed arguments are refused; a started or uncertain
|
|
//! operation blocks automatic replay. `<data>/desktop/desktop-operations.sqlite`.
|
|
use std::future::Future;
|
|
use std::path::Path;
|
|
|
|
use anyhow::{bail, Result};
|
|
use parking_lot::Mutex;
|
|
use rusqlite::{params, Connection, OptionalExtension};
|
|
use serde_json::{json, Value};
|
|
use sha2::{Digest, Sha256};
|
|
|
|
pub struct OpJournal {
|
|
db: Mutex<Connection>,
|
|
/// Serializes operations (one FIFO chain, at most 4 waiting).
|
|
chain: tokio::sync::Semaphore,
|
|
waiting: std::sync::atomic::AtomicUsize,
|
|
}
|
|
|
|
const MAX_ROWS: i64 = 10_000;
|
|
|
|
/// `sha256(sessionKey \0 sessionId \0 toolCallId)` for chat tool calls.
|
|
pub fn tool_operation_id(session_key: &str, session_id: &str, call_id: &str) -> String {
|
|
hex::encode(Sha256::digest(format!("{session_key}\0{session_id}\0{call_id}")))
|
|
}
|
|
|
|
impl OpJournal {
|
|
pub fn open(path: &Path) -> Result<Self> {
|
|
if let Some(dir) = path.parent() {
|
|
std::fs::create_dir_all(dir)?;
|
|
}
|
|
let db = Connection::open(path)?;
|
|
db.execute_batch(
|
|
"PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;
|
|
CREATE TABLE IF NOT EXISTS operations(id TEXT PRIMARY KEY, fingerprint TEXT, state TEXT, result TEXT, created INTEGER);
|
|
CREATE TABLE IF NOT EXISTS recovery(id TEXT PRIMARY KEY, scope TEXT, relative TEXT, backup TEXT, sha TEXT, bytes INTEGER);",
|
|
)?;
|
|
Ok(Self { db: Mutex::new(db), chain: tokio::sync::Semaphore::new(1), waiting: 0.into() })
|
|
}
|
|
|
|
/// Runs `run` once for `id`. Results that are not `ok` are stored as `uncertain`.
|
|
pub async fn operation<F, Fut>(&self, id: &str, args: &Value, run: F) -> Result<Value>
|
|
where
|
|
F: FnOnce() -> Fut,
|
|
Fut: Future<Output = Result<Value>>,
|
|
{
|
|
use std::sync::atomic::Ordering;
|
|
if self.waiting.fetch_add(1, Ordering::SeqCst) >= 5 {
|
|
self.waiting.fetch_sub(1, Ordering::SeqCst);
|
|
bail!("Too many pending desktop actions.");
|
|
}
|
|
let _turn = self.chain.acquire().await;
|
|
self.waiting.fetch_sub(1, Ordering::SeqCst);
|
|
let fingerprint = hex::encode(Sha256::digest(serde_json::to_vec(args)?));
|
|
{
|
|
let db = self.db.lock();
|
|
let row: Option<(String, String, Option<String>)> = db.query_row("SELECT fingerprint, state, result FROM operations WHERE id=?1", [id], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?))).optional()?;
|
|
if let Some((fp, state, result)) = row {
|
|
if fp != fingerprint {
|
|
bail!("An operation ID cannot change its arguments.");
|
|
}
|
|
if state == "complete" {
|
|
return Ok(serde_json::from_str(&result.unwrap_or_default()).unwrap_or(json!({"ok": true})));
|
|
}
|
|
bail!("An earlier action may have partially completed. Check its actual state before trying again.");
|
|
}
|
|
let count: i64 = db.query_row("SELECT COUNT(*) FROM operations", [], |r| r.get(0))?;
|
|
if count >= MAX_ROWS {
|
|
bail!("The desktop action journal is full.");
|
|
}
|
|
db.execute("INSERT INTO operations(id, fingerprint, state, created) VALUES (?1, ?2, 'started', ?3)", params![id, fingerprint, capri_perception::now_ms()])?;
|
|
}
|
|
let result = run().await;
|
|
let db = self.db.lock();
|
|
match &result {
|
|
Ok(v) => db.execute("UPDATE operations SET state='complete', result=?2 WHERE id=?1", params![id, v.to_string()])?,
|
|
Err(e) => db.execute("UPDATE operations SET state='uncertain', result=?2 WHERE id=?1", params![id, json!({"error": e.to_string()}).to_string()])?,
|
|
};
|
|
result
|
|
}
|
|
|
|
/// The 50 newest operations (Settings journal view).
|
|
pub fn recent(&self) -> Result<Vec<Value>> {
|
|
let db = self.db.lock();
|
|
let mut stmt = db.prepare("SELECT id, state, result, created FROM operations ORDER BY created DESC LIMIT 50")?;
|
|
let rows = stmt.query_map([], |r| {
|
|
let result: Option<String> = r.get(2)?;
|
|
Ok(json!({"id": r.get::<_, String>(0)?, "state": r.get::<_, String>(1)?, "result": result.and_then(|s| serde_json::from_str::<Value>(&s).ok()), "created": r.get::<_, i64>(3)?}))
|
|
})?;
|
|
Ok(rows.collect::<rusqlite::Result<_>>()?)
|
|
}
|
|
|
|
pub fn add_recovery(&self, id: &str, scope: &str, relative: &str, backup: &str, sha: &str, bytes: u64) -> Result<()> {
|
|
self.db.lock().execute("INSERT INTO recovery(id, scope, relative, backup, sha, bytes) VALUES (?1,?2,?3,?4,?5,?6)", params![id, scope, relative, backup, sha, bytes as i64])?;
|
|
Ok(())
|
|
}
|
|
|
|
pub fn recovery_bytes(&self) -> Result<u64> {
|
|
Ok(self.db.lock().query_row("SELECT COALESCE(SUM(bytes),0) FROM recovery", [], |r| r.get::<_, i64>(0))? as u64)
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
|
|
|
#[tokio::test]
|
|
async fn replay_rules() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let j = OpJournal::open(&dir.path().join("desktop/ops.sqlite")).unwrap();
|
|
let runs = AtomicUsize::new(0);
|
|
let run = || async {
|
|
runs.fetch_add(1, Ordering::SeqCst);
|
|
Ok(json!({"ok": true, "confirmation": "Pressed the requested keys."}))
|
|
};
|
|
let a = json!({"action": "press_keys", "keys": ["ENTER"]});
|
|
let first = j.operation("op1", &a, run).await.unwrap();
|
|
let again = j.operation("op1", &a, run).await.unwrap();
|
|
assert_eq!(first, again);
|
|
assert_eq!(runs.load(Ordering::SeqCst), 1, "a retransmitted call returns the original receipt");
|
|
assert!(j.operation("op1", &json!({"action": "scroll"}), run).await.unwrap_err().to_string().contains("cannot change"));
|
|
assert!(j.operation("op2", &a, || async { anyhow::bail!("native failure") }).await.is_err());
|
|
assert!(j.operation("op2", &a, run).await.unwrap_err().to_string().contains("partially completed"), "uncertain never replays");
|
|
assert_eq!(j.recent().unwrap().len(), 2);
|
|
assert_eq!(tool_operation_id("k", "s", "c").len(), 64);
|
|
}
|
|
}
|