Skip to main content

durable_workflow/testing/
environment.rs

1use super::WorkflowHistory;
2use crate::{
3    decode_wire_avro_value, encode_avro_value, ActivityContext, AvroValue, Client, Error,
4    ReplayFailure, Result, Value, Worker, WorkflowContext, DEFAULT_CODEC,
5};
6use std::future::Future;
7
8/// The outcome of replaying one recorded workflow snapshot.
9#[derive(Clone, Debug)]
10#[non_exhaustive]
11pub struct ReplayReport {
12    pub completed: bool,
13    pub commands: Vec<Value>,
14}
15
16/// In-process workflow/activity registration and recorded-history replay.
17pub struct WorkflowEnvironment {
18    pub(super) worker: Worker,
19    pub(super) last_history: Option<WorkflowHistory>,
20    pub(super) max_steps: usize,
21}
22
23impl WorkflowEnvironment {
24    /// Create an environment without contacting any Server.
25    pub fn new() -> Result<Self> {
26        Ok(Self::from_worker(Worker::new(
27            Client::new("http://127.0.0.1:9")?,
28            "test",
29        )))
30    }
31
32    /// Reuse an application's complete registered workflow/activity set.
33    /// Execution methods on this environment do not use the Worker's transport.
34    pub fn from_worker(worker: Worker) -> Self {
35        Self {
36            worker,
37            last_history: None,
38            max_steps: 10_000,
39        }
40    }
41
42    /// Access all existing typed, lossless and replayed-state registration APIs.
43    pub fn worker_mut(&mut self) -> &mut Worker {
44        &mut self.worker
45    }
46
47    pub fn register_workflow<F, Fut>(&mut self, name: impl Into<String>, handler: F)
48    where
49        F: Fn(WorkflowContext, Value) -> Fut + Send + Sync + 'static,
50        Fut: Future<Output = Result<Value>> + Send + 'static,
51    {
52        self.worker.register_workflow(name, handler);
53    }
54
55    pub fn register_workflow_avro_value<F, Fut>(&mut self, name: impl Into<String>, handler: F)
56    where
57        F: Fn(WorkflowContext, AvroValue) -> Fut + Send + Sync + 'static,
58        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
59    {
60        self.worker.register_workflow_avro_value(name, handler);
61    }
62
63    pub fn register_activity<F, Fut>(&mut self, name: impl Into<String>, handler: F)
64    where
65        F: Fn(ActivityContext, Value) -> Fut + Send + Sync + 'static,
66        Fut: Future<Output = Result<Value>> + Send + 'static,
67    {
68        self.worker.register_activity(name, handler);
69    }
70
71    pub fn register_activity_avro_value<F, Fut>(&mut self, name: impl Into<String>, handler: F)
72    where
73        F: Fn(ActivityContext, AvroValue) -> Fut + Send + Sync + 'static,
74        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
75    {
76        self.worker.register_activity_avro_value(name, handler);
77    }
78
79    /// Explicitly replace an activity callback for this environment, retaining
80    /// the production Worker's duplicate-registration checks for real handlers.
81    pub fn mock_activity<F, Fut>(&mut self, name: impl Into<String>, handler: F)
82    where
83        F: Fn(ActivityContext, Value) -> Fut + Send + Sync + 'static,
84        Fut: Future<Output = Result<Value>> + Send + 'static,
85    {
86        let name = name.into();
87        let mut mock = Worker::new(self.worker.client.clone(), &self.worker.task_queue);
88        mock.register_activity(name.clone(), handler);
89        self.worker.activities.insert(
90            name.clone(),
91            mock.activities.remove(&name).expect("registered mock"),
92        );
93    }
94
95    /// Lossless fixed-Avro counterpart to [`Self::mock_activity`].
96    pub fn mock_activity_avro_value<F, Fut>(&mut self, name: impl Into<String>, handler: F)
97    where
98        F: Fn(ActivityContext, AvroValue) -> Fut + Send + Sync + 'static,
99        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
100    {
101        let name = name.into();
102        let mut mock = Worker::new(self.worker.client.clone(), &self.worker.task_queue);
103        mock.register_activity_avro_value(name.clone(), handler);
104        self.worker.activities.insert(
105            name.clone(),
106            mock.activities.remove(&name).expect("registered mock"),
107        );
108    }
109
110    pub fn max_steps(mut self, limit: usize) -> Self {
111        self.max_steps = limit.max(1);
112        self
113    }
114    pub fn last_history(&self) -> Option<&WorkflowHistory> {
115        self.last_history.as_ref()
116    }
117
118    /// Replay through the worker's codec, durable-command and marker paths.
119    /// Newly emitted durable commands are divergences, including commands added
120    /// after the recorded history ended. No activity callbacks are invoked.
121    pub fn replay(&self, history: &WorkflowHistory) -> Result<ReplayReport> {
122        let _observations = crate::workflow_logging::ReconstructionGuard::enter();
123        self.worker.validate_registration()?;
124        let mut worker = self.worker.clone();
125        if let Some(queue) = &history.task_queue {
126            worker.task_queue = queue.clone();
127        }
128        let (decision, sequence) =
129            match worker.prepare_workflow_task_execution(history.task.clone(), None)? {
130                crate::PreparedWorkflowTask::Decision(decision) => (decision, 1),
131                crate::PreparedWorkflowTask::Execution {
132                    task,
133                    context,
134                    mut future,
135                } => {
136                    let sequence = {
137                        let state = context
138                            .state
139                            .lock()
140                            .map_err(|_| Error::WorkflowStatePoisoned)?;
141                        state
142                            .recorded_commands
143                            .last()
144                            .map_or(1, |command| command.sequence().saturating_add(1))
145                    };
146                    let outcome = Worker::poll_workflow_future(&context, &mut future)?;
147                    {
148                        let state = context
149                            .state
150                            .lock()
151                            .map_err(|_| Error::WorkflowStatePoisoned)?;
152                        if !state.local_activity_requests.is_empty() {
153                            validate_commands(&state.commands, sequence)?;
154                        }
155                    }
156                    (
157                        worker.finish_workflow_task_execution(&task, &context, outcome)?,
158                        sequence,
159                    )
160                }
161            };
162        if !decision.commands.is_empty() && recorded_structural_limit_failure(history) {
163            // The worker failed this run because the Server refused the next
164            // completion over a structural limit (completion size or history
165            // budget, .github#228). The refused commands were never recorded,
166            // so replay reproduces them after the recorded command stream; the
167            // recorded failure, not a workflow decision, closed the run.
168            return Ok(ReplayReport {
169                completed: true,
170                commands: decision.commands,
171            });
172        }
173        validate_commands(&decision.commands, sequence)?;
174        validate_terminal(history, &decision.commands, sequence)?;
175        Ok(ReplayReport {
176            completed: decision.commands.iter().any(terminal_command),
177            commands: decision.commands,
178        })
179    }
180}
181
182fn terminal_command(command: &Value) -> bool {
183    matches!(
184        command["type"].as_str(),
185        Some("complete_workflow" | "fail_workflow" | "continue_as_new")
186    )
187}
188
189/// Whether the run closed with the structural-limit failure a Worker records
190/// when the Server refuses a completion as too large (413) or over its
191/// history-transaction budget (409). Only the SDK writes that failure, and
192/// only in place of the refused commands.
193fn recorded_structural_limit_failure(history: &WorkflowHistory) -> bool {
194    history.events().last().is_some_and(|event| {
195        event.event_type == "WorkflowFailed"
196            && event.payload["failure_category"] == "structural_limit"
197            && event.payload["exception_type"] == "StructuralLimitExceeded"
198            && event.payload["message"]
199                .as_str()
200                .is_some_and(|message| message.starts_with("Structural limit exceeded: "))
201    })
202}
203
204fn validate_commands(commands: &[Value], sequence: u64) -> Result<()> {
205    if let Some(command) = commands.iter().find(|command| !terminal_command(command)) {
206        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
207            "unrecorded_command",
208            Some(sequence),
209            Some("end of recorded command stream".into()),
210            Some(command.to_string()),
211            "workflow produced a command absent from recorded history",
212        )));
213    }
214    Ok(())
215}
216
217fn validate_terminal(history: &WorkflowHistory, commands: &[Value], sequence: u64) -> Result<()> {
218    let Some((recorded, expected)) =
219        history
220            .events()
221            .iter()
222            .rev()
223            .find_map(|event| match event.event_type.as_str() {
224                "WorkflowCompleted" => Some((event, "complete_workflow")),
225                "WorkflowFailed" => Some((event, "fail_workflow")),
226                "WorkflowContinuedAsNew" => Some((event, "continue_as_new")),
227                _ => None,
228            })
229    else {
230        return Ok(());
231    };
232    let command = commands
233        .iter()
234        .find(|command| command["type"] == expected)
235        .ok_or_else(|| {
236            Error::NonDeterministicReplay(ReplayFailure::new(
237                "workflow_terminal_mismatch",
238                Some(sequence),
239                Some(expected.into()),
240                Some(format!("{commands:?}")),
241                format!(
242                    "workflow terminal decision differs from {}",
243                    recorded.event_type
244                ),
245            ))
246        })?;
247    if expected == "complete_workflow" {
248        let old = encode_avro_value(&decode_wire_avro_value(
249            &recorded.payload["output"],
250            DEFAULT_CODEC,
251        )?)?;
252        let new = encode_avro_value(&decode_wire_avro_value(&command["result"], DEFAULT_CODEC)?)?;
253        if old != new {
254            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
255                "workflow_result_mismatch",
256                Some(sequence),
257                Some(old.blob),
258                Some(new.blob),
259                "workflow completion differs from recorded output",
260            )));
261        }
262    }
263    Ok(())
264}