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
22#[derive(Clone, Copy)]
23pub(super) enum GroupFailure {
24 Legacy(u64),
25 FirstRecorded(u64),
26}
27
28impl GroupFailure {
29 fn sequence(self) -> u64 {
30 match self {
31 Self::Legacy(sequence) | Self::FirstRecorded(sequence) => sequence,
32 }
33 }
34}
35
36thread_local! {
37 static ACTIVE: RefCell<Option<Weak<Mutex<WorkflowState>>>> = const { RefCell::new(None) };
38 static QUERY_REPLAY: Cell<bool> = const { Cell::new(false) };
39}
40
41pub(super) struct Guard(Option<Weak<Mutex<WorkflowState>>>, bool);
42
43impl Guard {
44 pub(super) fn enter(context: &WorkflowContext) -> Self {
45 Self::scope(Some(Arc::downgrade(&context.state)), false)
46 }
47
48 pub(super) fn query(context: &WorkflowContext) -> Self {
49 Self::scope(Some(Arc::downgrade(&context.state)), true)
50 }
51
52 pub(super) fn unavailable() -> Self {
53 Self::scope(None, false)
54 }
55
56 fn scope(context: Option<Weak<Mutex<WorkflowState>>>, query: bool) -> Self {
57 Self(
58 ACTIVE.with(|active| active.replace(context)),
59 QUERY_REPLAY.with(|active| active.replace(query)),
60 )
61 }
62}
63
64impl Drop for Guard {
65 fn drop(&mut self) {
66 ACTIVE.with(|active| active.replace(self.0.take()));
67 QUERY_REPLAY.with(|active| active.set(self.1));
68 }
69}
70
71pub(super) fn observation_mode(context: &WorkflowContext) -> Option<bool> {
72 let active = ACTIVE.with(|active| active.borrow().as_ref().and_then(Weak::upgrade))?;
73 Arc::ptr_eq(&active, &context.state).then(|| QUERY_REPLAY.with(Cell::get))
74}
75
76fn unavailable() -> Error {
77 Error::ReplayClockUnavailable
78}
79
80fn parse(value: Option<&Value>) -> Option<DateTime<Utc>> {
81 DateTime::parse_from_rfc3339(value?.as_str()?)
82 .ok()
83 .map(|time| time.with_timezone(&Utc))
84}
85
86fn recorded_time(event: &HistoryEvent, reused: bool) -> Option<DateTime<Utc>> {
87 if reused && event.payload.get("reused_recorded_at").is_some() {
88 return parse(event.payload.get("reused_recorded_at"));
89 }
90 parse(
92 event
93 .raw
94 .get("timestamp")
95 .or_else(|| event.raw.get("recorded_at")),
96 )
97}
98
99fn boundary_time(event: &HistoryEvent, query: bool) -> Option<DateTime<Utc>> {
100 let internal = event.event_type == "TimerFired" && is_internal_timer_event(event);
101 if internal {
102 return if query {
105 None
106 } else {
107 parse(event.raw.get("recorded_at"))
108 };
109 }
110 recorded_time(
111 event,
112 matches!(
113 event.event_type.as_str(),
114 "ActivityCompleted" | "TimerFired" | "SignalApplied"
115 ),
116 )
117}
118
119fn start_time(history: &[HistoryEvent]) -> Option<DateTime<Utc>> {
120 let mut starts = history
121 .iter()
122 .filter(|event| event.event_type == "WorkflowStarted");
123 let start = starts.next()?;
124 if starts.next().is_some() || start.payload["recovery_kind"] != "redrive" {
125 return None;
128 }
129 parse(start.payload.get("replayed_started_at"))
130}
131
132const ENTRY_SCHEMA: &str = "durable-workflow.worker-replay-clock/v1";
134
135#[derive(Clone, Copy, Debug, PartialEq, Eq)]
137pub(super) struct Entry {
138 started_at: DateTime<Utc>,
139 redrive: bool,
140}
141
142fn strict_entry_time(text: &str) -> Option<DateTime<Utc>> {
144 let bytes = text.as_bytes();
145 let shape = bytes.len() == 27
146 && bytes.iter().enumerate().all(|(index, byte)| match index {
147 4 | 7 => *byte == b'-',
148 10 => *byte == b'T',
149 13 | 16 => *byte == b':',
150 19 => *byte == b'.',
151 26 => *byte == b'Z',
152 _ => byte.is_ascii_digit(),
153 });
154 let time = DateTime::parse_from_rfc3339(text).ok().filter(|_| shape)?;
155 (time.timestamp_subsec_nanos() < 1_000_000_000).then(|| time.with_timezone(&Utc))
157}
158
159pub(super) fn entry(task: &Value) -> Option<Entry> {
162 entry_for(
163 task.get("replay_clock"),
164 task.get("run_id").and_then(Value::as_str),
165 )
166}
167
168pub(super) fn entry_for(carrier: Option<&Value>, run_id: Option<&str>) -> Option<Entry> {
171 const KEYS: [&str; 4] = ["schema", "workflow_run_id", "started_at", "source"];
172 let carrier = carrier?.as_object()?;
173 let run_id = run_id.filter(|id| !id.is_empty())?;
174 if carrier.len() != KEYS.len()
175 || !KEYS.iter().all(|key| carrier.contains_key(*key))
176 || carrier.get("schema").and_then(Value::as_str) != Some(ENTRY_SCHEMA)
177 || carrier.get("workflow_run_id").and_then(Value::as_str) != Some(run_id)
178 {
179 return None;
180 }
181 let redrive = match carrier.get("source").and_then(Value::as_str)? {
182 "run_started_at" => false,
183 "redrive_replayed_started_at" => true,
184 _ => return None,
185 };
186 Some(Entry {
187 started_at: strict_entry_time(carrier.get("started_at")?.as_str()?)?,
188 redrive,
189 })
190}
191
192fn present(value: Option<&Value>) -> bool {
194 value.is_some_and(|value| !value.is_null())
195}
196
197#[derive(Clone, Copy, Debug, PartialEq, Eq)]
203pub(super) enum Attestation {
204 Unattested,
206 Unprovable,
210 Entry(Entry),
211}
212
213pub(super) fn attestation(task: &Value) -> Attestation {
214 let carrier = match task.get("replay_clock") {
215 None => return Attestation::Unattested,
216 Some(Value::Null) => return Attestation::Unprovable,
217 Some(carrier) => carrier,
218 };
219 let named = carrier.get("workflow_run_id").and_then(Value::as_str);
222 if entry_for(Some(carrier), named).is_none() {
223 return Attestation::Unprovable;
224 }
225 entry(task).map_or(Attestation::Unattested, Attestation::Entry)
228}
229
230fn declares_redrive(history: &[HistoryEvent]) -> bool {
232 history.iter().any(|event| match event.event_type.as_str() {
233 "WorkflowStarted" => {
234 event.payload["recovery_kind"] == "redrive"
235 || present(event.payload.get("replayed_started_at"))
236 || present(event.payload.get("resume_step_sequence"))
237 }
238 "StartAccepted" => event.payload["outcome"] == "redriven",
239 _ => false,
240 })
241}
242
243#[derive(Debug)]
244pub(super) struct Clock {
245 time: Option<DateTime<Utc>>,
246 boundaries: HashMap<u64, usize>,
247 selections: HashMap<String, Option<usize>>,
248 fresh_selection_start: Option<u64>,
249 parallel_activities: parallel::Members,
250 parallel_timers: parallel::Members,
251 parallel_children: parallel::Members,
252 at_entry: bool,
254 entry_unattested: bool,
256 unattested_entry_read: bool,
259}
260
261enum BoundaryKind {
262 Activity,
263 Timer,
264 Child,
265 Signal,
266 Condition,
267}
268
269fn supported_boundary(command: &RecordedCommand) -> Option<(u64, BoundaryKind)> {
270 match command {
271 RecordedCommand::Activity {
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::Activity))
278 }
279 RecordedCommand::Timer {
280 sequence,
281 fired: true,
282 parallel_group_path,
283 ..
284 } if parallel_group_path.as_ref().is_none_or(Vec::is_empty) => {
285 Some((*sequence, BoundaryKind::Timer))
286 }
287 RecordedCommand::ChildWorkflow {
288 sequence,
289 outcome: Some(_),
290 parallel_group_path,
291 ..
292 } if parallel_group_path.as_ref().is_none_or(Vec::is_empty) => {
293 Some((*sequence, BoundaryKind::Child))
294 }
295 RecordedCommand::SignalWait {
296 sequence,
297 value: Some(_),
298 parallel_group_path,
299 ..
300 } if parallel_group_path.as_ref().is_none_or(Vec::is_empty) => {
301 Some((*sequence, BoundaryKind::Signal))
302 }
303 RecordedCommand::ConditionWait {
304 sequence,
305 result: Some(_),
306 parallel_group_path,
307 ..
308 } if parallel_group_path.as_ref().is_none_or(Vec::is_empty) => {
309 Some((*sequence, BoundaryKind::Condition))
310 }
311 _ => None,
312 }
313}
314
315fn signal_boundary(history: &[HistoryEvent], indices: &[usize], sequence: u64) -> Option<usize> {
316 let (opened, timers, applied) = match indices {
317 [opened, applied] => (opened, &[][..], applied),
318 [opened, _, _, applied] => (opened, &indices[1..3], applied),
319 _ => return None,
320 };
321 let open = &history[*opened];
322 let apply = &history[*applied];
323 if open.event_type != "SignalWaitOpened"
324 || apply.event_type != "SignalApplied"
325 || apply.payload.get("value").is_none_or(Value::is_null)
326 {
327 return None;
328 }
329 let events: Vec<_> = indices.iter().map(|&index| &history[index]).collect();
330 if super::recorded_parallel_group_path(&events, sequence)
331 .ok()?
332 .is_some_and(|path| !path.is_empty())
333 {
334 return None;
335 }
336 for event in &events {
337 if event.payload.get("sequence").and_then(Value::as_u64) != Some(sequence)
338 || event
339 .payload
340 .get("workflow_sequence")
341 .is_some_and(|value| value.as_u64() != Some(sequence))
342 {
343 return None;
344 }
345 }
346 for key in ["signal_wait_id", "signal_name"] {
347 let identity = open
348 .payload
349 .get(key)?
350 .as_str()
351 .filter(|value| !value.is_empty())?;
352 if events
353 .iter()
354 .any(|event| event.payload.get(key).and_then(Value::as_str) != Some(identity))
355 {
356 return None;
357 }
358 }
359 signal_timeout(open, apply, history, timers)?;
360 Some(*applied)
361}
362
363fn signal_timeout(
364 open: &HistoryEvent,
365 apply: &HistoryEvent,
366 history: &[HistoryEvent],
367 timers: &[usize],
368) -> Option<()> {
369 let timeout = open.payload.get("timeout_seconds").filter(|v| !v.is_null());
370 let seconds = match timeout {
371 Some(value) => Some(value.as_u64()?),
372 None => None,
373 };
374 if apply
375 .payload
376 .get("timeout_seconds")
377 .filter(|value| !value.is_null())
378 .is_some_and(|value| Some(value) != timeout)
379 {
380 return None;
381 }
382 let [scheduled, cancelled] = timers else {
383 return timers.is_empty().then_some(());
386 };
387 let schedule = &history[*scheduled];
388 let cancel = &history[*cancelled];
389 if seconds? == 0
390 || schedule.event_type != "TimerScheduled"
391 || cancel.event_type != "TimerCancelled"
392 || parse(cancel.payload.get("cancelled_at")).is_none()
393 || cancel
394 .payload
395 .get("cancellation_scope")
396 .is_some_and(|v| !v.is_null())
397 {
398 return None;
399 }
400 for event in [schedule, cancel] {
401 if event.payload["timer_kind"] != "signal_timeout"
402 || event.payload.get("delay_seconds").and_then(Value::as_u64) != seconds
403 {
404 return None;
405 }
406 }
407 let timer_id = schedule
408 .payload
409 .get("timer_id")?
410 .as_str()
411 .filter(|v| !v.is_empty())?;
412 if cancel.payload.get("timer_id").and_then(Value::as_str) != Some(timer_id)
413 || parse(schedule.payload.get("fire_at")).is_none()
414 || cancel.payload.get("fire_at") != schedule.payload.get("fire_at")
415 {
416 return None;
417 }
418 Some(())
419}
420
421fn child_boundary(history: &[HistoryEvent], indices: &[usize]) -> Option<usize> {
422 child_lifecycle(history, indices)?
423}
424
425fn child_lifecycle(history: &[HistoryEvent], indices: &[usize]) -> Option<Option<usize>> {
426 let (&scheduled, terminal) = match indices {
429 [scheduled] => (scheduled, None),
430 [scheduled, started] if history[*started].event_type == "ChildRunStarted" => {
431 (scheduled, None)
432 }
433 [scheduled, terminal] => (scheduled, Some(*terminal)),
434 [scheduled, started, terminal] if history[*started].event_type == "ChildRunStarted" => {
435 (scheduled, Some(*terminal))
436 }
437 _ => return None,
438 };
439 let schedule = &history[scheduled];
440 if schedule.event_type != "ChildWorkflowScheduled"
441 || terminal.is_some_and(|terminal| {
442 !matches!(
443 history[terminal].event_type.as_str(),
444 "ChildRunCompleted" | "ChildRunFailed" | "ChildRunCancelled" | "ChildRunTerminated"
445 )
446 })
447 {
448 return None;
449 }
450 for key in [
451 "child_call_id",
452 "child_workflow_instance_id",
453 "child_workflow_run_id",
454 "child_workflow_type",
455 ] {
456 let identity = schedule
457 .payload
458 .get(key)?
459 .as_str()
460 .filter(|id| !id.is_empty())?;
461 if indices
462 .iter()
463 .any(|&index| history[index].payload.get(key).and_then(Value::as_str) != Some(identity))
464 {
465 return None;
468 }
469 }
470 Some(terminal)
471}
472
473impl Clock {
474 pub(super) fn new(history: &[HistoryEvent], commands: &[RecordedCommand]) -> Self {
475 let supported: HashMap<_, _> = commands.iter().filter_map(supported_boundary).collect();
476 let mut boundaries = HashMap::new();
477 let mut selections = HashMap::new();
478 let mut children: HashMap<u64, Vec<usize>> = HashMap::new();
479 let mut signals: HashMap<u64, Vec<usize>> = HashMap::new();
480 let mut conditions: HashMap<u64, Vec<usize>> = HashMap::new();
481 let mut signal_timers: HashMap<&str, Vec<usize>> = HashMap::new();
482 for (index, event) in history.iter().enumerate() {
483 if event.event_type == "SelectionResolved" {
484 if let Some(group) = event.payload["selection_group_id"].as_str() {
485 selections
486 .entry(group.to_owned())
487 .and_modify(|index| *index = None)
488 .or_insert(Some(index));
489 }
490 continue;
491 }
492 if event.event_type.starts_with("Timer") {
493 if let Some(wait) = event.payload.get("signal_wait_id").and_then(Value::as_str) {
494 signal_timers.entry(wait).or_default().push(index);
495 }
496 }
497 let Some(sequence) = durable_event_sequence(event) else {
498 continue;
499 };
500 let matched = match supported.get(&sequence) {
501 Some(BoundaryKind::Activity) => matches!(
502 event.event_type.as_str(),
503 "ActivityCompleted"
504 | "ActivityFailed"
505 | "ActivityTimedOut"
506 | "ActivityCancelled"
507 ),
508 Some(BoundaryKind::Timer) => {
509 event.event_type == "TimerFired" && !is_internal_timer_event(event)
510 }
511 Some(BoundaryKind::Child) => {
512 if event.event_type == "ChildWorkflowScheduled"
513 || event.event_type.starts_with("ChildRun")
514 {
515 children.entry(sequence).or_default().push(index);
516 }
517 false
518 }
519 Some(BoundaryKind::Signal) => {
520 if is_recorded_signal_wait_event(event) || event.event_type.starts_with("Timer")
521 {
522 signals.entry(sequence).or_default().push(index);
523 }
524 false
525 }
526 Some(BoundaryKind::Condition) => {
527 if super::is_recorded_condition_wait_event(event) {
528 conditions.entry(sequence).or_default().push(index);
529 }
530 false
531 }
532 None => false,
533 };
534 if matched {
535 boundaries.entry(sequence).or_insert(index);
536 }
537 }
538 for (sequence, indices) in children {
539 if let Some(index) = child_boundary(history, &indices) {
540 boundaries.insert(sequence, index);
541 }
542 }
543 for (sequence, mut indices) in signals {
544 let related: Vec<_> = indices
547 .iter()
548 .filter_map(|&index| history[index].payload.get("signal_wait_id")?.as_str())
549 .filter_map(|wait| signal_timers.get(wait))
550 .flatten()
551 .copied()
552 .collect();
553 indices.extend(related);
554 indices.sort_unstable();
555 indices.dedup();
556 if let Some(index) = signal_boundary(history, &indices, sequence) {
557 boundaries.insert(sequence, index);
558 }
559 }
560 let condition_timeouts = condition_timeout::Index::new(history);
561 boundaries.extend(conditions.into_iter().filter_map(|(sequence, indices)| {
562 condition::boundary(history, &indices, sequence)
563 .or_else(|| condition_timeouts.boundary(history, &indices, sequence))
564 .map(|index| (sequence, index))
565 }));
566 let time = start_time(history);
567 let fresh_selection_start = if selections.is_empty() {
568 None
569 } else if declares_redrive(history) {
570 time.and_then(|_| {
571 history
572 .iter()
573 .find(|event| event.event_type == "WorkflowStarted")?
574 .payload["resume_step_sequence"]
575 .as_u64()
576 .filter(|sequence| *sequence > 0)
577 })
578 } else {
579 Some(0)
580 };
581 Self {
584 time,
585 boundaries,
586 selections,
587 fresh_selection_start,
588 parallel_activities: parallel_activity::members(history, commands),
589 parallel_timers: parallel_timer::members(history, commands),
590 parallel_children: parallel_child::members(history, commands),
591 at_entry: true,
592 entry_unattested: false,
593 unattested_entry_read: false,
594 }
595 }
596
597 pub(super) fn unavailable(&mut self) {
598 self.time = None;
599 self.at_entry = false;
600 }
601
602 fn selection_time(
603 &self,
604 history: &[HistoryEvent],
605 group: &str,
606 base_sequence: u64,
607 resolution_index: usize,
608 ) -> Option<DateTime<Utc>> {
609 let marker_index = self.selections.get(group).copied().flatten()?;
610 if marker_index <= resolution_index || base_sequence < self.fresh_selection_start? {
611 return None;
612 }
613 let marker = &history[marker_index];
614 if marker.payload.get("reused_from_run_id").is_some()
617 || marker.payload.get("reused_recorded_at").is_some()
618 {
619 return None;
620 }
621 recorded_time(marker, false).filter(|time| {
622 let nanos = time.timestamp_subsec_nanos();
623 nanos < 1_000_000_000 && nanos % 1000 == 0
624 })
625 }
626
627 fn adopt_entry(&mut self, history: &[HistoryEvent], entry: Entry) {
631 let disagrees = history.iter().any(|event| {
635 event.event_type == "WorkflowStarted"
636 && event
637 .payload
638 .get("replayed_started_at")
639 .filter(|value| !value.is_null())
640 .is_some_and(|recorded| parse(Some(recorded)) != Some(entry.started_at))
641 });
642 if self.time.is_none() && entry.redrive == declares_redrive(history) && !disagrees {
643 self.time = Some(entry.started_at);
644 }
645 }
646}
647
648impl WorkflowState {
649 pub(super) fn adopt_replay_entry(&mut self, entry: Option<Entry>) {
652 if let Some(entry) = entry {
653 self.replay_clock.adopt_entry(&self.history_events, entry);
654 }
655 }
656
657 pub(super) fn attest_replay_entry(&mut self, attestation: Attestation) {
660 match attestation {
661 Attestation::Unattested => self.replay_clock.entry_unattested = true,
662 Attestation::Unprovable => {}
663 Attestation::Entry(entry) => self.adopt_replay_entry(Some(entry)),
664 }
665 }
666
667 pub(super) fn read_unattested_replay_entry(&self) -> bool {
671 self.replay_clock.unattested_entry_read
672 }
673
674 pub(super) fn consume_replay_sequence(
675 &mut self,
676 sequence: u64,
677 path: &[ParallelGroupMetadata],
678 ) {
679 if path.is_empty() {
680 self.observe_replay_sequence(sequence);
681 } else {
682 self.replay_clock.unavailable();
683 }
684 self.advance_cancellation_sequence(sequence, path);
685 }
686
687 pub(super) fn consume_unproven_boundary(&mut self, path: &[ParallelGroupMetadata]) {
688 if path.is_empty() {
689 self.observation_pending = false;
690 }
691 self.replay_clock.unavailable();
692 self.unavailable_cancellation_boundary(path);
693 }
694
695 pub(super) fn consume_replay_group(&mut self, sequences: &[u64], failed: Option<GroupFailure>) {
696 self.observation_pending = false;
697 self.replay_clock.at_entry = false;
700 self.replay_clock.time = if QUERY_REPLAY.with(Cell::get) {
701 None
702 } else {
703 parallel::Members::consumed_time(
704 &[
705 ("activity", &self.replay_clock.parallel_activities),
706 ("timer", &self.replay_clock.parallel_timers),
707 ("child", &self.replay_clock.parallel_children),
708 ],
709 &self.history_events,
710 sequences,
711 failed,
712 )
713 };
714 self.advance_cancellation_sequences(sequences, failed.map(GroupFailure::sequence));
715 }
716
717 pub(super) fn consume_replay_selection(
718 &mut self,
719 group: &str,
720 base_sequence: u64,
721 resolution_index: usize,
722 ) {
723 self.observation_pending = false;
724 self.replay_clock.at_entry = false;
725 self.replay_clock.time = self.replay_clock.selection_time(
726 &self.history_events,
727 group,
728 base_sequence,
729 resolution_index,
730 );
731 self.advance_cancellation_selection(group);
732 }
733
734 pub(super) fn consume_replay_receipt(&mut self, group: &str, sequence: u64) {
735 self.observation_pending = false;
736 self.replay_clock.unavailable();
737 self.advance_cancellation_receipt(group, sequence);
738 }
739
740 pub(super) fn consume_replay_handle(&mut self, handle: &DurableOperationHandle, failed: bool) {
741 self.observation_pending = false;
742 self.replay_clock.unavailable();
743 self.advance_cancellation_handle(handle, failed);
744 }
745
746 pub(super) fn replay_time(&self) -> Result<DateTime<Utc>> {
747 if self.cancellation_clock.is_some() {
750 return Err(unavailable());
751 }
752 self.replay_clock.time.ok_or_else(unavailable)
753 }
754
755 fn read_replay_time(&mut self) -> Result<DateTime<Utc>> {
757 let time = self.replay_time();
758 if time.is_err()
759 && self.cancellation_clock.is_none()
760 && self.replay_clock.at_entry
761 && self.replay_clock.entry_unattested
762 {
763 self.replay_clock.unattested_entry_read = true;
764 }
765 time
766 }
767
768 pub(super) fn observe_replay_sequence(&mut self, sequence: u64) {
769 self.observation_pending = false;
770 self.replay_clock.at_entry = false;
771 self.replay_clock.time = self
772 .replay_clock
773 .boundaries
774 .get(&sequence)
775 .and_then(|index| self.history_events.get(*index))
776 .and_then(|event| boundary_time(event, QUERY_REPLAY.with(Cell::get)));
777 }
778}
779
780impl WorkflowContext {
781 pub fn replay_now(&self) -> Result<DateTime<Utc>> {
817 let active = ACTIVE.with(|active| active.borrow().as_ref().and_then(Weak::upgrade));
818 if !active.is_some_and(|active| Arc::ptr_eq(&active, &self.state)) {
819 return Err(unavailable());
820 }
821 self.state
822 .lock()
823 .map_err(|_| Error::WorkflowStatePoisoned)?
824 .read_replay_time()
825 }
826}
827
828impl QueryContext {
829 pub fn replay_now(&self) -> Result<DateTime<Utc>> {
834 self.replay_time.ok_or_else(unavailable)
835 }
836}
837
838pub(super) fn snapshot_time(history: &[HistoryEvent], codec: &str) -> Option<DateTime<Utc>> {
839 let event = history.last()?;
840 if super::settled_at_run_close(event) {
841 return None;
842 }
843 if event.event_type == "WorkflowStarted" {
844 return start_time(history);
845 }
846 if !matches!(
847 event.event_type.as_str(),
848 "ActivityCompleted"
849 | "ActivityFailed"
850 | "ActivityTimedOut"
851 | "ActivityCancelled"
852 | "TimerFired"
853 | "ChildRunCompleted"
854 | "ChildRunFailed"
855 | "ChildRunCancelled"
856 | "ChildRunTerminated"
857 | "SignalApplied"
858 | "ConditionWaitSatisfied"
859 | "ConditionWaitTimedOut"
860 ) {
861 return None;
862 }
863 let commands = recorded_commands(
864 history,
865 codec,
866 WorkflowIdentity {
867 workflow_id: None,
868 run_id: None,
869 },
870 )
871 .ok()?;
872 Clock::new(history, &commands)
873 .boundaries
874 .get(&durable_event_sequence(event)?)
875 .and_then(|index| history.get(*index))
876 .and_then(|event| boundary_time(event, true))
877}
878
879pub(super) fn update_time(history: &[HistoryEvent], update_id: &str) -> Option<DateTime<Utc>> {
880 let mut events = history.iter().filter(|event| {
881 event.event_type == "UpdateAccepted"
882 && event.payload["update_id"].as_str() == Some(update_id)
883 });
884 let event = events.next()?;
885 if events.next().is_some() {
886 return None;
887 }
888 recorded_time(event, true)
889}
890
891#[cfg(test)]
892mod tests;