aboutsummaryrefslogtreecommitdiffstats
path: root/src/submission.rs
diff options
context:
space:
mode:
authortv <tv@krebsco.de>2026-11-29 14:21:34 +0000
committertv <tv@krebsco.de>2026-11-30 14:59:15 +0000
commiteaac60ba88728bb582778c726e5798156dddfc45 (patch)
tree557f4709762f95a7a440d1fa919dcce3bbf83cb4 /src/submission.rs
parent70367d17613ebe501fb2d3e9fa72b16c2eb9c2bd (diff)
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.
Diffstat (limited to 'src/submission.rs')
-rw-r--r--src/submission.rs219
1 files changed, 219 insertions, 0 deletions
diff --git a/src/submission.rs b/src/submission.rs
new file mode 100644
index 0000000..1958909
--- /dev/null
+++ b/src/submission.rs
@@ -0,0 +1,219 @@
+//! What gets handed to the host (docs/design.md, 5.4): a directory with a manifest,
+//! and the entries and records its items set at `channels/CHANNEL/SLOT`.
+//!
+//! ```json
+//! {
+//! "submission": 1,
+//! "channel": "fleet",
+//! "complete": false,
+//! "base": "4f0c…",
+//! "items": [
+//! { "address": "fleet/hosts/ne", "op": "set", "group": "ne" },
+//! { "address": "fleet/users/tv", "op": "set", "required": false },
+//! { "address": "fleet/hosts/wu", "op": "remove" }
+//! ],
+//! "groups": { "ne": { "required": true } }
+//! }
+//! ```
+//!
+//! Items and groups are required unless they say otherwise; an item in a group is as
+//! required as its group, and says nothing of its own. An item setting records has
+//! them in its entry's file, as an object holding just the records set.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::path::{Path, PathBuf};
+
+use anyhow::{Context, Result, bail};
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+
+use crate::content;
+use crate::name::Address;
+
+pub const VERSION: u32 = 1;
+pub const MANIFEST: &str = "manifest.json";
+pub const CHANNELS: &str = "channels";
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct Manifest {
+ pub submission: u32,
+ pub channel: String,
+ #[serde(default)]
+ pub complete: bool,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub base: Option<String>,
+ pub items: Vec<ItemSpec>,
+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
+ pub groups: BTreeMap<String, GroupSpec>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct ItemSpec {
+ pub address: Address,
+ pub op: Op,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub required: Option<bool>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub group: Option<String>,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum Op {
+ Set,
+ Remove,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct GroupSpec {
+ #[serde(default = "yes")]
+ pub required: bool,
+}
+
+fn yes() -> bool {
+ true
+}
+
+/// A submission, read.
+#[derive(Debug, Clone)]
+pub struct Submission {
+ pub dir: PathBuf,
+ pub channel: String,
+ pub complete: bool,
+ pub base: Option<String>,
+ pub items: Vec<Item>,
+}
+
+#[derive(Debug, Clone, PartialEq)]
+pub struct Item {
+ pub address: Address,
+ pub required: bool,
+ pub group: Option<String>,
+ pub change: Change,
+}
+
+#[derive(Debug, Clone, PartialEq)]
+pub enum Change {
+ Entry(Vec<u8>),
+ Record(Value),
+ Remove,
+}
+
+impl Submission {
+ pub fn load(dir: &Path) -> Result<Self> {
+ let path = dir.join(MANIFEST);
+ let bytes = std::fs::read(&path).with_context(|| format!("reading {}", path.display()))?;
+ let manifest: Manifest = serde_json::from_slice(&bytes)
+ .with_context(|| format!("manifest {}", path.display()))?;
+ Self::from_manifest(dir, manifest).with_context(|| format!("submission {}", dir.display()))
+ }
+
+ fn from_manifest(dir: &Path, manifest: Manifest) -> Result<Self> {
+ if manifest.submission != VERSION {
+ bail!(
+ "submission version {} is not {VERSION}",
+ manifest.submission
+ );
+ }
+ crate::name::check("channel", &manifest.channel)?;
+ let files = dir.join(CHANNELS).join(&manifest.channel);
+ let mut seen: Vec<&Address> = Vec::new();
+ let mut used = BTreeSet::new();
+ let mut items = Vec::new();
+ for spec in &manifest.items {
+ let address = &spec.address;
+ if address.channel != manifest.channel {
+ bail!("item {address} is not of channel {}", manifest.channel);
+ }
+ if let Some(other) = seen.iter().find(|other| other.overlaps(address)) {
+ bail!("items {other} and {address} overlap");
+ }
+ seen.push(address);
+ let required = match (&spec.group, spec.required) {
+ (Some(group), None) => match manifest.groups.get(group) {
+ Some(group) => group.required,
+ None => bail!("item {address}: no group {group}"),
+ },
+ (Some(_), Some(_)) => {
+ bail!("item {address} is in a group, which says whether it is required")
+ }
+ (None, required) => required.unwrap_or(true),
+ };
+ let change = match (spec.op, &address.key) {
+ (Op::Remove, _) => Change::Remove,
+ (Op::Set, None) => {
+ used.insert(address.slot.clone());
+ let path = files.join(&address.slot);
+ Change::Entry(
+ std::fs::read(&path).with_context(|| {
+ format!("item {address}: reading {}", path.display())
+ })?,
+ )
+ }
+ (Op::Set, Some(key)) => {
+ used.insert(address.slot.clone());
+ let path = files.join(&address.slot);
+ let bytes = std::fs::read(&path)
+ .with_context(|| format!("item {address}: reading {}", path.display()))?;
+ let records = content::records(&bytes)
+ .with_context(|| format!("item {address}: {}", path.display()))?;
+ match records.get(key) {
+ Some(value) => Change::Record(value.clone()),
+ None => bail!("item {address}: no record {key:?} in {}", path.display()),
+ }
+ }
+ };
+ items.push(Item {
+ address: address.clone(),
+ required,
+ group: spec.group.clone(),
+ change,
+ });
+ }
+ // Records a file holds that no item sets, and files no item reads, would be
+ // handed over and silently ignored.
+ for slot in &used {
+ let records_set: BTreeSet<&str> = items
+ .iter()
+ .filter(|item| item.address.slot == *slot)
+ .filter_map(|item| item.address.key.as_deref())
+ .collect();
+ if records_set.is_empty() {
+ continue;
+ }
+ let path = files.join(slot);
+ let records = content::records(&std::fs::read(&path)?)?;
+ if let Some(key) = records
+ .keys()
+ .find(|key| !records_set.contains(key.as_str()))
+ {
+ bail!(
+ "{} holds record {key:?}, which no item sets",
+ path.display()
+ );
+ }
+ }
+ for (slot, _) in content::read_dir(&files)? {
+ if !used.contains(&slot) {
+ bail!("{} is set by no item", files.join(slot).display());
+ }
+ }
+ if let Some(group) = manifest
+ .groups
+ .keys()
+ .find(|group| !items.iter().any(|item| item.group.as_ref() == Some(*group)))
+ {
+ bail!("group {group} has no items");
+ }
+ Ok(Self {
+ dir: dir.to_owned(),
+ channel: manifest.channel,
+ complete: manifest.complete,
+ base: manifest.base,
+ items,
+ })
+ }
+}