1use std::{fmt, sync::atomic::Ordering, time::Duration};
12
13use serde_json::Value;
14
15use crate::{
16 decode_wire_avro_value, decode_wire_value, path_segment, AvroValue, Client, Error,
17 RequestProtocol, Result, WorkflowHandle, DEFAULT_CODEC,
18};
19
20pub(crate) const UPDATE_OUTCOME_READS_CAPABILITY: &str = "update_outcome_reads";
22
23const WAIT_TRANSPORT_MARGIN: Duration = Duration::from_secs(30);
25
26#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
28#[non_exhaustive]
29pub enum UpdateWaitStage {
30 #[default]
32 Accepted,
33 Completed,
35}
36
37impl UpdateWaitStage {
38 pub fn as_str(self) -> &'static str {
40 match self {
41 Self::Accepted => "accepted",
42 Self::Completed => "completed",
43 }
44 }
45}
46
47#[derive(Clone, Debug, PartialEq)]
59#[non_exhaustive]
60pub struct UpdatePending {
61 pub workflow_id: String,
62 pub run_id: Option<String>,
63 pub update_name: Option<String>,
64 pub update_id: Option<String>,
65 pub request_id: Option<String>,
66 pub update_status: Option<String>,
68 pub wait_timed_out: bool,
70 pub receipt: Value,
71 from_outcome_read: bool,
72}
73
74impl UpdatePending {
75 fn from_receipt(workflow_id: &str, receipt: Value, from_outcome_read: bool) -> Self {
76 let string = |name: &str| {
77 receipt
78 .get(name)
79 .and_then(Value::as_str)
80 .filter(|value| !value.is_empty())
81 .map(str::to_string)
82 };
83 Self {
84 workflow_id: string("workflow_id").unwrap_or_else(|| workflow_id.to_string()),
85 run_id: string("run_id"),
86 update_name: string("update_name"),
87 update_id: string("update_id"),
88 request_id: string("request_id"),
89 update_status: string("update_status"),
90 wait_timed_out: receipt.get("wait_timed_out") == Some(&Value::Bool(true)),
91 receipt,
92 from_outcome_read,
93 }
94 }
95}
96
97impl fmt::Display for UpdatePending {
98 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99 let status = self.update_status.as_deref().unwrap_or("pending");
100 let update = match (&self.update_name, &self.update_id) {
101 (Some(name), Some(id)) => format!("{name} ({id})"),
102 (Some(name), None) => name.clone(),
103 (None, Some(id)) => id.clone(),
104 (None, None) => "update".to_string(),
105 };
106 write!(
107 f,
108 "update_still_pending: update {update} on workflow {} is still {status}; it has no result yet.",
109 self.workflow_id
110 )?;
111 match (&self.update_id, &self.request_id) {
112 (Some(id), _) if self.from_outcome_read => write!(
113 f,
114 " Call update_outcome() again with update id {id:?} to keep waiting. Reading never admits another update."
115 ),
116 (Some(id), Some(key)) => write!(
117 f,
118 " Read it again with update_outcome() and update id {id:?} on a Server that advertises update_outcome_reads, or call update_workflow() again with request_id {key:?}: the Server returns the retained update instead of admitting a second one."
119 ),
120 (Some(id), None) => write!(
121 f,
122 " Read it again with update_outcome() and update id {id:?} on a Server that advertises update_outcome_reads."
123 ),
124 (None, Some(key)) => write!(
125 f,
126 " Call update_workflow() again with request_id {key:?}: the Server returns the retained update instead of admitting a second one."
127 ),
128 (None, None) => Ok(()),
129 }
130 }
131}
132
133impl std::error::Error for UpdatePending {}
134
135pub(crate) fn update_receipt_is_pending(receipt: &Value) -> bool {
141 if receipt.get("result_envelope").is_some_and(Value::is_object) {
142 return false;
143 }
144 receipt.get("wait_timed_out") == Some(&Value::Bool(true))
145 || receipt
146 .get("update_status")
147 .and_then(Value::as_str)
148 .is_some_and(|status| !matches!(status, "completed" | "failed" | "rejected"))
149}
150
151pub(crate) fn reject_pending_update(
153 workflow_id: &str,
154 receipt: Value,
155 from_outcome_read: bool,
156) -> Result<Value> {
157 if update_receipt_is_pending(&receipt) {
158 return Err(Error::UpdateStillPending(UpdatePending::from_receipt(
159 workflow_id,
160 receipt,
161 from_outcome_read,
162 )));
163 }
164 Ok(receipt)
165}
166
167fn is_receipt_for(receipt: &Value, workflow_id: &str, update_id: &str) -> bool {
169 receipt.get("update_id").and_then(Value::as_str) == Some(update_id)
170 && receipt.get("update_status").is_some_and(Value::is_string)
171 && receipt
172 .get("workflow_id")
173 .and_then(Value::as_str)
174 .is_none_or(|echoed| echoed == workflow_id)
175}
176
177fn unrecognized(workflow_id: &str, update_id: &str, receipt: Value) -> Error {
178 Error::UnrecognizedUpdateOutcome {
179 workflow_id: workflow_id.to_string(),
180 update_id: update_id.to_string(),
181 receipt,
182 }
183}
184
185fn completed_update_avro_value(receipt: &Value) -> Result<AvroValue> {
186 let envelope = receipt
187 .get("result_envelope")
188 .filter(|envelope| !envelope.is_null())
189 .ok_or_else(|| {
190 Error::Codec(
191 "missing_payload_envelope: typed update result requires result_envelope"
192 .to_string(),
193 )
194 })?;
195 decode_wire_avro_value(envelope, DEFAULT_CODEC)
196}
197
198impl Client {
199 pub async fn update_outcome(
220 &self,
221 workflow_id: &str,
222 update_id: &str,
223 wait_timeout_seconds: Option<u64>,
224 ) -> Result<Value> {
225 let receipt = self
226 .completed_update_outcome(workflow_id, update_id, wait_timeout_seconds)
227 .await?;
228 match receipt
229 .get("result_envelope")
230 .filter(|envelope| !envelope.is_null())
231 {
232 Some(envelope) => decode_wire_value(envelope, DEFAULT_CODEC),
233 None => Ok(receipt.get("result").cloned().unwrap_or(Value::Null)),
234 }
235 }
236
237 pub async fn update_outcome_avro_value(
239 &self,
240 workflow_id: &str,
241 update_id: &str,
242 wait_timeout_seconds: Option<u64>,
243 ) -> Result<AvroValue> {
244 let receipt = self
245 .completed_update_outcome(workflow_id, update_id, wait_timeout_seconds)
246 .await?;
247 completed_update_avro_value(&receipt)
248 }
249
250 pub async fn update_outcome_receipt(
258 &self,
259 workflow_id: &str,
260 update_id: &str,
261 wait_for: UpdateWaitStage,
262 wait_timeout_seconds: Option<u64>,
263 ) -> Result<Value> {
264 let mut path = format!(
265 "/workflows/{}/updates/{}",
266 path_segment("workflow_id", workflow_id)?,
267 path_segment("update_id", update_id)?,
268 );
269 if update_id.trim().is_empty() {
270 return Err(Error::Codec(
271 "an update outcome read needs the update id".to_string(),
272 ));
273 }
274 self.require_update_outcome_reads().await?;
275
276 let mut query = Vec::new();
277 if wait_for == UpdateWaitStage::Completed {
278 query.push(format!("wait_for={}", wait_for.as_str()));
279 }
280 if let Some(seconds) = wait_timeout_seconds {
281 query.push(format!("wait_timeout_seconds={seconds}"));
282 }
283 if !query.is_empty() {
284 path.push('?');
285 path.push_str(&query.join("&"));
286 }
287 let timeout = wait_timeout_seconds
288 .map(|seconds| Duration::from_secs(seconds).saturating_add(WAIT_TRANSPORT_MARGIN))
289 .unwrap_or(Duration::ZERO)
290 .max(Duration::from_secs(60));
291 let receipt: Value = self
292 .request_json_with_timeout(
293 reqwest::Method::GET,
294 &path,
295 RequestProtocol::ControlPlane,
296 Option::<&Value>::None,
297 timeout,
298 )
299 .await?;
300 if !is_receipt_for(&receipt, workflow_id, update_id) {
301 return Err(unrecognized(workflow_id, update_id, receipt));
302 }
303 Ok(receipt)
304 }
305
306 async fn completed_update_outcome(
307 &self,
308 workflow_id: &str,
309 update_id: &str,
310 wait_timeout_seconds: Option<u64>,
311 ) -> Result<Value> {
312 let receipt = self
313 .update_outcome_receipt(
314 workflow_id,
315 update_id,
316 UpdateWaitStage::Completed,
317 wait_timeout_seconds,
318 )
319 .await?;
320 let receipt = reject_pending_update(workflow_id, receipt, true)?;
321 let completed = receipt.get("result_envelope").is_some_and(Value::is_object)
324 || receipt.get("update_status").and_then(Value::as_str) == Some("completed");
325 if !completed {
326 return Err(unrecognized(workflow_id, update_id, receipt));
327 }
328 Ok(receipt)
329 }
330
331 async fn require_update_outcome_reads(&self) -> Result<()> {
336 if self.update_outcome_reads_supported.load(Ordering::SeqCst) {
337 return Ok(());
338 }
339 let discovery = self.cluster_info().await?;
340 if discovery["capabilities"][UPDATE_OUTCOME_READS_CAPABILITY] != Value::Bool(true) {
341 return Err(Error::UpdateOutcomeReadsUnavailable);
342 }
343 self.update_outcome_reads_supported
344 .store(true, Ordering::SeqCst);
345 Ok(())
346 }
347}
348
349impl WorkflowHandle {
350 pub async fn update_outcome(
353 &self,
354 update_id: &str,
355 wait_timeout_seconds: Option<u64>,
356 ) -> Result<Value> {
357 self.client
358 .update_outcome(&self.workflow_id, update_id, wait_timeout_seconds)
359 .await
360 }
361
362 pub async fn update_outcome_avro_value(
365 &self,
366 update_id: &str,
367 wait_timeout_seconds: Option<u64>,
368 ) -> Result<AvroValue> {
369 self.client
370 .update_outcome_avro_value(&self.workflow_id, update_id, wait_timeout_seconds)
371 .await
372 }
373}
374
375impl Client {
376 pub(crate) fn submitted_update_value(workflow_id: &str, receipt: Value) -> Result<Value> {
378 let receipt = reject_pending_update(workflow_id, receipt, false)?;
379 if let Some(envelope) = receipt
380 .get("result_envelope")
381 .filter(|envelope| !envelope.is_null())
382 {
383 return decode_wire_value(envelope, DEFAULT_CODEC);
384 }
385 Ok(receipt.get("result").cloned().unwrap_or(receipt))
386 }
387
388 pub(crate) fn submitted_update_avro_value(
390 workflow_id: &str,
391 receipt: Value,
392 ) -> Result<AvroValue> {
393 let receipt = reject_pending_update(workflow_id, receipt, false)?;
394 completed_update_avro_value(&receipt)
395 }
396}
397
398#[cfg(test)]
399pub(crate) mod tests;