Skip to main content

durable_workflow/
signal_with_start.rs

1//! Atomic signal-with-start intake (durable-workflow/.github#222, server#1133).
2//!
3//! One request starts the workflow, or reuses its open run, and records one
4//! signal on that run in a single Server transaction. Unlike
5//! [`Client::start_workflow`] followed by [`Client::signal_workflow`], the run
6//! cannot close in between. Every refusal is atomic: nothing is started,
7//! signalled or reserved.
8
9use std::sync::atomic::Ordering;
10
11use serde::{Deserialize, Serialize};
12use serde_json::{json, Value};
13
14use crate::{
15    generated_request_id, normalize_avro_arguments, path_segment, validate_request_id,
16    validate_user_signal_name, with_request_id, AvroValue, Boundary, Client, Error,
17    RequestProtocol, Result, WorkflowStartOptions,
18};
19
20/// The cluster capability that advertises
21/// `POST /workflows/{workflow_id}/signal-with-start/{signal_name}`.
22pub(crate) const SIGNAL_WITH_START_CAPABILITY: &str = "signal_with_start";
23
24/// What an open run means for the intake (the start's `duplicate_policy`).
25#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
26#[serde(rename_all = "kebab-case")]
27#[non_exhaustive]
28pub enum OpenRunPolicy {
29    /// Signal the open run (`use-existing`, the default). Its input,
30    /// deadlines and history are unchanged.
31    #[default]
32    UseExisting,
33    /// Refuse an open run with `instance_already_started` (`fail`).
34    Fail,
35}
36
37impl OpenRunPolicy {
38    /// The `duplicate_policy` value sent to the Server.
39    pub fn as_str(self) -> &'static str {
40        match self {
41            Self::UseExisting => "use-existing",
42            Self::Fail => "fail",
43        }
44    }
45}
46
47/// What a closed current run means for the intake.
48#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
49#[serde(rename_all = "snake_case")]
50#[non_exhaustive]
51pub enum ClosedRunPolicy {
52    /// Refuse with `run_not_active` (the default). A closed run is never
53    /// reopened.
54    #[default]
55    Reject,
56    /// Start a fresh run after the closed one with this request's input and
57    /// timeouts. The closed run keeps its outcome and history.
58    StartNewRun,
59}
60
61impl ClosedRunPolicy {
62    /// The `closed_run_policy` value sent to the Server.
63    pub fn as_str(self) -> &'static str {
64        match self {
65            Self::Reject => "reject",
66            Self::StartNewRun => "start_new_run",
67        }
68    }
69}
70
71/// Options for [`Client::signal_with_start`].
72#[derive(Clone, Debug, Default, PartialEq, Eq)]
73#[non_exhaustive]
74pub struct SignalWithStartOptions {
75    /// Deadlines for a run the intake starts. A reused open run keeps its own.
76    pub start: WorkflowStartOptions,
77    pub open_run_policy: OpenRunPolicy,
78    pub closed_run_policy: ClosedRunPolicy,
79    /// The signal's caller command key (1 to 255 Unicode characters). When
80    /// `None`, one `sdk-rust-signal-with-start-<uuid>` key is generated per call.
81    pub request_id: Option<String>,
82    pub business_key: Option<String>,
83}
84
85impl SignalWithStartOptions {
86    pub fn new() -> Self {
87        Self::default()
88    }
89
90    pub fn start(mut self, start: WorkflowStartOptions) -> Self {
91        self.start = start;
92        self
93    }
94
95    pub fn open_run_policy(mut self, policy: OpenRunPolicy) -> Self {
96        self.open_run_policy = policy;
97        self
98    }
99
100    pub fn closed_run_policy(mut self, policy: ClosedRunPolicy) -> Self {
101        self.closed_run_policy = policy;
102        self
103    }
104
105    pub fn request_id(mut self, request_id: impl Into<String>) -> Self {
106        self.request_id = Some(request_id.into());
107        self
108    }
109
110    pub fn business_key(mut self, business_key: impl Into<String>) -> Self {
111        self.business_key = Some(business_key.into());
112        self
113    }
114}
115
116#[derive(Clone, Debug, Serialize, Deserialize)]
117#[serde(deny_unknown_fields)]
118pub(super) struct AtomicStart {
119    workflow_type: String,
120    task_queue: String,
121    execution_timeout_seconds: u64,
122    run_timeout_seconds: u64,
123    duplicate_policy: OpenRunPolicy,
124    closed_run_policy: ClosedRunPolicy,
125    #[serde(skip_serializing_if = "Option::is_none")]
126    business_key: Option<String>,
127}
128
129impl AtomicStart {
130    pub(super) fn new(
131        workflow_type: &str,
132        task_queue: &str,
133        options: &SignalWithStartOptions,
134    ) -> Result<Self> {
135        options.start.validate()?;
136        Ok(Self {
137            workflow_type: workflow_type.into(),
138            task_queue: task_queue.into(),
139            execution_timeout_seconds: options.start.execution_timeout_seconds,
140            run_timeout_seconds: options.start.run_timeout_seconds,
141            duplicate_policy: options.open_run_policy,
142            closed_run_policy: options.closed_run_policy,
143            business_key: options.business_key.clone(),
144        })
145    }
146
147    #[cfg(feature = "payload-protection")]
148    pub(super) fn validate(&self) -> Result<()> {
149        WorkflowStartOptions {
150            execution_timeout_seconds: self.execution_timeout_seconds,
151            run_timeout_seconds: self.run_timeout_seconds,
152        }
153        .validate()
154    }
155
156    pub(super) fn body(&self, input: &Value, signal_input: &Value, request_id: &str) -> Value {
157        let mut fields = json!(self);
158        fields["input"] = input.clone();
159        fields["signal_input"] = signal_input.clone();
160        fields["request_id"] = json!(request_id);
161        fields
162    }
163}
164
165pub(super) fn atomic_signal_path(workflow_id: &str, signal_name: &str) -> Result<String> {
166    validate_user_signal_name(signal_name)?;
167    Ok(format!(
168        "/workflows/{}/signal-with-start/{}",
169        path_segment("workflow_id", workflow_id)?,
170        path_segment("signal_name", signal_name)?,
171    ))
172}
173
174impl Client {
175    /// Start the workflow or reuse its open run, and signal it, in one Server
176    /// transaction (native Server `capabilities.signal_with_start`).
177    ///
178    /// - No run: a new run starts with `input` and `options.start`; the
179    ///   receipt's `start_outcome` is `started_new`.
180    /// - An open run, including the newest run after continue-as-new: the
181    ///   signal joins it and `start_outcome` is `returned_existing_active`.
182    ///   [`OpenRunPolicy::Fail`] refuses it with `instance_already_started`.
183    /// - A closed run: refused with `run_not_active` unless
184    ///   [`ClosedRunPolicy::StartNewRun`], which starts a fresh run after it
185    ///   (`closed_run_id` names the closed run).
186    ///
187    /// `workflow_type` must be the instance's type and `task_queue` the open
188    /// run's queue. The receipt carries the signal's `command_id`,
189    /// `command_sequence`, `run_id` and `outcome`, the start's
190    /// `start_command_id`, `start_outcome` and `start_command_status`,
191    /// `intake_group_id` and `request_id`. A retry with the same key, signal
192    /// name, arguments and workflow type returns the original receipt with
193    /// `retained: true`, even after the run closed or continued, and starts
194    /// nothing.
195    /// With payload protection, persist the output of `prepare_signal_with_start`
196    /// and resend it with `send_prepared_command` to preserve both ciphertexts
197    /// when recovering a request in another process.
198    ///
199    /// Before sending, the client checks discovery and returns
200    /// [`Error::SignalWithStartUnavailable`] when the Server does not
201    /// advertise the capability. Every Server refusal is an [`Error::Http`]
202    /// whose body `reason` names the cause (for example `run_not_active`,
203    /// `workflow_type_conflict`, `task_queue_conflict`, `unknown_signal`); see
204    /// [`Error::signal_with_start_refusal`]. Nothing was written for any of
205    /// them. An admitted signal is admitted once; effects it triggers still
206    /// need their own idempotency.
207    #[allow(clippy::too_many_arguments)]
208    pub async fn signal_with_start<I: Serialize, S: Serialize>(
209        &self,
210        workflow_type: &str,
211        task_queue: &str,
212        workflow_id: &str,
213        signal_name: &str,
214        input: I,
215        signal_input: S,
216        options: SignalWithStartOptions,
217    ) -> Result<Value> {
218        #[cfg(feature = "payload-protection")]
219        if self.protection_enabled() {
220            let command = self
221                .prepare_signal_with_start(
222                    workflow_type,
223                    task_queue,
224                    workflow_id,
225                    signal_name,
226                    input,
227                    signal_input,
228                    options,
229                )
230                .await?;
231            return self.send_prepared_command(&command).await;
232        }
233        let start = AtomicStart::new(workflow_type, task_queue, &options)?;
234        let request_id = match &options.request_id {
235            Some(request_id) => request_id.clone(),
236            None => Self::generate_signal_with_start_request_id(),
237        };
238        validate_request_id(&request_id)?;
239        let path = atomic_signal_path(workflow_id, signal_name)?;
240        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
241        let signal_input = normalize_avro_arguments(AvroValue::from_serialize(&signal_input)?);
242        let body = start.body(
243            &self.encode_client_payload(&input, Boundary::WorkflowInput)?,
244            &self.encode_client_payload(&signal_input, Boundary::SignalInput)?,
245            &request_id,
246        );
247        self.require_signal_with_start().await?;
248        let body = self.with_observability_context(body);
249        let receipt = self
250            .request_json(
251                reqwest::Method::POST,
252                &path,
253                RequestProtocol::ControlPlane,
254                Some(&body),
255            )
256            .await
257            .map_err(|error| error.with_sent_request_id(&request_id))?;
258        Ok(with_request_id(receipt, &request_id))
259    }
260
261    /// A fresh caller command key for one logical signal-with-start
262    /// (`sdk-rust-signal-with-start-<uuid>`). Obtain it up front and pass it
263    /// in [`SignalWithStartOptions::request_id`] so a transport failure does
264    /// not lose the key needed for a safe retry.
265    pub fn generate_signal_with_start_request_id() -> String {
266        generated_request_id("signal-with-start")
267    }
268
269    /// Refuse a Server that does not advertise `signal_with_start`. Discovery
270    /// runs until a Server advertises it; after that the client remembers it.
271    pub(super) async fn require_signal_with_start(&self) -> Result<()> {
272        if self.signal_with_start_supported.load(Ordering::SeqCst) {
273            return Ok(());
274        }
275        let discovery = self.cluster_info().await?;
276        if discovery["capabilities"][SIGNAL_WITH_START_CAPABILITY] != Value::Bool(true) {
277            return Err(Error::SignalWithStartUnavailable);
278        }
279        self.signal_with_start_supported
280            .store(true, Ordering::SeqCst);
281        Ok(())
282    }
283}
284
285impl Error {
286    /// The Server's refusal reason when a signal-with-start intake was
287    /// refused, such as `run_not_active`, `instance_already_started`,
288    /// `workflow_type_conflict`, `task_queue_conflict`,
289    /// `workflow_id_reserved_in_namespace`, `unknown_signal`,
290    /// `invalid_signal_arguments` or `request_id_conflict`. Nothing was
291    /// started, signalled or reserved. `None` for any other error.
292    pub fn signal_with_start_refusal(&self) -> Option<String> {
293        let body = self.refusal_body()?;
294        if body["control_plane"]["operation"] != "signal_with_start" {
295            return None;
296        }
297        body.get("reason")
298            .and_then(Value::as_str)
299            .filter(|reason| !reason.is_empty())
300            .map(str::to_string)
301    }
302}
303
304#[cfg(test)]
305mod tests;