1use std::collections::{HashMap, HashSet, VecDeque};
45use std::fmt;
46use std::sync::Arc;
47use std::sync::atomic::{AtomicBool, Ordering};
48
49#[path = "study/command.rs"]
50mod command;
51#[path = "study/display.rs"]
52mod display;
53#[path = "study/error.rs"]
54mod error;
55#[path = "study/phase.rs"]
56mod phase;
57#[path = "study/plan.rs"]
58mod plan;
59#[path = "study/record.rs"]
60mod record;
61#[path = "study/renderer.rs"]
62mod renderer;
63#[path = "study/scheduler.rs"]
64mod scheduler;
65#[path = "study/task.rs"]
66mod task;
67#[path = "study/timing.rs"]
68mod timing;
69#[path = "study/tui.rs"]
70mod tui;
71
72pub use error::StudyError;
73pub use phase::{
74 Phase, PhaseBuilder, PhaseFailurePolicy, PhaseId, Task, TaskId, TaskKey, TaskMode, TaskSelector,
75};
76pub use plan::StudyPlan;
77pub use record::{PhaseRecord, StudyRecord, TaskRecord};
78pub use renderer::{CancellationToken, ProgressSummary, TaskIdentity, TaskStatus};
79pub use task::{TaskContext, TaskResult};
80
81use display::DisplayMode;
82use renderer::StudyRenderer;
83
84static STUDY_OWNED: AtomicBool = AtomicBool::new(false);
85
86type SatisfiedPhaseVerifier = Arc<dyn Fn(PhaseId) -> bool + Send + Sync + 'static>;
87
88pub struct StudyBuilder {
90 phases: Vec<Phase>,
91 output: DisplayMode,
92 satisfied_phase: Option<SatisfiedPhaseVerifier>,
93 record_path: std::path::PathBuf,
94}
95
96impl StudyBuilder {
97 pub fn phase(mut self, phase: Phase) -> Self {
99 self.phases.push(phase);
100 self
101 }
102
103 pub fn phases<I>(mut self, phases: I) -> Self
105 where
106 I: IntoIterator<Item = Phase>,
107 {
108 self.phases.extend(phases);
109 self
110 }
111
112 pub fn satisfied_phase_verifier<F>(mut self, verifier: F) -> Self
114 where
115 F: Fn(PhaseId) -> bool + Send + Sync + 'static,
116 {
117 self.satisfied_phase = Some(Arc::new(verifier));
118 self
119 }
120
121 pub fn automatic(mut self) -> Self {
123 self.output = DisplayMode::Auto;
124 self
125 }
126
127 pub fn terminal(mut self) -> Self {
129 self.output = DisplayMode::Terminal;
130 self
131 }
132
133 pub fn plain(mut self) -> Self {
135 self.output = DisplayMode::Plain;
136 self
137 }
138
139 pub fn hidden(mut self) -> Self {
141 self.output = DisplayMode::Hidden;
142 self
143 }
144
145 pub fn build(self) -> Result<Study, StudyError> {
147 validate_plan(&self.phases)?;
148 Ok(Study {
149 phases: self.phases,
150 output: self.output,
151 satisfied_phase: self.satisfied_phase,
152 cancellation: CancellationToken::new(),
153 record_path: self.record_path,
154 })
155 }
156}
157
158impl fmt::Debug for StudyBuilder {
159 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
160 formatter
161 .debug_struct("StudyBuilder")
162 .field("phases", &self.phases.len())
163 .field("output", &self.output)
164 .field("record_path", &self.record_path)
165 .field(
166 "has_satisfied_phase_verifier",
167 &self.satisfied_phase.is_some(),
168 )
169 .finish_non_exhaustive()
170 }
171}
172
173pub struct Study {
175 phases: Vec<Phase>,
176 output: DisplayMode,
177 satisfied_phase: Option<SatisfiedPhaseVerifier>,
178 cancellation: CancellationToken,
179 record_path: std::path::PathBuf,
180}
181
182impl Study {
183 pub fn builder(record_path: impl Into<std::path::PathBuf>) -> StudyBuilder {
185 StudyBuilder {
186 phases: Vec::new(),
187 output: DisplayMode::Auto,
188 satisfied_phase: None,
189 record_path: record_path.into(),
190 }
191 }
192
193 pub fn phases(&self) -> &[Phase] {
195 &self.phases
196 }
197
198 pub fn plan(&self) -> StudyPlan {
201 StudyPlan::from_phases(&self.phases)
202 }
203
204 pub fn write_plan_json(&self, path: impl AsRef<std::path::Path>) -> Result<(), StudyError> {
208 self.plan().write_json(path)
209 }
210
211 pub fn phase(&self, id: impl Into<PhaseId>) -> Option<&Phase> {
213 let id = id.into();
214 self.phases.iter().find(|phase| phase.id() == id)
215 }
216
217 pub fn cancellation_token(&self) -> CancellationToken {
219 self.cancellation.clone()
220 }
221
222 pub fn unique_task_matching(&self, selector: &TaskSelector) -> Result<&Task, StudyError> {
224 let mut matches = self
225 .phases
226 .iter()
227 .flat_map(|phase| phase.tasks())
228 .filter(|task| selector.matches(task));
229 let first = matches.next().ok_or_else(|| StudyError::TaskNotFound {
230 selector: selector.to_string(),
231 })?;
232 if let Some(second) = matches.next() {
233 return Err(StudyError::TaskSelectorAmbiguous {
234 selector: selector.to_string(),
235 first: first.key().to_string(),
236 second: second.key().to_string(),
237 });
238 }
239 Ok(first)
240 }
241
242 pub fn run(self) -> Result<StudySummary, StudyError> {
244 let selected = topological_positions(&self.phases)?;
245 self.execute(selected)
246 }
247
248 pub fn run_phases<I, P>(self, phases: I) -> Result<StudySummary, StudyError>
250 where
251 I: IntoIterator<Item = P>,
252 P: Into<PhaseId>,
253 {
254 let selected = self.select_phases(phases, false)?;
255 self.execute(selected)
256 }
257
258 pub fn run_phases_with_dependencies<I, P>(self, phases: I) -> Result<StudySummary, StudyError>
260 where
261 I: IntoIterator<Item = P>,
262 P: Into<PhaseId>,
263 {
264 let selected = self.select_phases(phases, true)?;
265 self.execute(selected)
266 }
267
268 fn select_phases<I, P>(&self, phases: I, include_dependencies: bool) -> Result<Vec<usize>, StudyError>
269 where
270 I: IntoIterator<Item = P>,
271 P: Into<PhaseId>,
272 {
273 let mut selected = selected_ids(&self.phases, phases)?;
274 if include_dependencies {
275 let positions: HashMap<_, _> = self
276 .phases
277 .iter()
278 .enumerate()
279 .map(|(position, phase)| (phase.id(), position))
280 .collect();
281 let mut pending: Vec<_> = selected.iter().copied().collect();
282 while let Some(id) = pending.pop() {
283 let phase = &self.phases[positions[&id]];
284 for dependency in phase.dependencies() {
285 if !self.is_satisfied(*dependency) && selected.insert(*dependency) {
286 pending.push(*dependency);
287 }
288 }
289 }
290 } else {
291 for phase in self
292 .phases
293 .iter()
294 .filter(|phase| selected.contains(&phase.id()))
295 {
296 for dependency in phase.dependencies() {
297 if !selected.contains(dependency) && !self.is_satisfied(*dependency) {
298 return Err(StudyError::UnsatisfiedPhaseDependency {
299 phase: phase.id().get(),
300 dependency: dependency.get(),
301 });
302 }
303 }
304 }
305 }
306 Ok(topological_positions(&self.phases)?
307 .into_iter()
308 .filter(|position| selected.contains(&self.phases[*position].id()))
309 .collect())
310 }
311
312 fn is_satisfied(&self, phase: PhaseId) -> bool {
313 self.satisfied_phase
314 .as_ref()
315 .is_some_and(|verify| verify(phase))
316 }
317
318 fn execute(self, selected: Vec<usize>) -> Result<StudySummary, StudyError> {
319 let _lease = StudyLease::acquire()?;
320 let total_phases = selected.len();
321 let total_tasks = selected
322 .iter()
323 .map(|position| self.phases[*position].tasks().len())
324 .sum();
325 let execution = {
326 let selected_phases = selected
327 .iter()
328 .map(|position| &self.phases[*position])
329 .collect::<Vec<_>>();
330 record::StudyRecorder::start(self.record_path.clone(), &selected_phases)?
331 };
332 let mut summaries = Vec::with_capacity(total_phases);
333 let mut phases = self.phases.into_iter().map(Some).collect::<Vec<_>>();
334
335 for (selection_position, phase_position) in selected.iter().copied().enumerate() {
336 let phase = phases[phase_position]
337 .take()
338 .expect("selected phase positions are unique");
339 execution.phase_started(phase.id())?;
340 display::phase_start(self.output, &phase, selection_position + 1, total_phases);
341 let heading = display::phase_heading(&phase, selection_position + 1, total_phases);
342 let builder = StudyRenderer::for_phase(&phase, &heading)?
343 .cancellation_token(self.cancellation.clone());
344 let renderer = match self.output {
345 DisplayMode::Auto => builder,
346 DisplayMode::Terminal => builder.terminal(),
347 DisplayMode::Plain => builder.plain(),
348 DisplayMode::Hidden => builder.hidden(),
349 }
350 .start()?;
351 let phase_id = phase.id();
352 let phase_label: Arc<str> = phase.label().into();
353 let require_confirm = phase.requires_confirmation();
354 let result = scheduler::execute_phase(phase, &renderer, &execution);
355 let task_execution = renderer.task_execution_snapshots();
356 let progress = if result.is_ok() {
357 renderer.complete(format!("phase {phase_id} completed"))?
358 } else {
359 renderer.fail(format!("phase {phase_id} failed"))?
360 };
361 let success = result.is_ok() && progress.is_success();
362 execution.phase_finished(phase_id, success, &progress, task_execution)?;
363 display::phase_complete(self.output, phase_id, &phase_label, success);
364 summaries.push(PhaseSummary {
365 id: phase_id,
366 label: phase_label,
367 progress,
368 });
369 if let Err(error) = result {
370 return Err(Self::fail_phase_with_summary(
371 self.output,
372 &execution,
373 summaries,
374 total_tasks,
375 error,
376 )?);
377 }
378 if require_confirm && selection_position + 1 < total_phases {
379 let next = phases[selected[selection_position + 1]]
380 .as_ref()
381 .expect("the next selected phase has not executed");
382 let confirmed = match display::confirm_transition(phase_id, next) {
383 Ok(confirmed) => confirmed,
384 Err(source) => {
385 return Err(Self::fail_phase_with_summary(
386 self.output,
387 &execution,
388 summaries,
389 total_tasks,
390 StudyError::PhaseConfirmationInput {
391 phase: phase_id.get(),
392 source,
393 },
394 )?);
395 }
396 };
397 if !confirmed {
398 return Err(Self::fail_phase_with_summary(
399 self.output,
400 &execution,
401 summaries,
402 total_tasks,
403 StudyError::PhaseConfirmationEof {
404 phase: phase_id.get(),
405 },
406 )?);
407 }
408 }
409 }
410
411 display::study_complete(self.output, summaries.len(), total_tasks, true);
412 let record = execution.finish(true)?;
413 Ok(StudySummary {
414 phases: summaries.into(),
415 record: Box::new(record),
416 })
417 }
418
419 fn fail_phase_with_summary(
420 output: DisplayMode,
421 execution: &record::StudyRecorder,
422 summaries: Vec<PhaseSummary>,
423 total_tasks: usize,
424 source: StudyError,
425 ) -> Result<StudyError, StudyError> {
426 display::study_complete(output, summaries.len(), total_tasks, false);
427 let record = execution.finish(false)?;
428 Ok(StudyError::PhaseExecutionFailed {
429 summary: StudySummary {
430 phases: summaries.into(),
431 record: Box::new(record),
432 },
433 source: Box::new(source),
434 })
435 }
436}
437
438impl fmt::Debug for Study {
439 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
440 formatter
441 .debug_struct("Study")
442 .field("phases", &self.phases.len())
443 .field(
444 "tasks",
445 &self.phases.iter().map(|p| p.tasks().len()).sum::<usize>(),
446 )
447 .field("output", &self.output)
448 .finish_non_exhaustive()
449 }
450}
451
452#[derive(Clone, Debug, Eq, PartialEq)]
454pub struct PhaseSummary {
455 id: PhaseId,
456 label: Arc<str>,
457 progress: ProgressSummary,
458}
459
460impl PhaseSummary {
461 pub const fn id(&self) -> PhaseId {
462 self.id
463 }
464
465 pub fn label(&self) -> &str {
466 &self.label
467 }
468
469 pub fn progress(&self) -> &ProgressSummary {
470 &self.progress
471 }
472
473 pub fn is_success(&self) -> bool {
474 self.progress.is_success()
475 }
476}
477
478#[derive(Clone, Debug, Eq, PartialEq)]
480pub struct StudySummary {
481 phases: Arc<[PhaseSummary]>,
482 record: Box<StudyRecord>,
483}
484
485impl StudySummary {
486 pub fn phases(&self) -> &[PhaseSummary] {
487 &self.phases
488 }
489
490 pub fn record(&self) -> &StudyRecord {
492 self.record.as_ref()
493 }
494
495 pub fn total_tasks(&self) -> u64 {
496 self.phases.iter().map(|phase| phase.progress.total()).sum()
497 }
498
499 pub fn is_success(&self) -> bool {
500 !self.phases.is_empty() && self.phases.iter().all(PhaseSummary::is_success)
501 }
502}
503
504struct StudyLease;
505
506impl StudyLease {
507 fn acquire() -> Result<Self, StudyError> {
508 STUDY_OWNED
509 .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
510 .map(|_| Self)
511 .map_err(|_| StudyError::TerminalAlreadyOwned)
512 }
513}
514
515impl Drop for StudyLease {
516 fn drop(&mut self) {
517 STUDY_OWNED.store(false, Ordering::Release);
518 }
519}
520
521fn selected_ids<I, P>(phases: &[Phase], requested: I) -> Result<HashSet<PhaseId>, StudyError>
522where
523 I: IntoIterator<Item = P>,
524 P: Into<PhaseId>,
525{
526 let known: HashSet<_> = phases.iter().map(Phase::id).collect();
527 let selected: HashSet<_> = requested.into_iter().map(Into::into).collect();
528 if selected.is_empty() {
529 return Err(StudyError::EmptyPhaseSet);
530 }
531 if let Some(unknown) = selected.iter().find(|id| !known.contains(id)) {
532 return Err(StudyError::UnknownSelectedPhase {
533 phase: unknown.get(),
534 });
535 }
536 Ok(selected)
537}
538
539fn validate_plan(phases: &[Phase]) -> Result<(), StudyError> {
540 if phases.is_empty() {
541 return Err(StudyError::EmptyPhaseSet);
542 }
543 let mut ids = HashSet::with_capacity(phases.len());
544 for phase in phases {
545 if !ids.insert(phase.id()) {
546 return Err(StudyError::DuplicatePhaseId {
547 phase: phase.id().get(),
548 });
549 }
550 }
551 for phase in phases {
552 for dependency in phase.dependencies() {
553 if !ids.contains(dependency) {
554 return Err(StudyError::UnknownPhaseDependency {
555 phase: phase.id().get(),
556 dependency: dependency.get(),
557 });
558 }
559 }
560 for task in phase.tasks() {
561 if !task.has_workload() && !task.is_completed() {
562 return Err(StudyError::MissingTaskWorkload {
563 task: task.key().to_string(),
564 });
565 }
566 }
567 }
568 topological_positions(phases).map(|_| ())
569}
570
571fn topological_positions(phases: &[Phase]) -> Result<Vec<usize>, StudyError> {
572 let positions: HashMap<_, _> = phases
573 .iter()
574 .enumerate()
575 .map(|(position, phase)| (phase.id(), position))
576 .collect();
577 let mut dependents: Vec<Vec<usize>> = vec![Vec::new(); phases.len()];
578 let mut indegree = vec![0_usize; phases.len()];
579
580 for (position, phase) in phases.iter().enumerate() {
581 for dependency in phase.dependencies() {
582 let dependency_position = positions[dependency];
583 dependents[dependency_position].push(position);
584 indegree[position] += 1;
585 }
586 }
587
588 let mut queue = VecDeque::new();
589 for (position, degree) in indegree.iter().enumerate() {
590 if *degree == 0 {
591 queue.push_back(position);
592 }
593 }
594
595 let mut ordered = Vec::with_capacity(phases.len());
596 while let Some(position) = queue.pop_front() {
597 ordered.push(position);
598 for dependent in dependents[position].drain(..) {
599 indegree[dependent] -= 1;
600 if indegree[dependent] == 0 {
601 queue.push_back(dependent);
602 }
603 }
604 }
605
606 if ordered.len() != phases.len() {
607 let phase_position = indegree
608 .iter()
609 .position(|degree| *degree > 0)
610 .expect("cyclic dependency must leave at least one phase with indegree");
611 return Err(StudyError::PhaseDependencyCycle {
612 phase: phases[phase_position].id().get(),
613 });
614 }
615
616 Ok(ordered)
617}