1use super::{
4 durable_event_sequence, is_internal_timer_event, is_recorded_signal_wait_event,
5 recorded_commands, DurableOperationHandle, Error, HistoryEvent, ParallelGroupMetadata,
6 QueryContext, RecordedCommand, Result, Value, WorkflowContext, WorkflowIdentity, WorkflowState,
7};
8use chrono::{DateTime, Utc};
9use std::{
10 cell::{Cell, RefCell},
11 collections::HashMap,
12 sync::{Arc, Mutex, Weak},
13};
14
15mod condition;
16mod condition_timeout;
17mod parallel;
18mod parallel_activity;
19mod parallel_child;
20mod parallel_timer;
21
22thread_local! {
23 static ACTIVE: RefCell<Option<Weak<Mutex<WorkflowState>>>> = const { RefCell::new(None) };
24 static QUERY_REPLAY: Cell<bool> = const { Cell::new(false) };
25}
26
27pub(super) struct Guard(Option<Weak<Mutex<WorkflowState>>>, bool);
28
29impl Guard {
30 pub(super) fn enter(context: &WorkflowContext) -> Self {
31 Self::scope(Some(Arc::downgrade(&context.state)), false)
32 }
33
34 pub(super) fn query(context: &WorkflowContext) -> Self {
35 Self::scope(Some(Arc::downgrade(&context.state)), true)
36 }
37
38 pub(super) fn unavailable() -> Self {
39 Self::scope(None, false)
40 }
41
42 fn scope(context: Option<Weak<Mutex<WorkflowState>>>, query: bool) -> Self {
43 Self(
44 ACTIVE.with(|active| active.replace(context)),
45 QUERY_REPLAY.with(|active| active.replace(query)),
46 )
47 }
48}
49
50impl Drop for Guard {
51 fn drop(&mut self) {
52 ACTIVE.with(|active| active.replace(self.0.take()));
53 QUERY_REPLAY.with(|active| active.set(self.1));
54 }
55}
56
57fn unavailable() -> Error {
58 Error::ReplayClockUnavailable
59}
60
61fn parse(value: Option<&Value>) -> Option<DateTime<Utc>> {
62 DateTime::parse_from_rfc3339(value?.as_str()?)
63 .ok()
64 .map(|time| time.with_timezone(&Utc))
65}
66
67fn recorded_time(event: &HistoryEvent, reused: bool) -> Option<DateTime<Utc>> {
68 if reused && event.payload.get("reused_recorded_at").is_some() {
69 return parse(event.payload.get("reused_recorded_at"));
70 }
71 parse(
73 event
74 .raw
75 .get("timestamp")
76 .or_else(|| event.raw.get("recorded_at")),
77 )
78}
79
80fn boundary_time(event: &HistoryEvent, query: bool) -> Option<DateTime<Utc>> {
81 let internal = event.event_type == "TimerFired" && is_internal_timer_event(event);
82 if internal {
83 return if query {
86 None
87 } else {
88 parse(event.raw.get("recorded_at"))
89 };
90 }
91 recorded_time(
92 event,
93 matches!(
94 event.event_type.as_str(),
95 "ActivityCompleted" | "TimerFired" | "SignalApplied"
96 ),
97 )
98}
99
100fn start_time(history: &[HistoryEvent]) -> Option<DateTime<Utc>> {
101 let mut starts = history
102 .iter()
103 .filter(|event| event.event_type == "WorkflowStarted");
104 let start = starts.next()?;
105 if starts.next().is_some() || start.payload["recovery_kind"] != "redrive" {
106 return None;
109 }
110 parse(start.payload.get("replayed_started_at"))
111}
112
113#[derive(Debug)]
114pub(super) struct Clock {
115 time: Option<DateTime<Utc>>,
116 boundaries: HashMap<u64, usize>,
117 parallel_activities: parallel::Members,
118 parallel_timers: parallel::Members,
119 parallel_children: parallel::Members,
120}
121
122enum BoundaryKind {
123 Activity,
124 Timer,
125 Child,
126 Signal,
127 Condition,
128}
129
130fn supported_boundary(command: &RecordedCommand) -> Option<(u64, BoundaryKind)> {
131 match command {
132 RecordedCommand::Activity {
133 sequence,
134 outcome: Some(_),
135 parallel_group_path,
136 ..
137 } if parallel_group_path.as_ref().is_none_or(Vec::is_empty) => {
138 Some((*sequence, BoundaryKind::Activity))
139 }
140 RecordedCommand::Timer {
141 sequence,
142 fired: true,
143 parallel_group_path,
144 ..
145 } if parallel_group_path.as_ref().is_none_or(Vec::is_empty) => {
146 Some((*sequence, BoundaryKind::Timer))
147 }
148 RecordedCommand::ChildWorkflow {
149 sequence,
150 outcome: Some(_),
151 parallel_group_path,
152 ..
153 } if parallel_group_path.as_ref().is_none_or(Vec::is_empty) => {
154 Some((*sequence, BoundaryKind::Child))
155 }
156 RecordedCommand::SignalWait {
157 sequence,
158 value: Some(_),
159 parallel_group_path,
160 ..
161 } if parallel_group_path.as_ref().is_none_or(Vec::is_empty) => {
162 Some((*sequence, BoundaryKind::Signal))
163 }
164 RecordedCommand::ConditionWait {
165 sequence,
166 result: Some(_),
167 parallel_group_path,
168 ..
169 } if parallel_group_path.as_ref().is_none_or(Vec::is_empty) => {
170 Some((*sequence, BoundaryKind::Condition))
171 }
172 _ => None,
173 }
174}
175
176fn signal_boundary(history: &[HistoryEvent], indices: &[usize], sequence: u64) -> Option<usize> {
177 let (opened, timers, applied) = match indices {
178 [opened, applied] => (opened, &[][..], applied),
179 [opened, _, _, applied] => (opened, &indices[1..3], applied),
180 _ => return None,
181 };
182 let open = &history[*opened];
183 let apply = &history[*applied];
184 if open.event_type != "SignalWaitOpened"
185 || apply.event_type != "SignalApplied"
186 || apply.payload.get("value").is_none_or(Value::is_null)
187 {
188 return None;
189 }
190 let events: Vec<_> = indices.iter().map(|&index| &history[index]).collect();
191 if super::recorded_parallel_group_path(&events, sequence)
192 .ok()?
193 .is_some_and(|path| !path.is_empty())
194 {
195 return None;
196 }
197 for event in &events {
198 if event.payload.get("sequence").and_then(Value::as_u64) != Some(sequence)
199 || event
200 .payload
201 .get("workflow_sequence")
202 .is_some_and(|value| value.as_u64() != Some(sequence))
203 {
204 return None;
205 }
206 }
207 for key in ["signal_wait_id", "signal_name"] {
208 let identity = open
209 .payload
210 .get(key)?
211 .as_str()
212 .filter(|value| !value.is_empty())?;
213 if events
214 .iter()
215 .any(|event| event.payload.get(key).and_then(Value::as_str) != Some(identity))
216 {
217 return None;
218 }
219 }
220 signal_timeout(open, apply, history, timers)?;
221 Some(*applied)
222}
223
224fn signal_timeout(
225 open: &HistoryEvent,
226 apply: &HistoryEvent,
227 history: &[HistoryEvent],
228 timers: &[usize],
229) -> Option<()> {
230 let timeout = open.payload.get("timeout_seconds").filter(|v| !v.is_null());
231 let seconds = match timeout {
232 Some(value) => Some(value.as_u64()?),
233 None => None,
234 };
235 if apply
236 .payload
237 .get("timeout_seconds")
238 .filter(|value| !value.is_null())
239 .is_some_and(|value| Some(value) != timeout)
240 {
241 return None;
242 }
243 let [scheduled, cancelled] = timers else {
244 return timers.is_empty().then_some(());
247 };
248 let schedule = &history[*scheduled];
249 let cancel = &history[*cancelled];
250 if seconds? == 0
251 || schedule.event_type != "TimerScheduled"
252 || cancel.event_type != "TimerCancelled"
253 || parse(cancel.payload.get("cancelled_at")).is_none()
254 || cancel
255 .payload
256 .get("cancellation_scope")
257 .is_some_and(|v| !v.is_null())
258 {
259 return None;
260 }
261 for event in [schedule, cancel] {
262 if event.payload["timer_kind"] != "signal_timeout"
263 || event.payload.get("delay_seconds").and_then(Value::as_u64) != seconds
264 {
265 return None;
266 }
267 }
268 let timer_id = schedule
269 .payload
270 .get("timer_id")?
271 .as_str()
272 .filter(|v| !v.is_empty())?;
273 if cancel.payload.get("timer_id").and_then(Value::as_str) != Some(timer_id)
274 || parse(schedule.payload.get("fire_at")).is_none()
275 || cancel.payload.get("fire_at") != schedule.payload.get("fire_at")
276 {
277 return None;
278 }
279 Some(())
280}
281
282fn child_boundary(history: &[HistoryEvent], indices: &[usize]) -> Option<usize> {
283 child_lifecycle(history, indices)?
284}
285
286fn child_lifecycle(history: &[HistoryEvent], indices: &[usize]) -> Option<Option<usize>> {
287 let (&scheduled, terminal) = match indices {
290 [scheduled] => (scheduled, None),
291 [scheduled, started] if history[*started].event_type == "ChildRunStarted" => {
292 (scheduled, None)
293 }
294 [scheduled, terminal] => (scheduled, Some(*terminal)),
295 [scheduled, started, terminal] if history[*started].event_type == "ChildRunStarted" => {
296 (scheduled, Some(*terminal))
297 }
298 _ => return None,
299 };
300 let schedule = &history[scheduled];
301 if schedule.event_type != "ChildWorkflowScheduled"
302 || terminal.is_some_and(|terminal| {
303 !matches!(
304 history[terminal].event_type.as_str(),
305 "ChildRunCompleted" | "ChildRunFailed" | "ChildRunCancelled" | "ChildRunTerminated"
306 )
307 })
308 {
309 return None;
310 }
311 for key in [
312 "child_call_id",
313 "child_workflow_instance_id",
314 "child_workflow_run_id",
315 "child_workflow_type",
316 ] {
317 let identity = schedule
318 .payload
319 .get(key)?
320 .as_str()
321 .filter(|id| !id.is_empty())?;
322 if indices
323 .iter()
324 .any(|&index| history[index].payload.get(key).and_then(Value::as_str) != Some(identity))
325 {
326 return None;
329 }
330 }
331 Some(terminal)
332}
333
334impl Clock {
335 pub(super) fn new(history: &[HistoryEvent], commands: &[RecordedCommand]) -> Self {
336 let supported: HashMap<_, _> = commands.iter().filter_map(supported_boundary).collect();
337 let mut boundaries = HashMap::new();
338 let mut children: HashMap<u64, Vec<usize>> = HashMap::new();
339 let mut signals: HashMap<u64, Vec<usize>> = HashMap::new();
340 let mut conditions: HashMap<u64, Vec<usize>> = HashMap::new();
341 let mut signal_timers: HashMap<&str, Vec<usize>> = HashMap::new();
342 for (index, event) in history.iter().enumerate() {
343 if event.event_type.starts_with("Timer") {
344 if let Some(wait) = event.payload.get("signal_wait_id").and_then(Value::as_str) {
345 signal_timers.entry(wait).or_default().push(index);
346 }
347 }
348 let Some(sequence) = durable_event_sequence(event) else {
349 continue;
350 };
351 let matched = match supported.get(&sequence) {
352 Some(BoundaryKind::Activity) => matches!(
353 event.event_type.as_str(),
354 "ActivityCompleted"
355 | "ActivityFailed"
356 | "ActivityTimedOut"
357 | "ActivityCancelled"
358 ),
359 Some(BoundaryKind::Timer) => {
360 event.event_type == "TimerFired" && !is_internal_timer_event(event)
361 }
362 Some(BoundaryKind::Child) => {
363 if event.event_type == "ChildWorkflowScheduled"
364 || event.event_type.starts_with("ChildRun")
365 {
366 children.entry(sequence).or_default().push(index);
367 }
368 false
369 }
370 Some(BoundaryKind::Signal) => {
371 if is_recorded_signal_wait_event(event) || event.event_type.starts_with("Timer")
372 {
373 signals.entry(sequence).or_default().push(index);
374 }
375 false
376 }
377 Some(BoundaryKind::Condition) => {
378 if super::is_recorded_condition_wait_event(event) {
379 conditions.entry(sequence).or_default().push(index);
380 }
381 false
382 }
383 None => false,
384 };
385 if matched {
386 boundaries.entry(sequence).or_insert(index);
387 }
388 }
389 for (sequence, indices) in children {
390 if let Some(index) = child_boundary(history, &indices) {
391 boundaries.insert(sequence, index);
392 }
393 }
394 for (sequence, mut indices) in signals {
395 let related: Vec<_> = indices
398 .iter()
399 .filter_map(|&index| history[index].payload.get("signal_wait_id")?.as_str())
400 .filter_map(|wait| signal_timers.get(wait))
401 .flatten()
402 .copied()
403 .collect();
404 indices.extend(related);
405 indices.sort_unstable();
406 indices.dedup();
407 if let Some(index) = signal_boundary(history, &indices, sequence) {
408 boundaries.insert(sequence, index);
409 }
410 }
411 let condition_timeouts = condition_timeout::Index::new(history);
412 boundaries.extend(conditions.into_iter().filter_map(|(sequence, indices)| {
413 condition::boundary(history, &indices, sequence)
414 .or_else(|| condition_timeouts.boundary(history, &indices, sequence))
415 .map(|index| (sequence, index))
416 }));
417 Self {
420 time: start_time(history),
421 boundaries,
422 parallel_activities: parallel_activity::members(history, commands),
423 parallel_timers: parallel_timer::members(history, commands),
424 parallel_children: parallel_child::members(history, commands),
425 }
426 }
427
428 pub(super) fn unavailable(&mut self) {
429 self.time = None;
430 }
431}
432
433impl WorkflowState {
434 pub(super) fn consume_replay_sequence(
435 &mut self,
436 sequence: u64,
437 path: &[ParallelGroupMetadata],
438 ) {
439 if path.is_empty() {
440 self.observe_replay_sequence(sequence);
441 } else {
442 self.replay_clock.unavailable();
443 }
444 self.advance_cancellation_sequence(sequence, path);
445 }
446
447 pub(super) fn consume_unproven_boundary(&mut self, path: &[ParallelGroupMetadata]) {
448 self.replay_clock.unavailable();
449 self.unavailable_cancellation_boundary(path);
450 }
451
452 pub(super) fn consume_replay_group(&mut self, sequences: &[u64], failed: Option<u64>) {
453 self.replay_clock.time = if QUERY_REPLAY.with(Cell::get) {
456 None
457 } else {
458 self.replay_clock
459 .parallel_activities
460 .consumed_time(&self.history_events, sequences, failed)
461 .or_else(|| {
462 self.replay_clock.parallel_timers.consumed_time(
463 &self.history_events,
464 sequences,
465 failed,
466 )
467 })
468 .or_else(|| {
469 self.replay_clock.parallel_children.consumed_time(
470 &self.history_events,
471 sequences,
472 failed,
473 )
474 })
475 };
476 self.advance_cancellation_sequences(sequences, failed);
477 }
478
479 pub(super) fn consume_replay_selection(&mut self, group: &str) {
480 self.replay_clock.unavailable();
481 self.advance_cancellation_selection(group);
482 }
483
484 pub(super) fn consume_replay_receipt(&mut self, group: &str, sequence: u64) {
485 self.replay_clock.unavailable();
486 self.advance_cancellation_receipt(group, sequence);
487 }
488
489 pub(super) fn consume_replay_handle(&mut self, handle: &DurableOperationHandle, failed: bool) {
490 self.replay_clock.unavailable();
491 self.advance_cancellation_handle(handle, failed);
492 }
493
494 pub(super) fn replay_time(&self) -> Result<DateTime<Utc>> {
495 if self.cancellation_clock.is_some() {
498 return Err(unavailable());
499 }
500 self.replay_clock.time.ok_or_else(unavailable)
501 }
502
503 pub(super) fn observe_replay_sequence(&mut self, sequence: u64) {
504 self.replay_clock.time = self
505 .replay_clock
506 .boundaries
507 .get(&sequence)
508 .and_then(|index| self.history_events.get(*index))
509 .and_then(|event| boundary_time(event, QUERY_REPLAY.with(Cell::get)));
510 }
511}
512
513impl WorkflowContext {
514 pub fn replay_now(&self) -> Result<DateTime<Utc>> {
529 let active = ACTIVE.with(|active| active.borrow().as_ref().and_then(Weak::upgrade));
530 if !active.is_some_and(|active| Arc::ptr_eq(&active, &self.state)) {
531 return Err(unavailable());
532 }
533 self.state
534 .lock()
535 .map_err(|_| Error::WorkflowStatePoisoned)?
536 .replay_time()
537 }
538}
539
540impl QueryContext {
541 pub fn replay_now(&self) -> Result<DateTime<Utc>> {
546 self.replay_time.ok_or_else(unavailable)
547 }
548}
549
550pub(super) fn snapshot_time(history: &[HistoryEvent], codec: &str) -> Option<DateTime<Utc>> {
551 let event = history.last()?;
552 if super::settled_at_run_close(event) {
553 return None;
554 }
555 if event.event_type == "WorkflowStarted" {
556 return start_time(history);
557 }
558 if !matches!(
559 event.event_type.as_str(),
560 "ActivityCompleted"
561 | "ActivityFailed"
562 | "ActivityTimedOut"
563 | "ActivityCancelled"
564 | "TimerFired"
565 | "ChildRunCompleted"
566 | "ChildRunFailed"
567 | "ChildRunCancelled"
568 | "ChildRunTerminated"
569 | "SignalApplied"
570 | "ConditionWaitSatisfied"
571 | "ConditionWaitTimedOut"
572 ) {
573 return None;
574 }
575 let commands = recorded_commands(
576 history,
577 codec,
578 WorkflowIdentity {
579 workflow_id: None,
580 run_id: None,
581 },
582 )
583 .ok()?;
584 Clock::new(history, &commands)
585 .boundaries
586 .get(&durable_event_sequence(event)?)
587 .and_then(|index| history.get(*index))
588 .and_then(|event| boundary_time(event, true))
589}
590
591pub(super) fn update_time(history: &[HistoryEvent], update_id: &str) -> Option<DateTime<Utc>> {
592 let mut events = history.iter().filter(|event| {
593 event.event_type == "UpdateAccepted"
594 && event.payload["update_id"].as_str() == Some(update_id)
595 });
596 let event = events.next()?;
597 if events.next().is_some() {
598 return None;
599 }
600 recorded_time(event, true)
601}
602
603#[cfg(test)]
604mod tests;