1
//! Reference preflight: lists every stored template and declared source that
2
//! names an account or commodity other than by id, path or symbol that
3
//! resolves uniquely, and shows the trigger host resolves no names. It only
4
//! reads, so it may run on a live tenant as well as on a restored copy.
5

            
6
mod sources;
7
mod templates;
8
mod trigger;
9

            
10
use std::fmt;
11
use std::path::Path;
12

            
13
use server::db::DBError;
14
use server::preflight::tenants;
15
use uuid::Uuid;
16

            
17
use crate::lookup_log::LookupKind;
18
use crate::resolve::Directory;
19
use crate::resolve::class::Resolution;
20
pub use sources::{Source, load as load_sources};
21

            
22
#[derive(Debug, Clone, PartialEq, Eq)]
23
pub enum Subject {
24
    Tenant,
25
    Template(Uuid, Option<String>),
26
    Source(String),
27
    TriggerHost,
28
}
29

            
30
impl fmt::Display for Subject {
31
161
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32
161
        match self {
33
            Self::Tenant => f.write_str("tenant"),
34
            Self::Template(id, Some(name)) => write!(f, "template {id} '{name}'"),
35
            Self::Template(id, None) => write!(f, "template {id}"),
36
1
            Self::Source(path) => write!(f, "source {path}"),
37
160
            Self::TriggerHost => f.write_str("trigger host"),
38
        }
39
161
    }
40
}
41

            
42
#[derive(Debug, Clone, PartialEq, Eq)]
43
pub struct Finding {
44
    pub user: Option<Uuid>,
45
    pub subject: Subject,
46
    pub reason: String,
47
}
48

            
49
impl fmt::Display for Finding {
50
160
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51
160
        match self.user {
52
            Some(user) => write!(f, "user {user} {}: {}", self.subject, self.reason),
53
160
            None => write!(f, "{}: {}", self.subject, self.reason),
54
        }
55
160
    }
56
}
57

            
58
/// What one tenant's run looked at.
59
#[derive(Debug, Default, PartialEq, Eq)]
60
pub struct Coverage {
61
    pub templates: usize,
62
    pub sources: usize,
63
    pub lookups: usize,
64
    pub resolved: usize,
65
}
66

            
67
#[derive(Debug)]
68
pub struct TenantReport {
69
    pub user: Uuid,
70
    pub coverage: Coverage,
71
    pub findings: Vec<Finding>,
72
}
73

            
74
#[derive(Debug, Default)]
75
pub struct Report {
76
    /// Host imports the trigger linker binds, none of them a registry native.
77
    pub trigger_imports: usize,
78
    pub tenants: Vec<TenantReport>,
79
    pub findings: Vec<Finding>,
80
}
81

            
82
impl Report {
83
962
    pub fn findings(&self) -> impl Iterator<Item = &Finding> {
84
962
        self.findings
85
962
            .iter()
86
962
            .chain(self.tenants.iter().flat_map(|tenant| &tenant.findings))
87
962
    }
88

            
89
    /// One line per tenant, then the totals.
90
    #[must_use]
91
320
    pub fn summary(&self) -> Vec<String> {
92
320
        let mut lines: Vec<String> = self
93
320
            .tenants
94
320
            .iter()
95
            .map(|tenant| {
96
                let Coverage {
97
                    templates,
98
                    sources,
99
                    lookups,
100
                    resolved,
101
                } = &tenant.coverage;
102
                format!(
103
                    "user {}: {templates} templates, {sources} sources, {lookups} lookups \
104
                     ({resolved} resolved cleanly): {} findings",
105
                    tenant.user,
106
                    tenant.findings.len()
107
                )
108
            })
109
            .collect();
110
320
        lines.push(format!(
111
320
            "{} tenants, trigger host binds {} imports: {} findings",
112
320
            self.tenants.len(),
113
320
            self.trigger_imports,
114
320
            self.findings().count()
115
320
        ));
116
320
        lines
117
320
    }
118
}
119

            
120
31
fn how(kind: LookupKind) -> &'static str {
121
31
    match kind {
122
24
        LookupKind::Account => "account",
123
7
        LookupKind::Commodity => "commodity",
124
    }
