aboutsummaryrefslogtreecommitdiffstats
path: root/src/submission.rs
blob: 1958909da6dbeebb562d247f4522269c8146b32f (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
//! 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,
        })
    }
}