durable-workflow 4.27.0

Rust client and worker SDK for Durable Workflow Cloud and self-hosted Server
Documentation
//! Persistable signal and update admission requests for protected clients.

use serde::{Deserialize, Serialize};
use serde_json::{json, Value};

use crate::{
    client_payload::exact_inline,
    normalize_avro_arguments, path_segment,
    payload_protection::{ProtectionContext, ProtectionError},
    runtime_payloads::Reference,
    signal_with_start::{atomic_signal_path, AtomicStart},
    validate_request_id, validate_user_signal_name, AvroValue, Boundary, Client, Error,
    JsonPayloads, RequestProtocol, Result, SignalWithStartOptions, UpdateWaitStage, DEFAULT_CODEC,
};

const SCHEMA: &str = "durable-workflow.rust.prepared-payload-command.v1";

/// Store this record durably before submitting a command whose reply may be lost.
/// It contains the selected target, caller request ID, and encrypted wire input.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PreparedPayloadCommand {
    schema: String,
    namespace: String,
    workflow_id: String,
    run_id: Option<String>,
    name: String,
    request_id: String,
    operation: Operation,
    input: Value,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "kind", deny_unknown_fields)]
enum Operation {
    Signal,
    Update {
        wait_for: PreparedWait,
    },
    SignalWithStart {
        start: AtomicStart,
        signal_input: Value,
    },
}

#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
enum PreparedWait {
    Accepted,
    Completed,
}

impl Operation {
    fn path_part(&self) -> &'static str {
        match self {
            Self::Signal => "signal",
            Self::Update { .. } => "update",
            Self::SignalWithStart { .. } => "signal-with-start",
        }
    }

    fn boundary(&self) -> Boundary {
        match self {
            Self::Signal => Boundary::SignalInput,
            Self::Update { .. } => Boundary::UpdateInput,
            Self::SignalWithStart { .. } => Boundary::WorkflowInput,
        }
    }
}

impl PreparedPayloadCommand {
    /// The exact request ID retained across sends.
    pub fn request_id(&self) -> &str {
        &self.request_id
    }

    fn path(&self) -> Result<String> {
        if let Operation::SignalWithStart { start, .. } = &self.operation {
            if self.run_id.is_some() {
                return Err(ProtectionError::InvalidPreparedCommand.into());
            }
            start.validate()?;
            return atomic_signal_path(&self.workflow_id, &self.name);
        }
        let kind = self.operation.path_part();
        if matches!(self.operation, Operation::Signal) {
            validate_user_signal_name(&self.name)?;
        }
        let mut path = format!(
            "/workflows/{}",
            path_segment("workflow_id", &self.workflow_id)?
        );
        if let Some(run_id) = &self.run_id {
            path.push_str(&format!("/runs/{}", path_segment("run_id", run_id)?));
        }
        Ok(format!(
            "{path}/{kind}/{}",
            path_segment("command_name", &self.name)?
        ))
    }

    fn body(&self) -> Value {
        match &self.operation {
            Operation::Signal => json!({"input": self.input, "request_id": self.request_id}),
            Operation::Update { wait_for } => {
                json!({"input": self.input, "request_id": self.request_id, "wait_for":wait_for})
            }
            Operation::SignalWithStart {
                start,
                signal_input,
            } => start.body(&self.input, signal_input, &self.request_id),
        }
    }
}

impl Client {
    /// Seal one signal and, if required, prepare its external payload object.
    pub async fn prepare_signal<T: Serialize>(
        &self,
        workflow_id: &str,
        run_id: Option<&str>,
        signal_name: &str,
        input: T,
        request_id: Option<&str>,
    ) -> Result<PreparedPayloadCommand> {
        self.prepare_payload_command(
            workflow_id,
            run_id,
            signal_name,
            input,
            request_id,
            Operation::Signal,
        )
        .await
    }

    /// Seal one update for a stable workflow or a selected run.
    pub async fn prepare_update<T: Serialize>(
        &self,
        workflow_id: &str,
        run_id: Option<&str>,
        update_name: &str,
        input: T,
        request_id: Option<&str>,
        wait_for: UpdateWaitStage,
    ) -> Result<PreparedPayloadCommand> {
        let wait_for = match wait_for {
            UpdateWaitStage::Accepted => PreparedWait::Accepted,
            UpdateWaitStage::Completed => PreparedWait::Completed,
        };
        self.prepare_payload_command(
            workflow_id,
            run_id,
            update_name,
            input,
            request_id,
            Operation::Update { wait_for },
        )
        .await
    }

    async fn prepare_payload_command<T: Serialize>(
        &self,
        workflow_id: &str,
        run_id: Option<&str>,
        name: &str,
        input: T,
        request_id: Option<&str>,
        operation: Operation,
    ) -> Result<PreparedPayloadCommand> {
        if !self.protection_enabled() {
            return Err(ProtectionError::ProtectionRequired.into());
        }
        let request_id = request_id.map_or_else(
            || crate::generated_request_id(operation.path_part()),
            str::to_owned,
        );
        validate_request_id(&request_id)?;
        let mut prepared = PreparedPayloadCommand {
            schema: SCHEMA.into(),
            namespace: self.namespace.clone(),
            workflow_id: workflow_id.into(),
            run_id: run_id.map(str::to_owned),
            name: name.into(),
            request_id,
            operation,
            input: Value::Null,
        };
        let path = prepared.path()?;
        let args = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
        prepared.input = self.encode_client_payload(&args, prepared.operation.boundary())?;
        self.prepare_command_references(&mut prepared, &path)
            .await?;
        Ok(prepared)
    }

