aboutsummaryrefslogtreecommitdiffstats
path: root/src/schema.rs
blob: 8b2077700e9d3464ca4202dd141cf0731ddf9d9a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
//! 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,
    /// The name the slot had in an earlier schema (docs/design.md, section 6).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub renamed_from: Option<String>,
}

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)?;
                if let Some(old) = &spec.renamed_from {
                    name::check("slot", old)
                        .with_context(|| format!("slot {channel}/{slot}: renamedFrom"))?;
                }
                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}");
        }
    }
}