multicast-workflows 2.0.0

Durable Code Mode workflows attached to multicast CLIs as first-party commands
Documentation
//! Durable authority references for workflow continuation on any host.
//!
//! Only a server-owned reference is stored. Credentials and policy are resolved
//! afresh before a pass and every connector operation, including recovery. This
//! is separate from observations: restoring an execution never grants sharing.
use crate::WorkflowDatabase;
use async_trait::async_trait;
use multicast::command::RequestContext;
use multicast_codemode::{
    CallRecovery, Connector, ConnectorDescription, ConnectorTool, RetryPolicy, ToolContext,
};
use serde_json::Value;
use std::sync::Arc;

/// Host authentication and revocation boundary for durable workflow calls.
#[async_trait]
pub trait WorkflowAuthority: Send + Sync {
    /// Authenticates an ingress request and returns a stable, non-secret reference.
    /// `None` is an alarm/trigger admission; deny unless an explicit service identity
    /// is configured. Never return a bearer token or caller-selected scope label.
    fn capture(&self, request: Option<&RequestContext>) -> Result<String, String>;
    /// Resolves current credentials and policy. Revocation or missing bindings must
    /// fail; never substitute a default tenant, principal, or process credential.
    async fn resolve(&self, reference: &str) -> Result<RequestContext, String>;
}

