1use serde::de::DeserializeOwned;
4use serde_json::Value;
5use std::sync::Arc;
6
7pub trait WorkflowSql {
9 fn execute(&self, sql: &str, bindings: &[Value]) -> Result<usize, String>;
11 fn query(&self, sql: &str, bindings: &[Value]) -> Result<Vec<Vec<Value>>, String>;
13 fn execute_batch(&self, sql: &str) -> Result<(), String>;
15}
16
17pub trait WorkflowDatabase: WorkflowSql + Send + Sync {
22 fn transaction(
24 &self,
25 work: &mut dyn FnMut(&dyn WorkflowSql) -> Result<(), String>,
26 ) -> Result<(), String>;
27}
28
29#[derive(Debug)]
30pub(crate) enum Error {
31 Message(String),
32 NoRows,
33}
34impl std::fmt::Display for Error {
35 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36 match self {
37 Self::Message(s) => f.write_str(s),
38 Self::NoRows => f.write_str("Query returned no rows"),
39 }
40 }
41}
42impl From<&str> for Error {
43 fn from(value: &str) -> Self {
44 Self::Message(value.into())
45 }
46}
47impl From<String> for Error {
48 fn from(value: String) -> Self {
49 Self::Message(value)
50 }
51}
52pub(crate) type Result<T, E = Error> = std::result::Result<T, E>;
53fn err(e: String) -> Error {
54 Error::Message(e)
55}
56
57macro_rules! params { ($($p:expr),* $(,)?) => { vec![$(serde_json::json!($p)),*] }; }
58pub(crate) use params;
59
60pub(crate) trait OptionalExtension<T> {
61 fn optional(self) -> Result<Option<T>>;
62}
63impl<T> OptionalExtension<T> for Result<T> {
64 fn optional(self) -> Result<Option<T>> {
65 match self {
66 Ok(v) => Ok(Some(v)),
67 Err(Error::NoRows) => Ok(None),
68 Err(e) => Err(e),
69 }
70 }
71}
72pub(crate) struct Row(Vec<Value>);
73impl Row {
74 pub fn get<T: DeserializeOwned>(&self, index: usize) -> Result<T> {
75 serde_json::from_value(
76 self.0
77 .get(index)
78 .ok_or_else(|| err("Missing SQL column".into()))?
79 .clone(),
80 )
81 .map_err(|e| err(e.to_string()))
82 }
83}
84
85pub(crate) struct Connection {
86 database: Arc<dyn WorkflowDatabase>,
87}
88impl Connection {
89 pub fn new(database: Arc<dyn WorkflowDatabase>) -> Self {
90 Self { database }
91 }
92 #[cfg(all(feature = "native", not(target_arch = "wasm32")))]
93 pub fn open(path: &std::path::Path) -> Result<Self> {
94 Ok(Self::new(Arc::new(
95 native::SqliteDatabase::open(path).map_err(err)?,
96 )))
97 }
98 pub fn execute_batch(&self, sql: &str) -> Result<()> {
99 self.database.execute_batch(sql).map_err(err)
100 }
101 pub fn execute(&self, sql: &str, params: Vec<Value>) -> Result<usize> {
102 self.database.execute(sql, ¶ms).map_err(err)
103 }
104 pub fn query_row<T>(
105 &self,
106 sql: &str,
107 params: Vec<Value>,
108 f: impl FnOnce(&Row) -> Result<T>,
109 ) -> Result<T> {
110 Query(self.database.as_ref()).query_row(sql, params, f)
111 }
112 pub fn prepare(&self, sql: &str) -> Result<Statement<'_>> {
113 Ok(Statement {
114 sql: sql.into(),
115 database: self.database.as_ref(),
116 })
117 }
118 pub fn transaction<T>(&self, work: impl FnOnce(&Query<'_>) -> Result<T>) -> Result<T> {
119 let mut work = Some(work);
120 let mut result = None;
121 self.database
122 .transaction(&mut |sql| {
123 let value = work.take().ok_or("Transaction callback invoked twice")?(&Query(sql))
124 .map_err(|e| e.to_string())?;
125 result = Some(value);
126 Ok(())
127 })
128 .map_err(err)?;
129 result.ok_or_else(|| err("Transaction callback was not invoked".into()))
130 }
131}
132pub(crate) struct Query<'a>(&'a dyn WorkflowSql);
133impl Query<'_> {
134 pub fn execute(&self, sql: &str, params: Vec<Value>) -> Result<usize> {
135 self.0.execute(sql, ¶ms).map_err(err)
136 }
137 pub fn query_row<T>(
138 &self,
139 sql: &str,
140 params: Vec<Value>,
141 f: impl FnOnce(&Row) -> Result<T>,
142 ) -> Result<T> {
143 let row = self
144 .0
145 .query(sql, ¶ms)
146 .map_err(err)?
147 .into_iter()
148 .next()
149 .ok_or(Error::NoRows)?;
150 f(&Row(row))
151 }
152 pub fn prepare(&self, sql: &str) -> Result<Statement<'_>> {
153 Ok(Statement {
154 sql: sql.into(),
155 database: self.0,
156 })
157 }
158}
159pub(crate) struct Statement<'a> {
160 sql: String,
161 database: &'a dyn WorkflowSql,
162}
163impl Statement<'_> {
164 pub fn query_map<T>(
165 &self,
166 params: Vec<Value>,
167 mut f: impl FnMut(&Row) -> Result<T>,
168 ) -> Result<std::vec::IntoIter<Result<T>>> {
169 Ok(self
170 .database
171 .query(&self.sql, ¶ms)
172 .map_err(err)?
173 .into_iter()
174 .map(|v| f(&Row(v)))
175 .collect::<Vec<_>>()
176 .into_iter())
177 }
178}
179
180#[cfg(all(feature = "native", not(target_arch = "wasm32")))]
181mod native {
182 use super::{WorkflowDatabase, WorkflowSql};
183 use rusqlite::types::{Value as SqlValue, ValueRef};
184 use serde_json::Value;
185 use std::sync::Mutex;
186 pub(super) struct SqliteDatabase(Mutex<rusqlite::Connection>);
187 impl SqliteDatabase {
188 pub fn open(path: &std::path::Path) -> Result<Self, String> {
189 let conn = rusqlite::Connection::open(path).map_err(|e| e.to_string())?;
190 conn.busy_timeout(std::time::Duration::from_secs(5))
191 .map_err(|e| e.to_string())?;
192 let started = std::time::Instant::now();
194 loop {
195 match conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;") {
196 Ok(()) => break,
197 Err(e)
198 if matches!(
199 e.sqlite_error_code(),
200 Some(
201 rusqlite::ErrorCode::DatabaseBusy
202 | rusqlite::ErrorCode::DatabaseLocked
203 )
204 ) && started.elapsed() < std::time::Duration::from_secs(5) =>
205 {
206 std::thread::sleep(std::time::Duration::from_millis(10))
207 }
208 Err(e) => return Err(e.to_string()),
209 }
210 }
211 Ok(Self(Mutex::new(conn)))
212 }
213 }
214 struct View<'a>(&'a rusqlite::Connection);
215 fn bindings(values: &[Value]) -> Result<Vec<SqlValue>, String> {
216 values
217 .iter()
218 .map(|v| match v {
219 Value::Null => Ok(SqlValue::Null),
220 Value::String(v) => Ok(SqlValue::Text(v.clone())),
221 Value::Number(v) => v
222 .as_i64()
223 .map(SqlValue::Integer)
224 .ok_or("SQL integer out of range".into()),
225 _ => Err("Unsupported SQL binding".into()),
226 })
227 .collect()
228 }
229 impl WorkflowSql for View<'_> {
230 fn execute(&self, sql: &str, values: &[Value]) -> Result<usize, String> {
231 self.0
232 .execute(sql, rusqlite::params_from_iter(bindings(values)?))
233 .map_err(|e| e.to_string())
234 }
235 fn query(&self, sql: &str, values: &[Value]) -> Result<Vec<Vec<Value>>, String> {
236 let mut stmt = self.0.prepare(sql).map_err(|e| e.to_string())?;
237 let count = stmt.column_count();
238 stmt.query_map(rusqlite::params_from_iter(bindings(values)?), |row| {
239 (0..count)
240 .map(|i| {
241 Ok(match row.get_ref(i)? {
242 ValueRef::Null => Value::Null,
243 ValueRef::Integer(v) => Value::from(v),
244 ValueRef::Real(v) => Value::from(v),
245 ValueRef::Text(v) => {
246 Value::String(String::from_utf8_lossy(v).into_owned())
247 }
248 ValueRef::Blob(_) => return Err(rusqlite::Error::InvalidQuery),
249 })
250 })
251 .collect()
252 })
253 .map_err(|e| e.to_string())?
254 .collect::<rusqlite::Result<_>>()
255 .map_err(|e| e.to_string())
256 }
257 fn execute_batch(&self, sql: &str) -> Result<(), String> {
258 self.0.execute_batch(sql).map_err(|e| e.to_string())
259 }
260 }
261 impl WorkflowSql for SqliteDatabase {
262 fn execute(&self, sql: &str, values: &[Value]) -> Result<usize, String> {
263 View(&*self.0.lock().map_err(|e| e.to_string())?).execute(sql, values)
264 }
265 fn query(&self, sql: &str, values: &[Value]) -> Result<Vec<Vec<Value>>, String> {
266 View(&*self.0.lock().map_err(|e| e.to_string())?).query(sql, values)
267 }
268 fn execute_batch(&self, sql: &str) -> Result<(), String> {
269 View(&*self.0.lock().map_err(|e| e.to_string())?).execute_batch(sql)
270 }
271 }
272 impl WorkflowDatabase for SqliteDatabase {
273 fn transaction(
274 &self,
275 work: &mut dyn FnMut(&dyn WorkflowSql) -> Result<(), String>,
276 ) -> Result<(), String> {
277 let mut conn = self.0.lock().map_err(|e| e.to_string())?;
278 let tx = conn
279 .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)
280 .map_err(|e| e.to_string())?;
281 work(&View(&tx))?;
282 tx.commit().map_err(|e| e.to_string())
283 }
284 }
285}
286
287#[cfg(all(test, feature = "native", not(target_arch = "wasm32")))]
288mod tests {
289 use super::*;
290 #[test]
291 fn transaction_rolls_back_and_preserves_exact_integer_and_null() {
292 let conn = Connection::open(std::path::Path::new(":memory:")).unwrap();
293 conn.execute_batch("CREATE TABLE values_test(number INTEGER,note TEXT)")
294 .unwrap();
295 conn.execute(
296 "INSERT INTO values_test VALUES (?,?)",
297 params![9007199254740993_i64, Value::Null],
298 )
299 .unwrap();
300 let failed: Result<()> = conn.transaction(|tx| {
301 tx.execute(
302 "INSERT INTO values_test VALUES (?,?)",
303 params![2, "must roll back"],
304 )?;
305 Err(Error::Message("deliberate failure".into()))
306 });
307 assert!(
308 failed
309 .unwrap_err()
310 .to_string()
311 .contains("deliberate failure")
312 );
313 let rows = conn
314 .database
315 .query("SELECT number,note FROM values_test", &[])
316 .unwrap();
317 assert_eq!(
318 rows,
319 vec![vec![Value::from(9007199254740993_i64), Value::Null]]
320 );
321 conn.transaction(|tx| {
322 tx.execute(
323 "INSERT INTO values_test VALUES (?,?)",
324 params![3, "committed"],
325 )
326 })
327 .unwrap();
328 let count: u64 = conn
329 .query_row("SELECT COUNT(*) FROM values_test", params![], |r| r.get(0))
330 .unwrap();
331 assert_eq!(count, 2);
332 }
333}
334
335#[cfg(all(test, feature = "native", not(target_arch = "wasm32")))]
336mod authority_tests {
337 use super::*;
338 use crate::{WorkflowAuthority, WorkflowBindings};
339 use multicast::command::RequestContext;
340 use multicast_codemode::{Connector, ConnectorDescription, ToolContext};
341 use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
342 struct Authority {
343 revoked: AtomicBool,
344 generation: AtomicUsize,
345 }
346 #[async_trait::async_trait]
347 impl WorkflowAuthority for Authority {
348 fn capture(&self, request: Option<&RequestContext>) -> Result<String, String> {
349 request
350 .and_then(|r| r.headers.get("identity"))
351 .cloned()
352 .ok_or("NO_SERVICE_IDENTITY".into())
353 }
354 async fn resolve(&self, reference: &str) -> Result<RequestContext, String> {
355 if self.revoked.load(Ordering::SeqCst) {
356 return Err("REVOKED".into());
357 }
358 let mut request = RequestContext::default();
359 request.headers.insert(
360 "authorization".into(),
361 format!(
362 "fresh-{}-{reference}",
363 self.generation.load(Ordering::SeqCst)
364 ),
365 );
366 Ok(request)
367 }
368 }
369 fn request(identity: &str) -> RequestContext {
370 let mut request = RequestContext::default();
371 request.headers.insert("identity".into(), identity.into());
372 request.headers.insert(
373 "authorization".into(),
374 "ORIGINAL_BEARER_MUST_NOT_PERSIST".into(),
375 );
376 request
377 }
378 struct Tool(Arc<AtomicUsize>);
379 #[async_trait::async_trait]
380 impl Connector for Tool {
381 fn name(&self) -> &str {
382 "fixture"
383 }
384 async fn describe(&self) -> Result<ConnectorDescription, String> {
385 unreachable!()
386 }
387 async fn execute(&self, _: &str, _: Value, context: &ToolContext) -> Result<Value, String> {
388 self.0.fetch_add(1, Ordering::SeqCst);
389 Ok(Value::String(
390 context.request.as_ref().unwrap().headers["authorization"].clone(),
391 ))
392 }
393 }
394 #[tokio::test]
395 async fn authority_survives_restart_without_persisting_bearers_and_rechecks_every_call() {
396 let dir = tempfile::tempdir().unwrap();
397 let path = dir.path().join("authority.sqlite");
398 let authority = Arc::new(Authority {
399 revoked: AtomicBool::new(false),
400 generation: AtomicUsize::new(1),
401 });
402 let database = Arc::new(native::SqliteDatabase::open(&path).unwrap());
403 let bindings = WorkflowBindings::new(database.clone(), authority.clone()).unwrap();
404 bindings
405 .admit("execution-one", Some(&request("principal-one")))
406 .await
407 .unwrap();
408 bindings
409 .admit("execution-two", Some(&request("principal-two")))
410 .await
411 .unwrap();
412 let rows = database
413 .query(
414 "SELECT id,reference FROM incurs_workflow_authority ORDER BY id",
415 &[],
416 )
417 .unwrap();
418 assert_eq!(
419 rows,
420 vec![
421 vec![
422 Value::String("execution-one".into()),
423 Value::String("principal-one".into())
424 ],
425 vec![
426 Value::String("execution-two".into()),
427 Value::String("principal-two".into())
428 ]
429 ]
430 );
431 drop(bindings);
432 drop(database);
433 let database = Arc::new(native::SqliteDatabase::open(&path).unwrap());
434 let bindings = WorkflowBindings::new(database, authority.clone()).unwrap();
435 authority.generation.store(2, Ordering::SeqCst);
436 assert_eq!(
437 bindings.admit("execution-one", None).await.unwrap().headers["authorization"],
438 "fresh-2-principal-one"
439 );
440 assert!(
441 bindings
442 .admit("execution-one", Some(&request("principal-two")))
443 .await
444 .is_err()
445 );
446 assert!(bindings.admit("missing", None).await.is_err());
447 let calls = Arc::new(AtomicUsize::new(0));
448 let connector = bindings.connector(Arc::new(Tool(calls.clone())));
449 let context = ToolContext {
450 call: None,
451 execution_id: "execution-one".into(),
452 control: Default::default(),
453 request: Some(request("untrusted")),
454 telemetry_context: Default::default(),
455 };
456 assert_eq!(
457 connector
458 .execute("read", Value::Null, &context)
459 .await
460 .unwrap(),
461 Value::String("fresh-2-principal-one".into())
462 );
463 authority.revoked.store(true, Ordering::SeqCst);
464 assert_eq!(
465 connector
466 .execute("read", Value::Null, &context)
467 .await
468 .unwrap_err(),
469 "REVOKED"
470 );
471 assert!(bindings.admit("execution-one", None).await.is_err());
472 assert_eq!(
473 calls.load(Ordering::SeqCst),
474 1,
475 "revocation must stop before tool dispatch"
476 );
477 }
478}