//! 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, pub channels: BTreeMap, #[serde(default)] pub validators: BTreeMap, #[serde(default)] pub views: BTreeMap, } #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct TypeSpec { pub validator: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct ChannelSpec { pub slots: BTreeMap, } #[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
, pub program: PathBuf, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct ViewSpec { pub from: Vec
, pub renderer: Option, pub secret: Option, #[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, #[serde(default)] pub reload: Vec, } impl Schema { /// The schema in `path`, checked, its types normalized. pub fn load(path: &Path) -> Result { 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 { 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::>()?; 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 { 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 { 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
, 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}"); } } }