From eaac60ba88728bb582778c726e5798156dddfc45 Mon Sep 17 00:00:00 2001 From: tv Date: Sun, 29 Nov 2026 14:21:34 +0000 Subject: enstate: the receptor and the provider, a first version One program on a library: --plan and --apply of submissions (complete and partial, items required and optional, groups, removal, the chain as order), validators of types and across slots, views put in place by replacing a link, their reactions by systemctl; --status, --materialize; and --pack, a submission from a source list in JSON or TOML, by the config crate's sources. Programs by the protocol of design.md 5.2; tests with shell scripts as validators and renderers. --- src/plan.rs | 566 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 566 insertions(+) create mode 100644 src/plan.rs (limited to 'src/plan.rs') diff --git a/src/plan.rs b/src/plan.rs new file mode 100644 index 0000000..952f3aa --- /dev/null +++ b/src/plan.rs @@ -0,0 +1,566 @@ +//! What a submission would do, and doing it (docs/design.md, 5.5). +//! +//! The plan: check the channel and the base; apply the items to a copy of the current +//! snapshot; run the validators on it, leaving out optional items an objection names, +//! with their groups, and refusing for a required one or for what is in place; check +//! that every required slot is filled; render the views into scratch and compare. +//! Applying: the same, then the new snapshot becomes current, the views that changed +//! are put in place, and their reactions run, each unit once. + +use std::collections::{BTreeMap, BTreeSet}; +use std::path::Path; +use std::process::Command; + +use anyhow::{Context, Result, anyhow}; +use serde::Serialize; + +use crate::content::{self, Content}; +use crate::media; +use crate::name::Address; +use crate::program::{self, Given, ProgramFailed, Role}; +use crate::schema::{Reactions, Schema}; +use crate::scratch::Scratch; +use crate::store::Store; +use crate::submission::{Change, Item, Submission}; +use crate::view::{self, FileChange}; + +#[derive(Debug, Clone, Serialize)] +pub struct Plan { + pub channel: String, + /// The current snapshot's id. + pub current: Option, + /// The snapshot the submission builds on, if it names one. + pub base: Option, + pub accepted: bool, + /// Why not, if not. + pub refused: Vec, + pub items: Vec, + pub warnings: Vec, + pub views: Vec, + pub reactions: Reactions, + /// Whether the snapshot or a view would change. + pub changes: bool, + /// The new snapshot's id, once applied. + #[serde(skip_serializing_if = "Option::is_none")] + pub snapshot: Option, + /// Reactions that failed, once applied. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub failed: Vec, +} + +#[derive(Debug, Clone, Serialize)] +pub struct ItemOutcome { + pub address: Address, + pub op: &'static str, + pub required: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub group: Option, + pub goes_in: bool, + #[serde(skip_serializing_if = "Vec::is_empty")] + pub reasons: Vec, +} + +#[derive(Debug, Clone, Serialize)] +pub struct ViewOutcome { + pub name: String, + pub secret: bool, + pub change: view::Change, + pub files: Vec, +} + +/// A plan, and what applying it needs. +pub struct Planned { + pub plan: Plan, + content: Content, + content_changes: bool, + rendered: Vec<(String, Option, bool)>, +} + +/// A plan refused: nothing to apply. +fn refused(plan: Plan) -> Result { + Ok(Planned { + plan, + content: Content::new(), + content_changes: false, + rendered: Vec::new(), + }) +} + +/// Plans `submission` against `schema` and what `store` holds. +pub fn plan(schema: &Schema, store: &Store, submission: &Submission) -> Result { + let channel = submission.channel.as_str(); + let current = store.current(channel)?; + let mut plan = Plan { + channel: channel.to_owned(), + current: current.as_ref().map(|snapshot| snapshot.id.clone()), + base: submission.base.clone(), + accepted: false, + refused: Vec::new(), + items: submission + .items + .iter() + .map(|item| ItemOutcome { + address: item.address.clone(), + op: match item.change { + Change::Remove => "remove", + _ => "set", + }, + required: item.required, + group: item.group.clone(), + goes_in: true, + reasons: Vec::new(), + }) + .collect(), + warnings: Vec::new(), + views: Vec::new(), + reactions: Reactions::default(), + changes: false, + snapshot: None, + failed: Vec::new(), + }; + let Some(channel_spec) = schema.channel(channel) else { + plan.refused + .push(format!("the schema has no channel {channel}")); + return refused(plan); + }; + if let Some(base) = &submission.base { + let current_id = current.as_ref().map(|snapshot| snapshot.id.as_str()); + if current_id != Some(base.as_str()) { + plan.refused.push(format!( + "the submission builds on {base}, but the current snapshot is {}", + current_id.unwrap_or("none") + )); + return refused(plan); + } + } + let empty = Content::new(); + let base_content = match (¤t, submission.complete) { + (Some(snapshot), false) => &snapshot.content, + _ => &empty, + }; + // Other channels, for validators and views given their slots. + let mut others: BTreeMap = BTreeMap::new(); + let mut other_channels: BTreeSet<&str> = BTreeSet::new(); + for validator in schema.validators_of(channel) { + for address in validator.slots { + if address.channel != channel { + other_channels.insert(schema.channels.get_key_value(&address.channel).unwrap().0); + } + } + } + for (_, view) in schema.views_of(Some(channel)) { + for address in &view.from { + if address.channel != channel { + other_channels.insert(schema.channels.get_key_value(&address.channel).unwrap().0); + } + } + } + for other in other_channels { + let content = store + .current(other)? + .map(|snapshot| snapshot.content) + .unwrap_or_default(); + others.insert(other.to_owned(), content); + } + + let items = &submission.items; + // Items that can't go in, whatever the validators say. + let mut cannot: BTreeMap = BTreeMap::new(); + for (index, item) in items.iter().enumerate() { + if let Some(reason) = unfit(schema, item, base_content) { + cannot.insert(index, reason); + } + } + let mut excluded: BTreeSet = BTreeSet::new(); + let leave_out = + |plan: &mut Plan, excluded: &mut BTreeSet, index: usize, reason: String| -> bool { + // Whether it may be left out: else the submission is refused. + let item = &items[index]; + if item.required { + plan.refused + .push(format!("required item {}: {reason}", item.address)); + return false; + } + for (other, other_item) in items.iter().enumerate() { + let together = + other == index || (item.group.is_some() && other_item.group == item.group); + if together && excluded.insert(other) { + plan.items[other].goes_in = false; + let reason = if other == index { + reason.clone() + } else { + format!( + "its group {} can't go in", + item.group.as_deref().unwrap_or_default() + ) + }; + plan.warnings + .push(format!("left out: {}: {reason}", other_item.address)); + plan.items[other].reasons.push(reason); + } + } + true + }; + for (index, reason) in &cannot { + if !excluded.contains(index) && !leave_out(&mut plan, &mut excluded, *index, reason.clone()) + { + return refused(plan); + } + } + + let candidate = loop { + let candidate = apply_items(base_content, items, &excluded); + let mut blame: Vec<(usize, String)> = Vec::new(); + // Required slots first: validators are given filled slots. + for (slot, spec) in &channel_spec.slots { + if !spec.required || candidate.contains_key(slot) { + continue; + } + let address = Address::entry(channel, slot); + let removals: Vec = (0..items.len()) + .filter(|index| !excluded.contains(index)) + .filter(|index| { + items[*index].address == address && items[*index].change == Change::Remove + }) + .collect(); + if removals.is_empty() { + plan.refused + .push(format!("required slot {address} is unfilled")); + } + blame.extend( + removals + .into_iter() + .map(|index| (index, format!("required slot {address} would be unfilled"))), + ); + } + if !plan.refused.is_empty() { + return refused(plan); + } + if blame.is_empty() { + // Validators. + for validator in schema.validators_of(channel) { + let entry = |address: &Address| -> Option<&[u8]> { + if address.channel == channel { + candidate.get(&address.slot).map(Vec::as_slice) + } else { + others + .get(&address.channel)? + .get(&address.slot) + .map(Vec::as_slice) + } + }; + if validator.of_type && entry(&validator.slots[0]).is_none() { + continue; + } + let given = Given { + slots: validator + .slots + .iter() + .map(|address| { + let media_type = schema + .slot(address) + .map(|slot| slot.media_type.as_str()) + .unwrap_or_default(); + (address.clone(), (media_type, entry(address))) + }) + .collect(), + }; + let outcome = match program::run( + &validator.program, + Role::Validator, + &validator.name, + &given, + &store.scratch(), + ) { + Ok(outcome) => outcome, + Err(error) => match error.downcast::() { + Ok(failed) => { + plan.refused.push(failed.to_string()); + return refused(plan); + } + Err(error) => return Err(error), + }, + }; + for objection in outcome.objections { + let said = format!( + "{}: {} (validator {})", + objection.address, objection.message, validator.name + ); + let blamed: Vec = (0..items.len()) + .filter(|index| !excluded.contains(index)) + .filter(|index| items[*index].address.overlaps(&objection.address)) + .collect(); + if blamed.is_empty() { + plan.refused + .push(format!("objection to what is in place: {said}")); + } + blame.extend(blamed.into_iter().map(|index| (index, said.clone()))); + } + } + if !plan.refused.is_empty() { + return refused(plan); + } + } + if blame.is_empty() { + break candidate; + } + for (index, reason) in blame { + if !excluded.contains(&index) && !leave_out(&mut plan, &mut excluded, index, reason) { + return refused(plan); + } + } + }; + for slot in candidate.keys() { + if !channel_spec.slots.contains_key(slot) { + plan.warnings.push(format!( + "kept, but in no slot of the schema: {channel}/{slot}" + )); + } + } + + // Views. + let mut rendered_views = Vec::new(); + let mut entries: view::Entries = others + .iter() + .map(|(name, content)| (name.as_str(), content)) + .collect(); + entries.insert(channel, &candidate); + for (name, view_spec) in schema.views_of(Some(channel)) { + let secret = schema.view_is_secret(view_spec); + let rendered = match view::render(schema, name, view_spec, &entries, &store.scratch()) { + Ok(rendered) => rendered, + Err(error) => match error.downcast::() { + Ok(failed) => { + plan.refused.push(failed.to_string()); + return refused(plan); + } + Err(error) => return Err(error), + }, + }; + let installed = store.installed_view(name); + let (change, files) = view::compare( + installed.as_deref(), + rendered.as_ref().map(Scratch::path), + secret, + )?; + if change != view::Change::Unchanged { + plan.reactions + .restart + .extend(view_spec.reactions.restart.iter().cloned()); + plan.reactions + .reload + .extend(view_spec.reactions.reload.iter().cloned()); + } + plan.views.push(ViewOutcome { + name: name.clone(), + secret, + change, + files, + }); + rendered_views.push((name.clone(), rendered, secret)); + } + let restart: BTreeSet = std::mem::take(&mut plan.reactions.restart) + .into_iter() + .collect(); + let reload: BTreeSet = std::mem::take(&mut plan.reactions.reload) + .into_iter() + .filter(|unit| !restart.contains(unit)) + .collect(); + plan.reactions = Reactions { + restart: restart.into_iter().collect(), + reload: reload.into_iter().collect(), + }; + let content_changes = current.as_ref().map(|snapshot| &snapshot.content) != Some(&candidate); + plan.changes = content_changes + || plan + .views + .iter() + .any(|view| view.change != view::Change::Unchanged); + plan.accepted = true; + Ok(Planned { + plan, + content: candidate, + content_changes, + rendered: rendered_views, + }) +} + +/// Why `item` can't go in, whatever the validators say: no such slot, a record in an +/// entry that holds none. +fn unfit(schema: &Schema, item: &Item, base: &Content) -> Option { + let Some(slot) = schema.slot(&item.address) else { + return Some(format!( + "the schema has no slot {}", + item.address.of_entry() + )); + }; + if item.address.key.is_some() { + if !media::keyed(&slot.media_type) { + return Some(format!("type {} holds no records", slot.media_type)); + } + if let Some(bytes) = base.get(&item.address.slot) + && let Err(error) = content::records(bytes) + { + return Some(format!("the entry in place holds no records: {error}")); + } + } + None +} + +/// `base` with the items not `excluded` applied. +fn apply_items(base: &Content, items: &[Item], excluded: &BTreeSet) -> Content { + let mut content = base.clone(); + for (index, item) in items.iter().enumerate() { + if excluded.contains(&index) { + continue; + } + let slot = &item.address.slot; + match (&item.address.key, &item.change) { + (None, Change::Entry(bytes)) => { + content.insert(slot.clone(), bytes.clone()); + } + (None, Change::Remove) => { + content.remove(slot); + } + (Some(key), change) => { + // `unfit` made sure an entry in place holds records. + let mut records = content + .get(slot) + .and_then(|bytes| content::records(bytes).ok()) + .unwrap_or_default(); + match change { + Change::Record(value) => { + records.insert(key.clone(), value.clone()); + } + Change::Remove => { + records.remove(key); + } + Change::Entry(_) => unreachable!("an entry's item has no key"), + } + content.insert(slot.clone(), content::from_records(&records)); + } + (None, Change::Record(_)) => unreachable!("a record's item has a key"), + } + } + content +} + +impl Planned { + /// Applies the plan, if it was accepted: the new snapshot, the views that change, + /// and their reactions, by `systemctl`. + pub fn apply(self, store: &Store, schema_bytes: &[u8], systemctl: &Path) -> Result { + let mut plan = self.plan; + if !plan.accepted { + return Ok(plan); + } + if self.content_changes { + plan.snapshot = Some(store.commit( + &plan.channel, + &self.content, + plan.current.as_deref(), + schema_bytes, + )?); + } + for ((name, rendered, secret), outcome) in self.rendered.into_iter().zip(&plan.views) { + if outcome.change != view::Change::Unchanged { + store + .install_view(&name, rendered, secret) + .with_context(|| format!("view {name}"))?; + } + } + plan.failed = react(&plan.reactions, systemctl); + Ok(plan) + } +} + +/// Runs `reactions`; what failed. +pub fn react(reactions: &Reactions, systemctl: &Path) -> Vec { + let mut failed = Vec::new(); + for (verb, units) in [ + ("restart", &reactions.restart), + ("reload", &reactions.reload), + ] { + if units.is_empty() { + continue; + } + let result = Command::new(systemctl) + .arg(verb) + .args(units) + .status() + .map_err(|error| anyhow!("{error}")) + .and_then(|status| { + if status.success() { + Ok(()) + } else { + Err(anyhow!("{status}")) + } + }); + if let Err(error) = result { + failed.push(format!( + "{} {verb} {}: {error}", + systemctl.display(), + units.join(" ") + )); + } + } + failed +} + +/// Renders every view of `schema` from the current snapshots, puts those that differ +/// from what is in place there, and takes away views the schema doesn't have: at boot, +/// and after a generation change. Runs no reactions. Returns how each view changed. +pub fn materialize(schema: &Schema, store: &Store) -> Result> { + let mut contents: BTreeMap = BTreeMap::new(); + for channel in schema.channels.keys() { + if let Some(snapshot) = store.current(channel)? { + contents.insert(channel.clone(), snapshot.content); + } + } + let entries: view::Entries = contents + .iter() + .map(|(name, content)| (name.as_str(), content)) + .collect(); + let mut outcomes = Vec::new(); + for (name, view_spec) in schema.views_of(None) { + let secret = schema.view_is_secret(view_spec); + let rendered = view::render(schema, name, view_spec, &entries, &store.scratch()) + .with_context(|| format!("view {name}"))?; + let installed = store.installed_view(name); + let (change, files) = view::compare( + installed.as_deref(), + rendered.as_ref().map(Scratch::path), + secret, + )?; + if change != view::Change::Unchanged { + store.install_view(name, rendered, secret)?; + } + outcomes.push(ViewOutcome { + name: name.clone(), + secret, + change, + files, + }); + } + let views = store.run.join("views"); + if let Ok(entries) = std::fs::read_dir(&views) { + for entry in entries { + let name = entry?.file_name().to_string_lossy().into_owned(); + if name == ".generations" + || name.ends_with(".new-link") + || schema.views.contains_key(&name) + { + continue; + } + if store.installed_view(&name).is_some() { + store.install_view(&name, None, false)?; + outcomes.push(ViewOutcome { + name, + secret: false, + change: view::Change::Removed, + files: Vec::new(), + }); + } + } + } + Ok(outcomes) +} -- cgit v1.3.1