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::Serialize;
12use serde_json::{json, Value};
13
14use crate::{
15 encode_typed_envelope, generated_request_id, normalize_avro_arguments, path_segment,
16 validate_request_id, validate_user_signal_name, with_request_id, AvroValue, Client, Error,
17 RequestProtocol, Result, WorkflowStartOptions, DEFAULT_CODEC,
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)]
26#[non_exhaustive]
27pub enum OpenRunPolicy {
28 /// Signal the open run (`use-existing`, the default). Its input,
29 /// deadlines and history are unchanged.
30 #[default]
31 UseExisting,
32 /// Refuse an open run with `instance_already_started` (`fail`).
33 Fail,
34}
35
36impl OpenRunPolicy {
37 /// The `duplicate_policy` value sent to the Server.
38 pub fn as_str(self) -> &'static str {
39 match self {
40 Self::UseExisting => "use-existing",
41 Self::Fail => "fail",
42 }
43 }
44}
45
46/// What a closed current run means for the intake.
47#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
48#[non_exhaustive]
49pub enum ClosedRunPolicy {
50 /// Refuse with `run_not_active` (the default). A closed run is never
51 /// reopened.
52 #[default]
53 Reject,
54 /// Start a fresh run after the closed one with this request's input and
55 /// timeouts. The closed run keeps its outcome and history.
56 StartNewRun,
57}
58
59impl ClosedRunPolicy {
60 /// The `closed_run_policy` value sent to the Server.
61 pub fn as_str(self) -> &'static str {
62 match self {
63 Self::Reject => "reject",
64 Self::StartNewRun => "start_new_run",
65 }
66 }
67}
68
69/// Options for [`Client::signal_with_start`].
70#[derive(Clone, Debug, Default, PartialEq, Eq)]
71#[non_exhaustive]
72pub struct SignalWithStartOptions {
73 /// Deadlines for a run the intake starts. A reused open run keeps its own.
74 pub start: WorkflowStartOptions,
75 pub open_run_policy: OpenRunPolicy,
76 pub closed_run_policy: ClosedRunPolicy,
77 /// The signal's caller command key (1 to 255 Unicode characters). When
78 /// `None`, one `sdk-rust-signal-with-start-<uuid>` key is generated per call.
79 pub request_id: Option<String>,
80 pub business_key: Option<String>,
81}
82
83impl SignalWithStartOptions {
84 pub fn new() -> Self {
85 Self::default()
86 }
87
88 pub fn start(mut self, start: WorkflowStartOptions) -> Self {
89 self.start = start;
90 self
91 }
92
93 pub fn open_run_policy(mut self, policy: OpenRunPolicy) -> Self {
94 self.open_run_policy = policy;
95 self
96 }
97
98 pub fn closed_run_policy(mut self, policy: ClosedRunPolicy) -> Self {
99 self.closed_run_policy = policy;
100 self
101 }
102
103 pub fn request_id(mut self, request_id: impl Into<String>) -> Self {
104 self.request_id = Some(request_id.into());
105 self
106 }
107
108 pub fn business_key(mut self, business_key: impl Into<String>) -> Self {
109 self.business_key = Some(business_key.into());
110 self
111 }
112}
113
114impl Client {
115 /// Start the workflow or reuse its open run, and signal it, in one Server
116 /// transaction (native Server `capabilities.signal_with_start`).
117 ///
118 /// - No run: a new run starts with `input` and `options.start`; the
119 /// receipt's `start_outcome` is `started_new`.
120 /// - An open run, including the newest run after continue-as-new: the
121 /// signal joins it and `start_outcome` is `returned_existing_active`.
122 /// [`OpenRunPolicy::Fail`] refuses it with `instance_already_started`.
123 /// - A closed run: refused with `run_not_active` unless
124 /// [`ClosedRunPolicy::StartNewRun`], which starts a fresh run after it
125 /// (`closed_run_id` names the closed run).
126 ///
127 /// `workflow_type` must be the instance's type and `task_queue` the open
128 /// run's queue. The receipt carries the signal's `command_id`,
129 /// `command_sequence`, `run_id` and `outcome`, the start's
130 /// `start_command_id`, `start_outcome` and `start_command_status`,
131 /// `intake_group_id` and `request_id`. A retry with the same key, signal
132 /// name, arguments and workflow type returns the original receipt with
133 /// `retained: true`, even after the run closed or continued, and starts
134 /// nothing.
135 ///
136 /// Before sending, the client checks discovery and returns
137 /// [`Error::SignalWithStartUnavailable`] when the Server does not
138 /// advertise the capability. Every Server refusal is an [`Error::Http`]
139 /// whose body `reason` names the cause (for example `run_not_active`,
140 /// `workflow_type_conflict`, `task_queue_conflict`, `unknown_signal`); see
141 /// [`Error::signal_with_start_refusal`]. Nothing was written for any of
142 /// them. An admitted signal is admitted once; effects it triggers still
143 /// need their own idempotency.
144 #[allow(clippy::too_many_arguments)]
145 pub async fn signal_with_start<I: Serialize, S: Serialize>(
146 &self,
147 workflow_type: &str,
148 task_queue: &str,
149 workflow_id: &str,
150 signal_name: &str,
151 input: I,
152 signal_input: S,
153 options: SignalWithStartOptions,
154 ) -> Result<Value> {
155 options.start.validate()?;
156 validate_user_signal_name(signal_name)?;
157 let request_id = match &options.request_id {
158 Some(request_id) => request_id.clone(),
159 None => Self::generate_signal_with_start_request_id(),
160 };
161 validate_request_id(&request_id)?;
162 let path = format!(
163 "/workflows/{}/signal-with-start/{}",
164 path_segment("workflow_id", workflow_id)?,
165 path_segment("signal_name", signal_name)?,
166 );
167 let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
168 let signal_input = normalize_avro_arguments(AvroValue::from_serialize(&signal_input)?);
169 let mut body = json!({
170 "workflow_type": workflow_type,
171 "task_queue": task_queue,
172 "input": encode_typed_envelope(&input, DEFAULT_CODEC)?,
173 "signal_input": encode_typed_envelope(&signal_input, DEFAULT_CODEC)?,
174 "execution_timeout_seconds": options.start.execution_timeout_seconds,
175 "run_timeout_seconds": options.start.run_timeout_seconds,
176 "duplicate_policy": options.open_run_policy.as_str(),
177 "closed_run_policy": options.closed_run_policy.as_str(),
178 "request_id": request_id,
179 });
180 if let Some(business_key) = &options.business_key {
181 body["business_key"] = json!(business_key);
182 }
183 self.require_signal_with_start().await?;
184 let body = self.with_observability_context(body);
185 let receipt = self
186 .request_json(
187 reqwest::Method::POST,
188 &path,
189 RequestProtocol::ControlPlane,
190 Some(&body),
191 )
192 .await
193 .map_err(|error| error.with_sent_request_id(&request_id))?;
194 Ok(with_request_id(receipt, &request_id))
195 }
196
197 /// A fresh caller command key for one logical signal-with-start
198 /// (`sdk-rust-signal-with-start-<uuid>`). Obtain it up front and pass it
199 /// in [`SignalWithStartOptions::request_id`] so a transport failure does
200 /// not lose the key needed for a safe retry.
201 pub fn generate_signal_with_start_request_id() -> String {
202 generated_request_id("signal-with-start")
203 }
204
205 /// Refuse a Server that does not advertise `signal_with_start`. Discovery
206 /// runs until a Server advertises it; after that the client remembers it.
207 async fn require_signal_with_start(&self) -> Result<()> {
208 if self.signal_with_start_supported.load(Ordering::SeqCst) {
209 return Ok(());
210 }
211 let discovery = self.cluster_info().await?;
212 if discovery["capabilities"][SIGNAL_WITH_START_CAPABILITY] != Value::Bool(true) {
213 return Err(Error::SignalWithStartUnavailable);
214 }
215 self.signal_with_start_supported
216 .store(true, Ordering::SeqCst);
217 Ok(())
218 }
219}
220
221impl Error {
222 /// The Server's refusal reason when a signal-with-start intake was
223 /// refused, such as `run_not_active`, `instance_already_started`,
224 /// `workflow_type_conflict`, `task_queue_conflict`,
225 /// `workflow_id_reserved_in_namespace`, `unknown_signal`,
226 /// `invalid_signal_arguments` or `request_id_conflict`. Nothing was
227 /// started, signalled or reserved. `None` for any other error.
228 pub fn signal_with_start_refusal(&self) -> Option<String> {
229 let body = self.refusal_body()?;
230 if body["control_plane"]["operation"] != "signal_with_start" {
231 return None;
232 }
233 body.get("reason")
234 .and_then(Value::as_str)
235 .filter(|reason| !reason.is_empty())
236 .map(str::to_string)
237 }
238}
239
240#[cfg(test)]
241mod tests;