1use 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
20pub(crate) const SIGNAL_WITH_START_CAPABILITY: &str = "signal_with_start";
23
24#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
26#[serde(rename_all = "kebab-case")]
27#[non_exhaustive]
28pub enum OpenRunPolicy {
29 #[default]
32 UseExisting,
33 Fail,
35}
36
37impl OpenRunPolicy {
38 pub fn as_str(self) -> &'static str {
40 match self {
41 Self::UseExisting => "use-existing",
42 Self::Fail => "fail",
43 }
44 }
45}
46
47#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
49#[serde(rename_all = "snake_case")]
50#[non_exhaustive]
51pub enum ClosedRunPolicy {
52 #[default]
55 Reject,
56 StartNewRun,
59}
60
61impl ClosedRunPolicy {
62 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#[derive(Clone, Debug, Default, PartialEq, Eq)]
73#[non_exhaustive]
74pub struct SignalWithStartOptions {
75 pub start: WorkflowStartOptions,
77 pub open_run_policy: OpenRunPolicy,
78 pub closed_run_policy: ClosedRunPolicy,
79 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 #[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 pub fn generate_signal_with_start_request_id() -> String {
266 generated_request_id("signal-with-start")
267 }
268
269 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 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;