Skip to content
Durable Workflowrust

durable_workflow/
update_outcome.rs

1//! Pending update outcomes and reading an accepted update's outcome later
2//! by its update id (durable-workflow/.github#212, server#1131).
3//!
4//! A Server that ends a completion wait before the update handler finishes
5//! answers HTTP 202 with no result. That is a pending update, not a handler
6//! that returned null, so the client raises [`Error::UpdateStillPending`]
7//! instead of returning `Null`. On a Server that advertises
8//! `capabilities.update_outcome_reads`, [`Client::update_outcome`] reads the
9//! same update again by its id without submitting it again.
10
11use 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
20/// The cluster capability that advertises `GET /workflows/{id}/updates/{update_id}`.
21pub(crate) const UPDATE_OUTCOME_READS_CAPABILITY: &str = "update_outcome_reads";
22
23/// Extra transport time allowed beyond a requested completion wait.
24const WAIT_TRANSPORT_MARGIN: Duration = Duration::from_secs(30);
25
26/// How long an update outcome read waits before the Server answers.
27#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
28#[non_exhaustive]
29pub enum UpdateWaitStage {
30    /// Answer at once with the update's current receipt (the Server default).
31    #[default]
32    Accepted,
33    /// Wait for the update's outcome, up to the wait timeout.
34    Completed,
35}
36
37impl UpdateWaitStage {
38    /// The `wait_for` value sent to the Server.
39    pub fn as_str(self) -> &'static str {
40        match self {
41            Self::Accepted => "accepted",
42            Self::Completed => "completed",
43        }
44    }
45}
46
47/// An update the Server accepted that had not completed when the wait ended.
48///
49/// It has no result yet: this is never a handler that returned null. Read it
50/// again by [`update_id`](Self::update_id) with [`Client::update_outcome`] on a
51/// Server that advertises `update_outcome_reads` (native 3.6.0 and later). On
52/// an older Server, call [`Client::update_workflow`] again with the same
53/// [`request_id`](Self::request_id): the Server returns the retained update
54/// instead of admitting a second one.
55///
56/// `run_id` names the run that owns the update now, which can be a
57/// continue-as-new successor. `receipt` is the Server's full answer.
58#[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    /// The Server's `update_status`, normally `accepted`.
67    pub update_status: Option<String>,
68    /// Whether the Server's completion wait ran out.
69    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
135/// Whether a completion-wait receipt describes an update that has not finished.
136///
137/// A receipt with a result envelope is finished (an encoded null is a real
138/// null result). Otherwise a timed-out wait, or any status other than
139/// `completed`, `failed` or `rejected`, is pending.
140pub(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
151/// Raise [`Error::UpdateStillPending`] for a pending completion-wait receipt.
152pub(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
167/// Whether a successful answer is the Server's receipt for the update that was read.
168fn 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    /// Read an accepted update's outcome later by its update id, without
200    /// submitting it again.
201    ///
202    /// This waits for the outcome, like [`Client::update_workflow`], for up to
203    /// `wait_timeout_seconds` (the Server's update wait default when `None`).
204    /// It returns the decoded result of a completed update, including `Null`
205    /// when the handler returned null. While the update is still running it
206    /// returns [`Error::UpdateStillPending`]: call it again with the same
207    /// update id to keep waiting.
208    ///
209    /// A failed update is [`Error::Http`] with status 422 and the failure
210    /// receipt, and a rejected update keeps its original rejection status. An
211    /// unknown or pruned update id is 404 `update_not_found`
212    /// ([`Error::is_update_not_found`]), which does not prove the update was
213    /// never admitted.
214    ///
215    /// Needs a Server that advertises `capabilities.update_outcome_reads`
216    /// (native 3.6.0 and later). Any other Server is refused with
217    /// [`Error::UpdateOutcomeReadsUnavailable`] before anything is read: the
218    /// SDK never resubmits an update as a substitute for reading it.
219    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    /// [`Client::update_outcome`] that retains a bytes-capable Avro result.
238    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    /// Read an accepted update's Server receipt by update id. It writes nothing.
251    ///
252    /// [`UpdateWaitStage::Accepted`] answers at once; a still-running update
253    /// comes back as a receipt with `update_status: "accepted"`, never as an
254    /// error. [`UpdateWaitStage::Completed`] waits up to
255    /// `wait_timeout_seconds` first. Failures, rejections, `update_not_found`
256    /// and the capability check behave as in [`Client::update_outcome`].
257    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        // Only a completed receipt carries an outcome; never read one into
322        // any other successful answer.
323        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    /// Refuse a Server that does not advertise `update_outcome_reads`.
332    ///
333    /// Discovery runs until a Server advertises the capability; after that the
334    /// client remembers it.
335    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    /// Read one of this workflow's accepted updates by update id; see
351    /// [`Client::update_outcome`].
352    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    /// Read one of this workflow's accepted updates by update id with a
363    /// bytes-capable Avro result; see [`Client::update_outcome_avro_value`].
364    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    /// Decode a submitted update's completion-wait receipt.
377    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    /// Decode a submitted update's completion-wait receipt as a typed Avro value.
389    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;