Skip to main content

durable_workflow/testing/
history.rs

1use super::TestingError;
2use crate::{
3    decode_wire_avro_value, encode_typed_envelope, enrich_query_history_from_export,
4    hydrate_query_history_from_export, json, normalize_avro_arguments, path_segment,
5    validate_query_task_payloads, AvroValue, Client, HistoryEvent, QueryTask, RequestProtocol,
6    Result, Value, WorkflowTask, DEFAULT_CODEC,
7};
8use serde::Serialize;
9
10/// Recorded workflow input and history, independent of a live Server.
11#[derive(Clone, Debug)]
12pub struct WorkflowHistory {
13    pub(super) task: WorkflowTask,
14    pub(super) task_queue: Option<String>,
15    pub(super) replay_clock: Option<Value>,
16}
17
18fn invalid(message: &str) -> crate::Error {
19    TestingError::InvalidHistory(message.into()).into()
20}
21
22impl WorkflowHistory {
23    /// Import a `dw workflow:history-export` or SDK export bundle.
24    /// Payloads must be present and resolved; redacted/pruned input is refused.
25    pub fn from_export(export: Value) -> Result<Self> {
26        if export["schema"] != "durable-workflow.v2.history-export" {
27            return Err(invalid("expected durable-workflow.v2.history-export"));
28        }
29        if export
30            .pointer("/redaction/paths")
31            .and_then(Value::as_array)
32            .is_some_and(|paths| !paths.is_empty())
33        {
34            return Err(invalid("replay requires an unredacted history export"));
35        }
36        let events: Vec<HistoryEvent> = serde_json::from_value(
37            export
38                .get("history_events")
39                .cloned()
40                .ok_or_else(|| invalid("missing history_events"))?,
41        )?;
42        let started = events
43            .iter()
44            .find(|event| event.event_type == "WorkflowStarted");
45        let workflow_type = export["workflow"]["workflow_type"]
46            .as_str()
47            .or_else(|| started.and_then(|event| event.payload["workflow_type"].as_str()))
48            .filter(|value| !value.is_empty())
49            .ok_or_else(|| invalid("missing workflow type"))?;
50        let codec = export["payloads"]["codec"]
51            .as_str()
52            .unwrap_or(DEFAULT_CODEC);
53        let input = export
54            .pointer("/payloads/arguments/data")
55            .filter(|value| !value.is_null())
56            .or_else(|| started.and_then(|event| event.payload.get("arguments")))
57            .ok_or_else(|| {
58                invalid(
59                    "workflow input is unavailable; from_history accepts explicit original input",
60                )
61            })?;
62        let input = decode_wire_avro_value(input, codec)?;
63        let mut query: QueryTask = serde_json::from_value(json!({
64            "query_task_id":"offline", "workflow_type":workflow_type, "query_name":"offline",
65            "payload_codec":codec, "workflow_arguments":encode_typed_envelope(&normalize_avro_arguments(input),codec)?,
66            "history_events":events, "history_export":export,
67        }))?;
68        validate_query_task_payloads(&query)?;
69        hydrate_query_history_from_export(&mut query)?;
70        enrich_query_history_from_export(&mut query)?;
71        for event in &mut query.history_events {
72            if event.event_type == "WorkflowCompleted"
73                && event.payload.get("output").is_none_or(Value::is_null)
74            {
75                if let Some(output) = export
76                    .pointer("/payloads/output/data")
77                    .filter(|value| !value.is_null())
78                {
79                    event.payload["output"] = output.clone();
80                }
81            }
82        }
83        let queue = export["workflow"]["queue"]
84            .as_str()
85            .or_else(|| started.and_then(|event| event.payload["task_queue"].as_str()))
86            .map(str::to_string);
87        Self::build(
88            workflow_type,
89            query.workflow_arguments,
90            query.history_events,
91            export["workflow"]["instance_id"].as_str(),
92            export["workflow"]["run_id"].as_str(),
93            queue,
94        )
95    }
96
97    /// Import all pages of the Server history API, supplying original input.
98    /// Also accepts an array of events. A remaining page token is refused.
99    pub fn from_history<T: Serialize>(
100        workflow_type: &str,
101        input: T,
102        history: Value,
103    ) -> Result<Self> {
104        if history
105            .get("next_page_token")
106            .is_some_and(|token| !token.is_null() && token.as_str() != Some(""))
107        {
108            return Err(invalid(
109                "history has another page; combine all pages before replay",
110            ));
111        }
112        let raw = if history.is_array() {
113            history.clone()
114        } else {
115            history
116                .get("events")
117                .or_else(|| history.get("history_events"))
118                .cloned()
119                .ok_or_else(|| invalid("missing events"))?
120        };
121        let events: Vec<HistoryEvent> = serde_json::from_value(raw)?;
122        let queue = events
123            .iter()
124            .find(|event| event.event_type == "WorkflowStarted")
125            .and_then(|event| event.payload["task_queue"].as_str())
126            .map(str::to_string);
127        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
128        Self::build(
129            workflow_type,
130            Some(encode_typed_envelope(&input, DEFAULT_CODEC)?),
131            events,
132            history["workflow_id"].as_str(),
133            history["run_id"].as_str(),
134            queue,
135        )
136    }
137
138    fn build(
139        workflow_type: &str,
140        input: Option<Value>,
141        events: Vec<HistoryEvent>,
142        workflow_id: Option<&str>,
143        run_id: Option<&str>,
144        task_queue: Option<String>,
145    ) -> Result<Self> {
146        if workflow_type.trim().is_empty() {
147            return Err(invalid("workflow type must not be empty"));
148        }
149        for event in &events {
150            let field = match event.event_type.as_str() {
151                "ActivityCompleted" | "SideEffectRecorded" => Some("result"),
152                "WorkflowCompleted" => Some("output"),
153                "ChildRunCompleted" if event.payload.get("output").is_none_or(Value::is_null) => {
154                    Some("result")
155                }
156                _ => None,
157            };
158            if field.is_some_and(|field| event.payload.get(field).is_none_or(Value::is_null)) {
159                return Err(invalid("a recorded result is missing or redacted"));
160            }
161        }
162        let task = serde_json::from_value(json!({
163            "task_id":"offline-replay", "workflow_command_id":"offline-replay",
164            "workflow_type":workflow_type, "workflow_id":workflow_id, "run_id":run_id,
165            "payload_codec":DEFAULT_CODEC, "arguments":input, "history_events":events,
166        }))?;
167        Ok(Self {
168            task,
169            task_queue,
170            replay_clock: None,
171        })
172    }
173
174    /// Override task-queue context omitted by a raw history response.
175    pub fn task_queue(mut self, queue: impl Into<String>) -> Self {
176        self.task_queue = Some(queue.into());
177        self
178    }
179
180    /// Supply the run's `replay_clock` entry carrier (`WorkerReplayClock` v1)
181    /// that Server sent on its workflow tasks, so a replayed body that reads
182    /// [`crate::WorkflowContext::replay_now`] at entry sees the same instant.
183    /// The carrier is validated now against this history's run ID: an
184    /// invalid carrier, or one for another run, is refused. Without one,
185    /// entry stays unavailable. [`Self::export`] does not include it, and
186    /// [`crate::testing::WorkflowEnvironment::run_workflow`] supplies none.
187    pub fn replay_clock(mut self, carrier: Value) -> Result<Self> {
188        if crate::replay_clock::entry_for(Some(&carrier), self.task.run_id.as_deref()).is_none() {
189            return Err(invalid(
190                "replay_clock must be a v1 WorkerReplayClock object for this history's run",
191            ));
192        }
193        self.replay_clock = Some(carrier);
194        Ok(self)
195    }
196
197    pub(super) fn replay_entry(&self) -> Option<crate::replay_clock::Entry> {
198        crate::replay_clock::entry_for(self.replay_clock.as_ref(), self.task.run_id.as_deref())
199    }
200
201    pub fn workflow_type(&self) -> &str {
202        &self.task.workflow_type
203    }
204    pub fn events(&self) -> &[HistoryEvent] {
205        &self.task.history_events
206    }
207
208    /// Produce a portable self-contained export of this test history.
209    pub fn export(&self) -> Value {
210        json!({"schema":"durable-workflow.v2.history-export",
211            "history_complete":self.events().iter().any(|event|matches!(event.event_type.as_str(),"WorkflowCompleted"|"WorkflowFailed"|"WorkflowContinuedAsNew")),
212            "workflow":{"instance_id":self.task.workflow_id,"run_id":self.task.run_id,
213                "workflow_type":self.task.workflow_type,"queue":self.task_queue},
214            "payloads":{"codec":DEFAULT_CODEC,"arguments":{"available":true,"data":self.task.arguments}},
215            "history_events":self.task.history_events})
216    }
217}
218
219impl Client {
220    /// Download a replay bundle, hydrating runtime payload references before
221    /// returning it so replay itself does not need a Server connection.
222    pub async fn export_workflow_history(&self, workflow_id: &str, run_id: &str) -> Result<Value> {
223        self.request_json(
224            reqwest::Method::GET,
225            &format!(
226                "/workflows/{}/runs/{}/history/export",
227                path_segment("workflow_id", workflow_id)?,
228                path_segment("run_id", run_id)?
229            ),
230            RequestProtocol::ControlPlane,
231            Option::<&Value>::None,
232        )
233        .await
234    }
235}