Skip to content
Durable Workflowrust

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