durable_workflow/testing/
environment.rs1use 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#[derive(Clone, Debug)]
10#[non_exhaustive]
11pub struct ReplayReport {
12 pub completed: bool,
13 pub commands: Vec<Value>,
14}
15
16pub 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 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 pub fn from_worker(mut worker: Worker) -> Self {
35 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 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 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 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 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 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
199fn 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}