Skip to content
Durable Workflowrust

durable_workflow/
activity_checkpoint.rs

1//! Read-only acknowledged heartbeat snapshots supplied by a negotiated claim.
2
3use crate::{Error, Result, Value};
4use chrono::{DateTime, Utc};
5use serde::de::DeserializeOwned;
6use std::fmt;
7
8pub(super) const CAPABILITY: &str = "activity_heartbeat_resume";
9
10/// This claim does not provide the supported heartbeat-resume v1 contract.
11///
12/// This is distinct from a supported claim that explicitly reports no checkpoint.
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub struct ActivityHeartbeatResumeUnavailable;
15
16impl fmt::Display for ActivityHeartbeatResumeUnavailable {
17    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
18        f.write_str("activity_heartbeat_resume v1 is unavailable for this claim")
19    }
20}
21
22impl std::error::Error for ActivityHeartbeatResumeUnavailable {}
23
24impl From<ActivityHeartbeatResumeUnavailable> for Error {
25    fn from(value: ActivityHeartbeatResumeUnavailable) -> Self {
26        Self::Codec(value.to_string())
27    }
28}
29
30/// An immutable checkpoint received with this activity attempt's claim.
31///
32/// Heartbeat writes never change this snapshot, including when a response is
33/// rejected or lost. A later claim may carry a newer acknowledged checkpoint.
34/// A checkpoint does not atomically commit an external business effect.
35#[derive(Clone, PartialEq)]
36pub struct ActivityHeartbeatCheckpoint {
37    details: Value,
38    acknowledged_at: DateTime<Utc>,
39}
40
41impl fmt::Debug for ActivityHeartbeatCheckpoint {
42    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43        f.debug_struct("ActivityHeartbeatCheckpoint")
44            .field("details", &"<checkpoint>")
45            .field("acknowledged_at", &self.acknowledged_at)
46            .finish()
47    }
48}
49
50impl ActivityHeartbeatCheckpoint {
51    /// The acknowledged details, without defaults or mutation.
52    pub fn details(&self) -> &Value {
53        &self.details
54    }
55
56    /// Deserialize the received JSON details into an application type.
57    pub fn details_as<T: DeserializeOwned>(&self) -> serde_json::Result<T> {
58        serde_json::from_value(self.details.clone())
59    }
60
61    /// The producer's acknowledgement time, preserving fractional precision.
62    pub fn acknowledged_at(&self) -> &DateTime<Utc> {
63        &self.acknowledged_at
64    }
65
66    /// The negotiated contract version, not a checkpoint write sequence.
67    /// Server v1 does not supply a per-checkpoint sequence number.
68    pub fn contract_version(&self) -> u64 {
69        1
70    }
71}
72
73#[derive(Clone, Debug, Default)]
74pub(super) enum HeartbeatResume {
75    #[default]
76    Unavailable,
77    Available(Option<ActivityHeartbeatCheckpoint>),
78}
79
80impl HeartbeatResume {
81    pub(super) fn from_poll(wire: &Value, namespace: &str) -> Result<Self> {
82        let capability = &wire["server_capabilities"][CAPABILITY];
83        if capability["supported"] != true || capability["version"].as_u64() != Some(1) {
84            return Ok(Self::Unavailable);
85        }
86        let task = &wire["task"];
87        let (details, at) = (
88            task.get("last_heartbeat_details"),
89            task.get("last_heartbeat_at"),
90        );
91        // Older/nonparticipating claims omit both fields. An advertisement alone
92        // does not invent a supported empty checkpoint for such a delivery.
93        if details.is_none() && at.is_none() {
94            return Ok(Self::Unavailable);
95        }
96        let identity = |field: &str| task[field].as_str().is_some_and(|value| !value.is_empty());
97        let attempt = task["attempt_number"].as_u64().filter(|number| *number > 0);
98        if !identity("activity_execution_id")
99            || !identity("activity_attempt_id")
100            || !identity("workflow_id")
101            || !identity("run_id")
102            || task["namespace"].as_str() != Some(namespace)
103            || attempt.is_none()
104        {
105            return Err(invalid());
106        }
107        match (details, at) {
108            (Some(Value::Null), Some(Value::Null)) => Ok(Self::Available(None)),
109            (Some(details), Some(Value::String(at))) if !details.is_null() => {
110                if attempt == Some(1) {
111                    return Err(invalid());
112                }
113                let acknowledged_at = DateTime::parse_from_rfc3339(at)
114                    .map_err(|_| invalid())?
115                    .with_timezone(&Utc);
116                Ok(Self::Available(Some(ActivityHeartbeatCheckpoint {
117                    details: details.clone(),
118                    acknowledged_at,
119                })))
120            }
121            _ => Err(invalid()),
122        }
123    }
124
125    pub(super) fn version(&self) -> Option<u64> {
126        match self {
127            Self::Unavailable => None,
128            Self::Available(_) => Some(1),
129        }
130    }
131
132    pub(super) fn checkpoint(
133        &self,
134    ) -> std::result::Result<Option<&ActivityHeartbeatCheckpoint>, ActivityHeartbeatResumeUnavailable>
135    {
136        match self {
137            Self::Unavailable => Err(ActivityHeartbeatResumeUnavailable),
138            Self::Available(checkpoint) => Ok(checkpoint.as_ref()),
139        }
140    }
141}
142
143fn invalid() -> Error {
144    Error::Codec("activity_heartbeat_resume v1 claim has an invalid checkpoint".into())
145}