125
31
}
126

            
127
19
fn classify(directory: &Directory, kind: LookupKind, key: &str) -> Resolution {
128
19
    match kind {
129
15
        LookupKind::Account => directory.classify_account(key),
130
4
        LookupKind::Commodity => directory.classify_commodity(key),
131
    }
132
19
}
133

            
134
/// Why `key` is not a clean reference, or `None` when it resolves by id, path
135
/// or symbol.
136
19
fn defect(kind: LookupKind, key: &str, resolution: &Resolution) -> Option<String> {
137
19
    let entity = how(kind);
138
19
    match resolution {
139
11
        Resolution::Id | Resolution::Path | Resolution::Symbol => None,
140
4
        Resolution::Bare(path) => Some(format!(
141
4
            "{entity} '{key}' is a bare name: use the path '{path}' or the id"
142
4
        )),
143
        Resolution::Ambiguous(total) => {
144
1
            Some(format!("{entity} '{key}' is ambiguous ({total} matches)"))
145
        }
146
3
        Resolution::Unknown => Some(format!("{entity} '{key}' matches no entity of the user")),
147
    }
148
19
}
149

            
150
/// Why a logical-row key is not an id; the id is suggested when the key
151
/// resolves by the lookup rules.
152
4
fn row_defect(directory: &Directory, kind: LookupKind, key: &str) -> Option<String> {
153
4
    let entity = how(kind);
154
4
    let resolved = match kind {
155
2
        LookupKind::Account => directory.account(key),
156
2
        LookupKind::Commodity => directory.commodity(key),
157
    };
158
4
    match (Uuid::parse_str(key).is_ok(), resolved) {
159
2
        (true, Ok(_)) => None,
160
2
        (false, Ok(id)) => Some(format!(
161
2
            "row key {entity} '{key}' must be an id: use '{id}'"
162
2
        )),
163
        _ => Some(format!(
164
            "row key {entity} '{key}' must be the id of an entity of the user"
165
        )),
166
    }
167
4
}
168

            
169
/// Check every tenant of the directory except the admin; `sources` is the
170
/// declared directory of source files.
171
///
172
/// # Errors
173
/// [`DBError`] when the directory cannot be listed.
174
2
pub async fn check_references(admin: Uuid, sources: Option<&Path>) -> Result<Report, DBError> {
175
2
    let (trigger_imports, mut findings) = trigger::check();
176
2
    let (declared, unreadable) = sources.map(sources::load).unwrap_or_default();
177
2
    findings.extend(unreadable);
178
2
    let mut report = Report {
179
2
        trigger_imports,
180
2
        findings,
181
2
        ..Report::default()
182
2
    };
183
2
    for user in tenants(admin).await? {
184
2
        report.tenants.push(check_tenant(user, &declared).await);
185
    }
186
2
    Ok(report)
187
2
}
188

            
189
/// Check the stored templates and the declared sources of one tenant.
190
9
pub async fn check_tenant(user: Uuid, declared: &[Source]) -> TenantReport {
191
9
    let mut report = TenantReport {
192
9
        user,
193
9
        coverage: Coverage::default(),
194
9
        findings: Vec::new(),
195
9
    };
196
9
    match Directory::load("check-references", user).await {
197
        Ok(directory) => {
198
9
            templates::check(user, &directory, &mut report).await;
199
9
            sources::check(user, &directory, declared, &mut report);
200
        }
201
        Err(err) => report.findings.push(Finding {
202
            user: Some(user),
203
            subject: Subject::Tenant,
204
            reason: format!("{err:#}"),
205
        }),
206
    }
207
9
    report
208
9
}