refactor: drop single-use wrappers in the boot model, view and installer

This commit is contained in:
Willem Vanhulle committed 2026-10-25 13:55:27 +01:00
1 parent f8f1b54d75
commit d3fcd6f085
11 files changed
+121 -181

No files matched your search

-2
View File
@@ -1,6 +1,5 @@
mod boot_change;
pub mod boot_origin;
mod boot_projection;
mod job_ingestion;
mod reached_milestones;
mod unit_facts;
@@ -10,7 +9,6 @@ use std::{collections::HashMap, time::Duration};
pub use self::{
boot_change::BootChange,
boot_projection::BootProjection,
reached_milestones::MilestoneRow,
unit_facts::{ActiveState, Activity, JobKind, JobResult, UnitFacts, UnitKind, UnitTimeouts},
waiting_tree::{RowStatus, TreeNode, TreeRow, flatten_forest},
+6 -2
View File
@@ -43,12 +43,16 @@ impl BootState {
BootChange::QueueJob { id, unit, kind, at } => self.queue_job(id, &unit, kind, at),
BootChange::FinishJob { id, result, at } => self.finish_job(id, result, at),
BootChange::SetRoot(root) => self.set_root(root),
BootChange::SetHandoff(unit) => self.set_handoff(unit),
BootChange::SetHandoff(unit) => {
if let Some(handoff) = &mut self.handoff_unit {
*handoff = unit;
}
}
BootChange::SetOrigin(origin) => self.origin = origin,
BootChange::SwitchRoot { at } => self.switch_root(at),
BootChange::ForgetJobs => self.forget_jobs(),
BootChange::ManagerExited { at } => self.manager_exited_at = Some(at),
BootChange::BootFinished => self.mark_boot_finished(),
BootChange::BootFinished => self.boot_finished = true,
}
}
}
-21
View File
@@ -1,21 +0,0 @@
use std::time::Duration;
use super::{BootState, MilestoneRow, Tally, TreeNode};
#[derive(Clone, Debug)]
pub struct BootProjection {
pub forest: Vec<TreeNode>,
pub milestones: Vec<MilestoneRow>,
pub tally: Tally,
}
impl BootState {
#[must_use]
pub fn project(&self, finished_since: Duration) -> BootProjection {
BootProjection {
forest: self.waiting_forest(finished_since),
milestones: self.milestones(),
tally: self.tally(),
}
}
}
+12 -27
View File
@@ -103,16 +103,6 @@ impl BootState {
}
}
pub fn set_handoff(&mut self, unit: String) {
if self.handoff_unit.is_some() {
self.handoff_unit = Some(unit);
}
}
pub fn mark_boot_finished(&mut self) {
self.boot_finished = true;
}
pub fn track_unit(&mut self, facts: UnitFacts, activity: Activity) {
let record = self
.units
@@ -133,21 +123,20 @@ impl BootState {
}
pub fn queue_job(&mut self, id: u32, unit: &str, kind: JobKind, at: Duration) {
self.enqueue(id, unit, kind, at);
if kind == JobKind::BringsUp
&& self.jobs.get(&id).is_some_and(|tracked| tracked == unit)
if self.enqueue(id, unit, kind, at)
&& kind == JobKind::BringsUp
&& self.root == Root::Awaiting(unit.to_owned())
{
self.root = Root::Queued(unit.to_owned());
}
}
fn enqueue(&mut self, id: u32, unit: &str, kind: JobKind, at: Duration) {
if self.jobs.contains_key(&id) {
return;
fn enqueue(&mut self, id: u32, unit: &str, kind: JobKind, at: Duration) -> bool {
if let Some(tracked) = self.jobs.get(&id) {
return tracked == unit;
}
let Some(record) = self.units.get_mut(unit) else {
return;
return false;
};
record.progress = Progress::Pending(PendingJob {
id,
@@ -155,6 +144,7 @@ impl BootState {
kind,
});
self.jobs.insert(id, unit.to_owned());
true
}
pub fn finish_job(&mut self, id: u32, result: JobResult, at: Duration) {
@@ -252,11 +242,6 @@ impl BootState {
})
}
#[must_use]
pub fn display_manager_started(&self) -> bool {
self.started_display_manager().is_some()
}
#[must_use]
pub fn tally(&self) -> Tally {
let carried = Tally {
@@ -287,7 +272,7 @@ impl BootState {
mod tests {
use super::*;
use crate::{
boot_model::{RowStatus, UnitTimeouts},
boot_model::{BootChange, RowStatus, UnitTimeouts},
demo_script::boot_test_fixtures::{
MS, activating, facts, nested_boot_sample as sample, queue_unit, queued_boot, running,
waiting, waiting_rows,
@@ -335,24 +320,24 @@ mod tests {
fn display_manager_activation_does_not_complete_the_boot() {
let mut state = sample();
queue_unit(&mut state, 20, waiting(HANDOFF_UNIT, &[]), 500 * MS);
assert!(!state.display_manager_started());
assert_eq!(state.started_display_manager(), None);
state.update_activity(HANDOFF_UNIT, activating(6000 * MS));
assert!(!state.is_complete());
assert!(state.display_manager_started());
assert_eq!(state.started_display_manager(), Some(HANDOFF_UNIT));
}
#[test]
fn boot_finished_hands_the_console_over() {
let mut state = sample();
queue_unit(&mut state, 20, waiting(HANDOFF_UNIT, &[]), 500 * MS);
state.mark_boot_finished();
state.apply(BootChange::BootFinished);
assert!(state.is_complete());
}
#[test]
fn boot_finished_is_ignored_in_the_initrd() {
let mut state = BootState::new(Phase::Initrd);
state.mark_boot_finished();
state.apply(BootChange::BootFinished);
assert!(!state.is_complete());
}
+28 -39
View File
@@ -10,32 +10,11 @@ pub struct MilestoneRow {
pub reached_at: Duration,
}
struct ReachedMilestone<'a> {
target: &'a str,
reached_at: Duration,
}
struct MilestoneWalk {
rows: Vec<MilestoneRow>,
struct MilestoneCursor {
previous: Duration,
consumed: usize,
}
impl MilestoneWalk {
fn advance(mut self, reached: &ReachedMilestone, succeeded_sorted: &[Duration]) -> Self {
let upto = succeeded_sorted.partition_point(|at| *at <= reached.reached_at);
self.rows.push(MilestoneRow {
label: reached.target.to_owned(),
finished_units: upto.saturating_sub(self.consumed),
started_at: self.previous.min(reached.reached_at),
reached_at: reached.reached_at,
});
self.consumed = self.consumed.max(upto);
self.previous = reached.reached_at;
self
}
}
impl BootState {
fn milestone_reached_at(&self, target: &str) -> Option<Duration> {
let record = self.units.get(target)?;
@@ -59,31 +38,41 @@ impl BootState {
})
.collect();
succeeded.sort_unstable();
let start = MilestoneWalk {
rows: self
.finished_stages
.iter()
.map(|stage| MilestoneRow {
label: stage.label.to_owned(),
finished_units: stage.finished_units,
started_at: stage.started_at,
reached_at: stage.reached_at,
})
.collect(),
let start = MilestoneCursor {
previous: self
.finished_stages
.last()
.map_or(self.origin, |stage| stage.reached_at),
consumed: 0,
};
self.milestone_targets
let reached_rows = self
.milestone_targets
.iter()
.filter_map(|target| {
self.milestone_reached_at(target)
.map(|reached_at| ReachedMilestone { target, reached_at })
.scan(start, |cursor, target| {
Some(self.milestone_reached_at(target).map(|reached_at| {
let upto = succeeded.partition_point(|at| *at <= reached_at);
let row = MilestoneRow {
label: target.clone(),
finished_units: upto.saturating_sub(cursor.consumed),
started_at: cursor.previous.min(reached_at),
reached_at,
};
cursor.consumed = cursor.consumed.max(upto);
cursor.previous = reached_at;
row
}))
})
.fold(start, |walk, reached| walk.advance(&reached, &succeeded))
.rows
.flatten();
self.finished_stages
.iter()
.map(|stage| MilestoneRow {
label: stage.label.to_owned(),
finished_units: stage.finished_units,
started_at: stage.started_at,
reached_at: stage.reached_at,
})
.chain(reached_rows)
.collect()
}
}
+10 -15
View File
@@ -113,25 +113,20 @@ impl UnitKind {
Self::Scope => Some("Scope"),
}
}
fn labelled_by_description(self) -> bool {
matches!(
self,
Self::Device | Self::Mount | Self::Swap | Self::Automount
)
}
}
fn labelled_by_description(facts: &UnitFacts) -> bool {
facts.description.is_some() && UnitKind::of(&facts.name).labelled_by_description()
fn description_label(facts: &UnitFacts) -> Option<&String> {
facts.description.as_ref().filter(|_| {
matches!(
UnitKind::of(&facts.name),
UnitKind::Device | UnitKind::Mount | UnitKind::Swap | UnitKind::Automount
)
})
}
pub(super) fn display_label(facts: &UnitFacts) -> String {
if labelled_by_description(facts) {
return facts
.description
.clone()
.unwrap_or_else(|| facts.name.clone());
if let Some(description) = description_label(facts) {
return description.clone();
}
match UnitKind::of(&facts.name) {
UnitKind::Target | UnitKind::Other => facts.name.clone(),
@@ -146,7 +141,7 @@ pub(super) fn summary(facts: &UnitFacts) -> Option<String> {
let repeats_the_name = facts.description.as_deref().is_some_and(|description| {
description == facts.name || description.eq_ignore_ascii_case(&display_label(facts))
});
if labelled_by_description(facts) || repeats_the_name {
if description_label(facts).is_some() || repeats_the_name {
return None;
}
facts.description.clone()
+12 -3
View File
@@ -35,7 +35,7 @@ use self::{
};
use crate::{
boot_model::{
BootProjection, BootState, RowStatus, TreeRow, UnitKind, boot_origin::BootOrigin,
BootState, MilestoneRow, RowStatus, TreeNode, TreeRow, UnitKind, boot_origin::BootOrigin,
flatten_forest,
},
screen_settings::{color_scheme::Colors, config_file::Timing, font_glyphs::Glyphs},
@@ -136,7 +136,7 @@ impl Widget for BootView<'_> {
};
let timeline = self.timeline(&all_rows);
let footer = Footer {
tally: self.projection.tally,
tally: self.state.tally(),
colors: &self.colors.footer,
glyphs: self.glyphs,
};
@@ -218,9 +218,18 @@ impl Heights {
}
}
#[derive(Clone, Debug)]
pub struct BootProjection {
pub forest: Vec<TreeNode>,
pub milestones: Vec<MilestoneRow>,
}
#[must_use]
pub fn project_boot(state: &BootState, timing: &Timing, now: Duration) -> BootProjection {
state.project(now.saturating_sub(timing.keep_finished_units_for))
BootProjection {
forest: state.waiting_forest(now.saturating_sub(timing.keep_finished_units_for)),
milestones: state.milestones(),
}
}
fn rule(color: Color, left: Line<'static>) -> Block<'static> {
+2 -2
View File
@@ -6,9 +6,9 @@ use std::{
use ratatui::{Terminal, backend::TestBackend};
use super::{BootView, project_boot, screen_render_fixtures::ryzen_origin};
use super::{BootProjection, BootView, project_boot, screen_render_fixtures::ryzen_origin};
use crate::{
boot_model::{BootProjection, BootState, JobResult, Phase, flatten_forest},
boot_model::{BootState, JobResult, Phase, flatten_forest},
demo_script::boot_test_fixtures::{MS, QueuedUnit, queued_boot, running, waiting},
screen_settings::{color_scheme::Colors, config_file::Timing, font_glyphs::Glyphs},
};
+3 -8
View File
@@ -9,8 +9,8 @@ use ratatui::{
};
use crate::{
boot_model::{BootChange, BootProjection, BootState, boot_origin::BootOrigin},
boot_view::{BootView, PasswordPrompt, project_boot},
boot_model::{BootChange, BootState, boot_origin::BootOrigin},
boot_view::{BootProjection, BootView, PasswordPrompt, project_boot},
console_session::console_palette::ConsoleLook,
screen_settings::{color_scheme::Colors, config_file::Timing},
systemd_link::{link_error::Error, monotonic_clock::monotonic_now},
@@ -162,12 +162,7 @@ impl<Desk: ConsoleDesk> WatchScreen<Desk> {
if self.state.phase != phase_before {
self.origin = (self.read_origin)();
}
if self.state.display_manager_started() {
let display_manager = self
.state
.handoff_unit
.as_deref()
.unwrap_or("display manager");
if let Some(display_manager) = self.state.started_display_manager() {
self.desk
.begin_handover(display_manager, now + self.timing.wait_for_display_manager);
} else if self.state.is_complete() {
+8 -25
View File
@@ -92,8 +92,14 @@ enum DefaultsFormat {
fn main() -> ExitCode {
let cli = Cli::parse();
match cli.command {
Some(Command::Defaults(options)) => print_defaults(options.format),
Some(Command::Check(options)) => check_config_file(&options),
Some(Command::Defaults(options)) => report_outcome(
render_defaults(options.format).map(|text| println!("{}", text.trim_end())),
),
Some(Command::Check(options)) => report_outcome(
read_config_file(&options.path)
.map(|_| ())
.map_err(|error| format!("{}: {error}", options.path.display())),
),
Some(Command::Install(options)) => report_outcome(install_files(&options)),
Some(Command::Uninstall(options)) => report_outcome(uninstall_files(&options)),
None => watch_boot(cli.watch),
@@ -118,29 +124,6 @@ fn render_defaults(format: DefaultsFormat) -> Result<String, Box<dyn Error>> {
})
}
fn print_defaults(format: DefaultsFormat) -> ExitCode {
match render_defaults(format) {
Ok(text) => {
println!("{}", text.trim_end());
ExitCode::SUCCESS
}
Err(error) => {
eprintln!("bootvine: {error}");
ExitCode::FAILURE
}
}
}
fn check_config_file(options: &CheckOptions) -> ExitCode {
match read_config_file(&options.path) {
Ok(_) => ExitCode::SUCCESS,
Err(error) => {
eprintln!("bootvine: {}: {error}", options.path.display());
ExitCode::FAILURE
}
}
}
fn watch_boot(options: WatchOptions) -> ExitCode {
let config = match read_config_file(&options.config) {
Ok(config) => config,
+40 -37
View File
@@ -38,6 +38,8 @@ const DRACUT_MODULE_SETUP: &str =
include_str!("../../system-files/dracut/90bootvine/module-setup.sh");
const MKINITCPIO_INSTALL_HOOK: &str =
include_str!("../../system-files/mkinitcpio/install/sd-bootvine");
const INITRD_GENERATORS: [InitrdGenerator; 2] =
[InitrdGenerator::Dracut, InitrdGenerator::Mkinitcpio];
#[derive(Args)]
pub struct InstallTarget {
@@ -114,16 +116,41 @@ impl InstallTarget {
fn every_installed_path(&self) -> Vec<PathBuf> {
once(self.binary_path())
.chain(unit_names().map(|unit| self.unit_path(unit)))
.chain([
Path::new(DRACUT_MODULE_DIR).join("module-setup.sh"),
PathBuf::from(DRACUT_CONF),
PathBuf::from(MKINITCPIO_HOOK),
])
.chain(unit_files(self).map(|file| file.destination))
.chain(
INITRD_GENERATORS
.into_iter()
.flat_map(initrd_hook_files)
.map(|file| file.destination),
)
.collect()
}
}
impl InitrdGenerator {
fn install_hint(self) -> Option<&'static str> {
match self {
Self::None => None,
Self::Dracut => Some("rebuild the initramfs: sudo dracut --force"),
Self::Mkinitcpio => Some(
"add sd-bootvine after systemd in HOOKS in /etc/mkinitcpio.conf, then run: sudo \
mkinitcpio -P",
),
}
}
fn removal_hint(self) -> Option<&'static str> {
match self {
Self::None => None,
Self::Dracut => Some("rebuild the initramfs without bootvine: sudo dracut --force"),
Self::Mkinitcpio => Some(
"remove sd-bootvine from HOOKS in /etc/mkinitcpio.conf, then run: sudo mkinitcpio \
-P",
),
}
}
}
fn running_binary() -> Result<PathBuf, InstallError> {
env::current_exe().map_err(|source| InstallError::File {
path: PathBuf::from("/proc/self/exe"),
@@ -131,14 +158,10 @@ fn running_binary() -> Result<PathBuf, InstallError> {
})
}
fn is_running_binary(path: &Path, running: &Path) -> bool {
fs::canonicalize(path).is_ok_and(|resolved| resolved == running)
}
fn binary_file(target: &InstallTarget) -> Result<Option<InstalledFile>, InstallError> {
let running = running_binary()?;
let destination = target.binary_path();
if is_running_binary(&target.staged(&destination), &running) {
if fs::canonicalize(target.staged(&destination)).is_ok_and(|resolved| resolved == running) {
return Ok(None);
}
let contents = fs::read(&running).map_err(|source| InstallError::File {
@@ -244,17 +267,6 @@ fn rerun_with_sudo() -> Result<(), InstallError> {
)
}
fn print_initramfs_hint(initrd: InitrdGenerator) {
match initrd {
InitrdGenerator::None => {}
InitrdGenerator::Dracut => println!("rebuild the initramfs: sudo dracut --force"),
InitrdGenerator::Mkinitcpio => println!(
"add sd-bootvine after systemd in HOOKS in /etc/mkinitcpio.conf, then run: sudo \
mkinitcpio -P"
),
}
}
pub fn install_files(options: &InstallOptions) -> Result<(), InstallError> {
let target = &options.target;
if target.needs_sudo() {
@@ -270,25 +282,15 @@ pub fn install_files(options: &InstallOptions) -> Result<(), InstallError> {
if !options.no_enable {
systemctl(once("enable").chain(unit_names()))?;
}
print_initramfs_hint(options.initrd);
if let Some(hint) = options.initrd.install_hint() {
println!("{hint}");
}
}
Ok(())
}
fn print_initramfs_removal_hint(initrd: InitrdGenerator) {
match initrd {
InitrdGenerator::None => {}
InitrdGenerator::Dracut => {
println!("rebuild the initramfs without bootvine: sudo dracut --force");
}
InitrdGenerator::Mkinitcpio => println!(
"remove sd-bootvine from HOOKS in /etc/mkinitcpio.conf, then run: sudo mkinitcpio -P"
),
}
}
fn installed_initrd_hooks(target: &InstallTarget) -> Vec<InitrdGenerator> {
[InitrdGenerator::Dracut, InitrdGenerator::Mkinitcpio]
INITRD_GENERATORS
.into_iter()
.filter(|generator| {
initrd_hook_files(*generator)
@@ -330,7 +332,8 @@ pub fn uninstall_files(options: &UninstallOptions) -> Result<(), InstallError> {
systemctl(["daemon-reload"])?;
removed_initrd_hooks
.into_iter()
.for_each(print_initramfs_removal_hint);
.filter_map(InitrdGenerator::removal_hint)
.for_each(|hint| println!("{hint}"));
}
Ok(())
}