Skip to main content

rpc/
references.rs

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
6mod sources;
7mod templates;
8mod trigger;
9
10use std::fmt;
11use std::path::Path;
12
13use server::db::DBError;
14use server::preflight::tenants;
15use uuid::Uuid;
16
17use crate::lookup_log::LookupKind;
18use crate::resolve::Directory;
19use crate::resolve::class::Resolution;
20pub use sources::{Source, load as load_sources};
21
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub enum Subject {
24    Tenant,
25    Template(Uuid, Option<String>),
26    Source(String),
27    TriggerHost,
28}
29
30impl fmt::Display for Subject {
31    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32        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            Self::Source(path) => write!(f, "source {path}"),
37            Self::TriggerHost => f.write_str("trigger host"),
38        }
39    }
40}
41
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct Finding {
44    pub user: Option<Uuid>,
45    pub subject: Subject,
46    pub reason: String,
47}
48
49impl fmt::Display for Finding {
50    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51        match self.user {
52            Some(user) => write!(f, "user {user} {}: {}", self.subject, self.reason),
53            None => write!(f, "{}: {}", self.subject, self.reason),
54        }
55    }
56}
57
58/// What one tenant's run looked at.
59#[derive(Debug, Default, PartialEq, Eq)]
60pub struct Coverage {
61    pub templates: usize,
62    pub sources: usize,
63    pub lookups: usize,
64    pub resolved: usize,
65}
66
67#[derive(Debug)]
68pub struct TenantReport {
69    pub user: Uuid,
70    pub coverage: Coverage,
71    pub findings: Vec<Finding>,
72}
73
74#[derive(Debug, Default)]
75pub 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
82impl Report {
83    pub fn findings(&self) -> impl Iterator<Item = &Finding> {
84        self.findings
85            .iter()
86            .chain(self.tenants.iter().flat_map(|tenant| &tenant.findings))
87    }
88
89    /// One line per tenant, then the totals.
90    #[must_use]
91    pub fn summary(&self) -> Vec<String> {
92        let mut lines: Vec<String> = self
93            .tenants
94            .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        lines.push(format!(
111            "{} tenants, trigger host binds {} imports: {} findings",
112            self.tenants.len(),
113            self.trigger_imports,
114            self.findings().count()
115        ));
116        lines
117    }
118}
119
120fn how(kind: LookupKind) -> &'static str {
121    match kind {
122        LookupKind::Account => "account",
123        LookupKind::Commodity => "commodity",
124    }
125}
126
127fn classify(directory: &Directory, kind: LookupKind, key: &str) -> Resolution {
128    match kind {
129        LookupKind::Account => directory.classify_account(key),
130        LookupKind::Commodity => directory.classify_commodity(key),
131    }
132}
133
134/// Why `key` is not a clean reference, or `None` when it resolves by id, path
135/// or symbol.
136fn defect(kind: LookupKind, key: &str, resolution: &Resolution) -> Option<String> {
137    let entity = how(kind);
138    match resolution {
139        Resolution::Id | Resolution::Path | Resolution::Symbol => None,
140        Resolution::Bare(path) => Some(format!(
141            "{entity} '{key}' is a bare name: use the path '{path}' or the id"
142        )),
143        Resolution::Ambiguous(total) => {
144            Some(format!("{entity} '{key}' is ambiguous ({total} matches)"))
145        }
146        Resolution::Unknown => Some(format!("{entity} '{key}' matches no entity of the user")),
147    }
148}
149
150/// Why a logical-row key is not an id; the id is suggested when the key
151/// resolves by the lookup rules.
152fn row_defect(directory: &Directory, kind: LookupKind, key: &str) -> Option<String> {
153    let entity = how(kind);
154    let resolved = match kind {
155        LookupKind::Account => directory.account(key),
156        LookupKind::Commodity => directory.commodity(key),
157    };
158    match (Uuid::parse_str(key).is_ok(), resolved) {
159        (true, Ok(_)) => None,
160        (false, Ok(id)) => Some(format!(
161            "row key {entity} '{key}' must be an id: use '{id}'"
162        )),
163        _ => Some(format!(
164            "row key {entity} '{key}' must be the id of an entity of the user"
165        )),
166    }
167}
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.
174pub async fn check_references(admin: Uuid, sources: Option<&Path>) -> Result<Report, DBError> {
175    let (trigger_imports, mut findings) = trigger::check();
176    let (declared, unreadable) = sources.map(sources::load).unwrap_or_default();
177    findings.extend(unreadable);
178    let mut report = Report {
179        trigger_imports,
180        findings,
181        ..Report::default()
182    };
183    for user in tenants(admin).await? {
184        report.tenants.push(check_tenant(user, &declared).await);
185    }
186    Ok(report)
187}
188
189/// Check the stored templates and the declared sources of one tenant.
190pub async fn check_tenant(user: Uuid, declared: &[Source]) -> TenantReport {
191    let mut report = TenantReport {
192        user,
193        coverage: Coverage::default(),
194        findings: Vec::new(),
195    };
196    match Directory::load("check-references", user).await {
197        Ok(directory) => {
198            templates::check(user, &directory, &mut report).await;
199            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    report
208}