1use super::{
13 display::{DisplayRecordedRunInfo, DisplayRecordedRunInfoDetailed, RunListAlignment, Styles},
14 format::{
15 RUN_LOG_FILE_NAME, RecordedRunList, RunsJsonWritePermission, STORE_FORMAT_VERSION,
16 STORE_ZIP_FILE_NAME, StoreFormatVersion, StoreVersionIncompatibility,
17 store_format_version_for_new_run,
18 },
19 recorder::{RunRecorder, StoreSizes},
20 retention::{
21 PruneKind, PrunePlan, PruneResult, RecordRetentionPolicy, delete_orphaned_dirs, delete_runs,
22 },
23 run_id_index::{PrefixResolutionError, RunIdIndex, RunIdSelector, ShortestRunIdPrefix},
24};
25use crate::{
26 errors::{RunIdResolutionError, RunStoreError},
27 helpers::{ThemeCharacters, decimal_char_width},
28 redact::Redactor,
29};
30use camino::{Utf8Path, Utf8PathBuf};
31use chrono::{DateTime, FixedOffset, Local, TimeDelta, Utc};
32use debug_ignore::DebugIgnore;
33use quick_junit::ReportUuid;
34use semver::Version;
35use std::{
36 collections::{BTreeMap, HashMap, HashSet},
37 fmt,
38 fs::{File, TryLockError},
39 io,
40 num::NonZero,
41 thread,
42 time::{Duration, Instant},
43};
44
45static RUNS_LOCK_FILE_NAME: &str = "runs.lock";
46static RUNS_JSON_FILE_NAME: &str = "runs.json.zst";
47
48#[derive(Clone, Copy, Debug)]
52pub struct StoreRunsDir<'a>(&'a Utf8Path);
53
54impl<'a> StoreRunsDir<'a> {
55 pub fn new(path: &'a Utf8Path) -> Self {
57 Self(path)
58 }
59
60 pub fn run_dir(self, run_id: ReportUuid) -> Utf8PathBuf {
62 self.0.join(run_id.to_string())
63 }
64
65 pub fn run_files(self, run_id: ReportUuid) -> StoreRunFiles {
68 StoreRunFiles {
69 run_dir: self.run_dir(run_id),
70 }
71 }
72
73 pub fn as_path(self) -> &'a Utf8Path {
75 self.0
76 }
77}
78
79pub trait RunFilesExist {
83 fn store_zip_exists(&self) -> bool;
85 fn run_log_exists(&self) -> bool;
87}
88
89pub struct StoreRunFiles {
93 run_dir: Utf8PathBuf,
94}
95
96impl RunFilesExist for StoreRunFiles {
97 fn store_zip_exists(&self) -> bool {
98 self.run_dir.join(STORE_ZIP_FILE_NAME).exists()
99 }
100
101 fn run_log_exists(&self) -> bool {
102 self.run_dir.join(RUN_LOG_FILE_NAME).exists()
103 }
104}
105
106#[derive(Debug)]
112pub struct RunStore {
113 runs_dir: Utf8PathBuf,
114}
115
116impl RunStore {
117 pub fn new(store_dir: &Utf8Path) -> Result<Self, RunStoreError> {
121 let runs_dir = store_dir.join("runs");
122 std::fs::create_dir_all(&runs_dir).map_err(|error| RunStoreError::RunDirCreate {
123 run_dir: runs_dir.clone(),
124 error,
125 })?;
126
127 Ok(Self { runs_dir })
128 }
129
130 pub fn runs_dir(&self) -> StoreRunsDir<'_> {
132 StoreRunsDir(&self.runs_dir)
133 }
134
135 pub fn lock_shared(&self) -> Result<SharedLockedRunStore<'_>, RunStoreError> {
143 let lock_file_path = self.runs_dir.join(RUNS_LOCK_FILE_NAME);
144 let file = std::fs::OpenOptions::new()
145 .create(true)
146 .truncate(false)
147 .write(true)
148 .open(&lock_file_path)
149 .map_err(|error| RunStoreError::FileLock {
150 path: lock_file_path.clone(),
151 error,
152 })?;
153
154 acquire_lock_with_retry(&file, &lock_file_path, LockKind::Shared)?;
155 let result = read_runs_json(&self.runs_dir)?;
156 let run_id_index = RunIdIndex::new(&result.runs);
157
158 Ok(SharedLockedRunStore {
159 runs_dir: StoreRunsDir(&self.runs_dir),
160 locked_file: DebugIgnore(file),
161 runs: result.runs,
162 write_permission: result.write_permission,
163 run_id_index,
164 })
165 }
166
167 pub fn lock_exclusive(&self) -> Result<ExclusiveLockedRunStore<'_>, RunStoreError> {
175 let lock_file_path = self.runs_dir.join(RUNS_LOCK_FILE_NAME);
176 let file = std::fs::OpenOptions::new()
177 .create(true)
178 .truncate(false)
179 .write(true)
180 .open(&lock_file_path)
181 .map_err(|error| RunStoreError::FileLock {
182 path: lock_file_path.clone(),
183 error,
184 })?;
185
186 acquire_lock_with_retry(&file, &lock_file_path, LockKind::Exclusive)?;
187 let result = read_runs_json(&self.runs_dir)?;
188
189 Ok(ExclusiveLockedRunStore {
190 runs_dir: StoreRunsDir(&self.runs_dir),
191 locked_file: DebugIgnore(file),
192 runs: result.runs,
193 last_pruned_at: result.last_pruned_at,
194 write_permission: result.write_permission,
195 })
196 }
197}
198
199#[derive(Debug)]
204pub struct ExclusiveLockedRunStore<'store> {
205 runs_dir: StoreRunsDir<'store>,
206 #[expect(dead_code)]
208 locked_file: DebugIgnore<File>,
209 runs: Vec<RecordedRunInfo>,
210 last_pruned_at: Option<DateTime<Utc>>,
211 write_permission: RunsJsonWritePermission,
212}
213
214impl<'store> ExclusiveLockedRunStore<'store> {
215 pub fn runs_dir(&self) -> StoreRunsDir<'store> {
217 self.runs_dir
218 }
219
220 pub fn write_permission(&self) -> RunsJsonWritePermission {
224 self.write_permission
225 }
226
227 pub fn complete_run(
237 &mut self,
238 run_id: ReportUuid,
239 sizes: StoreSizes,
240 status: RecordedRunStatus,
241 duration_secs: Option<f64>,
242 ) -> Result<bool, RunStoreError> {
243 if let RunsJsonWritePermission::Denied {
244 file_version,
245 max_supported_version,
246 } = self.write_permission
247 {
248 return Err(RunStoreError::FormatVersionTooNew {
249 file_version,
250 max_supported_version,
251 });
252 }
253
254 let found = self.mark_run_completed_inner(run_id, sizes, status, duration_secs);
255 if found {
256 write_runs_json(self.runs_dir.as_path(), &self.runs, self.last_pruned_at)?;
257 }
258 Ok(found)
259 }
260
261 fn mark_run_completed_inner(
263 &mut self,
264 run_id: ReportUuid,
265 sizes: StoreSizes,
266 status: RecordedRunStatus,
267 duration_secs: Option<f64>,
268 ) -> bool {
269 for run in &mut self.runs {
270 if run.run_id == run_id {
271 run.sizes = RecordedSizes {
272 log: ComponentSizes {
273 compressed: sizes.log.compressed,
274 uncompressed: sizes.log.uncompressed,
275 entries: sizes.log.entries,
276 },
277 store: ComponentSizes {
278 compressed: sizes.store.compressed,
279 uncompressed: sizes.store.uncompressed,
280 entries: sizes.store.entries,
281 },
282 };
283 run.status = status;
284 run.duration_secs = duration_secs;
285 run.last_written_at = Local::now().fixed_offset();
286 return true;
287 }
288 }
289 false
290 }
291
292 pub fn prune(
309 &mut self,
310 policy: &RecordRetentionPolicy,
311 kind: PruneKind,
312 ) -> Result<PruneResult, RunStoreError> {
313 if let RunsJsonWritePermission::Denied {
314 file_version,
315 max_supported_version,
316 } = self.write_permission
317 {
318 return Err(RunStoreError::FormatVersionTooNew {
319 file_version,
320 max_supported_version,
321 });
322 }
323
324 let now = Utc::now();
325 let to_delete: HashSet<_> = policy
326 .compute_runs_to_delete(&self.runs, now)
327 .into_iter()
328 .collect();
329
330 let runs_dir = self.runs_dir();
331 let mut result = if to_delete.is_empty() {
332 PruneResult::default()
333 } else {
334 delete_runs(runs_dir, &mut self.runs, &to_delete)
335 };
336 result.kind = kind;
337
338 let known_runs: HashSet<_> = self.runs.iter().map(|r| r.run_id).collect();
339 delete_orphaned_dirs(self.runs_dir, &known_runs, &mut result);
340
341 if result.deleted_count > 0 || result.orphans_deleted > 0 {
342 self.last_pruned_at = Some(now);
344 write_runs_json(self.runs_dir.as_path(), &self.runs, self.last_pruned_at)?;
345 }
346
347 Ok(result)
348 }
349
350 pub fn prune_if_needed(
360 &mut self,
361 policy: &RecordRetentionPolicy,
362 ) -> Result<Option<PruneResult>, RunStoreError> {
363 const PRUNE_INTERVAL: TimeDelta = match TimeDelta::try_days(1) {
364 Some(d) => d,
365 None => panic!("1 day should always be a valid TimeDelta"),
366 };
367 const LIMIT_EXCEEDED_FACTOR: f64 = 1.5;
368
369 let now = Utc::now();
370
371 let time_since_last_prune = self
373 .last_pruned_at
374 .map(|last| now.signed_duration_since(last))
375 .unwrap_or(TimeDelta::MAX);
376
377 let should_prune = time_since_last_prune >= PRUNE_INTERVAL
378 || policy.limits_exceeded_by_factor(&self.runs, LIMIT_EXCEEDED_FACTOR);
379
380 if should_prune {
381 Ok(Some(self.prune(policy, PruneKind::Implicit)?))
382 } else {
383 Ok(None)
384 }
385 }
386
387 #[expect(clippy::too_many_arguments)]
399 pub(crate) fn create_run_recorder(
400 mut self,
401 run_id: ReportUuid,
402 nextest_version: Version,
403 started_at: DateTime<FixedOffset>,
404 cli_args: Vec<String>,
405 env_vars: BTreeMap<String, String>,
406 max_output_size: bytesize::ByteSize,
407 parent_run_id: Option<ReportUuid>,
408 ) -> Result<(RunRecorder, ShortestRunIdPrefix), RunStoreError> {
409 if let RunsJsonWritePermission::Denied {
410 file_version,
411 max_supported_version,
412 } = self.write_permission
413 {
414 return Err(RunStoreError::FormatVersionTooNew {
415 file_version,
416 max_supported_version,
417 });
418 }
419
420 let now = Local::now().fixed_offset();
426 let run = RecordedRunInfo {
427 run_id,
428 store_format_version: store_format_version_for_new_run(),
429 nextest_version,
430 started_at,
431 last_written_at: now,
432 duration_secs: None,
433 cli_args,
434 env_vars,
435 parent_run_id,
436 sizes: RecordedSizes::default(),
437 status: RecordedRunStatus::Incomplete,
438 };
439 self.runs.push(run);
440
441 if let Some(parent_run_id) = parent_run_id
443 && let Some(parent_run) = self.runs.iter_mut().find(|r| r.run_id == parent_run_id)
444 {
445 parent_run.last_written_at = now;
446 }
447
448 write_runs_json(self.runs_dir.as_path(), &self.runs, self.last_pruned_at)?;
449
450 let index = RunIdIndex::new(&self.runs);
452 let unique_prefix = index
453 .shortest_unique_prefix(run_id)
454 .expect("run was just added to the list");
455
456 let run_dir = self.runs_dir().run_dir(run_id);
461
462 let recorder = RunRecorder::new(run_dir, max_output_size)?;
463 Ok((recorder, unique_prefix))
464 }
465}
466
467#[derive(Clone, Debug)]
469pub struct RecordedRunInfo {
470 pub run_id: ReportUuid,
472 pub store_format_version: StoreFormatVersion,
476 pub nextest_version: Version,
478 pub started_at: DateTime<FixedOffset>,
480 pub last_written_at: DateTime<FixedOffset>,
485 pub duration_secs: Option<f64>,
489 pub cli_args: Vec<String>,
491 pub env_vars: BTreeMap<String, String>,
493 pub parent_run_id: Option<ReportUuid>,
497 pub sizes: RecordedSizes,
499 pub status: RecordedRunStatus,
501}
502
503#[derive(Clone, Copy, Debug, Default)]
505pub struct RecordedSizes {
506 pub log: ComponentSizes,
508 pub store: ComponentSizes,
510}
511
512#[derive(Clone, Copy, Debug, Default)]
514pub struct ComponentSizes {
515 pub compressed: u64,
517 pub uncompressed: u64,
519 pub entries: u64,
521}
522
523impl RecordedSizes {
524 pub fn total_compressed(&self) -> u64 {
526 self.log.compressed + self.store.compressed
527 }
528
529 pub fn total_uncompressed(&self) -> u64 {
531 self.log.uncompressed + self.store.uncompressed
532 }
533
534 pub fn total_entries(&self) -> u64 {
536 self.log.entries + self.store.entries
537 }
538}
539
540#[derive(Clone, Debug)]
542pub enum RecordedRunStatus {
543 Incomplete,
545 Completed(CompletedRunStats),
547 Cancelled(CompletedRunStats),
549 StressCompleted(StressCompletedRunStats),
551 StressCancelled(StressCompletedRunStats),
553 Unknown,
558}
559
560impl RecordedRunStatus {
561 pub fn short_status_str(&self) -> &'static str {
563 match self {
564 Self::Incomplete => "incomplete",
565 Self::Unknown => "unknown",
566 Self::Completed(_) => "completed",
567 Self::Cancelled(_) => "cancelled",
568 Self::StressCompleted(_) => "stress completed",
569 Self::StressCancelled(_) => "stress cancelled",
570 }
571 }
572
573 pub fn exit_code(&self) -> Option<i32> {
575 match self {
576 Self::Incomplete | Self::Unknown => None,
577 Self::Completed(stats) | Self::Cancelled(stats) => Some(stats.exit_code),
578 Self::StressCompleted(stats) | Self::StressCancelled(stats) => Some(stats.exit_code),
579 }
580 }
581}
582
583#[derive(Clone, Copy, Debug)]
585pub struct CompletedRunStats {
586 pub initial_run_count: usize,
588 pub passed: usize,
590 pub failed: usize,
592 pub exit_code: i32,
594}
595
596#[derive(Clone, Copy, Debug)]
598pub struct StressCompletedRunStats {
599 pub initial_iteration_count: Option<NonZero<u32>>,
604 pub success_count: u32,
606 pub failed_count: u32,
608 pub exit_code: i32,
610}
611
612#[derive(Clone, Debug)]
618pub enum ReplayabilityStatus {
619 Replayable,
623 NotReplayable(Vec<NonReplayableReason>),
627 Incomplete,
632}
633
634#[derive(Clone, Debug, PartialEq, Eq)]
636pub enum NonReplayableReason {
637 StoreVersionIncompatible {
641 incompatibility: StoreVersionIncompatibility,
643 },
644 MissingStoreZip,
646 MissingRunLog,
648 StatusUnknown,
652}
653
654impl fmt::Display for NonReplayableReason {
655 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
656 match self {
657 Self::StoreVersionIncompatible { incompatibility } => {
658 write!(f, "store format version incompatible: {}", incompatibility)
659 }
660 Self::MissingStoreZip => {
661 write!(f, "store.zip is missing")
662 }
663 Self::MissingRunLog => {
664 write!(f, "run.log.zst is missing")
665 }
666 Self::StatusUnknown => {
667 write!(f, "run status is unknown (from a newer nextest version)")
668 }
669 }
670 }
671}
672
673#[derive(Clone, Copy, Debug)]
675pub struct ResolveRunIdResult {
676 pub run_id: ReportUuid,
678}
679
680impl RecordedRunStatus {
681 pub fn passed_count_width(&self) -> usize {
686 match self {
687 Self::Incomplete | Self::Unknown => 0,
688 Self::Completed(stats) | Self::Cancelled(stats) => decimal_char_width(stats.passed),
689 Self::StressCompleted(stats) | Self::StressCancelled(stats) => {
690 decimal_char_width(stats.success_count)
691 }
692 }
693 }
694}
695
696impl RecordedRunInfo {
697 pub fn check_replayability(&self, files: &dyn RunFilesExist) -> ReplayabilityStatus {
709 let mut blocking = Vec::new();
710 let mut is_incomplete = false;
711
712 if let Err(incompatibility) = self
714 .store_format_version
715 .check_readable_by(STORE_FORMAT_VERSION)
716 {
717 blocking.push(NonReplayableReason::StoreVersionIncompatible { incompatibility });
718 }
719
720 if !files.store_zip_exists() {
722 blocking.push(NonReplayableReason::MissingStoreZip);
723 }
724 if !files.run_log_exists() {
725 blocking.push(NonReplayableReason::MissingRunLog);
726 }
727
728 match &self.status {
730 RecordedRunStatus::Unknown => {
731 blocking.push(NonReplayableReason::StatusUnknown);
732 }
733 RecordedRunStatus::Incomplete => {
734 is_incomplete = true;
735 }
736 RecordedRunStatus::Completed(_)
737 | RecordedRunStatus::Cancelled(_)
738 | RecordedRunStatus::StressCompleted(_)
739 | RecordedRunStatus::StressCancelled(_) => {
740 }
742 }
743
744 if !blocking.is_empty() {
746 ReplayabilityStatus::NotReplayable(blocking)
747 } else if is_incomplete {
748 ReplayabilityStatus::Incomplete
749 } else {
750 ReplayabilityStatus::Replayable
751 }
752 }
753
754 pub fn display<'a>(
766 &'a self,
767 run_id_index: &'a RunIdIndex,
768 replayability: &'a ReplayabilityStatus,
769 alignment: RunListAlignment,
770 styles: &'a Styles,
771 redactor: &'a Redactor,
772 ) -> DisplayRecordedRunInfo<'a> {
773 DisplayRecordedRunInfo::new(
774 self,
775 run_id_index,
776 replayability,
777 alignment,
778 styles,
779 redactor,
780 )
781 }
782
783 pub fn display_detailed<'a>(
797 &'a self,
798 run_id_index: &'a RunIdIndex,
799 replayability: &'a ReplayabilityStatus,
800 now: DateTime<Utc>,
801 styles: &'a Styles,
802 theme_characters: &'a ThemeCharacters,
803 redactor: &'a Redactor,
804 ) -> DisplayRecordedRunInfoDetailed<'a> {
805 DisplayRecordedRunInfoDetailed::new(
806 self,
807 run_id_index,
808 replayability,
809 now,
810 styles,
811 theme_characters,
812 redactor,
813 )
814 }
815}
816
817struct ReadRunsJsonResult {
819 runs: Vec<RecordedRunInfo>,
820 last_pruned_at: Option<DateTime<Utc>>,
821 write_permission: RunsJsonWritePermission,
822}
823
824fn read_runs_json(runs_dir: &Utf8Path) -> Result<ReadRunsJsonResult, RunStoreError> {
827 let runs_json_path = runs_dir.join(RUNS_JSON_FILE_NAME);
828 let file = match File::open(&runs_json_path) {
829 Ok(file) => file,
830 Err(error) => {
831 if error.kind() == io::ErrorKind::NotFound {
832 return Ok(ReadRunsJsonResult {
834 runs: Vec::new(),
835 last_pruned_at: None,
836 write_permission: RunsJsonWritePermission::Allowed,
837 });
838 } else {
839 return Err(RunStoreError::RunListRead {
840 path: runs_json_path,
841 error,
842 });
843 }
844 }
845 };
846
847 let decoder = zstd::stream::Decoder::new(file).map_err(|error| RunStoreError::RunListRead {
848 path: runs_json_path.clone(),
849 error,
850 })?;
851
852 let list: RecordedRunList =
853 serde_json::from_reader(decoder).map_err(|error| RunStoreError::RunListDeserialize {
854 path: runs_json_path,
855 error,
856 })?;
857 let write_permission = list.write_permission();
858 let data = list.into_data();
859 Ok(ReadRunsJsonResult {
860 runs: data.runs,
861 last_pruned_at: data.last_pruned_at,
862 write_permission,
863 })
864}
865
866fn write_runs_json(
868 runs_dir: &Utf8Path,
869 runs: &[RecordedRunInfo],
870 last_pruned_at: Option<DateTime<Utc>>,
871) -> Result<(), RunStoreError> {
872 let runs_json_path = runs_dir.join(RUNS_JSON_FILE_NAME);
873 let list = RecordedRunList::from_data(runs, last_pruned_at);
874
875 atomicwrites::AtomicFile::new(&runs_json_path, atomicwrites::AllowOverwrite)
876 .write(|file| {
877 let mut encoder = zstd::stream::Encoder::new(file, 3)?;
879 serde_json::to_writer_pretty(&mut encoder, &list)?;
880 encoder.finish()?;
881 Ok(())
882 })
883 .map_err(|error| RunStoreError::RunListWrite {
884 path: runs_json_path,
885 error,
886 })?;
887
888 Ok(())
889}
890
891#[derive(Debug)]
896pub struct SharedLockedRunStore<'store> {
897 runs_dir: StoreRunsDir<'store>,
898 #[expect(dead_code, reason = "held for lock duration")]
899 locked_file: DebugIgnore<File>,
900 runs: Vec<RecordedRunInfo>,
901 write_permission: RunsJsonWritePermission,
902 run_id_index: RunIdIndex,
903}
904
905impl<'store> SharedLockedRunStore<'store> {
906 pub fn into_snapshot(self) -> RunStoreSnapshot {
909 RunStoreSnapshot {
910 runs_dir: self.runs_dir.as_path().to_owned(),
911 runs: self.runs,
912 write_permission: self.write_permission,
913 run_id_index: self.run_id_index,
914 }
915 }
916}
917
918#[derive(Debug)]
920pub struct RunStoreSnapshot {
921 runs_dir: Utf8PathBuf,
922 runs: Vec<RecordedRunInfo>,
923 write_permission: RunsJsonWritePermission,
924 run_id_index: RunIdIndex,
925}
926
927impl RunStoreSnapshot {
928 pub fn runs_dir(&self) -> StoreRunsDir<'_> {
930 StoreRunsDir(&self.runs_dir)
931 }
932
933 pub fn write_permission(&self) -> RunsJsonWritePermission {
937 self.write_permission
938 }
939
940 pub fn runs(&self) -> &[RecordedRunInfo] {
942 &self.runs
943 }
944
945 pub fn run_count(&self) -> usize {
947 self.runs.len()
948 }
949
950 pub fn total_size(&self) -> u64 {
952 self.runs.iter().map(|r| r.sizes.total_compressed()).sum()
953 }
954
955 pub fn resolve_run_id(
961 &self,
962 selector: &RunIdSelector,
963 ) -> Result<ResolveRunIdResult, RunIdResolutionError> {
964 match selector {
965 RunIdSelector::Latest => self.most_recent_run(),
966 RunIdSelector::Prefix(prefix) => {
967 let run_id = self.resolve_run_id_prefix(prefix)?;
968 Ok(ResolveRunIdResult { run_id })
969 }
970 }
971 }
972
973 fn resolve_run_id_prefix(&self, prefix: &str) -> Result<ReportUuid, RunIdResolutionError> {
979 self.run_id_index.resolve_prefix(prefix).map_err(|err| {
980 match err {
981 PrefixResolutionError::NotFound => RunIdResolutionError::NotFound {
982 prefix: prefix.to_string(),
983 },
984 PrefixResolutionError::Ambiguous { count, candidates } => {
985 let mut candidates: Vec<_> = candidates
987 .into_iter()
988 .filter_map(|run_id| self.get_run(run_id).cloned())
989 .collect();
990 candidates.sort_by_key(|run| std::cmp::Reverse(run.started_at));
991 RunIdResolutionError::Ambiguous {
992 prefix: prefix.to_string(),
993 count,
994 candidates,
995 run_id_index: self.run_id_index.clone(),
996 }
997 }
998 PrefixResolutionError::InvalidPrefix => RunIdResolutionError::InvalidPrefix {
999 prefix: prefix.to_string(),
1000 },
1001 }
1002 })
1003 }
1004
1005 pub fn run_id_index(&self) -> &RunIdIndex {
1007 &self.run_id_index
1008 }
1009
1010 pub fn get_run(&self, run_id: ReportUuid) -> Option<&RecordedRunInfo> {
1012 self.runs.iter().find(|r| r.run_id == run_id)
1013 }
1014
1015 pub fn most_recent_run(&self) -> Result<ResolveRunIdResult, RunIdResolutionError> {
1019 self.runs
1020 .iter()
1021 .max_by_key(|r| r.started_at)
1022 .map(|r| ResolveRunIdResult { run_id: r.run_id })
1023 .ok_or(RunIdResolutionError::NoRuns)
1024 }
1025
1026 pub fn compute_prune_plan(&self, policy: &RecordRetentionPolicy) -> PrunePlan {
1032 PrunePlan::compute(&self.runs, policy)
1033 }
1034}
1035
1036#[derive(Debug)]
1042pub struct SnapshotWithReplayability<'a> {
1043 snapshot: &'a RunStoreSnapshot,
1044 replayability: HashMap<ReportUuid, ReplayabilityStatus>,
1045 latest_run_id: Option<ReportUuid>,
1046}
1047
1048impl<'a> SnapshotWithReplayability<'a> {
1049 pub fn new(snapshot: &'a RunStoreSnapshot) -> Self {
1054 let runs_dir = snapshot.runs_dir();
1055 let replayability: HashMap<_, _> = snapshot
1056 .runs()
1057 .iter()
1058 .map(|run| {
1059 (
1060 run.run_id,
1061 run.check_replayability(&runs_dir.run_files(run.run_id)),
1062 )
1063 })
1064 .collect();
1065
1066 let latest_run_id = snapshot.most_recent_run().ok().map(|r| r.run_id);
1068
1069 Self {
1070 snapshot,
1071 replayability,
1072 latest_run_id,
1073 }
1074 }
1075
1076 pub fn snapshot(&self) -> &'a RunStoreSnapshot {
1078 self.snapshot
1079 }
1080
1081 pub fn replayability(&self) -> &HashMap<ReportUuid, ReplayabilityStatus> {
1083 &self.replayability
1084 }
1085
1086 pub fn get_replayability(&self, run_id: ReportUuid) -> &ReplayabilityStatus {
1093 self.replayability
1094 .get(&run_id)
1095 .expect("run ID should be in replayability map")
1096 }
1097
1098 pub fn latest_run_id(&self) -> Option<ReportUuid> {
1100 self.latest_run_id
1101 }
1102}
1103
1104#[cfg(test)]
1105impl SnapshotWithReplayability<'_> {
1106 pub fn new_for_test(snapshot: &RunStoreSnapshot) -> SnapshotWithReplayability<'_> {
1110 let replayability: HashMap<_, _> = snapshot
1111 .runs()
1112 .iter()
1113 .map(|run| (run.run_id, ReplayabilityStatus::Replayable))
1114 .collect();
1115
1116 let latest_run_id = snapshot
1118 .runs()
1119 .iter()
1120 .max_by_key(|r| r.started_at)
1121 .map(|r| r.run_id);
1122
1123 SnapshotWithReplayability {
1124 snapshot,
1125 replayability,
1126 latest_run_id,
1127 }
1128 }
1129}
1130
1131#[cfg(test)]
1132impl RunStoreSnapshot {
1133 pub(crate) fn new_for_test(runs: Vec<RecordedRunInfo>) -> Self {
1135 use super::run_id_index::RunIdIndex;
1136
1137 let run_id_index = RunIdIndex::new(&runs);
1138 Self {
1139 runs_dir: Utf8PathBuf::from("/test/runs"),
1140 runs,
1141 write_permission: RunsJsonWritePermission::Allowed,
1142 run_id_index,
1143 }
1144 }
1145}
1146
1147#[derive(Clone, Copy)]
1149enum LockKind {
1150 Shared,
1151 Exclusive,
1152}
1153
1154fn acquire_lock_with_retry(
1159 file: &File,
1160 lock_file_path: &Utf8Path,
1161 kind: LockKind,
1162) -> Result<(), RunStoreError> {
1163 const LOCK_TIMEOUT: Duration = Duration::from_secs(5);
1164 const LOCK_RETRY_INTERVAL: Duration = Duration::from_millis(100);
1165
1166 let start = Instant::now();
1167 loop {
1168 let result = match kind {
1169 LockKind::Shared => file.try_lock_shared(),
1170 LockKind::Exclusive => file.try_lock(),
1171 };
1172
1173 match result {
1174 Ok(()) => return Ok(()),
1175 Err(TryLockError::WouldBlock) => {
1176 if start.elapsed() >= LOCK_TIMEOUT {
1178 return Err(RunStoreError::FileLockTimeout {
1179 path: lock_file_path.to_owned(),
1180 timeout_secs: LOCK_TIMEOUT.as_secs(),
1181 });
1182 }
1183 thread::sleep(LOCK_RETRY_INTERVAL);
1184 }
1185 Err(TryLockError::Error(error)) => {
1186 return Err(RunStoreError::FileLock {
1188 path: lock_file_path.to_owned(),
1189 error,
1190 });
1191 }
1192 }
1193 }
1194}