aboutsummaryrefslogtreecommitdiffstats
path: root/src/schema.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/schema.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/schema.rs')
-rw-r--r--src/schema.rs292
1 files changed, 292 insertions, 0 deletions
diff --git a/src/schema.rs b/src/schema.rs
new file mode 100644
index 0000000..a44f6f8
--- /dev/null
+++ b/src/schema.rs
@@ -0,0 +1,292 @@
+//! What a generation accepts (docs/design.md, 5.1 to 5.3): its channels and their
+//! slots, the types' validators and the schema's own, and the views. A JSON file in
+//! the system, which the NixOS module writes.
+//!
+//! ```json
+//! {
+//! "schema": 1,
+//! "types": { "application/x-enstate-hosts+json": { "validator": "/nix/store/…" } },
+//! "channels": {
+//! "secrets": { "slots": { "retiolum.key": { "type": "…", "secret": true } } }
+//! },
+//! "validators": { "key-pair": { "slots": ["secrets/a.key", "secrets/a.pub"], "program": "…" } },
+//! "views": {
+//! "known-hosts": { "from": ["fleet/hosts"], "renderer": "…", "reactions": { "reload": [] } },
+//! "retiolum.key": { "from": ["secrets/retiolum.key"] }
+//! }
+//! }
+//! ```
+//!
+//! Slots are required unless they say otherwise. A view without a renderer is the one
+//! entry it is from. A view is secret if one of the slots it is from is, unless it
+//! says it isn't.
+
+use std::collections::BTreeMap;
+use std::path::{Path, PathBuf};
+
+use anyhow::{Context, Result, bail};
+use serde::{Deserialize, Serialize};
+
+use crate::media;
+use crate::name::{self, Address};
+
+pub const VERSION: u32 = 1;
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct Schema {
+ pub schema: u32,
+ #[serde(default)]
+ pub types: BTreeMap<String, TypeSpec>,
+ pub channels: BTreeMap<String, ChannelSpec>,
+ #[serde(default)]
+ pub validators: BTreeMap<String, ValidatorSpec>,
+ #[serde(default)]
+ pub views: BTreeMap<String, ViewSpec>,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct TypeSpec {
+ pub validator: Option<PathBuf>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct ChannelSpec {
+ pub slots: BTreeMap<String, SlotSpec>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(deny_unknown_fields, rename_all = "camelCase")]
+pub struct SlotSpec {
+ #[serde(rename = "type")]
+ pub media_type: String,
+ #[serde(default = "yes")]
+ pub required: bool,
+ #[serde(default)]
+ pub secret: bool,
+}
+
+fn yes() -> bool {
+ true
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct ValidatorSpec {
+ pub slots: Vec<Address>,
+ pub program: PathBuf,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct ViewSpec {
+ pub from: Vec<Address>,
+ pub renderer: Option<PathBuf>,
+ pub secret: Option<bool>,
+ #[serde(default)]
+ pub reactions: Reactions,
+}
+
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct Reactions {
+ #[serde(default)]
+ pub restart: Vec<String>,
+ #[serde(default)]
+ pub reload: Vec<String>,
+}
+
+impl Schema {
+ /// The schema in `path`, checked, its types normalized.
+ pub fn load(path: &Path) -> Result<Self> {
+ let bytes = std::fs::read(path).with_context(|| format!("reading {}", path.display()))?;
+ Self::from_slice(&bytes).with_context(|| format!("schema {}", path.display()))
+ }
+
+ pub fn from_slice(bytes: &[u8]) -> Result<Self> {
+ let mut schema: Schema = serde_json::from_slice(bytes)?;
+ schema.check()?;
+ Ok(schema)
+ }
+
+ fn check(&mut self) -> Result<()> {
+ if self.schema != VERSION {
+ bail!("schema version {} is not {VERSION}", self.schema);
+ }
+ self.types = std::mem::take(&mut self.types)
+ .into_iter()
+ .map(|(media_type, spec)| Ok((media::normalize(&media_type)?, spec)))
+ .collect::<Result<_>>()?;
+ for (channel, spec) in &mut self.channels {
+ name::check("channel", channel)?;
+ for (slot, spec) in &mut spec.slots {
+ name::check("slot", slot)?;
+ spec.media_type = media::normalize(&spec.media_type)
+ .with_context(|| format!("slot {channel}/{slot}"))?;
+ }
+ }
+ for (name, validator) in &self.validators {
+ if validator.slots.is_empty() {
+ bail!("validator {name} is given no slots");
+ }
+ for address in &validator.slots {
+ self.entry_slot(address)
+ .with_context(|| format!("validator {name}"))?;
+ }
+ }
+ for (name, view) in &self.views {
+ name::check("view", name)?;
+ if view.from.is_empty() {
+ bail!("view {name} is made from no slots");
+ }
+ for address in &view.from {
+ self.entry_slot(address)
+ .with_context(|| format!("view {name}"))?;
+ }
+ if view.renderer.is_none() && view.from.len() != 1 {
+ bail!("view {name} has no renderer, so it must be made from one slot");
+ }
+ }
+ Ok(())
+ }
+
+ /// The slot `address` names, which must be an entry's address.
+ fn entry_slot(&self, address: &Address) -> Result<&SlotSpec> {
+ if address.key.is_some() {
+ bail!("{address} is a record's address, not a slot's");
+ }
+ self.slot(address)
+ .with_context(|| format!("no slot {address}"))
+ }
+
+ /// The slot of the entry `address` is, or is in.
+ pub fn slot(&self, address: &Address) -> Option<&SlotSpec> {
+ self.channels
+ .get(&address.channel)?
+ .slots
+ .get(&address.slot)
+ }
+
+ pub fn channel(&self, channel: &str) -> Option<&ChannelSpec> {
+ self.channels.get(channel)
+ }
+
+ /// The validators that see `channel`: each slot's type's own, for that slot, and
+ /// the schema's that are given one of its slots.
+ pub fn validators_of(&self, channel: &str) -> Vec<Validator> {
+ let mut validators = Vec::new();
+ if let Some(spec) = self.channels.get(channel) {
+ for (slot, slot_spec) in &spec.slots {
+ if let Some(program) = self
+ .types
+ .get(&slot_spec.media_type)
+ .and_then(|spec| spec.validator.as_ref())
+ {
+ validators.push(Validator {
+ name: format!("type {}", slot_spec.media_type),
+ slots: vec![Address::entry(channel, slot)],
+ program: program.clone(),
+ of_type: true,
+ });
+ }
+ }
+ }
+ for (name, spec) in &self.validators {
+ if spec.slots.iter().any(|address| address.channel == channel) {
+ validators.push(Validator {
+ name: name.clone(),
+ slots: spec.slots.clone(),
+ program: spec.program.clone(),
+ of_type: false,
+ });
+ }
+ }
+ validators
+ }
+
+ /// The views made from one of `channel`'s slots, or all views.
+ pub fn views_of(&self, channel: Option<&str>) -> impl Iterator<Item = (&String, &ViewSpec)> {
+ self.views.iter().filter(move |(_, view)| match channel {
+ None => true,
+ Some(channel) => view.from.iter().any(|address| address.channel == channel),
+ })
+ }
+
+ pub fn view_is_secret(&self, view: &ViewSpec) -> bool {
+ view.secret.unwrap_or_else(|| {
+ view.from
+ .iter()
+ .any(|address| self.slot(address).is_some_and(|slot| slot.secret))
+ })
+ }
+}
+
+/// A validator to run: a type's, for one slot, or the schema's.
+#[derive(Debug, Clone)]
+pub struct Validator {
+ pub name: String,
+ pub slots: Vec<Address>,
+ pub program: PathBuf,
+ /// A type's own: an unfilled slot isn't checked.
+ pub of_type: bool,
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_schema() {
+ let schema = Schema::from_slice(
+ br#"{
+ "schema": 1,
+ "types": { "Application/X-Hosts+JSON": { "validator": "/bin/check" } },
+ "channels": {
+ "fleet": { "slots": { "hosts": { "type": "application/x-hosts+json" } } },
+ "secrets": { "slots": { "a.key": { "type": "application/octet-stream", "secret": true, "required": false } } }
+ },
+ "validators": { "both": { "slots": ["fleet/hosts", "secrets/a.key"], "program": "/bin/both" } },
+ "views": {
+ "hosts": { "from": ["fleet/hosts"], "renderer": "/bin/render" },
+ "a.key": { "from": ["secrets/a.key"] }
+ }
+ }"#,
+ )
+ .unwrap();
+ let validators = schema.validators_of("fleet");
+ assert_eq!(validators.len(), 2);
+ assert_eq!(validators[0].name, "type application/x-hosts+json");
+ assert!(schema.view_is_secret(&schema.views["a.key"]));
+ assert!(!schema.view_is_secret(&schema.views["hosts"]));
+ assert!(schema.channels["fleet"].slots["hosts"].required);
+ }
+
+ #[test]
+ fn mistakes() {
+ for (bad, said) in [
+ (r#"{"schema": 2, "channels": {}}"#, "version"),
+ (
+ r#"{"schema": 1, "channels": {"-x": {"slots": {}}}}"#,
+ "portable",
+ ),
+ (
+ r#"{"schema": 1, "channels": {"c": {"slots": {"s": {"type": "text"}}}}}"#,
+ "media type",
+ ),
+ (
+ r#"{"schema": 1, "channels": {}, "views": {"v": {"from": ["c/s"]}}}"#,
+ "no slot c/s",
+ ),
+ (
+ r#"{"schema": 1, "channels": {"c": {"slots": {"s": {"type": "a/b"}, "t": {"type": "a/b"}}}},
+ "views": {"v": {"from": ["c/s", "c/t"]}}}"#,
+ "no renderer",
+ ),
+ ] {
+ let error = format!("{:#}", Schema::from_slice(bad.as_bytes()).unwrap_err());
+ assert!(error.contains(said), "{bad}: {error}");
+ }
+ }
+}