assay-workflow 0.4.5

Durable workflow engine with REST+SSE API on PostgreSQL 18 and SQLite backends. Embeddable library or standalone server (via assay-engine).
Documentation
//! Signal and event-history methods.

use anyhow::Result;

use crate::ctx::{WorkflowCtx, timestamp_now};
use crate::events::WorkflowBusEvent;
use crate::store::WorkflowStore;
use crate::types::*;

impl<S: WorkflowStore> WorkflowCtx<S> {
    /// Deliver a signal to a workflow. The signal row, its `SignalReceived`
    /// history event and the dispatch arming land in one store transaction,
    /// so a stored signal is never invisible to the workflow that has to
    /// react to it.
    pub async fn send_signal(
        &self,
        workflow_id: &str,
        name: &str,
        payload: Option<&str>,
    ) -> Result<()> {
        let now = timestamp_now();
        // Parse the incoming payload string back to a JSON value so the
        // event payload nests cleanly (otherwise the recorded payload is
        // a stringified JSON-inside-JSON and Lua workers would have to
        // double-decode).
        let payload_value: serde_json::Value = payload
            .and_then(|s| serde_json::from_str(s).ok())
            .unwrap_or(serde_json::Value::Null);
        let event_payload =
            serde_json::json!({ "signal": name, "payload": payload_value }).to_string();

        self.store
            .deliver_signal(
                &WorkflowSignal {
                    id: None,
                    workflow_id: workflow_id.to_string(),
                    name: name.to_string(),
                    payload: payload.map(String::from),
                    consumed: false,
                    received_at: now,
                },
                &event_payload,
            )
            .await?;

        // so the worker can replay and notice the signal in history.
        self.emit_needs_dispatch(workflow_id).await;

        // Emit so the dashboard can refresh the run's row (signal
        // count bump, log-tail tick, etc.).
        let ns = self
            .store
            .get_workflow(workflow_id)
            .await?
            .map(|w| w.namespace)
            .unwrap_or_default();
        self.emit(
            &ns,
            WorkflowBusEvent::SignalReceived {
                workflow_id: workflow_id.to_string(),
                signal_name: name.to_string(),
            },
        )
        .await;

        Ok(())
    }

    pub async fn get_events(&self, workflow_id: &str) -> Result<Vec<WorkflowEvent>> {
        self.store.list_events(workflow_id).await
    }

    pub async fn get_events_page(
        &self,
        workflow_id: &str,
        cursor: Option<i32>,
        limit: i64,
        descending: bool,
    ) -> Result<Vec<WorkflowEvent>> {
        self.store
            .list_events_page(workflow_id, cursor, limit, descending)
            .await
    }
}