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
118const ENTRY_SCHEMA: &str = "durable-workflow.worker-replay-clock/v1";
120
121#[derive(Clone, Copy, Debug, PartialEq, Eq)]
123pub(super) struct Entry {
124 started_at: DateTime<Utc>,
125 redrive: bool,
126}
127
128fn strict_entry_time(text: &str) -> Option<DateTime<Utc>> {
130 let bytes = text.as_bytes();
131 let shape = bytes.len() == 27
132 && bytes.iter().enumerate().all(|(index, byte)| match index {
133 4 | 7 => *byte == b'-',
134 10 => *byte == b'T',
135 13 | 16 => *byte == b':',
136 19 => *byte == b'.',
137 26 => *byte == b'Z',
138 _ => byte.is_ascii_digit(),
139 });
140 let time = DateTime::parse_from_rfc3339(text).ok().filter(|_| shape)?;
141 (time.timestamp_subsec_nanos() < 1_000_000_000).then(|| time.with_timezone(&Utc))
143}
144
145pub(super) fn entry(task: &Value) -> Option<Entry> {
148 entry_for(
149 task.get("replay_clock"),
150 task.get("run_id").and_then(Value::as_str),
151 )
152}
153
154pub(super) fn entry_for(carrier: Option<&Value>, run_id: Option<&str>) -> Option<Entry> {
157 const KEYS: [&str; 4] = ["schema", "workflow_run_id", "started_at", "source"];
158 let carrier = carrier?.as_object()?;
159 let run_id = run_id.filter(|id| !id.is_empty())?;
160 if carrier.len() != KEYS.len()
161 || !KEYS.iter().all(|key| carrier.contains_key(*key))
162 || carrier.get("schema").and_then(Value::as_str) != Some(ENTRY_SCHEMA)
163 || carrier.get("workflow_run_id").and_then(Value::as_str) != Some(run_id)
164 {
165 return None;
166 }
167 let redrive = match carrier.get("source").and_then(Value::as_str)? {
168 "run_started_at" => false,
169 "redrive_replayed_started_at" => true,
170 _ => return None,
171 };
172 Some(Entry {
173 started_at: strict_entry_time(carrier.get("started_at")?.as_str()?)?,
174 redrive,
175 })
176}
177
178fn present(value: Option<&Value>) -> bool {
180 value.is_some_and(|value| !value.is_null())
181}
182
183#[derive(Clone, Copy, Debug, PartialEq, Eq)]
189pub(super) enum Attestation {
190 Unattested,
192 Unprovable,
196 Entry(Entry),
197}
198
199pub(super) fn attestation(task: &Value) -> Attestation {
200 let carrier = match task.get("replay_clock") {
201 None => return Attestation::Unattested,
202 Some(Value::Null) => return Attestation::Unprovable,
203 Some(carrier) => carrier,
204 };
205 let named = carrier.get("workflow_run_id").and_then(Value::as_str);
208 if entry_for(Some(carrier), named).is_none() {
209 return Attestation::Unprovable;
210 }
211 entry(task).map_or(Attestation::Unattested, Attestation::Entry)
214}
215
216fn declares_redrive(history: &[HistoryEvent]) -> bool {
218 history.iter().any(|event| match event.event_type.as_str() {
219 "WorkflowStarted" => {
220 event.payload["recovery_kind"] == "redrive"
221 || present(event.payload.get("replayed_started_at"))
222 || present(event.payload.get("resume_step_sequence"))
223 }
224 "StartAccepted" => event.payload["outcome"] == "redriven",
225 _ => false,
226 })
227}
228
229#[derive(Debug)]
230pub(super) struct Clock {
231 time: Option<DateTime<Utc>>,
232 boundaries: HashMap<u64, usize>,
233 parallel_activities: parallel::Members,
234 parallel_timers: parallel::Members,
235 parallel_children: parallel::Members,
236 at_entry: bool,
238 entry_unattested: bool,
240 unattested_entry_read: bool,
243}
244
245enum BoundaryKind {
246 Activity,
247 Timer,
248 Child,
249 Signal,
250 Condition,
251}
252
253fn supported_boundary(command: &RecordedCommand) -> Option<(u64, BoundaryKind)> {
254 match command {
255 RecordedCommand::Activity {
256 sequence,
257 outcome: Some(_),
258 parallel_group_path,
259 ..
260 } if parallel_group_path.as_ref().is_none_or(Vec::is_empty) => {
261 Some((*sequence, BoundaryKind::Activity))
262 }
263 RecordedCommand::Timer {
264 sequence,
265 fired: true,
266 parallel_group_path,
267 ..
268 } if parallel_group_path.as_ref().is_none_or(Vec::is_empty) => {
269 Some((*sequence, BoundaryKind::Timer))
270 }
271 RecordedCommand::ChildWorkflow {
272 sequence,
273 outcome: Some(_),
274 parallel_group_path,
275 ..
276 } if parallel_group_path.as_ref().is_none_or(Vec::is_empty) => {
277 Some((*sequence, BoundaryKind::Child))
278 }
279 RecordedCommand::SignalWait {
280 sequence,
281 value: Some(_),
282 parallel_group_path,
283 ..
284 } if parallel_group_path.as_ref().is_none_or(Vec::is_empty) => {
285 Some((*sequence, BoundaryKind::Signal))
286 }
287 RecordedCommand::ConditionWait {
288 sequence,
289 result: Some(_),
290 parallel_group_path,
291 ..
292 } if parallel_group_path.as_ref().is_none_or(Vec::is_empty) => {
293 Some((*sequence, BoundaryKind::Condition))
294 }
295 _ => None,
296 }
297}
298
299fn signal_boundary(history: &[HistoryEvent], indices: &[usize], sequence: u64) -> Option<usize> {
300 let (opened, timers, applied) = match indices {
301 [opened, applied] => (opened, &[][..], applied),
302 [opened, _, _, applied] => (opened, &indices[1..3], applied),
303 _ => return None,
304 };
305 let open = &history[*opened];
306 let apply = &history[*applied];
307 if open.event_type != "SignalWaitOpened"
308 || apply.event_type != "SignalApplied"
309 || apply.payload.get("value").is_none_or(Value::is_null)
310 {
311 return None;
312 }
313 let events: Vec<_> = indices.iter().map(|&index| &history[index]).collect();
314 if super::recorded_parallel_group_path(&events, sequence)
315 .ok()?
316 .is_some_and(|path| !path.is_empty())
317 {
318 return None;
319 }
320 for event in &events {
321 if event.payload.get("sequence").and_then(Value::as_u64) != Some(sequence)
322 || event
323 .payload
324 .get("workflow_sequence")
325 .is_some_and(|value| value.as_u64() != Some(sequence))
326 {
327 return None;
328 }
329 }
330 for key in ["signal_wait_id", "signal_name"] {
331 let identity = open
332 .payload
333 .get(key)?
334 .as_str()
335 .filter(|value| !value.is_empty())?;
336 if events
337 .iter()
338 .any(|event| event.payload.get(key).and_then(Value::as_str) != Some(identity))
339 {
340 return None;
341 }
342 }
343 signal_timeout(open, apply, history, timers)?;
344 Some(*applied)
345}
346
347fn signal_timeout(
348 open: &HistoryEvent,
349 apply: &HistoryEvent,
350 history: &[HistoryEvent],
351 timers: &[usize],
352) -> Option<()> {
353 let timeout = open.payload.get("timeout_seconds").filter(|v| !v.is_null());
354 let seconds = match timeout {
355 Some(value) => Some(value.as_u64()?),
356 None => None,
357 };
358 if apply
359 .payload
360 .get("timeout_seconds")
361 .filter(|value| !value.is_null())
362 .is_some_and(|value| Some(value) != timeout)
363 {
364 return None;
365 }
366 let [scheduled, cancelled] = timers else {
367 return timers.is_empty().then_some(());
370 };
371 let schedule = &history[*scheduled];
372 let cancel = &history[*cancelled];
373 if seconds? == 0
374 || schedule.event_type != "TimerScheduled"
375 || cancel.event_type != "TimerCancelled"
376 || parse(cancel.payload.get("cancelled_at")).is_none()
377 || cancel
378 .payload
379 .get("cancellation_scope")
380 .is_some_and(|v| !v.is_null())
381 {
382 return None;
383 }
384 for event in [schedule, cancel] {
385 if event.payload["timer_kind"] != "signal_timeout"
386 || event.payload.get("delay_seconds").and_then(Value::as_u64) != seconds
387 {
388 return None;
389 }
390 }
391 let timer_id = schedule
392 .payload
393 .get("timer_id")?
394 .as_str()
395 .filter(|v| !v.is_empty())?;
396 if cancel.payload.get("timer_id").and_then(Value::as_str) != Some(timer_id)
397 || parse(schedule.payload.get("fire_at")).is_none()
398 || cancel.payload.get("fire_at") != schedule.payload.get("fire_at")
399 {
400 return None;
401 }
402 Some(())
403}
404
405fn child_boundary(history: &[HistoryEvent], indices: &[usize]) -> Option<usize> {
406 child_lifecycle(history, indices)?
407}
408
409fn child_lifecycle(history: &[HistoryEvent], indices: &[usize]) -> Option<Option<usize>> {
410 let (&scheduled, terminal) = match indices {
413 [scheduled] => (scheduled, None),
414 [scheduled, started] if history[*started].event_type == "ChildRunStarted" => {
415 (scheduled, None)
416 }
417 [scheduled, terminal] => (scheduled, Some(*terminal)),
418 [scheduled, started, terminal] if history[*started].event_type == "ChildRunStarted" => {
419 (scheduled, Some(*terminal))
420 }
421 _ => return None,
422 };
423 let schedule = &history[scheduled];
424 if schedule.event_type != "ChildWorkflowScheduled"
425 || terminal.is_some_and(|terminal| {
426 !matches!(
427 history[terminal].event_type.as_str(),
428 "ChildRunCompleted" | "ChildRunFailed" | "ChildRunCancelled" | "ChildRunTerminated"
429 )
430 })
431 {
432 return None;
433 }
434 for key in [
435 "child_call_id",
436 "child_workflow_instance_id",
437 "child_workflow_run_id",
438 "child_workflow_type",
439 ] {
440 let identity = schedule
441 .payload
442 .get(key)?
443 .as_str()
444 .filter(|id| !id.is_empty())?;
445 if indices
446 .iter()
447 .any(|&index| history[index].payload.get(key).and_then(Value::as_str) != Some(identity))
448 {
449 return None;
452 }
453 }
454 Some(terminal)
455}
456
457impl Clock {
458 pub(super) fn new(history: &[HistoryEvent], commands: &[RecordedCommand]) -> Self {
459 let supported: HashMap<_, _> = commands.iter().filter_map(supported_boundary).collect();
460 let mut boundaries = HashMap::new();
461 let mut children: HashMap<u64, Vec<usize>> = HashMap::new();
462 let mut signals: HashMap<u64, Vec<usize>> = HashMap::new();
463 let mut conditions: HashMap<u64, Vec<usize>> = HashMap::new();
464 let mut signal_timers: HashMap<&str, Vec<usize>> = HashMap::new();
465 for (index, event) in history.iter().enumerate() {
466 if event.event_type.starts_with("Timer") {
467 if let Some(wait) = event.payload.get("signal_wait_id").and_then(Value::as_str) {
468 signal_timers.entry(wait).or_default().push(index);
469 }
470 }
471 let Some(sequence) = durable_event_sequence(event) else {
472 continue;
473 };
474 let matched = match supported.get(&sequence) {
475 Some(BoundaryKind::Activity) => matches!(
476 event.event_type.as_str(),
477 "ActivityCompleted"
478 | "ActivityFailed"
479 | "ActivityTimedOut"
480 | "ActivityCancelled"
481 ),
482 Some(BoundaryKind::Timer) => {
483 event.event_type == "TimerFired" && !is_internal_timer_event(event)
484 }
485 Some(BoundaryKind::Child) => {
486 if event.event_type == "ChildWorkflowScheduled"
487 || event.event_type.starts_with("ChildRun")
488 {
489 children.entry(sequence).or_default().push(index);
490 }
491 false
492 }
493 Some(BoundaryKind::Signal) => {
494 if is_recorded_signal_wait_event(event) || event.event_type.starts_with("Timer")
495 {
496 signals.entry(sequence).or_default().push(index);
497 }
498 false
499 }
500 Some(BoundaryKind::Condition) => {
501 if super::is_recorded_condition_wait_event(event) {
502 conditions.entry(sequence).or_default().push(index);
503 }
504 false
505 }
506 None => false,
507 };
508 if matched {
509 boundaries.entry(sequence).or_insert(index);
510 }
511 }
512 for (sequence, indices) in children {
513 if let Some(index) = child_boundary(history, &indices) {
514 boundaries.insert(sequence, index);
515 }
516 }
517 for (sequence, mut indices) in signals {
518 let related: Vec<_> = indices
521 .iter()
522 .filter_map(|&index| history[index].payload.get("signal_wait_id")?.as_str())
523 .filter_map(|wait| signal_timers.get(wait))
524 .flatten()
525 .copied()
526 .collect();
527 indices.extend(related);
528 indices.sort_unstable();
529 indices.dedup();
530 if let Some(index) = signal_boundary(history, &indices, sequence) {
531 boundaries.insert(sequence, index);
532 }
533 }
534 let condition_timeouts = condition_timeout::Index::new(history);
535 boundaries.extend(conditions.into_iter().filter_map(|(sequence, indices)| {
536 condition::boundary(history, &indices, sequence)
537 .or_else(|| condition_timeouts.boundary(history, &indices, sequence))
538 .map(|index| (sequence, index))
539 }));
540 Self {
543 time: start_time(history),
544 boundaries,
545 parallel_activities: parallel_activity::members(history, commands),
546 parallel_timers: parallel_timer::members(history, commands),
547 parallel_children: parallel_child::members(history, commands),
548 at_entry: true,
549 entry_unattested: false,
550 unattested_entry_read: false,
551 }
552 }
553
554 pub(super) fn unavailable(&mut self) {
555 self.time = None;
556 self.at_entry = false;
557 }
558
559 fn adopt_entry(&mut self, history: &[HistoryEvent], entry: Entry) {
563 let disagrees = history.iter().any(|event| {
567 event.event_type == "WorkflowStarted"
568 && event
569 .payload
570 .get("replayed_started_at")
571 .filter(|value| !value.is_null())
572 .is_some_and(|recorded| parse(Some(recorded)) != Some(entry.started_at))
573 });
574 if self.time.is_none() && entry.redrive == declares_redrive(history) && !disagrees {
575 self.time = Some(entry.started_at);
576 }
577 }
578}
579
580impl WorkflowState {
581 pub(super) fn adopt_replay_entry(&mut self, entry: Option<Entry>) {
584 if let Some(entry) = entry {
585 self.replay_clock.adopt_entry(&self.history_events, entry);
586 }
587 }
588
589 pub(super) fn attest_replay_entry(&mut self, attestation: Attestation) {
592 match attestation {
593 Attestation::Unattested => self.replay_clock.entry_unattested = true,
594 Attestation::Unprovable => {}
595 Attestation::Entry(entry) => self.adopt_replay_entry(Some(entry)),
596 }
597 }
598
599 pub(super) fn read_unattested_replay_entry(&self) -> bool {
603 self.replay_clock.unattested_entry_read
604 }
605
606 pub(super) fn consume_replay_sequence(
607 &mut self,
608 sequence: u64,
609 path: &[ParallelGroupMetadata],
610 ) {
611 if path.is_empty() {
612 self.observe_replay_sequence(sequence);
613 } else {
614 self.replay_clock.unavailable();
615 }
616 self.advance_cancellation_sequence(sequence, path);
617 }
618
619 pub(super) fn consume_unproven_boundary(&mut self, path: &[ParallelGroupMetadata]) {
620 if path.is_empty() {
621 self.observation_pending = false;
622 }
623 self.replay_clock.unavailable();
624 self.unavailable_cancellation_boundary(path);
625 }
626
627 pub(super) fn consume_replay_group(&mut self, sequences: &[u64], failed: Option<u64>) {
628 self.observation_pending = false;
629 self.replay_clock.at_entry = false;
632 self.replay_clock.time = if QUERY_REPLAY.with(Cell::get) {
633 None
634 } else {
635 self.replay_clock
636 .parallel_activities
637 .consumed_time(&self.history_events, sequences, failed)
638 .or_else(|| {
639 self.replay_clock.parallel_timers.consumed_time(
640 &self.history_events,
641 sequences,
642 failed,
643 )
644 })
645 .or_else(|| {
646 self.replay_clock.parallel_children.consumed_time(
647 &self.history_events,
648 sequences,
649 failed,
650 )
651 })
652 };
653 self.advance_cancellation_sequences(sequences, failed);
654 }
655
656 pub(super) fn consume_replay_selection(&mut self, group: &str) {
657 self.observation_pending = false;
658 self.replay_clock.unavailable();
659 self.advance_cancellation_selection(group);
660 }
661
662 pub(super) fn consume_replay_receipt(&mut self, group: &str, sequence: u64) {
663 self.observation_pending = false;
664 self.replay_clock.unavailable();
665 self.advance_cancellation_receipt(group, sequence);
666 }
667
668 pub(super) fn consume_replay_handle(&mut self, handle: &DurableOperationHandle, failed: bool) {
669 self.observation_pending = false;
670 self.replay_clock.unavailable();
671 self.advance_cancellation_handle(handle, failed);
672 }
673
674 pub(super) fn replay_time(&self) -> Result<DateTime<Utc>> {
675 if self.cancellation_clock.is_some() {
678 return Err(unavailable());
679 }
680 self.replay_clock.time.ok_or_else(unavailable)
681 }
682
683 fn read_replay_time(&mut self) -> Result<DateTime<Utc>> {
685 let time = self.replay_time();
686 if time.is_err()
687 && self.cancellation_clock.is_none()
688 && self.replay_clock.at_entry
689 && self.replay_clock.entry_unattested
690 {
691 self.replay_clock.unattested_entry_read = true;
692 }
693 time
694 }
695
696 pub(super) fn observe_replay_sequence(&mut self, sequence: u64) {
697 self.observation_pending = false;
698 self.replay_clock.at_entry = false;
699 self.replay_clock.time = self
700 .replay_clock
701 .boundaries
702 .get(&sequence)
703 .and_then(|index| self.history_events.get(*index))
704 .and_then(|event| boundary_time(event, QUERY_REPLAY.with(Cell::get)));
705 }
706}
707
708impl WorkflowContext {
709 pub fn replay_now(&self) -> Result<DateTime<Utc>> {
743 let active = ACTIVE.with(|active| active.borrow().as_ref().and_then(Weak::upgrade));
744 if !active.is_some_and(|active| Arc::ptr_eq(&active, &self.state)) {
745 return Err(unavailable());
746 }
747 self.state
748 .lock()
749 .map_err(|_| Error::WorkflowStatePoisoned)?
750 .read_replay_time()
751 }
752}
753
754impl QueryContext {
755 pub fn replay_now(&self) -> Result<DateTime<Utc>> {
760 self.replay_time.ok_or_else(unavailable)
761 }
762}
763
764pub(super) fn snapshot_time(history: &[HistoryEvent], codec: &str) -> Option<DateTime<Utc>> {
765 let event = history.last()?;
766 if super::settled_at_run_close(event) {
767 return None;
768 }
769 if event.event_type == "WorkflowStarted" {
770 return start_time(history);
771 }
772 if !matches!(
773 event.event_type.as_str(),
774 "ActivityCompleted"
775 | "ActivityFailed"
776 | "ActivityTimedOut"
777 | "ActivityCancelled"
778 | "TimerFired"
779 | "ChildRunCompleted"
780 | "ChildRunFailed"
781 | "ChildRunCancelled"
782 | "ChildRunTerminated"
783 | "SignalApplied"
784 | "ConditionWaitSatisfied"
785 | "ConditionWaitTimedOut"
786 ) {
787 return None;
788 }
789 let commands = recorded_commands(
790 history,
791 codec,
792 WorkflowIdentity {
793 workflow_id: None,
794 run_id: None,
795 },
796 )
797 .ok()?;
798 Clock::new(history, &commands)
799 .boundaries
800 .get(&durable_event_sequence(event)?)
801 .and_then(|index| history.get(*index))
802 .and_then(|event| boundary_time(event, true))
803}
804
805pub(super) fn update_time(history: &[HistoryEvent], update_id: &str) -> Option<DateTime<Utc>> {
806 let mut events = history.iter().filter(|event| {
807 event.event_type == "UpdateAccepted"
808 && event.payload["update_id"].as_str() == Some(update_id)
809 });
810 let event = events.next()?;
811 if events.next().is_some() {
812 return None;
813 }
814 recorded_time(event, true)
815}
816
817#[cfg(test)]
818mod tests;