phoebus_os/installer-rs/crates/phoebus-core/src/update.rs
Phoebus 084c315117
Some checks are pending
ci / test (push) Waiting to run
fix(sys): stream package output and harden package lanes
2026-10-01 10:23:41 -07:00

237 lines
7.1 KiB
Rust

//! Background update preparation.
//!
//! Preparation is non-destructive: distfiles are fetched and reusable local
//! binary packages are built *without* installing anything. Activation is a
//! separate, conservative, user-approved step. Only real Portage capabilities
//! are used (`--fetchonly`, `--buildpkgonly`).
use serde::{Deserialize, Serialize};
/// The stability channel used for system updates.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum UpdateChannel {
/// Security, kernel, and core system packages only (glibc, systemd, btrfs-progs, pam, seatd).
Core,
/// Default workstation channel: bi-weekly vetted snapshots for desktop, Mesa, PipeWire.
#[default]
Proven,
/// Upstream rolling Gentoo tree (~amd64 / live testing).
Edge,
}
impl UpdateChannel {
pub fn as_str(&self) -> &'static str {
match self {
Self::Core => "core",
Self::Proven => "proven",
Self::Edge => "edge",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PowerState {
Ac,
Battery,
Unknown,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PrepareStatus {
Idle,
Running,
Ready,
Failed,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct PrepareState {
pub last_prepared_unix: u64,
pub status: PrepareStatus,
pub prepared_packages: u32,
pub note: String,
}
impl Default for PrepareState {
fn default() -> Self {
Self {
last_prepared_unix: 0,
status: PrepareStatus::Idle,
prepared_packages: 0,
note: String::new(),
}
}
}
/// Whether a background build should run now.
///
/// Conservative defaults: never build on battery, and only when the machine is
/// not under heavy load.
pub fn should_prepare(power: PowerState, load_average: f32, cores: u32, idle: bool) -> bool {
if power == PowerState::Battery {
return false;
}
let cores = cores.max(1) as f32;
// Allow when the run queue is below half the core count.
if load_average > cores / 2.0 {
return false;
}
// On AC we may prepare even if not fully idle, but an interactive system is
// still respected by the load check above.
power == PowerState::Ac || idle
}
/// Real Portage arguments for the preparation steps. Kept as data so they are
/// unit-testable and reused verbatim by the executor.
pub fn fetch_args() -> Vec<&'static str> {
vec!["--fetchonly", "--update", "--deep", "--newuse", "@world"]
}
pub fn build_args() -> Vec<&'static str> {
// --buildpkgonly builds and stores binary packages without installing.
vec![
"--buildpkgonly",
"--update",
"--deep",
"--newuse",
"--binpkg-respect-use=y",
"@world",
]
}
use crate::selection::Backend;
/// One package update item.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PackageUpdateItem {
pub name: String,
pub current_version: Option<String>,
pub new_version: String,
pub source: String,
}
/// Update overview for a specific source / lane.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SourceUpdateOverview {
pub backend: Backend,
pub updates: Vec<PackageUpdateItem>,
pub supported: bool,
pub note: String,
}
/// Unified multi-source update overview.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct UnifiedUpdateOverview {
pub sources: Vec<SourceUpdateOverview>,
pub reboot_required: bool,
pub reboot_reason: Option<String>,
}
impl UnifiedUpdateOverview {
pub fn total_updates(&self) -> usize {
self.sources.iter().map(|s| s.updates.len()).sum()
}
pub fn updates_for(&self, backend: Backend) -> usize {
self.sources
.iter()
.find(|s| s.backend == backend)
.map(|s| s.updates.len())
.unwrap_or(0)
}
pub fn render(&self) -> String {
let mut out = String::new();
out.push_str("Unified Update Overview:\n");
let total_updates = self.total_updates();
if total_updates == 0
&& !self.sources.is_empty()
&& self.sources.iter().all(|s| s.supported)
{
out.push_str(" All supported package sources are up to date.\n");
}
if self.sources.is_empty() {
out.push_str(" No package sources were checked.\n");
}
for src in &self.sources {
out.push_str(&format!(" [{}] - ", src.backend.as_str()));
if !src.supported {
out.push_str(&format!("not checked: {}\n", src.note));
} else if src.updates.is_empty() {
out.push_str(&format!("up to date ({})\n", src.note));
} else {
out.push_str(&format!(
"{} update(s) available ({}):\n",
src.updates.len(),
src.note
));
for item in &src.updates {
let prev = item.current_version.as_deref().unwrap_or("none");
out.push_str(&format!(
" - {} ({} -> {})\n",
item.name, prev, item.new_version
));
}
}
}
if self.reboot_required {
out.push_str("\nReboot is required:\n");
if let Some(reason) = &self.reboot_reason {
out.push_str(&format!(" {}\n", reason));
} else {
out.push_str(" Kernel or core system changes require a reboot.\n");
}
}
out
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn battery_never_prepares() {
assert!(!should_prepare(PowerState::Battery, 0.0, 8, true));
}
#[test]
fn ac_and_idle_prepares_when_load_low() {
assert!(should_prepare(PowerState::Ac, 1.0, 8, false));
assert!(should_prepare(PowerState::Unknown, 0.5, 8, true));
}
#[test]
fn high_load_defers() {
assert!(!should_prepare(PowerState::Ac, 7.0, 8, false));
}
#[test]
fn args_are_real_portage_flags() {
assert!(fetch_args().contains(&"--fetchonly"));
assert!(build_args().contains(&"--buildpkgonly"));
assert!(build_args().contains(&"@world"));
}
#[test]
fn overview_does_not_claim_freshness_for_unchecked_lanes() {
let mut report = UnifiedUpdateOverview::default();
report.sources.push(SourceUpdateOverview {
backend: Backend::Nix,
updates: Vec::new(),
supported: false,
note: "manual profile update required".into(),
});
let text = report.render();
assert!(text.contains("not checked: manual profile update required"));
assert!(!text.contains("up to date"));
report.sources[0].supported = true;
assert!(report
.render()
.contains("All supported package sources are up to date"));
}
}