Skip to main content

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    path_segment, AvroValue, Boundary, Client, Error, RequestProtocol, Result, WorkflowHandle,
17};
18
19/// The cluster capability that advertises `GET /workflows/{id}/updates/{update_id}`.
20pub(crate) const UPDATE_OUTCOME_READS_CAPABILITY: &str = "update_outcome_reads";
21
22/// Extra transport time allowed beyond a requested completion wait.
23const WAIT_TRANSPORT_MARGIN: Duration = Duration::from_secs(30);
24
25/// How long an update outcome read waits before the Server answers.
26#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
27#[non_exhaustive]
28pub enum UpdateWaitStage {
29    /// Answer at once with the update's current receipt (the Server default).
30    #[default]
31    Accepted,
32    /// Wait for the update's outcome, up to the wait timeout.
33    Completed,
34}
35
36impl UpdateWaitStage {
37    /// The `wait_for` value sent to the Server.
38    pub fn as_str(self) -> &'static str {
39        match self {
40            Self::Accepted => "accepted",
41            Self::Completed => "completed",
42        }
43    }
44}
45
46/// An update the Server accepted that had not completed when the wait ended.
47///
48/// It has no result yet: this is never a handler that returned null. Read it
49/// again by [`update_id`](Self::update_id) with [`Client::update_outcome`] on a
50/// Server that advertises `update_outcome_reads` (native 3.6.0 and later). On
51/// an older Server, call [`Client::update_workflow`] again with the same
52/// [`request_id`](Self::request_id): the Server returns the retained update
53/// instead of admitting a second one.
54///
55/// `run_id` names the run that owns the update now, which can be a
56/// continue-as-new successor. `receipt` is the Server's full answer.
57#[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    /// The Server's `update_status`, normally `accepted`.
66    pub update_status: Option<String>,
67    /// Whether the Server's completion wait ran out.
68    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
134/// Whether a completion-wait receipt describes an update that has not finished.
135///
136/// A receipt with a result envelope is finished (an encoded null is a real
137/// null result). Otherwise a timed-out wait, or any status other than
138/// `completed`, `failed` or `rejected`, is pending.
139pub(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
150/// Raise [`Error::UpdateStillPending`] for a pending completion-wait receipt.
151pub(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
166/// Whether a successful answer is the Server's receipt for the update that was read.
167fn 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    /// 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) => self.decode_client_json(envelope, Boundary::UpdateResult),
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(self, &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        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        // Only a completed receipt carries an outcome; never read one into
326        // any other successful answer.
327        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    /// Refuse a Server that does not advertise `update_outcome_reads`.
336    ///
337    /// Discovery runs until a Server advertises the capability; after that the
338    /// client remembers it.
339    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    /// Read one of this workflow's accepted updates by update id; see
355    /// [`Client::update_outcome`].
356    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    /// Read one of this workflow's accepted updates by update id with a
367    /// bytes-capable Avro result; see [`Client::update_outcome_avro_value`].
368    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    /// Decode a submitted update's completion-wait receipt.
381    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    /// Decode a submitted update's completion-wait receipt as a typed Avro value.
398    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;