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/program.rs | 201 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 201 insertions(+) create mode 100644 src/program.rs (limited to 'src/program.rs') diff --git a/src/program.rs b/src/program.rs new file mode 100644 index 0000000..8c4a565 --- /dev/null +++ b/src/program.rs @@ -0,0 +1,201 @@ +//! The protocol of validators, renderers, converters and steps (docs/design.md, 5.2). +//! +//! `PROGRAM IN OUT`, standard input `/dev/null`, an empty environment, in `IN`. `IN` +//! holds `invocation.json` and the slots given at `channels/CHANNEL/SLOT`; `OUT` is +//! empty. Objections are JSON lines on standard output; an exit status but 0 is a +//! failure. +//! +//! `IN` is read-only (for its owner, as root ignores modes). Not yet: a sandbox (no +//! network, nothing writable but `OUT`). + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; + +use anyhow::{Context, Result, anyhow, bail}; +use serde::{Deserialize, Serialize}; + +use crate::content; +use crate::name::Address; +use crate::scratch::Scratch; + +pub const PROTOCOL: u32 = 1; +pub const INVOCATION: &str = "invocation.json"; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum Role { + Validator, + Renderer, + Converter, + Step, +} + +/// What a program is given: slots, by address, with their types and entries (none for +/// an unfilled one). +pub struct Given<'a> { + pub slots: BTreeMap)>, +} + +#[derive(Serialize)] +struct Invocation<'a> { + protocol: u32, + program: Role, + #[serde(skip_serializing_if = "Option::is_none")] + view: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + validator: Option<&'a str>, + slots: BTreeMap>, + produces: BTreeMap>, +} + +#[derive(Serialize)] +struct SlotType<'a> { + #[serde(rename = "type")] + media_type: &'a str, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Objection { + pub address: Address, + pub message: String, +} + +/// What a program did: its objections, and what it wrote, in `OUT`. +pub struct Outcome { + pub objections: Vec, + pub out: Scratch, +} + +/// Runs `program` as `role`, named `name` (a view's or validator's), on `given`, in a +/// scratch directory below `scratch`. +pub fn run( + program: &Path, + role: Role, + name: &str, + given: &Given, + scratch: &Path, +) -> Result { + let what = format!("{} {name} ({})", role_name(role), program.display()); + let input = Scratch::new(scratch, "in-")?; + let out = Scratch::new(scratch, "out-")?; + let invocation = Invocation { + protocol: PROTOCOL, + program: role, + view: (role == Role::Renderer).then_some(name), + validator: (role == Role::Validator).then_some(name), + slots: given + .slots + .iter() + .map(|(address, (media_type, _))| (address.to_string(), SlotType { media_type })) + .collect(), + produces: BTreeMap::new(), + }; + content::write_file( + &input.path().join(INVOCATION), + &serde_json::to_vec_pretty(&invocation)?, + 0o600, + )?; + for (address, (_, bytes)) in &given.slots { + let Some(bytes) = bytes else { continue }; + let dir = input.path().join("channels").join(&address.channel); + std::fs::create_dir_all(&dir)?; + content::write_file(&dir.join(&address.slot), bytes, 0o600)?; + } + input.set_modes(0o400)?; + let program = std::path::absolute(program).unwrap_or_else(|_| program.to_owned()); + let output = Command::new(&program) + .arg(input.path()) + .arg(out.path()) + .current_dir(input.path()) + .env_clear() + .stdin(Stdio::null()) + .output() + .with_context(|| format!("running {what}"))?; + let stderr = String::from_utf8_lossy(&output.stderr); + if !output.status.success() { + return Err(ProgramFailed { + what, + status: output.status.to_string(), + stderr: stderr.trim_end().to_owned(), + } + .into()); + } + let mut objections = Vec::new(); + let stdout = String::from_utf8(output.stdout) + .map_err(|_| anyhow!("{what}: its standard output is not UTF-8"))?; + for line in stdout.lines().filter(|line| !line.trim().is_empty()) { + let objection: Objection = serde_json::from_str(line) + .with_context(|| format!("{what}: not an objection: {line}"))?; + if !given + .slots + .keys() + .any(|address| address.overlaps(&objection.address)) + { + bail!( + "{what} objects to {}, which it wasn't given", + objection.address + ); + } + objections.push(objection); + } + Ok(Outcome { objections, out }) +} + +fn role_name(role: Role) -> &'static str { + match role { + Role::Validator => "validator", + Role::Renderer => "renderer", + Role::Converter => "converter", + Role::Step => "step", + } +} + +/// A program that didn't exit with 0: no item is to blame. +#[derive(Debug)] +pub struct ProgramFailed { + pub what: String, + pub status: String, + pub stderr: String, +} + +impl std::fmt::Display for ProgramFailed { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{} failed ({})", self.what, self.status)?; + if !self.stderr.is_empty() { + write!(f, ":\n{}", self.stderr)?; + } + Ok(()) + } +} + +impl std::error::Error for ProgramFailed {} + +/// The regular files below `dir`, by path relative to it; anything but regular files +/// and directories is an error. +pub fn files_below(dir: &Path) -> Result>> { + let mut files = BTreeMap::new(); + let mut pending = vec![PathBuf::new()]; + while let Some(relative) = pending.pop() { + let path = dir.join(&relative); + for entry in + std::fs::read_dir(&path).with_context(|| format!("reading {}", path.display()))? + { + let entry = entry?; + let kind = entry.file_type()?; + let relative = relative.join(entry.file_name()); + if kind.is_dir() { + pending.push(relative); + } else if kind.is_file() { + files.insert(relative, std::fs::read(entry.path())?); + } else { + bail!( + "{}: neither a regular file nor a directory", + entry.path().display() + ); + } + } + } + Ok(files) +} -- cgit v1.3.1