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