/// Immutable execution-to-authority bindings in the host's durable database.
#[derive(Clone)]
pub struct WorkflowBindings {
    database: Arc<dyn WorkflowDatabase>,
    authority: Arc<dyn WorkflowAuthority>,
}
impl WorkflowBindings {
    /// Opens the binding table alongside a host-owned workflow database.
    pub fn new(
        database: Arc<dyn WorkflowDatabase>,
        authority: Arc<dyn WorkflowAuthority>,
    ) -> Result<Self, String> {
        database.execute_batch("CREATE TABLE IF NOT EXISTS incurs_workflow_authority(id TEXT PRIMARY KEY, reference TEXT NOT NULL)")?;
        Ok(Self {
            database,
            authority,
        })
    }
    /// Binds an admitted execution, or validates an explicit continuation actor.
    /// Alarm recovery loads the existing binding without a caller credential.
    pub async fn admit(
        &self,
        id: &str,
        request: Option<&RequestContext>,
    ) -> Result<RequestContext, String> {
        let existing = self.reference(id)?;
        let reference = match existing {
            Some(reference) => {
                if request.is_some() && self.authority.capture(request)? != reference {
                    return Err("WORKFLOW_AUTHORITY_MISMATCH".into());
                }
                reference
            }
            None => {
                let reference = self.authority.capture(request)?;
                if reference.is_empty() || reference.len() > 1024 {
                    return Err("WORKFLOW_AUTHORITY_REFERENCE".into());
                }
                // Resolve before storing so rejected admissions leave no authority binding.
                self.authority.resolve(&reference).await?;
                let mut write = |sql: &dyn crate::WorkflowSql| {
                    sql.execute("INSERT OR IGNORE INTO incurs_workflow_authority(id,reference) VALUES (?,?)",&[Value::String(id.into()),Value::String(reference.clone())])?;
                    let rows = sql.query(
                        "SELECT reference FROM incurs_workflow_authority WHERE id=?",
                        &[Value::String(id.into())],
                    )?;
                    if rows.first().and_then(|r| r.first()).and_then(Value::as_str)
                        != Some(reference.as_str())
                    {
                        return Err("WORKFLOW_AUTHORITY_MISMATCH".into());
                    }
                    Ok(())
                };
                self.database.transaction(&mut write)?;
                reference
            }
        };
        self.authority.resolve(&reference).await
    }
    /// Re-resolves an existing execution before any connector operation.
    pub async fn resolve(&self, id: &str) -> Result<RequestContext, String> {
        let reference = self.reference(id)?.ok_or("WORKFLOW_AUTHORITY_MISSING")?;
        self.authority.resolve(&reference).await
    }
    /// Copies only the parent's stable server-owned reference to a prepared child.
    /// Resolve current policy before binding; caller data never selects a principal.
    pub async fn inherit(&self, parent: &str, child: &str) -> Result<(), String> {
        let reference = self
            .reference(parent)?
            .ok_or("WORKFLOW_AUTHORITY_MISSING")?;
        self.authority.resolve(&reference).await?;
        let mut write = |sql: &dyn crate::WorkflowSql| {
            sql.execute(
                "INSERT OR IGNORE INTO incurs_workflow_authority(id,reference) VALUES (?,?)",
                &[
                    Value::String(child.into()),
                    Value::String(reference.clone()),
                ],
            )?;
            let rows = sql.query(
                "SELECT reference FROM incurs_workflow_authority WHERE id=?",
                &[Value::String(child.into())],
            )?;
            if rows.first().and_then(|r| r.first()).and_then(Value::as_str)
                != Some(reference.as_str())
            {
                return Err("WORKFLOW_AUTHORITY_MISMATCH".into());
            }
            Ok(())
        };
        self.database.transaction(&mut write)
    }
    fn reference(&self, id: &str) -> Result<Option<String>, String> {
        let rows = self.database.query(
            "SELECT reference FROM incurs_workflow_authority WHERE id=?",
            &[Value::String(id.into())],
        )?;
        rows.first()
            .map(|row| {
                row.first()
                    .and_then(Value::as_str)
                    .map(str::to_string)
                    .ok_or_else(|| "WORKFLOW_AUTHORITY_CORRUPT".into())
            })
            .transpose()
    }
    /// Wraps a connector while retaining its dispatch, retry, and lifecycle behavior.
    pub fn connector(&self, inner: Arc<dyn Connector>) -> Arc<dyn Connector> {
        Arc::new(AuthorityConnector {
            inner,
            bindings: self.clone(),
        })
    }
}
struct AuthorityConnector {
    inner: Arc<dyn Connector>,
    bindings: WorkflowBindings,
}
impl AuthorityConnector {
    async fn context(&self, context: &ToolContext) -> Result<ToolContext, String> {
        let mut context = context.clone();
        context.request = Some(self.bindings.resolve(&context.execution_id).await?);
        Ok(context)
    }
}
#[async_trait]
impl Connector for AuthorityConnector {
    async fn admit_child(
        &self,
        parent: &str,
        child: &str,
        request: Option<&RequestContext>,
    ) -> Result<(), String> {
        self.bindings.inherit(parent, child).await?;
        self.inner.admit_child(parent, child, request).await
    }
    fn name(&self) -> &str {
        self.inner.name()
    }
    async fn describe(&self) -> Result<ConnectorDescription, String> {
        self.inner.describe().await
    }
    fn retry_policy(&self, method: &str) -> RetryPolicy {
        self.inner.retry_policy(method)
    }
    async fn prepare_arguments(
        &self,
        seq: u64,
        tool: &ConnectorTool,
        arguments: Value,
        context: &ToolContext,
    ) -> Result<Value, String> {
        self.inner
            .prepare_arguments(seq, tool, arguments, &self.context(context).await?)
            .await
    }
    async fn execute(
        &self,
        method: &str,
        arguments: Value,
        context: &ToolContext,
    ) -> Result<Value, String> {
        self.inner
            .execute(method, arguments, &self.context(context).await?)
            .await
    }
    async fn recover(
        &self,
        method: &str,
        arguments: &Value,
        context: &ToolContext,
    ) -> Result<CallRecovery, String> {
        self.inner
            .recover(method, arguments, &self.context(context).await?)
            .await
    }
    async fn revert(
        &self,
        method: &str,
        arguments: Value,
        result: Value,
        context: &ToolContext,
    ) -> Result<bool, String> {
        self.inner
            .revert(method, arguments, result, &self.context(context).await?)
            .await
    }
    async fn pass_ended(&self, id: &str, status: &str) {
        self.inner.pass_ended(id, status).await;
    }
    async fn execution_ended(&self, id: &str, status: &str) {
        self.inner.execution_ended(id, status).await;
    }
}