use serde::de::DeserializeOwned;
use serde_json::Value;
use std::sync::Arc;
pub trait WorkflowSql {
fn execute(&self, sql: &str, bindings: &[Value]) -> Result<usize, String>;
fn query(&self, sql: &str, bindings: &[Value]) -> Result<Vec<Vec<Value>>, String>;
fn execute_batch(&self, sql: &str) -> Result<(), String>;
}
pub trait WorkflowDatabase: WorkflowSql + Send + Sync {
fn transaction(
&self,
work: &mut dyn FnMut(&dyn WorkflowSql) -> Result<(), String>,
) -> Result<(), String>;
}
#[derive(Debug)]
pub(crate) enum Error {
Message(String),
NoRows,
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Message(s) => f.write_str(s),
Self::NoRows => f.write_str("Query returned no rows"),
}
}
}
impl From<&str> for Error {
fn from(value: &str) -> Self {
Self::Message(value.into())
}
}
impl From<String> for Error {
fn from(value: String) -> Self {
Self::Message(value)
}
}
pub(crate) type Result<T, E = Error> = std::result::Result<T, E>;
fn err(e: String) -> Error {
Error::Message(e)
}
macro_rules! params { ($($p:expr),* $(,)?) => { vec![$(serde_json::json!($p)),*] }; }
pub(crate) use params;
pub(crate) trait OptionalExtension<T> {
fn optional(self) -> Result<Option<T>>;
}
impl<T> OptionalExtension<T> for Result<T> {
fn optional(self) -> Result<Option<T>> {
match self {
Ok(v) => Ok(Some(v)),
Err(Error::NoRows) => Ok(None),
Err(e) => Err(e),
}
}
}
pub(crate) struct Row(Vec<Value>);
impl Row {
pub fn get<T: DeserializeOwned>(&self, index: usize) -> Result<T> {
serde_json::from_value(
self.0
.get(index)
.ok_or_else(|| err("Missing SQL column".into()))?
.clone(),
)
.map_err(|e| err(e.to_string()))
}
}
pub(crate) struct Connection {
database: Arc<dyn WorkflowDatabase>,
}
impl Connection {
pub fn new(database: Arc<dyn WorkflowDatabase>) -> Self {
Self { database }
}
#[cfg(all(feature = "native", not(target_arch = "wasm32")))]
pub fn open(path: &std::path::Path) -> Result<Self> {
Ok(Self::new(Arc::new(
native::SqliteDatabase::open(path).map_err(err)?,
)))
}
pub fn execute_batch(&self, sql: &str) -> Result<()> {
self.database.execute_batch(sql).map_err(err)
}
pub fn execute(&self, sql: &str, params: Vec<Value>) -> Result<usize> {
self.database.execute(sql, ¶ms).map_err(err)
}
pub fn query_row<T>(
&self,
sql: &str,
params: Vec<Value>,
f: impl FnOnce(&Row) -> Result<T>,
) -> Result<T> {
Query(self.database.as_ref()).query_row(sql, params, f)
}
pub fn prepare(&self, sql: &str) -> Result<Statement<'_>> {
Ok(Statement {
sql: sql.into(),
database: self.database.as_ref(),
})
}
pub fn transaction<T>(&self, work: impl FnOnce(&Query<'_>) -> Result<T>) -> Result<T> {
let mut work = Some(work);
let mut result = None;
self.database
.transaction(&mut |sql| {
let value = work.take().ok_or("Transaction callback invoked twice")?(&Query(sql))
.map_err(|e| e.to_string())?;
result = Some(value);
Ok(())
})
.map_err(err)?;
result.ok_or_else(|| err("Transaction callback was not invoked".into()))
}
}
pub(crate) struct Query<'a>(&'a dyn WorkflowSql);
impl Query<'_> {
pub fn execute(&self, sql: &str, params: Vec<Value>) -> Result<usize> {
self.0.execute(sql, ¶ms).map_err(err)
}
pub fn query_row<T>(
&self,
sql: &str,
params: Vec<Value>,
f: impl FnOnce(&Row) -> Result<T>,
) -> Result<T> {
let row = self
.0
.query(sql, ¶ms)
.map_err(err)?
.into_iter()
.next()
.ok_or(Error::NoRows)?;
f(&Row(row))
}
pub fn prepare(&self, sql: &str) -> Result<Statement<'_>> {
Ok(Statement {
sql: sql.into(),
database: self.0,
})
}
}
pub(crate) struct Statement<'a> {
sql: String,
database: &'a dyn WorkflowSql,
}
impl Statement<'_> {
pub fn query_map<T>(
&self,
params: Vec<Value>,
mut f: impl FnMut(&Row) -> Result<T>,
) -> Result<std::vec::IntoIter<Result<T>>> {
Ok(self
.database
.query(&self.sql, ¶ms)
.map_err(err)?
.into_iter()
.map(|v| f(&Row(v)))
.collect::<Vec<_>>()
.into_iter())
}
}
#[cfg(all(feature = "native", not(target_arch = "wasm32")))]
mod native {
use super::{WorkflowDatabase, WorkflowSql};
use rusqlite::types::{Value as SqlValue, ValueRef};
use serde_json::Value;
use std::sync::Mutex;
pub(super) struct SqliteDatabase(Mutex<rusqlite::Connection>);
impl SqliteDatabase {
pub fn open(path: &std::path::Path) -> Result<Self, String> {
let conn = rusqlite::Connection::open(path).map_err(|e| e.to_string())?;
conn.busy_timeout(std::time::Duration::from_secs(5))
.map_err(|e| e.to_string())?;
let started = std::time::Instant::now();
loop {
match conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;") {
Ok(()) => break,
Err(e)
if matches!(
e.sqlite_error_code(),
Some(
rusqlite::ErrorCode::DatabaseBusy
| rusqlite::ErrorCode::DatabaseLocked
)
) && started.elapsed() < std::time::Duration::from_secs(5) =>
{
std::thread::sleep(std::time::Duration::from_millis(10))
}
Err(e) => return Err(e.to_string()),
}
}
Ok(Self(Mutex::new(conn)))
}
}
struct View<'a>(&'a rusqlite::Connection);
fn bindings(values: &[Value]) -> Result<Vec<SqlValue>, String> {
values
.iter()
.map(|v| match v {
Value::Null => Ok(SqlValue::Null),
Value::String(v) => Ok(SqlValue::Text(v.clone())),
Value::Number(v) => v
.as_i64()
.map(SqlValue::Integer)
.ok_or("SQL integer out of range".into()),
_ => Err("Unsupported SQL binding".into()),
})
.collect()
}
impl WorkflowSql for View<'_> {
fn execute(&self, sql: &str, values: &[Value]) -> Result<usize, String> {
self.0
.execute(sql, rusqlite::params_from_iter(bindings(values)?))
.map_err(|e| e.to_string())
}
fn query(&self, sql: &str, values: &[Value]) -> Result<Vec<Vec<Value>>, String> {
let mut stmt = self.0.prepare(sql).map_err(|e| e.to_string())?;
let count = stmt.column_count();
stmt.query_map(rusqlite::params_from_iter(bindings(values)?), |row| {
(0..count)
.map(|i| {
Ok(match row.get_ref(i)? {
ValueRef::Null => Value::Null,
ValueRef::Integer(v) => Value::from(v),
ValueRef::Real(v) => Value::from(v),
ValueRef::Text(v) => {
Value::String(String::from_utf8_lossy(v).into_owned())
}
ValueRef::Blob(_) => return Err(rusqlite::Error::InvalidQuery),
})
})
.collect()
})
.map_err(|e| e.to_string())?
.collect::<rusqlite::Result<_>>()
.map_err(|e| e.to_string())
}
fn execute_batch(&self, sql: &str) -> Result<(), String> {
self.0.execute_batch(sql).map_err(|e| e.to_string())
}
}
impl WorkflowSql for SqliteDatabase {
fn execute(&self, sql: &str, values: &[Value]) -> Result<usize, String> {
View(&*self.0.lock().map_err(|e| e.to_string())?).execute(sql, values)
}
fn query(&self, sql: &str, values: &[Value]) -> Result<Vec<Vec<Value>>, String> {
View(&*self.0.lock().map_err(|e| e.to_string())?).query(sql, values)
}
fn execute_batch(&self, sql: &str) -> Result<(), String> {
View(&*self.0.lock().map_err(|e| e.to_string())?).execute_batch(sql)
}
}
impl WorkflowDatabase for SqliteDatabase {
fn transaction(
&self,
work: &mut dyn FnMut(&dyn WorkflowSql) -> Result<(), String>,
) -> Result<(), String> {
let mut conn = self.0.lock().map_err(|e| e.to_string())?;
let tx = conn
.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)
.map_err(|e| e.to_string())?;
work(&View(&tx))?;
tx.commit().map_err(|e| e.to_string())
}
}
}
#[cfg(all(test, feature = "native", not(target_arch = "wasm32")))]
mod tests {
use super::*;
#[test]
fn transaction_rolls_back_and_preserves_exact_integer_and_null() {
let conn = Connection::open(std::path::Path::new(":memory:")).unwrap();
conn.execute_batch("CREATE TABLE values_test(number INTEGER,note TEXT)")
.unwrap();
conn.execute(
"INSERT INTO values_test VALUES (?,?)",
params![9007199254740993_i64, Value::Null],
)
.unwrap();
let failed: Result<()> = conn.transaction(|tx| {
tx.execute(
"INSERT INTO values_test VALUES (?,?)",
params![2, "must roll back"],
)?;
Err(Error::Message("deliberate failure".into()))
});
assert!(
failed
.unwrap_err()
.to_string()
.contains("deliberate failure")
);
let rows = conn
.database
.query("SELECT number,note FROM values_test", &[])
.unwrap();
assert_eq!(
rows,
vec![vec![Value::from(9007199254740993_i64), Value::Null]]
);
conn.transaction(|tx| {
tx.execute(
"INSERT INTO values_test VALUES (?,?)",
params![3, "committed"],
)
})
.unwrap();
let count: u64 = conn
.query_row("SELECT COUNT(*) FROM values_test", params![], |r| r.get(0))
.unwrap();
assert_eq!(count, 2);
}
}
#[cfg(all(test, feature = "native", not(target_arch = "wasm32")))]
mod authority_tests {
use super::*;
use crate::{WorkflowAuthority, WorkflowBindings};
use multicast::command::RequestContext;
use multicast_codemode::{Connector, ConnectorDescription, ToolContext};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
struct Authority {
revoked: AtomicBool,
generation: AtomicUsize,
}
#[async_trait::async_trait]
impl WorkflowAuthority for Authority {
fn capture(&self, request: Option<&RequestContext>) -> Result<String, String> {
request
.and_then(|r| r.headers.get("identity"))
.cloned()
.ok_or("NO_SERVICE_IDENTITY".into())
}
async fn resolve(&self, reference: &str) -> Result<RequestContext, String> {
if self.revoked.load(Ordering::SeqCst) {
return Err("REVOKED".into());
}
let mut request = RequestContext::default();
request.headers.insert(
"authorization".into(),
format!(
"fresh-{}-{reference}",
self.generation.load(Ordering::SeqCst)
),
);
Ok(request)
}
}
fn request(identity: &str) -> RequestContext {
let mut request = RequestContext::default();
request.headers.insert("identity".into(), identity.into());
request.headers.insert(
"authorization".into(),
"ORIGINAL_BEARER_MUST_NOT_PERSIST".into(),
);
request
}
struct Tool(Arc<AtomicUsize>);
#[async_trait::async_trait]
impl Connector for Tool {
fn name(&self) -> &str {
"fixture"
}
async fn describe(&self) -> Result<ConnectorDescription, String> {
unreachable!()
}
async fn execute(&self, _: &str, _: Value, context: &ToolContext) -> Result<Value, String> {
self.0.fetch_add(1, Ordering::SeqCst);
Ok(Value::String(
context.request.as_ref().unwrap().headers["authorization"].clone(),
))
}
}
#[tokio::test]
async fn authority_survives_restart_without_persisting_bearers_and_rechecks_every_call() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("authority.sqlite");
let authority = Arc::new(Authority {
revoked: AtomicBool::new(false),
generation: AtomicUsize::new(1),
});
let database = Arc::new(native::SqliteDatabase::open(&path).unwrap());
let bindings = WorkflowBindings::new(database.clone(), authority.clone()).unwrap();
bindings
.admit("execution-one", Some(&request("principal-one")))
.await
.unwrap();
bindings
.admit("execution-two", Some(&request("principal-two")))
.await
.unwrap();
let rows = database
.query(
"SELECT id,reference FROM incurs_workflow_authority ORDER BY id",
&[],
)
.unwrap();
assert_eq!(
rows,
vec![
vec![
Value::String("execution-one".into()),
Value::String("principal-one".into())
],
vec![
Value::String("execution-two".into()),
Value::String("principal-two".into())
]
]
);
drop(bindings);
drop(database);
let database = Arc::new(native::SqliteDatabase::open(&path).unwrap());
let bindings = WorkflowBindings::new(database, authority.clone()).unwrap();
authority.generation.store(2, Ordering::SeqCst);
assert_eq!(
bindings.admit("execution-one", None).await.unwrap().headers["authorization"],
"fresh-2-principal-one"
);
assert!(
bindings
.admit("execution-one", Some(&request("principal-two")))
.await
.is_err()
);
assert!(bindings.admit("missing", None).await.is_err());
let calls = Arc::new(AtomicUsize::new(0));
let connector = bindings.connector(Arc::new(Tool(calls.clone())));
let context = ToolContext {
call: None,
execution_id: "execution-one".into(),
control: Default::default(),
request: Some(request("untrusted")),
telemetry_context: Default::default(),
};
assert_eq!(
connector
.execute("read", Value::Null, &context)
.await
.unwrap(),
Value::String("fresh-2-principal-one".into())
);
authority.revoked.store(true, Ordering::SeqCst);
assert_eq!(
connector
.execute("read", Value::Null, &context)
.await
.unwrap_err(),
"REVOKED"
);
assert!(bindings.admit("execution-one", None).await.is_err());
assert_eq!(
calls.load(Ordering::SeqCst),
1,
"revocation must stop before tool dispatch"
);
}
}