1use std::{fmt, sync::atomic::Ordering, time::Duration};
12
13use serde_json::Value;
14
15use crate::{
16 path_segment, AvroValue, Boundary, Client, Error, RequestProtocol, Result, WorkflowHandle,
17};
18
19pub(crate) const UPDATE_OUTCOME_READS_CAPABILITY: &str = "update_outcome_reads";
21
22const WAIT_TRANSPORT_MARGIN: Duration = Duration::from_secs(30);
24
25#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
27#[non_exhaustive]
28pub enum UpdateWaitStage {
29 #[default]
31 Accepted,
32 Completed,
34}
35
36impl UpdateWaitStage {
37 pub fn as_str(self) -> &'static str {
39 match self {
40 Self::Accepted => "accepted",
41 Self::Completed => "completed",
42 }
43 }
44}
45
46#[derive(Clone, Debug, PartialEq)]
58#[non_exhaustive]
59pub struct UpdatePending {
60 pub workflow_id: String,
61 pub run_id: Option<String>,
62 pub update_name: Option<String>,
63 pub update_id: Option<String>,
64 pub request_id: Option<String>,
65 pub update_status: Option<String>,
67 pub wait_timed_out: bool,
69 pub receipt: Value,
70 from_outcome_read: bool,
71}
72
73impl UpdatePending {
74 fn from_receipt(workflow_id: &str, receipt: Value, from_outcome_read: bool) -> Self {
75 let string = |name: &str| {
76 receipt
77 .get(name)
78 .and_then(Value::as_str)
79 .filter(|value| !value.is_empty())
80 .map(str::to_string)
81 };
82 Self {
83 workflow_id: string("workflow_id").unwrap_or_else(|| workflow_id.to_string()),
84 run_id: string("run_id"),
85 update_name: string("update_name"),
86 update_id: string("update_id"),
87 request_id: string("request_id"),
88 update_status: string("update_status"),
89 wait_timed_out: receipt.get("wait_timed_out") == Some(&Value::Bool(true)),
90 receipt,
91 from_outcome_read,
92 }
93 }
94}
95
96impl fmt::Display for UpdatePending {
97 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98 let status = self.update_status.as_deref().unwrap_or("pending");
99 let update = match (&self.update_name, &self.update_id) {
100 (Some(name), Some(id)) => format!("{name} ({id})"),
101 (Some(name), None) => name.clone(),
102 (None, Some(id)) => id.clone(),
103 (None, None) => "update".to_string(),
104 };
105 write!(
106 f,
107 "update_still_pending: update {update} on workflow {} is still {status}; it has no result yet.",
108 self.workflow_id
109 )?;
110 match (&self.update_id, &self.request_id) {
111 (Some(id), _) if self.from_outcome_read => write!(
112 f,
113 " Call update_outcome() again with update id {id:?} to keep waiting. Reading never admits another update."
114 ),
115 (Some(id), Some(key)) => write!(
116 f,
117 " 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."
118 ),
119 (Some(id), None) => write!(
120 f,
121 " Read it again with update_outcome() and update id {id:?} on a Server that advertises update_outcome_reads."
122 ),
123 (None, Some(key)) => write!(
124 f,
125 " Call update_workflow() again with request_id {key:?}: the Server returns the retained update instead of admitting a second one."
126 ),
127 (None, None) => Ok(()),
128 }
129 }
130}
131
132impl std::error::Error for UpdatePending {}
133
134pub(crate) fn update_receipt_is_pending(receipt: &Value) -> bool {
140 if receipt.get("result_envelope").is_some_and(Value::is_object) {
141 return false;
142 }
143 receipt.get("wait_timed_out") == Some(&Value::Bool(true))
144 || receipt
145 .get("update_status")
146 .and_then(Value::as_str)
147 .is_some_and(|status| !matches!(status, "completed" | "failed" | "rejected"))
148}
149
150pub(crate) fn reject_pending_update(
152 workflow_id: &str,
153 receipt: Value,
154 from_outcome_read: bool,
155) -> Result<Value> {
156 if update_receipt_is_pending(&receipt) {
157 return Err(Error::UpdateStillPending(UpdatePending::from_receipt(
158 workflow_id,
159 receipt,
160 from_outcome_read,
161 )));
162 }
163 Ok(receipt)
164}
165
166fn is_receipt_for(receipt: &Value, workflow_id: &str, update_id: &str) -> bool {
168 receipt.get("update_id").and_then(Value::as_str) == Some(update_id)
169 && receipt.get("update_status").is_some_and(Value::is_string)
170 && receipt
171 .get("workflow_id")
172 .and_then(Value::as_str)
173 .is_none_or(|echoed| echoed == workflow_id)
174}
175
176fn unrecognized(workflow_id: &str, update_id: &str, receipt: Value) -> Error {
177 Error::UnrecognizedUpdateOutcome {
178 workflow_id: workflow_id.to_string(),
179 update_id: update_id.to_string(),
180 receipt,
181 }
182}
183
184fn completed_update_avro_value(client: &Client, receipt: &Value) -> Result<AvroValue> {
185 client.assert_protected_result_receipt(receipt, true)?;
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 client.decode_client_payload(envelope, Boundary::UpdateResult)
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) => self.decode_client_json(envelope, Boundary::UpdateResult),
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(self, &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 self.assert_protected_result_receipt(
301 &receipt,
302 receipt.get("update_status").and_then(Value::as_str) == Some("completed"),
303 )?;
304 if !is_receipt_for(&receipt, workflow_id, update_id) {
305 return Err(unrecognized(workflow_id, update_id, receipt));
306 }
307 Ok(receipt)
308 }
309
310 async fn completed_update_outcome(
311 &self,
312 workflow_id: &str,
313 update_id: &str,
314 wait_timeout_seconds: Option<u64>,
315 ) -> Result<Value> {
316 let receipt = self
317 .update_outcome_receipt(
318 workflow_id,
319 update_id,
320 UpdateWaitStage::Completed,
321 wait_timeout_seconds,
322 )
323 .await?;
324 let receipt = reject_pending_update(workflow_id, receipt, true)?;
325 let completed = receipt.get("result_envelope").is_some_and(Value::is_object)
328 || receipt.get("update_status").and_then(Value::as_str) == Some("completed");
329 if !completed {
330 return Err(unrecognized(workflow_id, update_id, receipt));
331 }
332 Ok(receipt)
333 }
334
335 async fn require_update_outcome_reads(&self) -> Result<()> {
340 if self.update_outcome_reads_supported.load(Ordering::SeqCst) {
341 return Ok(());
342 }
343 let discovery = self.cluster_info().await?;
344 if discovery["capabilities"][UPDATE_OUTCOME_READS_CAPABILITY] != Value::Bool(true) {
345 return Err(Error::UpdateOutcomeReadsUnavailable);
346 }
347 self.update_outcome_reads_supported
348 .store(true, Ordering::SeqCst);
349 Ok(())
350 }
351}
352
353impl WorkflowHandle {
354 pub async fn update_outcome(
357 &self,
358 update_id: &str,
359 wait_timeout_seconds: Option<u64>,
360 ) -> Result<Value> {
361 self.client
362 .update_outcome(&self.workflow_id, update_id, wait_timeout_seconds)
363 .await
364 }
365
366 pub async fn update_outcome_avro_value(
369 &self,
370 update_id: &str,
371 wait_timeout_seconds: Option<u64>,
372 ) -> Result<AvroValue> {
373 self.client
374 .update_outcome_avro_value(&self.workflow_id, update_id, wait_timeout_seconds)
375 .await
376 }
377}
378
379impl Client {
380 pub(crate) fn submitted_update_value(
382 &self,
383 workflow_id: &str,
384 receipt: Value,
385 ) -> Result<Value> {
386 let receipt = reject_pending_update(workflow_id, receipt, false)?;
387 self.assert_protected_result_receipt(&receipt, true)?;
388 if let Some(envelope) = receipt
389 .get("result_envelope")
390 .filter(|envelope| !envelope.is_null())
391 {
392 return self.decode_client_json(envelope, Boundary::UpdateResult);
393 }
394 Ok(receipt.get("result").cloned().unwrap_or(receipt))
395 }
396
397 pub(crate) fn submitted_update_avro_value(
399 &self,
400 workflow_id: &str,
401 receipt: Value,
402 ) -> Result<AvroValue> {
403 let receipt = reject_pending_update(workflow_id, receipt, false)?;
404 completed_update_avro_value(self, &receipt)
405 }
406}
407
408#[cfg(test)]
409pub(crate) mod tests;