//! Durable admission and host-driven delivery of webhook and interval triggers.
#[cfg(all(feature = "native", not(target_arch = "wasm32")))]
use std::path::Path;
use std::sync::{Arc, Mutex, OnceLock};
#[cfg(all(test, feature = "native", not(target_arch = "wasm32")))]
use std::time::Duration;
use web_time::{SystemTime, UNIX_EPOCH};
use crate::database::{Connection, OptionalExtension, params};
use multicast_codemode::{CodeModeRunOptions, ExecutionStatus, WorkflowIdentity};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::{State, ledger, program};
/// An authenticated host delivery, deduplicated by its stable source event key.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct TriggerRequest {
/// Stable event key, unique within this CLI's webhook admission namespace.
pub key: String,
/// Shipped or saved workflow name.
pub workflow: String,
/// Input validated before admission and again before execution.
pub input: Value,
/// Earliest start, in Unix milliseconds.
pub not_before: u64,
/// Absolute end-to-end deadline in Unix milliseconds, after `not_before`.
pub deadline: u64,
}
/// A durable fixed-interval schedule; missed intervals coalesce to the latest due one.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct TriggerSchedule {
/// Stable schedule identifier, at most 256 bytes.
pub id: String,
/// Workflow name, pinned to its current version when registered.
pub workflow: String,
/// Validated input used by every occurrence.
pub input: Value,
/// First occurrence in Unix milliseconds.
pub first_at: u64,
/// Positive interval in milliseconds.
pub every_ms: u64,
/// Positive deadline duration measured from each occurrence's due time.
pub deadline_ms: u64,
}
/// Durable delivery receipt. Repeated admission returns the original receipt.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TriggerReceipt {
/// `webhook` for host deliveries or `schedule` for interval occurrences.
pub source: String,
/// Delivery key, or a schedule identifier and its occurrence time.
pub key: String,
/// Named workflow.
pub workflow: String,
/// Program and input-schema version pinned at admission.
pub version: String,
/// Identifier committed before any execution pass starts.
pub execution_id: Option<String>,
/// `queued`, `preparing`, an execution status, `expired`, or `blocked`.
pub status: String,
/// Diagnostic for blocked, expired, or failed work.
pub error: Option<String>,
/// Earliest start in Unix milliseconds.
pub not_before: u64,
/// End-to-end deadline in Unix milliseconds.
pub deadline: u64,
}
struct Queue {
connection: Mutex<Connection>,
}
struct Delivery {
request: TriggerRequest,
receipt: TriggerReceipt,
}
/// Host boundary for authenticated webhooks and fixed-interval schedules.
///
/// Admission is durable and has no command effects. The host supplies its own
/// authentication, authorization, HTTP server, and polling lifetime. `tick`
/// serializes delivery across handle clones; unfinished work limits each workflow
/// to one execution, including approval and uncertain-outcome pauses. There is no
/// automatic approval, effect retry, or whole-workflow restart.
#[derive(Clone)]
pub struct WorkflowTriggers {
state: Arc<State>,
queue: Arc<OnceLock<Result<Queue, String>>>,
tick_lock: Arc<tokio::sync::Mutex<()>>,
}
impl WorkflowTriggers {
pub(super) fn new(state: Arc<State>) -> Self {
Self {
state,
queue: Arc::default(),
tick_lock: Arc::default(),
}
}
fn queue(&self) -> Result<&Queue, String> {
self.queue
.get_or_init(|| {
if let Some(host) = &self.state.host {
return host
.database(crate::WorkflowDatabaseKind::Triggers)
.and_then(Queue::from_database);
}
#[cfg(all(feature = "native", not(target_arch = "wasm32")))]
{
Queue::open(&self.state.store_path.with_extension("triggers.sqlite"))
}
#[cfg(not(all(feature = "native", not(target_arch = "wasm32"))))]
{
Err("A workflow host is required".into())
}
})
.as_ref()
.map_err(Clone::clone)
}
/// Admits a delivery after the adapter authenticates and authorizes its caller.
///
/// Keys are at most 256 bytes and serialized requests at most 1 MiB. A repeated
/// key with identical request data returns its receipt; changed data returns
/// `TRIGGER_KEY_CONFLICT`. Receipts persist without automatic pruning, so a
/// process restart or completed execution does not reset deduplication.
pub async fn enqueue(&self, request: TriggerRequest) -> Result<TriggerReceipt, String> {
validate_request(&request)?;
if let Some(existing) = self.queue()?.get("webhook", &request.key)? {
return duplicate(existing, &request);
}
let workflow = self
.state
.resolve(&request.workflow)
.await?
.ok_or_else(|| format!("Workflow '{}' not found", request.workflow))?;
program(&workflow, request.input.clone())?;
if let Some(host) = &self.state.host {
host.wake_at(request.not_before).await?;
}
self.queue()?
.insert("webhook", &request, &workflow.version())
}
/// Registers an immutable, durable interval schedule.
///
/// Repeating an identical registration preserves progress. Changed settings
/// or workflow versions require removing the schedule and registering again.
/// Removal stops future occurrences but retains already admitted receipts.
pub async fn schedule(&self, schedule: TriggerSchedule) -> Result<(), String> {
validate_key(&schedule.id)?;
if schedule.every_ms == 0
|| schedule.deadline_ms == 0
|| schedule
.first_at
.checked_add(schedule.every_ms)
.is_none_or(|value| value > i64::MAX as u64)
{
return Err("Schedule durations must be positive".into());
}
let request = TriggerRequest {
key: schedule.id.clone(),
workflow: schedule.workflow.clone(),
input: schedule.input.clone(),
not_before: schedule.first_at,
deadline: schedule
.first_at
.checked_add(schedule.deadline_ms)
.ok_or("Schedule deadline overflow")?,
};
validate_request(&request)?;
let workflow = self
.state
.resolve(&schedule.workflow)
.await?
.ok_or("Scheduled workflow not found")?;
program(&workflow, schedule.input.clone())?;
if let Some(host) = &self.state.host {
host.wake_at(schedule.first_at).await?;
}
self.queue()?.schedule(&schedule, &workflow.version())
}
/// Stops future occurrences while retaining admitted work and deduplication.
pub fn remove_schedule(&self, id: &str) -> Result<bool, String> {
Ok(self
.queue()?
.lock()?
.execute("DELETE FROM schedules WHERE id = ?1", params![id])
.map_err(sql)?
!= 0)
}
/// Reads a receipt by its source (`webhook` or `schedule`) and delivery key.
pub fn receipt(&self, source: &str, key: &str) -> Result<Option<TriggerReceipt>, String> {
Ok(self
.queue()?
.get(source, key)?
.map(|delivery| delivery.receipt))
}
/// Returns the next due schedule, delivery, or deadline for host wakeups.
/// Running deliveries are checked within one second; approval pauses keep
/// their concurrency slot until a decision or their deadline.
pub fn next_wake(&self) -> Result<Option<u64>, String> {
let now = now_ms()?;
self.queue()?.lock()?.query_row("SELECT MIN(wake) FROM (SELECT next_at AS wake FROM schedules UNION ALL SELECT CASE WHEN execution_id IS NULL THEN CASE WHEN EXISTS (SELECT 1 FROM deliveries busy WHERE busy.workflow=deliveries.workflow AND busy.execution_id IS NOT NULL AND busy.status IN ('preparing','running','paused','blocked')) THEN deadline ELSE MIN(deadline,MAX(?1,not_before)) END WHEN status IN ('preparing','running') THEN MIN(deadline,?1+1000) ELSE deadline END AS wake FROM deliveries WHERE status IN ('queued','preparing','running','paused'))", params![now], |row| row.get(0)).map_err(sql)
}
/// Refreshes unfinished receipts and delivers at most `limit` due executions.
///
/// `limit` must be 1..=100. Calls serialize across clones and the Code Mode
/// store enforces single-process ownership. The host must keep polling for
/// deadlines to be enforced while stopped or paused. A running delivery is
/// cancelled at its deadline while this call is alive; cancellation cannot
/// undo a command effect already committed by its destination.
pub async fn tick(&self, limit: usize) -> Result<Vec<TriggerReceipt>, String> {
if !(1..=100).contains(&limit) {
return Err("Trigger tick limit must be 1..=100".into());
}
let _guard = self.tick_lock.lock().await;
// Acquire the execution store's exclusive owner before claiming delivery.
let service = self.state.service().await?;
let queue = self.queue()?;
let now = now_ms()?;
if self.next_wake()?.is_some_and(|wake| wake <= now)
&& let Some(host) = &self.state.host
{
host.wake_at(now.saturating_add(1000)).await?;
}
queue.materialize(now_ms()?)?;
let mut changed = Vec::new();
for delivery in queue.active()? {
if delivery.receipt.execution_id.is_some() {
changed.push(self.deliver(delivery).await?);
}
}
for _ in 0..limit {
let Some(mut delivery) = queue.claim(now_ms()?)? else {
break;
};
let Some(workflow) = self.state.resolve(&delivery.request.workflow).await? else {
queue.finish(
&delivery.receipt,
"blocked",
Some("Workflow no longer exists"),
)?;
changed.push(
queue
.get(&delivery.receipt.source, &delivery.receipt.key)?
.unwrap()
.receipt,
);
continue;
};
if workflow.version() != delivery.receipt.version {
queue.finish(
&delivery.receipt,
"blocked",
Some("Workflow version changed; review a new delivery"),
)?;
changed.push(
queue
.get(&delivery.receipt.source, &delivery.receipt.key)?
.unwrap()
.receipt,
);
continue;
}
let (_, code) = program(&workflow, delivery.request.input.clone())?;
let execution = service.prepare(code).await?;
// A crash before binding leaves only an idle execution with no effects.
// Once bound, every restart recovers this identifier, never a new run.
queue.bind(&delivery.receipt, &execution.id)?;
delivery.receipt.execution_id = Some(execution.id);
if let Some(ledger) = self.state.ledger() {
crate::warn_ledger(ledger.start(&ledger::RunStart {
execution_id: delivery.receipt.execution_id.as_deref().unwrap(),
workflow: &workflow.name,
origin: workflow.origin,
version: &workflow.version(),
at: execution.created_at,
}));
}
changed.push(self.deliver(delivery).await?);
}
Ok(changed)
}
async fn deliver(&self, delivery: Delivery) -> Result<TriggerReceipt, String> {
let queue = self.queue()?;
let receipt = &delivery.receipt;
let id = receipt.execution_id.as_deref().ok_or("Unbound trigger")?;
let service = self.state.service().await?;
let mut execution = match service.execution(id.into()).await {
Ok(execution) => execution,
Err(error) => {
queue.finish(
receipt,
"blocked",
Some(&format!(
"Bound execution unavailable; reconcile without restarting: {error}"
)),
)?;
return Ok(queue.get(&receipt.source, &receipt.key)?.unwrap().receipt);
}
};
let unfinished = matches!(
execution.status,
ExecutionStatus::Running | ExecutionStatus::Paused
);
let now = now_ms()?;
if unfinished && now >= receipt.deadline {
execution = service.cancel(id.into()).await?;
} else if execution.status == ExecutionStatus::Running {
let options = CodeModeRunOptions {
workflow: Some(WorkflowIdentity {
name: receipt.workflow.clone(),
version: receipt.version.clone(),
}),
..CodeModeRunOptions::default()
};
let run = async {
let execution = service.recover(id.into(), options).await?;
self.state.settle(service, execution).await
};
let deadline = self.state.sleep(receipt.deadline - now);
futures_util::pin_mut!(run, deadline);
execution = match futures_util::future::select(run, deadline).await {
futures_util::future::Either::Left((result, _)) => result?,
futures_util::future::Either::Right(((), _)) => service.cancel(id.into()).await?,
};
}
self.state.record(&execution);
queue.finish(
receipt,
ledger::status_name(execution.status),
execution.error.as_deref(),
)?;
Ok(queue.get(&receipt.source, &receipt.key)?.unwrap().receipt)
}
}
fn now_ms() -> Result<u64, String> {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|error| error.to_string())?
.as_millis()
.try_into()
.map_err(|_| "Clock overflow".into())
}
fn validate_key(key: &str) -> Result<(), String> {
if key.is_empty() || key.len() > 256 {
Err("Trigger key must contain 1..=256 bytes".into())
} else {
Ok(())
}
}
fn validate_request(request: &TriggerRequest) -> Result<(), String> {
validate_key(&request.key)?;
if request.not_before >= request.deadline || request.deadline > i64::MAX as u64 {
return Err(
"Trigger deadline must follow notBefore and fit a signed 64-bit timestamp".into(),
);
}
if serde_json::to_vec(request)
.map_err(|error| error.to_string())?
.len()
> 1024 * 1024
{
return Err("Trigger request exceeds 1 MiB".into());
}
Ok(())
}
fn duplicate(delivery: Delivery, request: &TriggerRequest) -> Result<TriggerReceipt, String> {
if delivery.request == *request {
Ok(delivery.receipt)
} else {
Err("TRIGGER_KEY_CONFLICT: event key already has different request data".into())
}
}
fn sql(error: crate::database::Error) -> String {
format!("Trigger store: {error}")
}
impl Queue {
#[cfg(all(feature = "native", not(target_arch = "wasm32")))]
fn open(path: &Path) -> Result<Self, String> {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|error| error.to_string())?;
}
let connection = Connection::open(path).map_err(sql)?;
Self::initialize(&connection)?;
Ok(Self {
connection: Mutex::new(connection),
})
}
fn from_database(database: Arc<dyn crate::WorkflowDatabase>) -> Result<Self, String> {
let connection = Connection::new(database);
Self::initialize(&connection)?;
Ok(Self {
connection: Mutex::new(connection),
})
}
fn initialize(connection: &Connection) -> Result<(), String> {
connection.execute_batch("CREATE TABLE IF NOT EXISTS deliveries (source TEXT NOT NULL, key TEXT NOT NULL, body TEXT NOT NULL, version TEXT NOT NULL, status TEXT NOT NULL, execution_id TEXT, error TEXT, workflow TEXT NOT NULL, not_before INTEGER NOT NULL, deadline INTEGER NOT NULL, PRIMARY KEY(source,key));
CREATE TABLE IF NOT EXISTS schedules (id TEXT PRIMARY KEY, body TEXT NOT NULL, version TEXT NOT NULL, next_at INTEGER NOT NULL);").map_err(sql)
}
fn lock(&self) -> Result<std::sync::MutexGuard<'_, Connection>, String> {
self.connection.lock().map_err(|error| error.to_string())
}
fn get(&self, source: &str, key: &str) -> Result<Option<Delivery>, String> {
self.lock()?.query_row("SELECT source,key,body,version,status,execution_id,error FROM deliveries WHERE source=?1 AND key=?2", params![source,key], row).optional().map_err(sql)
}
fn insert(
&self,
source: &str,
request: &TriggerRequest,
version: &str,
) -> Result<TriggerReceipt, String> {
let body = serde_json::to_string(request).map_err(|error| error.to_string())?;
self.lock()?.execute("INSERT OR IGNORE INTO deliveries(source,key,body,version,status,workflow,not_before,deadline) VALUES(?1,?2,?3,?4,'queued',?5,?6,?7)", params![source,request.key,body,version,request.workflow,request.not_before,request.deadline]).map_err(sql)?;
duplicate(self.get(source, &request.key)?.unwrap(), request)
}
fn schedule(&self, schedule: &TriggerSchedule, version: &str) -> Result<(), String> {
let body = serde_json::to_string(schedule).map_err(|error| error.to_string())?;
let connection = self.lock()?;
connection
.execute(
"INSERT OR IGNORE INTO schedules(id,body,version,next_at) VALUES(?1,?2,?3,?4)",
params![schedule.id, body, version, schedule.first_at],
)
.map_err(sql)?;
let existing: (String, String) = connection
.query_row(
"SELECT body,version FROM schedules WHERE id=?1",
params![&schedule.id],
|row| Ok((row.get(0)?, row.get(1)?)),
)
.map_err(sql)?;
if existing == (body, version.into()) {
Ok(())
} else {
Err("TRIGGER_SCHEDULE_CONFLICT: remove the old schedule before replacing it".into())
}
}
fn materialize(&self, now: u64) -> Result<(), String> {
let connection = self.lock()?;
connection.transaction(|transaction| {
let due: Vec<(String, String, u64)> = transaction
.prepare("SELECT body,version,next_at FROM schedules WHERE next_at<=?1")
.map_err(sql)?
.query_map(params![now], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))
.map_err(sql)?
.collect::<Result<_, _>>()
.map_err(sql)?;
for (body, version, next) in due {
let schedule: TriggerSchedule =
serde_json::from_str(&body).map_err(|error| error.to_string())?;
let occurrence = next + ((now - next) / schedule.every_ms) * schedule.every_ms;
let next = occurrence
.checked_add(schedule.every_ms)
.filter(|value| *value <= i64::MAX as u64)
.ok_or("Schedule timestamp overflow")?;
let request = TriggerRequest {
key: format!("{}:{occurrence}", schedule.id),
workflow: schedule.workflow,
input: schedule.input,
not_before: occurrence,
deadline: occurrence
.checked_add(schedule.deadline_ms)
.filter(|value| *value <= i64::MAX as u64)
.ok_or("Schedule deadline overflow")?,
};
let body = serde_json::to_string(&request).map_err(|error| error.to_string())?;
transaction.execute("INSERT OR IGNORE INTO deliveries(source,key,body,version,status,workflow,not_before,deadline) VALUES('schedule',?1,?2,?3,'queued',?4,?5,?6)", params![request.key,body,version,request.workflow,request.not_before,request.deadline]).map_err(sql)?;
transaction
.execute(
"UPDATE schedules SET next_at=?1 WHERE id=?2",
params![next, schedule.id],
)
.map_err(sql)?;
}
Ok(())
}).map_err(sql)
}
fn active(&self) -> Result<Vec<Delivery>, String> {
self.lock()?.prepare("SELECT source,key,body,version,status,execution_id,error FROM deliveries WHERE execution_id IS NOT NULL AND status IN ('preparing','running','paused','blocked') ORDER BY rowid").map_err(sql)?.query_map(params![],row).map_err(sql)?.collect::<Result<_,_>>().map_err(sql)
}
fn claim(&self, now: u64) -> Result<Option<Delivery>, String> {
let connection = self.lock()?;
connection.transaction(|transaction| {
transaction.execute("UPDATE deliveries SET status='expired',error='Deadline elapsed before execution' WHERE execution_id IS NULL AND status IN ('queued','preparing') AND deadline<=?1",params![now]).map_err(sql)?;
let delivery = transaction.query_row("SELECT source,key,body,version,status,execution_id,error FROM deliveries d WHERE execution_id IS NULL AND status IN ('queued','preparing') AND not_before<=?1 AND NOT EXISTS (SELECT 1 FROM deliveries busy WHERE busy.workflow=d.workflow AND busy.execution_id IS NOT NULL AND busy.status IN ('preparing','running','paused','blocked')) ORDER BY not_before,rowid LIMIT 1", params![now],row).optional().map_err(sql)?;
if let Some(delivery) = &delivery {
transaction
.execute(
"UPDATE deliveries SET status='preparing' WHERE source=?1 AND key=?2",
params![delivery.receipt.source, delivery.receipt.key],
)
.map_err(sql)?;
}
Ok(delivery)
}).map_err(sql)
}
fn bind(&self, receipt: &TriggerReceipt, id: &str) -> Result<(), String> {
let count = self.lock()?.execute("UPDATE deliveries SET execution_id=?1,status='running' WHERE source=?2 AND key=?3 AND execution_id IS NULL AND status='preparing'",params![id,receipt.source,receipt.key]).map_err(sql)?;
if count == 1 {
Ok(())
} else {
Err("Trigger binding lost ownership".into())
}
}
fn finish(
&self,
receipt: &TriggerReceipt,
status: &str,
error: Option<&str>,
) -> Result<(), String> {
self.lock()?
.execute(
"UPDATE deliveries SET status=?1,error=?2 WHERE source=?3 AND key=?4",
params![status, error, receipt.source, receipt.key],
)
.map_err(sql)?;
Ok(())
}
}
fn row(row: &crate::database::Row) -> crate::database::Result<Delivery> {
let body: String = row.get(2)?;
let request: TriggerRequest = serde_json::from_str(&body)
.map_err(|error| crate::database::Error::Message(error.to_string()))?;
let receipt = TriggerReceipt {
source: row.get(0)?,
key: row.get(1)?,
workflow: request.workflow.clone(),
version: row.get(3)?,
execution_id: row.get(5)?,
status: row.get(4)?,
error: row.get(6)?,
not_before: request.not_before,
deadline: request.deadline,
};
Ok(Delivery { request, receipt })
}
#[cfg(all(test, feature = "native", not(target_arch = "wasm32")))]
mod tests {
use super::*;
use multicast::cli::Cli;
use multicast::command::{
CommandContext, CommandDef, CommandHandler, McpAnnotations, McpCommandOptions,
};
use multicast::output::CommandResult;
use serde_json::json;
use std::sync::atomic::{AtomicUsize, Ordering};
#[test]
fn journal_mode_initialization_waits_for_a_concurrent_reader() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("queue.sqlite");
let reader = rusqlite::Connection::open(&path).unwrap();
reader
.execute_batch("CREATE TABLE control (value INTEGER); BEGIN;")
.unwrap();
assert_eq!(
reader
.query_row("SELECT COUNT(*) FROM control", [], |row| row
.get::<_, i64>(0))
.unwrap(),
0
);
let (sender, receiver) = std::sync::mpsc::channel();
let worker = std::thread::spawn(move || {
let result = (|| {
let connection = Connection::open(&path).map_err(sql)?;
Queue::initialize(&connection)?;
connection
.query_row("PRAGMA journal_mode", params![], |row| row.get::<String>(0))
.map_err(sql)
})();
sender.send(result).unwrap();
});
assert!(matches!(
receiver.recv_timeout(Duration::from_millis(100)),
Err(std::sync::mpsc::RecvTimeoutError::Timeout)
));
reader.execute_batch("COMMIT").unwrap();
assert_eq!(
receiver
.recv_timeout(Duration::from_secs(6))
.unwrap()
.unwrap(),
"wal"
);
worker.join().unwrap();
}
struct Read(Arc<AtomicUsize>);
#[async_trait::async_trait]
impl CommandHandler for Read {
async fn run(&self, _: CommandContext) -> CommandResult {
self.0.fetch_add(1, Ordering::SeqCst);
CommandResult::Ok {
data: json!(73),
cta: None,
exit_code: None,
}
}
}
fn host(path: &Path, calls: &Arc<AtomicUsize>, code: &str) -> WorkflowTriggers {
let cli = Cli::create("preparation").command(
"observe",
CommandDef::build("observe", Read(calls.clone()))
.mcp(McpCommandOptions {
annotations: Some(McpAnnotations {
read_only_hint: Some(true),
..Default::default()
}),
..Default::default()
})
.done(),
);
crate::Workflows::new()
.store_path(path)
.shipped("job", "Observe", json!({"type":"object"}), code)
.attach_with_triggers(cli)
.unwrap()
.1
}
fn request(key: &str) -> TriggerRequest {
TriggerRequest {
key: key.into(),
workflow: "job".into(),
input: json!({}),
not_before: 0,
deadline: now_ms().unwrap() + 30_000,
}
}
#[tokio::test]
async fn wakeups_cover_due_work_paused_deadlines_and_schedules_without_busy_polling() {
let dir = tempfile::tempdir().unwrap();
let calls = Arc::default();
let host = host(
&dir.path().join("state.sqlite"),
&calls,
"async () => preparation.observe({})",
);
assert_eq!(host.next_wake().unwrap(), None);
let now = now_ms().unwrap();
let mut first = request("first");
first.not_before = now + 60_000;
first.deadline = now + 120_000;
host.enqueue(first.clone()).await.unwrap();
assert_eq!(host.next_wake().unwrap(), Some(first.not_before));
let queue = host.queue().unwrap();
let claimed = queue.claim(first.not_before).unwrap().unwrap();
queue.bind(&claimed.receipt, "bound-execution").unwrap();
queue.finish(&claimed.receipt, "paused", None).unwrap();
let mut second = request("second");
second.deadline = now + 180_000;
host.enqueue(second).await.unwrap();
// The queued delivery cannot take the paused workflow's slot.
assert_eq!(host.next_wake().unwrap(), Some(first.deadline));
host.schedule(TriggerSchedule {
id: "earlier".into(),
workflow: "job".into(),
input: json!({}),
first_at: now + 30_000,
every_ms: 60_000,
deadline_ms: 10_000,
})
.await
.unwrap();
assert_eq!(host.next_wake().unwrap(), Some(now + 30_000));
assert!(host.remove_schedule("earlier").unwrap());
assert_eq!(host.next_wake().unwrap(), Some(first.deadline));
queue.finish(&claimed.receipt, "cancelled", None).unwrap();
let wake = host.next_wake().unwrap().unwrap();
assert!(wake >= now && wake <= now_ms().unwrap());
assert_eq!(calls.load(Ordering::SeqCst), 0);
}
#[tokio::test]
async fn admission_rejects_invalid_keys_inputs_timestamps_and_payloads() {
let dir = tempfile::tempdir().unwrap();
let calls = Arc::default();
let host = host(
&dir.path().join("state.sqlite"),
&calls,
"async () => preparation.observe({})",
);
let mut invalid = vec![
request(""),
request(&"x".repeat(257)),
request(&"é".repeat(129)),
];
let mut input = request("invalid-input");
input.input = Value::Null;
invalid.push(input);
let mut time = request("invalid-time");
time.not_before = time.deadline;
invalid.push(time);
let mut overflow = request("overflow-time");
overflow.deadline = u64::MAX;
invalid.push(overflow);
let mut large = request("oversized");
large.input = json!({"payload":"x".repeat(1_048_576)});
invalid.push(large);
for request in invalid {
let key = request.key.clone();
assert!(host.enqueue(request).await.is_err(), "accepted {key}");
assert!(
host.receipt("webhook", &key).unwrap().is_none(),
"persisted {key}"
);
}
assert_eq!(calls.load(Ordering::SeqCst), 0);
let accepted = request(&"é".repeat(128));
assert_eq!(host.enqueue(accepted).await.unwrap().status, "queued");
let mut accepted = request("large-valid");
accepted.input = json!({"payload":"x".repeat(1_000_000)});
assert_eq!(host.enqueue(accepted).await.unwrap().status, "queued");
assert_eq!(calls.load(Ordering::SeqCst), 0);
}
#[tokio::test]
async fn schedules_and_tick_limits_reject_invalid_values_before_delivery() {
let dir = tempfile::tempdir().unwrap();
let calls = Arc::default();
let host = host(
&dir.path().join("state.sqlite"),
&calls,
"async () => preparation.observe({})",
);
let valid = TriggerSchedule {
id: "schedule".into(),
workflow: "job".into(),
input: json!({}),
first_at: now_ms().unwrap() + 60_000,
every_ms: 1000,
deadline_ms: 500,
};
let mut zero_interval = valid.clone();
zero_interval.every_ms = 0;
let mut zero_deadline = valid.clone();
zero_deadline.deadline_ms = 0;
let mut overflow = valid.clone();
overflow.first_at = i64::MAX as u64;
let mut bad_input = valid.clone();
bad_input.input = Value::Null;
for schedule in [zero_interval, zero_deadline, overflow, bad_input] {
assert!(host.schedule(schedule).await.is_err());
}
assert!(!host.remove_schedule("schedule").unwrap());
assert!(host.tick(0).await.is_err());
assert!(host.tick(101).await.is_err());
host.schedule(valid).await.unwrap();
assert!(host.tick(100).await.unwrap().is_empty());
assert_eq!(calls.load(Ordering::SeqCst), 0);
}
#[tokio::test]
async fn preparation_has_no_effects_and_binding_reuses_the_same_execution() {
let dir = tempfile::tempdir().unwrap();
let calls = Arc::default();
let host = host(
&dir.path().join("state.sqlite"),
&calls,
"async () => preparation.observe({})",
);
host.enqueue(request("bound-window")).await.unwrap();
let delivery = host
.queue()
.unwrap()
.claim(now_ms().unwrap())
.unwrap()
.unwrap();
let workflow = host.state.resolve("job").await.unwrap().unwrap();
let (_, code) = program(&workflow, json!({})).unwrap();
let prepared = host
.state
.service()
.await
.unwrap()
.prepare(code)
.await
.unwrap();
assert_eq!(prepared.status, ExecutionStatus::Running);
assert!(prepared.log.is_empty());
assert_eq!(calls.load(Ordering::SeqCst), 0);
host.queue()
.unwrap()
.bind(&delivery.receipt, &prepared.id)
.unwrap();
let receipts = host.tick(1).await.unwrap();
assert_eq!(
receipts[0].execution_id.as_deref(),
Some(prepared.id.as_str())
);
assert_eq!(receipts[0].status, "completed");
assert_eq!(calls.load(Ordering::SeqCst), 1);
host.tick(1).await.unwrap();
assert_eq!(calls.load(Ordering::SeqCst), 1);
}
#[tokio::test]
async fn abandoned_unbound_preparation_is_safe_to_replace() {
let dir = tempfile::tempdir().unwrap();
let calls = Arc::default();
let host = host(
&dir.path().join("state.sqlite"),
&calls,
"async () => preparation.observe({})",
);
host.enqueue(request("unbound-window")).await.unwrap();
host.queue()
.unwrap()
.claim(now_ms().unwrap())
.unwrap()
.unwrap();
let orphan = host
.state
.service()
.await
.unwrap()
.prepare("async () => preparation.observe({})".into())
.await
.unwrap();
assert_eq!(calls.load(Ordering::SeqCst), 0);
let receipts = host.tick(1).await.unwrap();
assert_eq!(receipts[0].status, "completed");
assert_ne!(
receipts[0].execution_id.as_deref(),
Some(orphan.id.as_str())
);
assert_eq!(calls.load(Ordering::SeqCst), 1);
assert!(
host.state
.service()
.await
.unwrap()
.execution(orphan.id)
.await
.unwrap()
.log
.is_empty()
);
}
#[tokio::test]
async fn changed_program_blocks_before_a_new_execution() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("state.sqlite");
let calls = Arc::default();
let old = host(&path, &calls, "async () => preparation.observe({})");
old.enqueue(request("version")).await.unwrap();
drop(old);
let new = host(
&path,
&calls,
"async () => { await preparation.observe({}); return 74; }",
);
let receipts = new.tick(1).await.unwrap();
assert_eq!(receipts[0].status, "blocked");
assert!(receipts[0].execution_id.is_none());
assert_eq!(calls.load(Ordering::SeqCst), 0);
}
#[tokio::test]
async fn missing_bound_execution_blocks_without_a_replacement() {
let dir = tempfile::tempdir().unwrap();
let calls = Arc::default();
let host = host(
&dir.path().join("state.sqlite"),
&calls,
"async () => preparation.observe({})",
);
host.enqueue(request("missing")).await.unwrap();
let delivery = host
.queue()
.unwrap()
.claim(now_ms().unwrap())
.unwrap()
.unwrap();
host.queue()
.unwrap()
.bind(&delivery.receipt, "missing-execution")
.unwrap();
let receipts = host.tick(1).await.unwrap();
assert_eq!(receipts[0].status, "blocked");
assert_eq!(
receipts[0].execution_id.as_deref(),
Some("missing-execution")
);
assert_eq!(calls.load(Ordering::SeqCst), 0);
host.enqueue(request("after-missing")).await.unwrap();
let refreshed = host.tick(1).await.unwrap();
assert_eq!(refreshed.len(), 1);
assert_eq!(refreshed[0].key, "missing");
assert_eq!(refreshed[0].status, "blocked");
assert_eq!(
host.receipt("webhook", "after-missing")
.unwrap()
.unwrap()
.status,
"queued"
);
assert_eq!(calls.load(Ordering::SeqCst), 0);
}
}