refactor: build graph first and then render

This commit is contained in:
Willem Vanhulle committed 2026-10-16 11:42:53 +02:00
1 parent 2da498c268
commit 196356ba0b
9 files changed
+401 -361

No files matched your search

+76 -37
View File
@@ -1,5 +1,7 @@
use std::{ use std::{
collections::HashMap, collections::HashMap,
mem,
os::fd::{AsFd, BorrowedFd},
path::Path as FilePath, path::Path as FilePath,
process, process,
time::{Duration, Instant}, time::{Duration, Instant},
@@ -30,30 +32,62 @@ const SHUTDOWN_FALLBACK_ROOT: &str = "shutdown.target";
const SILENT_STATUS: &str = "no"; const SILENT_STATUS: &str = "no";
const CONFIGURED_STATUS: &str = ""; const CONFIGURED_STATUS: &str = "";
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RootRequest {
Named(String),
ManagerDefault,
}
enum Link {
Connected(Session),
Connecting { deadline: Instant },
}
impl Link {
fn connecting() -> Self {
Self::Connecting {
deadline: Instant::now() + RECONNECT_PATIENCE,
}
}
}
enum RootFs {
Initrd,
SwitchingTo(Sysroot),
Host,
}
pub struct Feed { pub struct Feed {
pub connections: u32, pub connections: u32,
scope: Scope, scope: Scope,
target: Option<String>, target: RootRequest,
pub session: Option<Session>, link: Link,
unit_paths: HashMap<Path<'static>, String>, unit_paths: HashMap<Path<'static>, String>,
in_initrd: bool, root_fs: RootFs,
sysroot: Option<Sysroot>,
gave_origin: bool, gave_origin: bool,
reconnect_deadline: Instant,
} }
impl Feed { impl Feed {
pub fn new(scope: Scope, target: Option<String>) -> Self { pub fn new(scope: Scope, target: RootRequest) -> Self {
Self { Self {
connections: 0, connections: 0,
in_initrd: scope == Scope::System && FilePath::new(INITRD_RELEASE).exists(), root_fs: if scope == Scope::System && FilePath::new(INITRD_RELEASE).exists() {
RootFs::Initrd
} else {
RootFs::Host
},
scope, scope,
target, target,
session: None, link: Link::connecting(),
unit_paths: HashMap::new(), unit_paths: HashMap::new(),
sysroot: None,
gave_origin: false, gave_origin: false,
reconnect_deadline: Instant::now() + RECONNECT_PATIENCE, }
}
pub fn session_fd(&self) -> Option<BorrowedFd<'_>> {
match &self.link {
Link::Connected(session) => Some(session.as_fd()),
Link::Connecting { .. } => None,
} }
} }
@@ -61,47 +95,49 @@ impl Feed {
if state.manager_exited_at.is_some() { if state.manager_exited_at.is_some() {
return Ok(()); return Ok(());
} }
let Some(session) = self.session.take() else { match mem::replace(&mut self.link, Link::connecting()) {
return self.connect(state); Link::Connecting { deadline } => self.connect(state, deadline),
}; Link::Connected(session) => match session.receive() {
match session.receive() { Ok(signals) => {
Ok(signals) => { signals
signals .into_iter()
.into_iter() .for_each(|signal| self.apply(&session, state, signal));
.for_each(|signal| self.apply(&session, state, signal)); self.link = Link::Connected(session);
self.session = Some(session); Ok(())
} }
Err(_) => self.lose_connection(state)?, Err(_) => self.lose_connection(state),
},
} }
Ok(())
} }
fn connect(&mut self, state: &mut BootState) -> Result<(), Error> { fn connect(&mut self, state: &mut BootState, deadline: Instant) -> Result<(), Error> {
match self.open_session(state) { match self.open_session(state) {
Ok(session) => { Ok(session) => {
self.session = Some(session); self.link = Link::Connected(session);
self.connections += 1; self.connections += 1;
Ok(()) Ok(())
} }
Err(_) if Instant::now() < self.reconnect_deadline => Ok(()), Err(_) if Instant::now() < deadline => {
self.link = Link::Connecting { deadline };
Ok(())
}
Err(_) => Err(Error::ManagerUnreachable), Err(_) => Err(Error::ManagerUnreachable),
} }
} }
fn lose_connection(&mut self, state: &mut BootState) -> Result<(), Error> { fn lose_connection(&mut self, state: &mut BootState) -> Result<(), Error> {
match self.sysroot.take() { match &self.root_fs {
Some(sysroot) => { RootFs::SwitchingTo(sysroot) => {
sysroot.enter()?; sysroot.enter()?;
self.in_initrd = false; self.root_fs = RootFs::Host;
self.unit_paths.clear(); self.unit_paths.clear();
state.switch_root(monotonic_now()); state.switch_root(monotonic_now());
} }
None if state.phase == Phase::Shutdown => { RootFs::Initrd | RootFs::Host if state.phase == Phase::Shutdown => {
state.manager_exited_at = Some(monotonic_now()); state.manager_exited_at = Some(monotonic_now());
} }
None => state.forget_jobs(), RootFs::Initrd | RootFs::Host => state.forget_jobs(),
} }
self.reconnect_deadline = Instant::now() + RECONNECT_PATIENCE;
Ok(()) Ok(())
} }
@@ -118,8 +154,8 @@ impl Feed {
.filter(|job| shutting_down || job.kind == JobKind::BringsUp) .filter(|job| shutting_down || job.kind == JobKind::BringsUp)
.collect(); .collect();
let requested_root = match &self.target { let requested_root = match &self.target {
Some(target) => target.clone(), RootRequest::Named(target) => target.clone(),
None if shutting_down => SHUTDOWN_ROOTS RootRequest::ManagerDefault if shutting_down => SHUTDOWN_ROOTS
.into_iter() .into_iter()
.find(|root| { .find(|root| {
jobs.iter() jobs.iter()
@@ -127,7 +163,7 @@ impl Feed {
}) })
.unwrap_or(SHUTDOWN_FALLBACK_ROOT) .unwrap_or(SHUTDOWN_FALLBACK_ROOT)
.to_owned(), .to_owned(),
None => session.default_target()?, RootRequest::ManagerDefault => session.default_target()?,
}; };
let milestones: &[&str] = if shutting_down { let milestones: &[&str] = if shutting_down {
&SHUTDOWN_MILESTONES &SHUTDOWN_MILESTONES
@@ -193,8 +229,11 @@ impl Feed {
return; return;
} }
let unit = self.track(session, state, &unit).unwrap_or(unit); let unit = self.track(session, state, &unit).unwrap_or(unit);
if self.in_initrd && unit == SWITCH_ROOT_UNIT { if matches!(self.root_fs, RootFs::Initrd)
self.sysroot = Sysroot::hold().ok(); && unit == SWITCH_ROOT_UNIT
&& let Ok(sysroot) = Sysroot::hold()
{
self.root_fs = RootFs::SwitchingTo(sysroot);
} }
state.queue_job(id, &unit, kind, monotonic_now()); state.queue_job(id, &unit, kind, monotonic_now());
} }
@@ -210,7 +249,7 @@ impl Feed {
impl Drop for Feed { impl Drop for Feed {
fn drop(&mut self) { fn drop(&mut self) {
if let Some(session) = &self.session if let Link::Connected(session) = &self.link
&& self.scope == Scope::System && self.scope == Scope::System
{ {
session.set_show_status(CONFIGURED_STATUS).ok(); session.set_show_status(CONFIGURED_STATUS).ok();
+7 -4
View File
@@ -14,7 +14,8 @@ use clap::Parser;
use jiff::fmt::friendly::SpanParser; use jiff::fmt::friendly::SpanParser;
use crate::{ use crate::{
run::{Options, run}, feed::RootRequest,
run::{Settings, run},
systemd::Scope, systemd::Scope,
}; };
@@ -61,17 +62,19 @@ fn main() -> ExitCode {
Config::default() Config::default()
} }
}; };
let options = Options { let settings = Settings {
scope: if cli.user { Scope::User } else { Scope::System }, scope: if cli.user { Scope::User } else { Scope::System },
shutdown: cli.shutdown, shutdown: cli.shutdown,
target: cli.target, target: cli
.target
.map_or(RootRequest::ManagerDefault, RootRequest::Named),
timing: Timing { timing: Timing {
keep_final_frame_for: cli.hold.unwrap_or(config.timing.keep_final_frame_for), keep_final_frame_for: cli.hold.unwrap_or(config.timing.keep_final_frame_for),
..config.timing ..config.timing
}, },
palette: config.palette, palette: config.palette,
}; };
match run(&options) { match run(&settings) {
Ok(()) => ExitCode::SUCCESS, Ok(()) => ExitCode::SUCCESS,
Err(error) => { Err(error) => {
eprintln!("bootvine: {error}"); eprintln!("bootvine: {error}");
+171 -198
View File
@@ -110,6 +110,13 @@ enum Outcome {
Abandoned, Abandoned,
} }
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Progress {
Untouched,
Pending(PendingJob),
Finished(Outcome),
}
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
struct UnitRecord { struct UnitRecord {
facts: UnitFacts, facts: UnitFacts,
@@ -117,8 +124,7 @@ struct UnitRecord {
inactive_exit: Option<Duration>, inactive_exit: Option<Duration>,
active_enter: Option<Duration>, active_enter: Option<Duration>,
active_exit: Option<Duration>, active_exit: Option<Duration>,
job: Option<PendingJob>, progress: Progress,
outcome: Option<Outcome>,
} }
impl UnitRecord { impl UnitRecord {
@@ -145,7 +151,9 @@ impl UnitRecord {
} }
fn running_since(&self) -> Option<Duration> { fn running_since(&self) -> Option<Duration> {
let job = self.job?; let Progress::Pending(job) = self.progress else {
return None;
};
let transitioning = matches!( let transitioning = matches!(
self.state, self.state,
ActiveState::Activating | ActiveState::Deactivating | ActiveState::Reloading ActiveState::Activating | ActiveState::Deactivating | ActiveState::Reloading
@@ -153,8 +161,36 @@ impl UnitRecord {
transitioning.then(|| self.transition_started(job.kind).unwrap_or(job.queued_at)) transitioning.then(|| self.transition_started(job.kind).unwrap_or(job.queued_at))
} }
fn row_status(&self) -> RowStatus {
match self.progress {
Progress::Pending(job) => {
self.running_since()
.map_or(RowStatus::Waiting, |since| RowStatus::Running {
queued_at: job.queued_at,
since,
})
}
Progress::Finished(Outcome::Failed) => RowStatus::Failed,
Progress::Finished(_) | Progress::Untouched => RowStatus::Done,
}
}
fn is_pending(&self) -> bool {
matches!(self.progress, Progress::Pending(_))
}
fn is_finished(&self) -> bool {
matches!(self.progress, Progress::Finished(_))
}
fn takes_down(&self) -> bool { fn takes_down(&self) -> bool {
self.job.is_some_and(|job| job.kind == JobKind::TakesDown) matches!(
self.progress,
Progress::Pending(PendingJob {
kind: JobKind::TakesDown,
..
})
)
} }
} }
@@ -220,7 +256,10 @@ impl UnitKind {
#[derive(Clone, Copy, Debug, PartialEq, Eq)] #[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RowStatus { pub enum RowStatus {
Waiting, Waiting,
Running, Running {
queued_at: Duration,
since: Duration,
},
Failed, Failed,
Done, Done,
} }
@@ -228,13 +267,10 @@ pub enum RowStatus {
#[derive(Clone, Debug, PartialEq, Eq)] #[derive(Clone, Debug, PartialEq, Eq)]
pub struct TreeRow { pub struct TreeRow {
pub depth: usize, pub depth: usize,
pub is_last_sibling: Vec<bool>,
pub label: String, pub label: String,
pub description: String, pub description: String,
pub kind: UnitKind, pub kind: UnitKind,
pub status: RowStatus, pub status: RowStatus,
pub queued_at: Duration,
pub running_since: Option<Duration>,
pub chain: Vec<String>, pub chain: Vec<String>,
} }
@@ -243,7 +279,7 @@ pub struct MilestoneRow {
pub label: String, pub label: String,
pub finished_units: usize, pub finished_units: usize,
pub started_at: Duration, pub started_at: Duration,
pub reached_at: Option<Duration>, pub reached_at: Duration,
} }
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
@@ -271,17 +307,33 @@ pub struct FinishedStage {
pub reached_at: Duration, pub reached_at: Duration,
} }
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Root {
Unresolved,
Awaiting(String),
Queued(String),
}
impl Root {
#[must_use]
pub fn unit(&self) -> Option<&str> {
match self {
Self::Unresolved => None,
Self::Awaiting(unit) | Self::Queued(unit) => Some(unit),
}
}
}
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct BootState { pub struct BootState {
pub phase: Phase, pub phase: Phase,
pub origin: Duration, pub origin: Duration,
pub root: Option<String>, pub root: Root,
pub failed: Vec<String>, pub failed: Vec<String>,
pub finished_stages: Vec<FinishedStage>, pub finished_stages: Vec<FinishedStage>,
pub finished_runs: Vec<FinishedRun>, pub finished_runs: Vec<FinishedRun>,
pub handoff_unit: Option<String>, pub handoff_unit: Option<String>,
pub manager_exited_at: Option<Duration>, pub manager_exited_at: Option<Duration>,
root_job_seen: bool,
milestone_targets: Vec<String>, milestone_targets: Vec<String>,
finished_before_reconnect: usize, finished_before_reconnect: usize,
units: HashMap<String, UnitRecord>, units: HashMap<String, UnitRecord>,
@@ -319,11 +371,10 @@ impl BootState {
Self { Self {
phase, phase,
origin: Duration::ZERO, origin: Duration::ZERO,
root: None, root: Root::Unresolved,
failed: Vec::new(), failed: Vec::new(),
finished_stages: Vec::new(), finished_stages: Vec::new(),
finished_runs: Vec::new(), finished_runs: Vec::new(),
root_job_seen: false,
handoff_unit, handoff_unit,
manager_exited_at: None, manager_exited_at: None,
milestone_targets, milestone_targets,
@@ -334,13 +385,12 @@ impl BootState {
} }
pub fn set_root(&mut self, root: String) { pub fn set_root(&mut self, root: String) {
if self.root.as_ref() != Some(&root) {
self.root_job_seen = false;
}
if self.phase == Phase::User && !self.milestone_targets.contains(&root) { if self.phase == Phase::User && !self.milestone_targets.contains(&root) {
self.milestone_targets.push(root.clone()); self.milestone_targets.push(root.clone());
} }
self.root = Some(root); if self.root.unit() != Some(&root) {
self.root = Root::Awaiting(root);
}
} }
pub fn set_handoff(&mut self, unit: String) { pub fn set_handoff(&mut self, unit: String) {
@@ -359,8 +409,7 @@ impl BootState {
inactive_exit: None, inactive_exit: None,
active_enter: None, active_enter: None,
active_exit: None, active_exit: None,
job: None, progress: Progress::Untouched,
outcome: None,
}); });
record.facts = facts; record.facts = facts;
record.apply(activity); record.apply(activity);
@@ -376,9 +425,9 @@ impl BootState {
self.enqueue(id, unit, kind, at); self.enqueue(id, unit, kind, at);
if kind == JobKind::BringsUp if kind == JobKind::BringsUp
&& self.jobs.get(&id).is_some_and(|tracked| tracked == unit) && self.jobs.get(&id).is_some_and(|tracked| tracked == unit)
&& self.root.as_deref() == Some(unit) && self.root == Root::Awaiting(unit.to_owned())
{ {
self.root_job_seen = true; self.root = Root::Queued(unit.to_owned());
} }
} }
@@ -389,12 +438,11 @@ impl BootState {
let Some(record) = self.units.get_mut(unit) else { let Some(record) = self.units.get_mut(unit) else {
return; return;
}; };
record.job = Some(PendingJob { record.progress = Progress::Pending(PendingJob {
id, id,
queued_at: at, queued_at: at,
kind, kind,
}); });
record.outcome = None;
self.jobs.insert(id, unit.to_owned()); self.jobs.insert(id, unit.to_owned());
} }
@@ -405,36 +453,31 @@ impl BootState {
let Some(record) = self.units.get_mut(&unit) else { let Some(record) = self.units.get_mut(&unit) else {
return; return;
}; };
let started_at = record
.job
.filter(|job| job.id == id && job.kind != JobKind::Unknown)
.and_then(|job| record.transition_started(job.kind))
.filter(|started| *started >= self.origin && *started <= at);
if record.job.is_some_and(|job| job.id == id) {
record.job = None;
}
if let Some(started_at) = started_at
&& UnitKind::of(&record.facts.name) != UnitKind::Target
{
self.finished_runs.push(FinishedRun {
label: display_label(&record.facts),
started_at,
finished_at: at,
failed: matches!(
result,
JobResult::Failed | JobResult::Timeout | JobResult::Dependency
),
});
}
let outcome = match result { let outcome = match result {
JobResult::Done => Outcome::Succeeded { at }, JobResult::Done => Outcome::Succeeded { at },
JobResult::Skipped | JobResult::Canceled => Outcome::Abandoned, JobResult::Skipped | JobResult::Canceled => Outcome::Abandoned,
JobResult::Failed | JobResult::Timeout | JobResult::Dependency => Outcome::Failed, JobResult::Failed | JobResult::Timeout | JobResult::Dependency => Outcome::Failed,
}; };
record.outcome = Some(outcome);
let label = display_label(&record.facts); let label = display_label(&record.facts);
if outcome == Outcome::Failed && !self.failed.contains(&label) { if outcome == Outcome::Failed && !self.failed.contains(&label) {
self.failed.push(label); self.failed.push(label.clone());
}
let job = match record.progress {
Progress::Pending(job) if job.id == id => job,
_ => return,
};
record.progress = Progress::Finished(outcome);
if let Some(started_at) = record
.transition_started(job.kind)
.filter(|started| job.kind != JobKind::Unknown && (self.origin..=at).contains(started))
&& UnitKind::of(&record.facts.name) != UnitKind::Target
{
self.finished_runs.push(FinishedRun {
label,
started_at,
finished_at: at,
failed: outcome == Outcome::Failed,
});
} }
} }
@@ -442,7 +485,7 @@ impl BootState {
let finished_here = self let finished_here = self
.units .units
.values() .values()
.filter(|record| record.outcome.is_some()) .filter(|record| record.is_finished())
.count(); .count();
self.finished_stages.push(FinishedStage { self.finished_stages.push(FinishedStage {
label: Phase::Initrd.label(), label: Phase::Initrd.label(),
@@ -450,14 +493,13 @@ impl BootState {
failed_units: self failed_units: self
.units .units
.values() .values()
.filter(|record| record.outcome == Some(Outcome::Failed)) .filter(|record| record.progress == Progress::Finished(Outcome::Failed))
.count(), .count(),
started_at: self.origin, started_at: self.origin,
reached_at: at, reached_at: at,
}); });
self.phase = Phase::Host; self.phase = Phase::Host;
self.root = None; self.root = Root::Unresolved;
self.root_job_seen = false;
self.finished_before_reconnect = 0; self.finished_before_reconnect = 0;
self.units.clear(); self.units.clear();
self.jobs.clear(); self.jobs.clear();
@@ -467,13 +509,12 @@ impl BootState {
self.finished_before_reconnect += self self.finished_before_reconnect += self
.units .units
.values() .values()
.filter(|record| record.outcome.is_some()) .filter(|record| record.is_finished())
.count(); .count();
self.jobs.clear(); self.jobs.clear();
self.units.values_mut().for_each(|record| { self.units
record.job = None; .values_mut()
record.outcome = None; .for_each(|record| record.progress = Progress::Untouched);
});
} }
#[must_use] #[must_use]
@@ -489,10 +530,10 @@ impl BootState {
{ {
return true; return true;
} }
let Some(root) = self.root.as_deref().and_then(|root| self.units.get(root)) else { let Root::Queued(root) = &self.root else {
return false; return false;
}; };
self.root_job_seen && root.job.is_none() self.units.get(root).is_some_and(|root| !root.is_pending())
} }
#[must_use] #[must_use]
@@ -508,17 +549,13 @@ impl BootState {
..Tally::default() ..Tally::default()
}; };
self.units.values().fold(carried, |mut tally, record| { self.units.values().fold(carried, |mut tally, record| {
if record.job.is_some() { match record.progress {
if record.running_since().is_some() { Progress::Pending(_) if record.running_since().is_some() => tally.running += 1,
tally.running += 1; Progress::Pending(_) => tally.waiting += 1,
} else { Progress::Finished(Outcome::Succeeded { .. } | Outcome::Abandoned) => {
tally.waiting += 1; tally.done += 1;
} }
} else if matches!( Progress::Finished(Outcome::Failed) | Progress::Untouched => {}
record.outcome,
Some(Outcome::Succeeded { .. } | Outcome::Abandoned)
) {
tally.done += 1;
} }
tally tally
}) })
@@ -526,15 +563,12 @@ impl BootState {
fn milestone_reached_at(&self, target: &str) -> Option<Duration> { fn milestone_reached_at(&self, target: &str) -> Option<Duration> {
let record = self.units.get(target)?; let record = self.units.get(target)?;
if record.job.is_some() { match record.progress {
return None; Progress::Finished(Outcome::Succeeded { at }) => Some(at),
} Progress::Untouched => record
match record.outcome {
Some(Outcome::Succeeded { at }) => Some(at),
Some(_) => None,
None => record
.active_enter .active_enter
.filter(|entered| record.state == ActiveState::Active && *entered >= self.origin), .filter(|entered| record.state == ActiveState::Active && *entered >= self.origin),
Progress::Pending(_) | Progress::Finished(Outcome::Failed | Outcome::Abandoned) => None,
} }
} }
@@ -543,8 +577,8 @@ impl BootState {
let mut succeeded: Vec<Duration> = self let mut succeeded: Vec<Duration> = self
.units .units
.values() .values()
.filter_map(|record| match record.outcome { .filter_map(|record| match record.progress {
Some(Outcome::Succeeded { at }) => Some(at), Progress::Finished(Outcome::Succeeded { at }) => Some(at),
_ => None, _ => None,
}) })
.collect(); .collect();
@@ -557,7 +591,7 @@ impl BootState {
label: stage.label.to_owned(), label: stage.label.to_owned(),
finished_units: stage.finished_units, finished_units: stage.finished_units,
started_at: stage.started_at, started_at: stage.started_at,
reached_at: Some(stage.reached_at), reached_at: stage.reached_at,
}) })
.collect(), .collect(),
previous: self previous: self
@@ -566,24 +600,14 @@ impl BootState {
.map_or(self.origin, |stage| stage.reached_at), .map_or(self.origin, |stage| stage.reached_at),
consumed: 0, consumed: 0,
}; };
let mut walk = self self.milestone_targets
.milestone_targets
.iter() .iter()
.filter_map(|target| { .filter_map(|target| {
self.milestone_reached_at(target) self.milestone_reached_at(target)
.map(|reached_at| ReachedMilestone { target, reached_at }) .map(|reached_at| ReachedMilestone { target, reached_at })
}) })
.fold(start, |walk, reached| walk.advance(&reached, &succeeded)); .fold(start, |walk, reached| walk.advance(&reached, &succeeded))
let remaining = succeeded.len() - walk.consumed + self.finished_before_reconnect; .rows
if remaining > 0 {
walk.rows.push(MilestoneRow {
label: "Finished".to_owned(),
finished_units: remaining,
started_at: walk.previous,
reached_at: None,
});
}
walk.rows
} }
#[must_use] #[must_use]
@@ -591,19 +615,17 @@ impl BootState {
let pending: HashSet<&str> = self let pending: HashSet<&str> = self
.units .units
.iter() .iter()
.filter(|(name, record)| { .filter(|(name, record)| match record.progress {
let finished_recently = matches!( Progress::Pending(_) | Progress::Finished(Outcome::Failed) => true,
record.outcome, Progress::Finished(Outcome::Succeeded { at }) => {
Some(Outcome::Succeeded { at }) if at >= finished_since at >= finished_since || self.is_milestone(name)
); }
record.job.is_some() Progress::Finished(Outcome::Abandoned) => self.is_milestone(name),
|| finished_recently Progress::Untouched => false,
|| record.outcome == Some(Outcome::Failed)
|| (self.is_milestone(name) && record.outcome.is_some())
}) })
.map(|(name, _)| name.as_str()) .map(|(name, _)| name.as_str())
.collect(); .collect();
let root = self.root.as_deref().filter(|root| pending.contains(root)); let root = self.root.unit().filter(|root| pending.contains(root));
let stages: Vec<&str> = self let stages: Vec<&str> = self
.milestone_targets .milestone_targets
.iter() .iter()
@@ -627,64 +649,41 @@ impl BootState {
unblocked.clear(); unblocked.clear();
leftovers.clear(); leftovers.clear();
} }
let mut rows = Vec::new();
let mut visited = HashSet::new(); let mut visited = HashSet::new();
let mut rows = Vec::new();
stages stages
.iter() .iter()
.copied() .copied()
.chain(unblocked) .chain(unblocked)
.chain(leftovers) .chain(leftovers)
.for_each(|top| { .for_each(|top| {
if !visited.contains(top) { if visited.contains(top) {
self.emit( return;
top, }
&pending, let stage = self.grow(top, &pending, &mut visited);
&mut visited, if stage.row.status != RowStatus::Done || !stage.children.is_empty() {
&mut Vec::new(), stage.flatten_into(0, &mut rows);
true,
&mut rows,
);
} }
}); });
let mut kept = Vec::new(); rows
grow_forest(&mut rows.into_iter().peekable(), 0)
.into_iter()
.filter(|stage| stage.row.status != RowStatus::Done || !stage.children.is_empty())
.for_each(|stage| stage.flatten_into(0, &mut kept));
relink_siblings(kept)
} }
fn emit<'a>( fn grow<'a>(
&'a self, &'a self,
unit: &'a str, unit: &'a str,
pending: &HashSet<&'a str>, pending: &HashSet<&'a str>,
visited: &mut HashSet<&'a str>, visited: &mut HashSet<&'a str>,
ancestry: &mut Vec<bool>, ) -> TreeNode {
is_last: bool,
rows: &mut Vec<TreeRow>,
) {
visited.insert(unit); visited.insert(unit);
let record = &self.units[unit]; let record = &self.units[unit];
let running_since = record.running_since(); let row = TreeRow {
let status = match (record.job, running_since, record.outcome) { depth: 0,
(Some(_), Some(_), _) => RowStatus::Running,
(Some(_), None, _) => RowStatus::Waiting,
(None, _, Some(Outcome::Failed)) => RowStatus::Failed,
(None, ..) => RowStatus::Done,
};
let mut is_last_sibling = ancestry.clone();
is_last_sibling.push(is_last);
rows.push(TreeRow {
depth: ancestry.len(),
is_last_sibling,
label: display_label(&record.facts), label: display_label(&record.facts),
description: summary(&record.facts), description: summary(&record.facts),
kind: UnitKind::of(&record.facts.name), kind: UnitKind::of(&record.facts.name),
status, status: record.row_status(),
queued_at: record.job.map(|job| job.queued_at).unwrap_or_default(),
running_since,
chain: Vec::new(), chain: Vec::new(),
}); };
let candidates: Vec<&str> = self let candidates: Vec<&str> = self
.waits_for(unit, pending) .waits_for(unit, pending)
.into_iter() .into_iter()
@@ -704,13 +703,16 @@ impl BootState {
self.sort_siblings(&mut children); self.sort_siblings(&mut children);
children.dedup(); children.dedup();
visited.extend(children.iter().copied()); visited.extend(children.iter().copied());
ancestry.push(is_last); TreeNode {
let count = children.len(); row,
children.into_iter().enumerate().for_each(|(index, child)| { children: children
visited.remove(child); .into_iter()
self.emit(child, pending, visited, ancestry, index + 1 == count, rows); .map(|child| {
}); visited.remove(child);
ancestry.pop(); self.grow(child, pending, visited)
})
.collect(),
}
} }
fn is_milestone(&self, unit: &str) -> bool { fn is_milestone(&self, unit: &str) -> bool {
@@ -754,13 +756,17 @@ impl BootState {
fn sort_siblings(&self, names: &mut [&str]) { fn sort_siblings(&self, names: &mut [&str]) {
let rank = |name: &str| { let rank = |name: &str| {
let record = &self.units[name]; let record = &self.units[name];
match (record.running_since(), record.outcome) { match record.progress {
(Some(since), _) => SiblingRank::RunningSince(since), Progress::Pending(_) => record
(None, Some(Outcome::Succeeded { at })) => { .running_since()
.map_or(SiblingRank::Waiting, SiblingRank::RunningSince),
Progress::Finished(Outcome::Succeeded { at }) => {
SiblingRank::RunningSince(record.inactive_exit.unwrap_or(at)) SiblingRank::RunningSince(record.inactive_exit.unwrap_or(at))
} }
(None, Some(Outcome::Failed)) => SiblingRank::Failed, Progress::Finished(Outcome::Failed) => SiblingRank::Failed,
(None, _) => SiblingRank::Waiting, Progress::Finished(Outcome::Abandoned) | Progress::Untouched => {
SiblingRank::Waiting
}
} }
}; };
names.sort_by(|left, right| rank(left).cmp(&rank(right)).then_with(|| left.cmp(right))); names.sort_by(|left, right| rank(left).cmp(&rank(right)).then_with(|| left.cmp(right)));
@@ -792,7 +798,7 @@ impl MilestoneWalk {
label: reached.target.to_owned(), label: reached.target.to_owned(),
finished_units: upto.saturating_sub(self.consumed), finished_units: upto.saturating_sub(self.consumed),
started_at: self.previous.min(reached.reached_at), started_at: self.previous.min(reached.reached_at),
reached_at: Some(reached.reached_at), reached_at: reached.reached_at,
}); });
self.consumed = self.consumed.max(upto); self.consumed = self.consumed.max(upto);
self.previous = reached.reached_at; self.previous = reached.reached_at;
@@ -809,7 +815,7 @@ fn on_paths_to_running(rows: &[TreeRow]) -> Vec<bool> {
let descendant_kept = kept_below.iter().skip(row.depth + 1).any(|kept| *kept); let descendant_kept = kept_below.iter().skip(row.depth + 1).any(|kept| *kept);
kept_below.resize(row.depth + 1, false); kept_below.resize(row.depth + 1, false);
let anchors_the_tree = row.depth == 0 && row.kind == UnitKind::Target; let anchors_the_tree = row.depth == 0 && row.kind == UnitKind::Target;
let keep = matches!(row.status, RowStatus::Running | RowStatus::Failed) let keep = matches!(row.status, RowStatus::Running { .. } | RowStatus::Failed)
|| descendant_kept || descendant_kept
|| anchors_the_tree; || anchors_the_tree;
kept_below[row.depth] |= keep; kept_below[row.depth] |= keep;
@@ -838,15 +844,13 @@ fn with_spare_rows(essential: &[bool], budget: usize) -> Vec<bool> {
#[must_use] #[must_use]
pub fn fit_to_height(rows: Vec<TreeRow>, budget: usize) -> Vec<TreeRow> { pub fn fit_to_height(rows: Vec<TreeRow>, budget: usize) -> Vec<TreeRow> {
if rows.len() <= budget { if rows.len() <= budget {
return relink_siblings(rows); return rows;
} }
let kept = with_spare_rows(&on_paths_to_running(&rows), budget); let kept = with_spare_rows(&on_paths_to_running(&rows), budget);
let survivors: Vec<TreeRow> = rows rows.into_iter()
.into_iter()
.zip(kept) .zip(kept)
.filter_map(|(row, keep)| keep.then_some(row)) .filter_map(|(row, keep)| keep.then_some(row))
.collect(); .collect()
relink_siblings(survivors)
} }
const MIN_FOLDED_LINKS: usize = 2; const MIN_FOLDED_LINKS: usize = 2;
@@ -918,34 +922,7 @@ pub fn fold_chains(rows: Vec<TreeRow>) -> Vec<TreeRow> {
grow_forest(&mut rows.into_iter().peekable(), 0) grow_forest(&mut rows.into_iter().peekable(), 0)
.into_iter() .into_iter()
.for_each(|root| root.fold(false).flatten_into(0, &mut flattened)); .for_each(|root| root.fold(false).flatten_into(0, &mut flattened));
relink_siblings(flattened) flattened
}
fn relink_siblings(rows: Vec<TreeRow>) -> Vec<TreeRow> {
let mut later_sibling: Vec<bool> = Vec::new();
let mut is_last: Vec<bool> = rows
.iter()
.rev()
.map(|row| {
let last = !later_sibling.get(row.depth).copied().unwrap_or(false);
later_sibling.resize(row.depth + 1, false);
later_sibling[row.depth] = true;
last
})
.collect();
is_last.reverse();
let mut ancestry: Vec<bool> = Vec::new();
rows.into_iter()
.zip(is_last)
.map(|(row, last)| {
ancestry.truncate(row.depth);
ancestry.push(last);
TreeRow {
is_last_sibling: ancestry.clone(),
..row
}
})
.collect()
} }
fn labelled_by_description(facts: &UnitFacts) -> bool { fn labelled_by_description(facts: &UnitFacts) -> bool {
@@ -1078,11 +1055,6 @@ mod tests {
"graphical.target", "graphical.target",
] ]
); );
let lasts: Vec<bool> = rows
.iter()
.map(|row| *row.is_last_sibling.last().unwrap())
.collect();
assert_eq!(lasts, [false, false, false, true, true, true]);
} }
#[test] #[test]
@@ -1244,12 +1216,10 @@ mod tests {
folded_outline(&state), folded_outline(&state),
["root.target", " a", " b", " d"] ["root.target", " a", " b", " d"]
); );
let rows = fold_chains(fit_to_height(both.tree_rows(Duration::MAX), 0)); assert_eq!(
let lasts: Vec<bool> = rows folded_outline(&both),
.iter() ["root.target", " a", " b", " c"]
.map(|row| *row.is_last_sibling.last().unwrap()) );
.collect();
assert_eq!(lasts, [true, true, false, true]);
} }
#[test] #[test]
@@ -1362,7 +1332,7 @@ mod tests {
reached_at: 2000 * MS, reached_at: 2000 * MS,
}] }]
); );
assert_eq!(state.milestones()[0].reached_at, Some(2000 * MS)); assert_eq!(state.milestones()[0].reached_at, 2000 * MS);
assert_eq!(state.tally().done, 2); assert_eq!(state.tally().done, 2);
assert!(state.tree_rows(Duration::MAX).is_empty()); assert!(state.tree_rows(Duration::MAX).is_empty());
} }
@@ -1508,8 +1478,11 @@ mod tests {
}, },
); );
assert_eq!( assert_eq!(
state.tree_rows(Duration::MAX)[0].running_since, state.tree_rows(Duration::MAX)[0].status,
Some(1200 * MS) RowStatus::Running {
queued_at: 1000 * MS,
since: 1200 * MS
}
); );
state.finish_job(1, JobResult::Done, 1700 * MS); state.finish_job(1, JobResult::Done, 1700 * MS);
assert_eq!( assert_eq!(
+17 -19
View File
@@ -36,7 +36,7 @@ use crate::{
clock::monotonic_now, clock::monotonic_now,
console::Console, console::Console,
error::Error, error::Error,
feed::Feed, feed::{Feed, RootRequest},
password::{PasswordEntry, RequestWatch}, password::{PasswordEntry, RequestWatch},
sysroot::INITRD_RELEASE, sysroot::INITRD_RELEASE,
systemd::{Scope, Session}, systemd::{Scope, Session},
@@ -45,19 +45,19 @@ use crate::{
const FRAME_INTERVAL: Duration = Duration::from_millis(100); const FRAME_INTERVAL: Duration = Duration::from_millis(100);
const FULL_REPAINT_INTERVAL: Duration = Duration::from_secs(1); const FULL_REPAINT_INTERVAL: Duration = Duration::from_secs(1);
pub struct Options { pub struct Settings {
pub scope: Scope, pub scope: Scope,
pub shutdown: bool, pub shutdown: bool,
pub target: Option<String>, pub target: RootRequest,
pub timing: Timing, pub timing: Timing,
pub palette: Palette, pub palette: Palette,
} }
pub fn run(options: &Options) -> Result<(), Error> { pub fn run(settings: &Settings) -> Result<(), Error> {
let terminate = Arc::new(AtomicBool::new(false)); let terminate = Arc::new(AtomicBool::new(false));
flag::register(SIGTERM, Arc::clone(&terminate))?; flag::register(SIGTERM, Arc::clone(&terminate))?;
if options.scope == Scope::System if settings.scope == Scope::System
&& !options.shutdown && !settings.shutdown
&& Session::open(Scope::System) && Session::open(Scope::System)
.and_then(|session| session.boot_in_progress()) .and_then(|session| session.boot_in_progress())
.is_ok_and(|booting| !booting) .is_ok_and(|booting| !booting)
@@ -65,24 +65,23 @@ pub fn run(options: &Options) -> Result<(), Error> {
eprintln!("bootvine: boot already finished, leaving the console alone"); eprintln!("bootvine: boot already finished, leaving the console alone");
return Ok(()); return Ok(());
} }
let phase = match options.scope { let phase = match settings.scope {
_ if options.shutdown => Phase::Shutdown, _ if settings.shutdown => Phase::Shutdown,
Scope::User => Phase::User, Scope::User => Phase::User,
Scope::System if Path::new(INITRD_RELEASE).exists() => Phase::Initrd, Scope::System if Path::new(INITRD_RELEASE).exists() => Phase::Initrd,
Scope::System => Phase::Host, Scope::System => Phase::Host,
}; };
let mut state = BootState::new(phase); let mut state = BootState::new(phase);
let mut feed = Feed::new(options.scope, options.target.clone()); let mut feed = Feed::new(settings.scope, settings.target.clone());
let mut console = Console::take(options.scope == Scope::System); let mut console = Console::take(settings.scope == Scope::System);
let mut terminal = ratatui::try_init()?; let mut terminal = ratatui::try_init()?;
let watched = watch( let watched = watch(
&mut state, &mut state,
&mut feed, &mut feed,
&mut terminal, &mut terminal,
&terminate, &terminate,
&options.palette, settings,
&mut console, &mut console,
&options.timing,
); );
ratatui::restore(); ratatui::restore();
watched watched
@@ -143,9 +142,8 @@ fn watch(
feed: &mut Feed, feed: &mut Feed,
terminal: &mut DefaultTerminal, terminal: &mut DefaultTerminal,
terminate: &AtomicBool, terminate: &AtomicBool,
palette: &Palette, settings: &Settings,
console: &mut Console, console: &mut Console,
timing: &Timing,
) -> Result<(), Error> { ) -> Result<(), Error> {
let mut origin = BootOrigin::read(); let mut origin = BootOrigin::read();
let mut origin_phase = state.phase; let mut origin_phase = state.phase;
@@ -178,8 +176,8 @@ fn watch(
canvas.render_widget( canvas.render_widget(
BootView { BootView {
state, state,
palette, palette: &settings.palette,
timing, timing: &settings.timing,
glyphs: &console.glyphs, glyphs: &console.glyphs,
now: monotonic_now(), now: monotonic_now(),
origin: &origin, origin: &origin,
@@ -201,9 +199,9 @@ fn watch(
if state.is_complete() { if state.is_complete() {
eprintln!( eprintln!(
"bootvine: {} reached, handing the console over", "bootvine: {} reached, handing the console over",
state.root.as_deref().unwrap_or("boot") state.root.unit().unwrap_or("boot")
); );
sleep(timing.keep_final_frame_for); sleep(settings.timing.keep_final_frame_for);
return Ok(()); return Ok(());
} }
if terminate.load(Ordering::Relaxed) { if terminate.load(Ordering::Relaxed) {
@@ -212,7 +210,7 @@ fn watch(
sleep_until_readable( sleep_until_readable(
[ [
Some(stdin()), Some(stdin()),
feed.session.as_ref().map(AsFd::as_fd), feed.session_fd(),
requests.as_ref().map(AsFd::as_fd), requests.as_ref().map(AsFd::as_fd),
] ]
.into_iter() .into_iter()
+1 -1
View File
@@ -23,7 +23,7 @@ impl Sysroot {
Ok(Self { directory }) Ok(Self { directory })
} }
pub fn enter(self) -> Result<(), Errno> { pub fn enter(&self) -> Result<(), Errno> {
fchdir(&self.directory)?; fchdir(&self.directory)?;
chroot(".")?; chroot(".")?;
chdir("/") chdir("/")
+23 -34
View File
@@ -19,7 +19,7 @@ pub use self::chrome::PasswordPrompt;
use self::{ use self::{
chrome::{FOOTER_HEIGHT, Footer, Header, PasswordPopup}, chrome::{FOOTER_HEIGHT, Footer, Header, PasswordPopup},
stages::Stages, stages::Stages,
timeline::Timeline, timeline::{RunningRun, Timeline},
tree::UnitTree, tree::UnitTree,
}; };
use crate::{ use crate::{
@@ -59,11 +59,19 @@ pub struct BootView<'a> {
impl BootView<'_> { impl BootView<'_> {
fn timeline<'a>(&'a self, rows: &'a [TreeRow]) -> Timeline<'a> { fn timeline<'a>(&'a self, rows: &'a [TreeRow]) -> Timeline<'a> {
let mut running: Vec<&TreeRow> = rows let mut running: Vec<RunningRun> = rows
.iter() .iter()
.filter(|row| row.kind != UnitKind::Target && row.status == RowStatus::Running) .filter(|row| row.kind != UnitKind::Target)
.filter_map(|row| match row.status {
RowStatus::Running { queued_at, since } => Some(RunningRun {
label: &row.label,
queued_at,
since,
}),
_ => None,
})
.collect(); .collect();
running.sort_by_key(|row| row.running_since); running.sort_by_key(|run| run.since);
Timeline { Timeline {
origin: self.state.origin, origin: self.state.origin,
now: self.now, now: self.now,
@@ -73,12 +81,7 @@ impl BootView<'_> {
.iter() .iter()
.map(|stage| stage.reached_at) .map(|stage| stage.reached_at)
.collect(), .collect(),
milestones: self milestones: self.state.milestones(),
.state
.milestones()
.into_iter()
.filter(|row| row.reached_at.is_some())
.collect(),
finished: self finished: self
.state .state
.finished_runs .finished_runs
@@ -101,7 +104,6 @@ impl Widget for BootView<'_> {
.state .state
.tree_rows(self.now.saturating_sub(self.timing.keep_finished_units_for)); .tree_rows(self.now.saturating_sub(self.timing.keep_finished_units_for));
let pending_count = all_rows.len(); let pending_count = all_rows.len();
let pruned_rows = fold_chains(fit_to_height(all_rows.clone(), 0));
let header = Header { let header = Header {
origin: self.origin, origin: self.origin,
total: (!self.state.finished_stages.is_empty()) total: (!self.state.finished_stages.is_empty())
@@ -114,17 +116,7 @@ impl Widget for BootView<'_> {
palette: self.palette, palette: self.palette,
glyphs: self.glyphs, glyphs: self.glyphs,
}; };
let pruned = UnitTree { let timeline = self.timeline(&all_rows);
phase: stages.current_phase(),
rows: &pruned_rows,
hidden: pending_count - shown_units(&pruned_rows),
now: self.now,
hide_runs_shorter_than: self.timing.hide_runs_shorter_than,
frame: self.frame,
palette: self.palette,
glyphs: self.glyphs,
};
let timeline = self.timeline(&pruned_rows);
let footer = Footer { let footer = Footer {
tally: self.state.tally(), tally: self.state.tally(),
palette: self.palette, palette: self.palette,
@@ -135,28 +127,25 @@ impl Widget for BootView<'_> {
let free = area let free = area
.height .height
.saturating_sub(HEADER_HEIGHT + stages.height() + FOOTER_HEIGHT); .saturating_sub(HEADER_HEIGHT + stages.height() + FOOTER_HEIGHT);
let whole_tree = fit_to_height(all_rows.clone(), usize::MAX);
let whole_tree_height = UnitTree {
phase: pruned.phase.clone(),
rows: &whole_tree,
hidden: 0,
..pruned
}
.height();
let heights = Heights::share( let heights = Heights::share(
free, free,
whole_tree_height, UnitTree::height_of(pending_count, 0),
if fits_timeline { timeline.height() } else { 0 }, if fits_timeline { timeline.height() } else { 0 },
); );
let budget = usize::from(heights.tree.saturating_sub(1)); let budget = usize::from(heights.tree.saturating_sub(1));
let rows = [whole_tree.clone(), fold_chains(whole_tree)] let rows = [all_rows.clone(), fold_chains(all_rows.clone())]
.into_iter() .into_iter()
.find(|rows| rows.len() <= budget) .find(|rows| rows.len() <= budget)
.unwrap_or_else(|| fold_chains(fit_to_height(all_rows, budget))); .unwrap_or_else(|| fold_chains(fit_to_height(all_rows.clone(), budget)));
let tree = UnitTree { let tree = UnitTree {
phase: stages.current_phase(),
rows: &rows, rows: &rows,
hidden: pending_count - shown_units(&rows), hidden: pending_count - shown_units(&rows),
..pruned now: self.now,
hide_runs_shorter_than: self.timing.hide_runs_shorter_than,
frame: self.frame,
palette: self.palette,
glyphs: self.glyphs,
}; };
let tree_height = tree.height().min(heights.tree); let tree_height = tree.height().min(heights.tree);
+3 -7
View File
@@ -29,7 +29,7 @@ struct Conclusion<'a> {
impl Stages<'_> { impl Stages<'_> {
pub fn height(&self) -> u16 { pub fn height(&self) -> u16 {
u16::try_from(self.lines().len()).unwrap_or(u16::MAX) u16::try_from(self.state.finished_stages.len()).unwrap_or(u16::MAX)
} }
fn conclusion(&self) -> Option<Conclusion<'_>> { fn conclusion(&self) -> Option<Conclusion<'_>> {
@@ -47,7 +47,7 @@ impl Stages<'_> {
.state .state
.handoff_unit .handoff_unit
.as_deref() .as_deref()
.or(self.state.root.as_deref()) .or(self.state.root.unit())
.unwrap_or("the console"), .unwrap_or("the console"),
}) })
} }
@@ -110,14 +110,10 @@ impl Stages<'_> {
elapsed.fg(self.palette.text), elapsed.fg(self.palette.text),
]) ])
} }
fn lines(&self) -> Vec<Line<'static>> {
self.finished_phases().collect()
}
} }
impl Widget for Stages<'_> { impl Widget for Stages<'_> {
fn render(self, area: Rect, buf: &mut Buffer) { fn render(self, area: Rect, buf: &mut Buffer) {
Paragraph::new(self.lines()).render(area, buf); Paragraph::new(self.finished_phases().collect::<Vec<_>>()).render(area, buf);
} }
} }
+26 -25
View File
@@ -16,7 +16,7 @@ use ratatui::{
use super::{fit_width, rule, unit_count}; use super::{fit_width, rule, unit_count};
use crate::{ use crate::{
glyphs::Glyphs, glyphs::Glyphs,
model::{FinishedRun, MilestoneRow, TreeRow}, model::{FinishedRun, MilestoneRow},
palette::Palette, palette::Palette,
}; };
@@ -50,11 +50,17 @@ pub struct Timeline<'a> {
pub root_switches: Vec<Duration>, pub root_switches: Vec<Duration>,
pub milestones: Vec<MilestoneRow>, pub milestones: Vec<MilestoneRow>,
pub finished: Vec<&'a FinishedRun>, pub finished: Vec<&'a FinishedRun>,
pub running: Vec<&'a TreeRow>, pub running: Vec<RunningRun<'a>>,
pub palette: &'a Palette, pub palette: &'a Palette,
pub glyphs: &'a Glyphs, pub glyphs: &'a Glyphs,
} }
pub struct RunningRun<'a> {
pub label: &'a str,
pub queued_at: Duration,
pub since: Duration,
}
impl Timeline<'_> { impl Timeline<'_> {
pub fn height(&self) -> u16 { pub fn height(&self) -> u16 {
let entries = self.milestones.len() let entries = self.milestones.len()
@@ -87,17 +93,13 @@ impl Timeline<'_> {
), ),
self.palette.done, self.palette.done,
), ),
segments: row segments: vec![Segment {
.reached_at from: row.started_at,
.map(|reached_at| Segment { to: row.reached_at,
from: row.started_at, symbol: self.glyphs.bead,
to: reached_at, color: self.palette.done,
symbol: self.glyphs.bead, }],
color: self.palette.done, still_going: false,
})
.into_iter()
.collect(),
still_going_at: None,
} }
} }
@@ -123,7 +125,7 @@ impl Timeline<'_> {
symbol: self.glyphs.bead, symbol: self.glyphs.bead,
color: outcome, color: outcome,
}], }],
still_going_at: None, still_going: false,
} }
} }
@@ -135,16 +137,15 @@ impl Timeline<'_> {
) )
} }
fn running_entry<'a>(&self, row: &'a TreeRow) -> TimelineEntry<'a> { fn running_entry(&self, run: &RunningRun) -> TimelineEntry<'static> {
let since = row.running_since.unwrap_or(row.queued_at); let waited = (run.since > run.queued_at).then_some(Segment {
let waited = (since > row.queued_at).then_some(Segment { from: run.queued_at,
from: row.queued_at, to: run.since,
to: since,
symbol: self.glyphs.waiting_bead, symbol: self.glyphs.waiting_bead,
color: self.palette.waiting, color: self.palette.waiting,
}); });
let ran = Segment { let ran = Segment {
from: since, from: run.since,
to: self.now, to: self.now,
symbol: self.glyphs.bead, symbol: self.glyphs.bead,
color: self.palette.running, color: self.palette.running,
@@ -152,10 +153,10 @@ impl Timeline<'_> {
TimelineEntry { TimelineEntry {
label: Line::from(vec![ label: Line::from(vec![
format!("{} ", self.glyphs.running_mark).fg(self.palette.running), format!("{} ", self.glyphs.running_mark).fg(self.palette.running),
self.fitted(&row.label).fg(self.palette.text), self.fitted(run.label).fg(self.palette.text),
]), ]),
segments: waited.into_iter().chain(once(ran)).collect(), segments: waited.into_iter().chain(once(ran)).collect(),
still_going_at: Some(self.now), still_going: true,
} }
} }
} }
@@ -208,9 +209,9 @@ impl Widget for Timeline<'_> {
segment.color, segment.color,
)); ));
}); });
if let Some(now) = entry.still_going_at { if entry.still_going {
ctx.marker(Marker::Custom(self.glyphs.still_going)); ctx.marker(Marker::Custom(self.glyphs.still_going));
ctx.draw(&Points::new(&[(now.as_secs_f64(), y)], muted)); ctx.draw(&Points::new(&[(self.now.as_secs_f64(), y)], muted));
} }
}); });
ctx.marker(Marker::Custom(self.glyphs.root_switch_mark)); ctx.marker(Marker::Custom(self.glyphs.root_switch_mark));
@@ -233,7 +234,7 @@ impl Widget for Timeline<'_> {
struct TimelineEntry<'a> { struct TimelineEntry<'a> {
label: Line<'a>, label: Line<'a>,
segments: Vec<Segment>, segments: Vec<Segment>,
still_going_at: Option<Duration>, still_going: bool,
} }
struct Segment { struct Segment {
+77 -36
View File
@@ -56,12 +56,16 @@ fn width_of(text: &str) -> u16 {
} }
impl UnitTree<'_> { impl UnitTree<'_> {
pub fn height(&self) -> u16 { pub fn height_of(rows: usize, hidden: usize) -> u16 {
u16::try_from(self.rows.len() + usize::from(self.hidden > 0)) u16::try_from(rows + usize::from(hidden > 0))
.unwrap_or(u16::MAX) .unwrap_or(u16::MAX)
.saturating_add(HEADER_ROWS) .saturating_add(HEADER_ROWS)
} }
pub fn height(&self) -> u16 {
Self::height_of(self.rows.len(), self.hidden)
}
fn phase_fits_its_column(&self, columns: &Columns) -> bool { fn phase_fits_its_column(&self, columns: &Columns) -> bool {
self.phase.width() <= usize::from(columns.label) self.phase.width() <= usize::from(columns.label)
} }
@@ -103,7 +107,7 @@ impl UnitTree<'_> {
(Stage::Reached, ..) => self.palette.done.into(), (Stage::Reached, ..) => self.palette.done.into(),
(_, _, RowStatus::Failed) => Style::from(self.palette.failed).bold(), (_, _, RowStatus::Failed) => Style::from(self.palette.failed).bold(),
(_, UnitKind::Target, _) => self.palette.target.into(), (_, UnitKind::Target, _) => self.palette.target.into(),
(_, _, RowStatus::Running) => self.palette.text.into(), (_, _, RowStatus::Running { .. }) => self.palette.text.into(),
(_, _, RowStatus::Waiting) => self.palette.waiting.into(), (_, _, RowStatus::Waiting) => self.palette.waiting.into(),
(_, _, RowStatus::Done) => self.palette.muted.into(), (_, _, RowStatus::Done) => self.palette.muted.into(),
} }
@@ -122,7 +126,7 @@ impl UnitTree<'_> {
format!("[{}] ", self.glyphs.failed).fg(self.palette.failed) format!("[{}] ", self.glyphs.failed).fg(self.palette.failed)
} }
(_, UnitKind::Target, _) => Span::default(), (_, UnitKind::Target, _) => Span::default(),
(_, _, RowStatus::Running) => { (_, _, RowStatus::Running { .. }) => {
let spinner = SPINNER[usize::try_from(self.frame % 4).unwrap_or_default()]; let spinner = SPINNER[usize::try_from(self.frame % 4).unwrap_or_default()];
format!("[{spinner}] ").fg(self.palette.running) format!("[{spinner}] ").fg(self.palette.running)
} }
@@ -131,10 +135,6 @@ impl UnitTree<'_> {
} }
} }
fn lead_width(&self, row: &TreeRow, stage: Stage) -> usize {
tree_prefix(row).width() + self.status_marker(row, stage).width()
}
fn chained_label(&self, row: &TreeRow, room: usize) -> String { fn chained_label(&self, row: &TreeRow, room: usize) -> String {
let link = format!(" {} ", self.glyphs.chain_link); let link = format!(" {} ", self.glyphs.chain_link);
let full: String = once(row.label.as_str()) let full: String = once(row.label.as_str())
@@ -182,10 +182,9 @@ impl UnitTree<'_> {
) )
} }
fn row(&self, row: &TreeRow, stage: Stage, columns: &Columns) -> Row<'static> { fn row(&self, row: &TreeRow, stage: Stage, prefix: String, columns: &Columns) -> Row<'static> {
let prefix = tree_prefix(row);
let marker = self.status_marker(row, stage); let marker = self.status_marker(row, stage);
let room = usize::from(columns.label).saturating_sub(self.lead_width(row, stage)); let room = usize::from(columns.label).saturating_sub(prefix.width() + marker.width());
let annotation = |text: &str, width: u16| { let annotation = |text: &str, width: u16| {
if row.chain.is_empty() { if row.chain.is_empty() {
fit_width(text, usize::from(width), self.glyphs.ellipsis) fit_width(text, usize::from(width), self.glyphs.ellipsis)
@@ -193,12 +192,14 @@ impl UnitTree<'_> {
String::new() String::new()
} }
}; };
let timer = row let timer = match row.status {
.running_since RowStatus::Running { since, .. }
.map(|since| self.now.saturating_sub(since)) if self.now.saturating_sub(since) >= self.hide_runs_shorter_than =>
.filter(|running_for| *running_for >= self.hide_runs_shorter_than) {
.map(|running_for| ELAPSED.unsigned_duration_to_string(&running_for)) ELAPSED.unsigned_duration_to_string(&self.now.saturating_sub(since))
.unwrap_or_default(); }
_ => String::new(),
};
let style = self.label_style(row, stage); let style = self.label_style(row, stage);
Row::new(columns.shown([ Row::new(columns.shown([
Line::from(vec![ Line::from(vec![
@@ -248,8 +249,9 @@ impl Widget for UnitTree<'_> {
self.rows self.rows
.iter() .iter()
.zip(self.stages()) .zip(self.stages())
.zip(tree_prefixes(self.rows))
.take(shown) .take(shown)
.map(|(row, stage)| self.row(row, stage, &columns)) .map(|((row, stage), prefix)| self.row(row, stage, prefix, &columns))
.chain(overflow), .chain(overflow),
columns.widths(), columns.widths(),
) )
@@ -261,24 +263,63 @@ impl Widget for UnitTree<'_> {
} }
} }
fn tree_prefix(row: &TreeRow) -> String { fn tree_prefixes(rows: &[TreeRow]) -> Vec<String> {
let ancestors = row let mut later_sibling: Vec<bool> = Vec::new();
.is_last_sibling let mut is_last: Vec<bool> = rows
.iter() .iter()
.take(row.depth) .rev()
.map(|ancestor_is_last| { .map(|row| {
if *ancestor_is_last { let last = !later_sibling.get(row.depth).copied().unwrap_or(false);
ENDED_TRUNK later_sibling.resize(row.depth + 1, false);
} else { later_sibling[row.depth] = true;
PASSING_TRUNK last
} })
}); .collect();
let connector = match row.is_last_sibling.last() { is_last.reverse();
Some(false) => BRANCH, let mut trunks: Vec<&str> = Vec::new();
_ => LAST_BRANCH, rows.iter()
}; .zip(is_last)
once(ENDED_TRUNK) .map(|(row, last)| {
.chain(ancestors) trunks.truncate(row.depth);
.chain(once(connector)) let connector = if last { LAST_BRANCH } else { BRANCH };
let prefix = once(ENDED_TRUNK)
.chain(trunks.iter().copied())
.chain(once(connector))
.collect();
trunks.push(if last { ENDED_TRUNK } else { PASSING_TRUNK });
prefix
})
.collect() .collect()
} }
#[cfg(test)]
mod tests {
use super::*;
fn at_depth(depth: usize) -> TreeRow {
TreeRow {
depth,
label: String::new(),
description: String::new(),
kind: UnitKind::Service,
status: RowStatus::Waiting,
chain: Vec::new(),
}
}
#[test]
fn prefixes_close_each_branch_at_its_last_sibling() {
let rows: Vec<TreeRow> = [0, 0, 1, 1, 2, 0].into_iter().map(at_depth).collect();
assert_eq!(
tree_prefixes(&rows),
[
" ├─ ",
" ├─ ",
" │ ├─ ",
" │ └─ ",
" │ └─ ",
" └─ ",
]
);
}
}