Skip to content
Durable Workflowrust

durable_workflow/
prepared_payload.rs

1//! Persistable signal and update admission requests for protected clients.
2
3use serde::{Deserialize, Serialize};
4use serde_json::{json, Value};
5
6use crate::{
7    client_payload::exact_inline,
8    normalize_avro_arguments, path_segment,
9    payload_protection::{ProtectionContext, ProtectionError},
10    runtime_payloads::Reference,
11    signal_with_start::{atomic_signal_path, AtomicStart},
12    validate_request_id, validate_user_signal_name, AvroValue, Boundary, Client, Error,
13    JsonPayloads, RequestProtocol, Result, SignalWithStartOptions, UpdateWaitStage, DEFAULT_CODEC,
14};
15
16const SCHEMA: &str = "durable-workflow.rust.prepared-payload-command.v1";
17
18/// Store this record durably before submitting a command whose reply may be lost.
19/// It contains the selected target, caller request ID, and encrypted wire input.
20#[derive(Clone, Debug, Serialize, Deserialize)]
21#[serde(deny_unknown_fields)]
22pub struct PreparedPayloadCommand {
23    schema: String,
24    namespace: String,
25    workflow_id: String,
26    run_id: Option<String>,
27    name: String,
28    request_id: String,
29    operation: Operation,
30    input: Value,
31}
32
33#[derive(Clone, Debug, Serialize, Deserialize)]
34#[serde(rename_all = "snake_case", tag = "kind", deny_unknown_fields)]
35enum Operation {
36    Signal,
37    Update {
38        wait_for: PreparedWait,
39    },
40    SignalWithStart {
41        start: AtomicStart,
42        signal_input: Value,
43    },
44}
45
46#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
47#[serde(rename_all = "snake_case")]
48enum PreparedWait {
49    Accepted,
50    Completed,
51}
52
53impl Operation {
54    fn path_part(&self) -> &'static str {
55        match self {
56            Self::Signal => "signal",
57            Self::Update { .. } => "update",
58            Self::SignalWithStart { .. } => "signal-with-start",
59        }
60    }
61
62    fn boundary(&self) -> Boundary {
63        match self {
64            Self::Signal => Boundary::SignalInput,
65            Self::Update { .. } => Boundary::UpdateInput,
66            Self::SignalWithStart { .. } => Boundary::WorkflowInput,
67        }
68    }
69}
70
71impl PreparedPayloadCommand {
72    /// The exact request ID retained across sends.
73    pub fn request_id(&self) -> &str {
74        &self.request_id
75    }
76
77    fn path(&self) -> Result<String> {
78        if let Operation::SignalWithStart { start, .. } = &self.operation {
79            if self.run_id.is_some() {
80                return Err(ProtectionError::InvalidPreparedCommand.into());
81            }
82            start.validate()?;
83            return atomic_signal_path(&self.workflow_id, &self.name);
84        }
85        let kind = self.operation.path_part();
86        if matches!(self.operation, Operation::Signal) {
87            validate_user_signal_name(&self.name)?;
88        }
89        let mut path = format!(
90            "/workflows/{}",
91            path_segment("workflow_id", &self.workflow_id)?
92        );
93        if let Some(run_id) = &self.run_id {
94            path.push_str(&format!("/runs/{}", path_segment("run_id", run_id)?));
95        }
96        Ok(format!(
97            "{path}/{kind}/{}",
98            path_segment("command_name", &self.name)?
99        ))
100    }
101
102    fn body(&self) -> Value {
103        match &self.operation {
104            Operation::Signal => json!({"input": self.input, "request_id": self.request_id}),
105            Operation::Update { wait_for } => {
106                json!({"input": self.input, "request_id": self.request_id, "wait_for":wait_for})
107            }
108            Operation::SignalWithStart {
109                start,
110                signal_input,
111            } => start.body(&self.input, signal_input, &self.request_id),
112        }
113    }
114}
115
116impl Client {
117    /// Seal one signal and, if required, prepare its external payload object.
118    pub async fn prepare_signal<T: Serialize>(
119        &self,
120        workflow_id: &str,
121        run_id: Option<&str>,
122        signal_name: &str,
123        input: T,
124        request_id: Option<&str>,
125    ) -> Result<PreparedPayloadCommand> {
126        self.prepare_payload_command(
127            workflow_id,
128            run_id,
129            signal_name,
130            input,
131            request_id,
132            Operation::Signal,
133        )
134        .await
135    }
136
137    /// Seal one update for a stable workflow or a selected run.
138    pub async fn prepare_update<T: Serialize>(
139        &self,
140        workflow_id: &str,
141        run_id: Option<&str>,
142        update_name: &str,
143        input: T,
144        request_id: Option<&str>,
145        wait_for: UpdateWaitStage,
146    ) -> Result<PreparedPayloadCommand> {
147        let wait_for = match wait_for {
148            UpdateWaitStage::Accepted => PreparedWait::Accepted,
149            UpdateWaitStage::Completed => PreparedWait::Completed,
150        };
151        self.prepare_payload_command(
152            workflow_id,
153            run_id,
154            update_name,
155            input,
156            request_id,
157            Operation::Update { wait_for },
158        )
159        .await
160    }
161
162    async fn prepare_payload_command<T: Serialize>(
163        &self,
164        workflow_id: &str,
165        run_id: Option<&str>,
166        name: &str,
167        input: T,
168        request_id: Option<&str>,
169        operation: Operation,
170    ) -> Result<PreparedPayloadCommand> {
171        if !self.protection_enabled() {
172            return Err(ProtectionError::ProtectionRequired.into());
173        }
174        let request_id = request_id.map_or_else(
175            || crate::generated_request_id(operation.path_part()),
176            str::to_owned,
177        );
178        validate_request_id(&request_id)?;
179        let mut prepared = PreparedPayloadCommand {
180            schema: SCHEMA.into(),
181            namespace: self.namespace.clone(),
182            workflow_id: workflow_id.into(),
183            run_id: run_id.map(str::to_owned),
184            name: name.into(),
185            request_id,
186            operation,
187            input: Value::Null,
188        };
189        let path = prepared.path()?;
190        let args = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
191        prepared.input = self.encode_client_payload(&args, prepared.operation.boundary())?;
192        self.prepare_command_references(&mut prepared, &path)
193            .await?;
194        Ok(prepared)
195    }
196
197    /// Seal both inputs to an atomic signal-with-start. Persist the returned
198    /// command and submit it with [`Client::send_prepared_command`] so recovery
199    /// can reuse the exact request ID, inputs and start options.
200    #[allow(clippy::too_many_arguments)]
201    pub async fn prepare_signal_with_start<I: Serialize, S: Serialize>(
202        &self,
203        workflow_type: &str,
204        task_queue: &str,
205        workflow_id: &str,
206        signal_name: &str,
207        input: I,
208        signal_input: S,
209        options: SignalWithStartOptions,
210    ) -> Result<PreparedPayloadCommand> {
211        if !self.protection_enabled() {
212            return Err(ProtectionError::ProtectionRequired.into());
213        }
214        let start = AtomicStart::new(workflow_type, task_queue, &options)?;
215        let request_id = options
216            .request_id
217            .unwrap_or_else(Self::generate_signal_with_start_request_id);
218        validate_request_id(&request_id)?;
219        let path = atomic_signal_path(workflow_id, signal_name)?;
220        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
221        let signal_input = normalize_avro_arguments(AvroValue::from_serialize(&signal_input)?);
222        let mut command = PreparedPayloadCommand {
223            schema: SCHEMA.into(),
224            namespace: self.namespace.clone(),
225            workflow_id: workflow_id.into(),
226            run_id: None,
227            name: signal_name.into(),
228            request_id,
229            operation: Operation::SignalWithStart {
230                start,
231                signal_input: self.encode_client_payload(&signal_input, Boundary::SignalInput)?,
232            },
233            input: self.encode_client_payload(&input, Boundary::WorkflowInput)?,
234        };
235        self.require_signal_with_start().await?;
236        self.prepare_command_references(&mut command, &path).await?;
237        Ok(command)
238    }
239
240    async fn prepare_command_references(
241        &self,
242        command: &mut PreparedPayloadCommand,
243        path: &str,
244    ) -> Result<()> {
245        let mut body = command.body();
246        self.externalize_runtime_payloads(&mut body, path, RequestProtocol::ControlPlane)
247            .await?;
248        let fields = body
249            .as_object_mut()
250            .ok_or(ProtectionError::InvalidPreparedCommand)?;
251        command.input = fields
252            .remove("input")
253            .ok_or(ProtectionError::InvalidPreparedCommand)?;
254        if let Operation::SignalWithStart { signal_input, .. } = &mut command.operation {
255            *signal_input = fields
256                .remove("signal_input")
257                .ok_or(ProtectionError::InvalidPreparedCommand)?;
258        }
259        Ok(())
260    }
261
262    /// Submit or resend a persisted command without re-encrypting or replacing its input.
263    /// A client with retained read keys can resend a command without a writer key.
264    /// External objects are fetched through the same authenticated namespace
265    /// and verified before the saved reference is submitted.
266    pub async fn send_prepared_command(&self, command: &PreparedPayloadCommand) -> Result<Value> {
267        if !self.protection_enabled() {
268            return Err(ProtectionError::ProtectionRequired.into());
269        }
270        if command.schema != SCHEMA {
271            return Err(ProtectionError::InvalidPreparedCommand.into());
272        }
273        if command.namespace != self.namespace {
274            return Err(ProtectionError::AuthenticationFailed.into());
275        }
276        validate_request_id(&command.request_id)?;
277        let path = command.path()?;
278        self.verify_prepared_input(&command.input, command.operation.boundary())
279            .await?;
280        if let Operation::SignalWithStart { signal_input, .. } = &command.operation {
281            self.verify_prepared_input(signal_input, Boundary::SignalInput)
282                .await?;
283            self.require_signal_with_start().await?;
284        }
285        let receipt = self
286            .send_payload_command(
287                &path,
288                &command.body(),
289                &command.request_id,
290                JsonPayloads::PREPARED,
291            )
292            .await?;
293        self.assert_protected_response_namespace(receipt.get("namespace"))?;
294        if matches!(command.operation, Operation::Update { .. }) {
295            self.assert_protected_result_receipt(
296                &receipt,
297                receipt.get("update_status").and_then(Value::as_str) == Some("completed"),
298            )?;
299        }
300        Ok(receipt)
301    }
302
303    async fn verify_prepared_input(&self, input: &Value, boundary: Boundary) -> Result<()> {
304        let protection = self
305            .payload_protection
306            .as_ref()
307            .ok_or(ProtectionError::ProtectionRequired)?;
308        let context = ProtectionContext::new(&self.namespace, boundary)?;
309        let envelope = if let Some(reference) = Reference::parse(input)? {
310            if reference.size_bytes > self.max_external_payload_bytes {
311                return Err(Error::Codec(
312                    "external_payload_oversized: prepared payload exceeds the response byte limit"
313                        .into(),
314                ));
315            }
316            let blob = self
317                .fetch_runtime_payload(&reference, RequestProtocol::ControlPlane)
318                .await?;
319            crate::PayloadEnvelope {
320                codec: DEFAULT_CODEC.into(),
321                blob,
322            }
323        } else {
324            exact_inline(input)?
325        };
326        // A deserialized record can name an arbitrary object or contain a plain
327        // frame. Verify the same immutable bytes and binding before admission.
328        if !matches!(
329            protection.open_strict(&envelope, context)?,
330            AvroValue::Array(_)
331        ) {
332            return Err(ProtectionError::InvalidPreparedCommand.into());
333        }
334        Ok(())
335    }
336}