multicast-workflows 2.0.0

Durable Code Mode workflows attached to multicast CLIs as first-party commands
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
//! Host-supplied SQL storage shared by workflow history and trigger admission.

use serde::de::DeserializeOwned;
use serde_json::Value;
use std::sync::Arc;

/// Synchronous SQL operations; callbacks must never yield to another request.
pub trait WorkflowSql {
    /// Executes a statement and returns the number of changed rows.
    fn execute(&self, sql: &str, bindings: &[Value]) -> Result<usize, String>;
    /// Returns positional column values, preserving SQL nulls and integer values.
    fn query(&self, sql: &str, bindings: &[Value]) -> Result<Vec<Vec<Value>>, String>;
    /// Executes schema statements, without changing the host's durability settings.
    fn execute_batch(&self, sql: &str) -> Result<(), String>;
}

/// A tenant-owned database with atomic synchronous transactions.
///
/// On failure, every write in the callback must roll back. The callback receives
/// the transaction's SQL view and must not call the parent database recursively.
pub trait WorkflowDatabase: WorkflowSql + Send + Sync {
    /// Runs the callback atomically, rolling back if it returns an error.
    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, &params).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, &params).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, &params)
            .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, &params)
            .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())?;
            // PRAGMA journal_mode may bypass SQLite's busy handler.
            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"
        );
    }
}