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(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        worker.ordered_condition_claim.replay_entry = history.replay_entry();
134        let (decision, sequence, continuation_consumed) = match worker
135            .prepare_workflow_task_execution(history.task.clone(), None)?
136        {
137            crate::PreparedWorkflowTask::Decision(decision) => (decision, 1, false),
138            crate::PreparedWorkflowTask::Execution {
139                task,
140                context,
141                mut future,
142            } => {
143                let sequence = {
144                    let state = context
145                        .state
146                        .lock()
147                        .map_err(|_| Error::WorkflowStatePoisoned)?;
148                    state
149                        .recorded_commands
150                        .last()
151                        .map_or(1, |command| command.sequence().saturating_add(1))
152                };
153                let outcome = Worker::poll_workflow_future(&context, &mut future)?;
154                {
155                    let state = context
156                        .state
157                        .lock()
158                        .map_err(|_| Error::WorkflowStatePoisoned)?;
159                    if !state.local_activity_requests.is_empty() {
160                        validate_commands(&state.commands, sequence)?;
161                    }
162                }
163                let decision = worker.finish_workflow_task_execution(&task, &context, outcome)?;
164                let continuation_consumed = context
165                    .state
166                    .lock()
167                    .map_err(|_| Error::WorkflowStatePoisoned)?
168                    .continue_as_new_consumed;
169                (decision, sequence, continuation_consumed)
170            }
171        };
172        if !decision.commands.is_empty() && recorded_structural_limit_failure(history) {
173            // The worker failed this run because the Server refused the next
174            // completion over a structural limit (completion size or history
175            // budget, .github#228). The refused commands were never recorded,
176            // so replay reproduces them after the recorded command stream; the
177            // recorded failure, not a workflow decision, closed the run.
178            return Ok(ReplayReport {
179                completed: true,
180                commands: decision.commands,
181            });
182        }
183        validate_commands(&decision.commands, sequence)?;
184        validate_terminal(history, &decision.commands, sequence, continuation_consumed)?;
185        Ok(ReplayReport {
186            completed: continuation_consumed || decision.commands.iter().any(terminal_command),
187            commands: decision.commands,
188        })
189    }
190}
191
192fn terminal_command(command: &Value) -> bool {
193    matches!(
194        command["type"].as_str(),
195        Some("complete_workflow" | "fail_workflow" | "continue_as_new")
196    )
197}
198
199/// Whether the run closed with the structural-limit failure a Worker records
200/// when the Server refuses a completion as too large (413) or over its
201/// history-transaction budget (409). Only the SDK writes that failure, and
202/// only in place of the refused commands.
203fn recorded_structural_limit_failure(history: &WorkflowHistory) -> bool {
204    history.events().last().is_some_and(|event| {
205        event.event_type == "WorkflowFailed"
206            && event.payload["failure_category"] == "structural_limit"
207            && event.payload["exception_type"] == "StructuralLimitExceeded"
208            && event.payload["message"]
209                .as_str()
210                .is_some_and(|message| message.starts_with("Structural limit exceeded: "))
211    })
212}
213
214fn validate_commands(commands: &[Value], sequence: u64) -> Result<()> {
215    if let Some(command) = commands.iter().find(|command| !terminal_command(command)) {
216        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
217            "unrecorded_command",
218            Some(sequence),
219            Some("end of recorded command stream".into()),
220            Some(command.to_string()),
221            "workflow produced a command absent from recorded history",
222        )));
223    }
224    Ok(())
225}
226
227fn validate_terminal(
228    history: &WorkflowHistory,
229    commands: &[Value],
230    sequence: u64,
231    continuation_consumed: bool,
232) -> Result<()> {
233    let Some((recorded, expected)) =
234        history
235            .events()
236            .iter()
237            .rev()
238            .find_map(|event| match event.event_type.as_str() {
239                "WorkflowCompleted" => Some((event, "complete_workflow")),
240                "WorkflowFailed" => Some((event, "fail_workflow")),
241                "WorkflowContinuedAsNew" => Some((event, "continue_as_new")),
242                _ => None,
243            })
244    else {
245        return Ok(());
246    };
247    if expected == "continue_as_new" && continuation_consumed && commands.is_empty() {
248        return Ok(());
249    }
250    let command = commands
251        .iter()
252        .find(|command| command["type"] == expected)
253        .ok_or_else(|| {
254            Error::NonDeterministicReplay(ReplayFailure::new(
255                "workflow_terminal_mismatch",
256                Some(sequence),
257                Some(expected.into()),
258                Some(format!("{commands:?}")),
259                format!(
260                    "workflow terminal decision differs from {}",
261                    recorded.event_type
262                ),
263            ))
264        })?;
265    if expected == "complete_workflow" {
266        let old = encode_avro_value(&decode_wire_avro_value(
267            &recorded.payload["output"],
268            DEFAULT_CODEC,
269        )?)?;
270        let new = encode_avro_value(&decode_wire_avro_value(&command["result"], DEFAULT_CODEC)?)?;
271        if old != new {
272            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
273                "workflow_result_mismatch",
274                Some(sequence),
275                Some(old.blob),
276                Some(new.blob),
277                "workflow completion differs from recorded output",
278            )));
279        }
280    }
281    Ok(())
282}