    /// Seal both inputs to an atomic signal-with-start. Persist the returned
    /// command and submit it with [`Client::send_prepared_command`] so recovery
    /// can reuse the exact request ID, inputs and start options.
    #[allow(clippy::too_many_arguments)]
    pub async fn prepare_signal_with_start<I: Serialize, S: Serialize>(
        &self,
        workflow_type: &str,
        task_queue: &str,
        workflow_id: &str,
        signal_name: &str,
        input: I,
        signal_input: S,
        options: SignalWithStartOptions,
    ) -> Result<PreparedPayloadCommand> {
        if !self.protection_enabled() {
            return Err(ProtectionError::ProtectionRequired.into());
        }
        let start = AtomicStart::new(workflow_type, task_queue, &options)?;
        let request_id = options
            .request_id
            .unwrap_or_else(Self::generate_signal_with_start_request_id);
        validate_request_id(&request_id)?;
        let path = atomic_signal_path(workflow_id, signal_name)?;
        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
        let signal_input = normalize_avro_arguments(AvroValue::from_serialize(&signal_input)?);
        let mut command = PreparedPayloadCommand {
            schema: SCHEMA.into(),
            namespace: self.namespace.clone(),
            workflow_id: workflow_id.into(),
            run_id: None,
            name: signal_name.into(),
            request_id,
            operation: Operation::SignalWithStart {
                start,
                signal_input: self.encode_client_payload(&signal_input, Boundary::SignalInput)?,
            },
            input: self.encode_client_payload(&input, Boundary::WorkflowInput)?,
        };
        self.require_signal_with_start().await?;
        self.prepare_command_references(&mut command, &path).await?;
        Ok(command)
    }

    async fn prepare_command_references(
        &self,
        command: &mut PreparedPayloadCommand,
        path: &str,
    ) -> Result<()> {
        let mut body = command.body();
        self.externalize_runtime_payloads(&mut body, path, RequestProtocol::ControlPlane)
            .await?;
        let fields = body
            .as_object_mut()
            .ok_or(ProtectionError::InvalidPreparedCommand)?;
        command.input = fields
            .remove("input")
            .ok_or(ProtectionError::InvalidPreparedCommand)?;
        if let Operation::SignalWithStart { signal_input, .. } = &mut command.operation {
            *signal_input = fields
                .remove("signal_input")
                .ok_or(ProtectionError::InvalidPreparedCommand)?;
        }
        Ok(())
    }

    /// Submit or resend a persisted command without re-encrypting or replacing its input.
    /// A client with retained read keys can resend a command without a writer key.
    /// External objects are fetched through the same authenticated namespace
    /// and verified before the saved reference is submitted.
    pub async fn send_prepared_command(&self, command: &PreparedPayloadCommand) -> Result<Value> {
        if !self.protection_enabled() {
            return Err(ProtectionError::ProtectionRequired.into());
        }
        if command.schema != SCHEMA {
            return Err(ProtectionError::InvalidPreparedCommand.into());
        }
        if command.namespace != self.namespace {
            return Err(ProtectionError::AuthenticationFailed.into());
        }
        validate_request_id(&command.request_id)?;
        let path = command.path()?;
        self.verify_prepared_input(&command.input, command.operation.boundary())
            .await?;
        if let Operation::SignalWithStart { signal_input, .. } = &command.operation {
            self.verify_prepared_input(signal_input, Boundary::SignalInput)
                .await?;
            self.require_signal_with_start().await?;
        }
        let receipt = self
            .send_payload_command(
                &path,
                &command.body(),
                &command.request_id,
                JsonPayloads::PREPARED,
            )
            .await?;
        self.assert_protected_response_namespace(receipt.get("namespace"))?;
        if matches!(command.operation, Operation::Update { .. }) {
            self.assert_protected_result_receipt(
                &receipt,
                receipt.get("update_status").and_then(Value::as_str) == Some("completed"),
            )?;
        }
        Ok(receipt)
    }

    async fn verify_prepared_input(&self, input: &Value, boundary: Boundary) -> Result<()> {
        let protection = self
            .payload_protection
            .as_ref()
            .ok_or(ProtectionError::ProtectionRequired)?;
        let context = ProtectionContext::new(&self.namespace, boundary)?;
        let envelope = if let Some(reference) = Reference::parse(input)? {
            if reference.size_bytes > self.max_external_payload_bytes {
                return Err(Error::Codec(
                    "external_payload_oversized: prepared payload exceeds the response byte limit"
                        .into(),
                ));
            }
            let blob = self
                .fetch_runtime_payload(&reference, RequestProtocol::ControlPlane)
                .await?;
            crate::PayloadEnvelope {
                codec: DEFAULT_CODEC.into(),
                blob,
            }
        } else {
            exact_inline(input)?
        };
        // A deserialized record can name an arbitrary object or contain a plain
        // frame. Verify the same immutable bytes and binding before admission.
        if !matches!(
            protection.open_strict(&envelope, context)?,
            AvroValue::Array(_)
        ) {
            return Err(ProtectionError::InvalidPreparedCommand.into());
        }
        Ok(())
    }
}