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