Lines
80.2 %
Functions
53.57 %
Branches
100 %
//! Reference preflight: lists every stored template and declared source that
//! names an account or commodity other than by id, path or symbol that
//! resolves uniquely, and shows the trigger host resolves no names. It only
//! reads, so it may run on a live tenant as well as on a restored copy.
mod sources;
mod templates;
mod trigger;
use std::fmt;
use std::path::Path;
use server::db::DBError;
use server::preflight::tenants;
use uuid::Uuid;
use crate::lookup_log::LookupKind;
use crate::resolve::Directory;
use crate::resolve::class::Resolution;
pub use sources::{Source, load as load_sources};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Subject {
Tenant,
Template(Uuid, Option<String>),
Source(String),
TriggerHost,
}
impl fmt::Display for Subject {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Tenant => f.write_str("tenant"),
Self::Template(id, Some(name)) => write!(f, "template {id} '{name}'"),
Self::Template(id, None) => write!(f, "template {id}"),
Self::Source(path) => write!(f, "source {path}"),
Self::TriggerHost => f.write_str("trigger host"),
pub struct Finding {
pub user: Option<Uuid>,
pub subject: Subject,
pub reason: String,
impl fmt::Display for Finding {
match self.user {
Some(user) => write!(f, "user {user} {}: {}", self.subject, self.reason),
None => write!(f, "{}: {}", self.subject, self.reason),
/// What one tenant's run looked at.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct Coverage {
pub templates: usize,
pub sources: usize,
pub lookups: usize,
pub resolved: usize,
#[derive(Debug)]
pub struct TenantReport {
pub user: Uuid,
pub coverage: Coverage,
pub findings: Vec<Finding>,
#[derive(Debug, Default)]
pub struct Report {
/// Host imports the trigger linker binds, none of them a registry native.
pub trigger_imports: usize,
pub tenants: Vec<TenantReport>,
impl Report {
pub fn findings(&self) -> impl Iterator<Item = &Finding> {
self.findings
.iter()
.chain(self.tenants.iter().flat_map(|tenant| &tenant.findings))
/// One line per tenant, then the totals.
#[must_use]
pub fn summary(&self) -> Vec<String> {
let mut lines: Vec<String> = self
.tenants
.map(|tenant| {
let Coverage {
templates,
sources,
lookups,
resolved,
} = &tenant.coverage;
format!(
"user {}: {templates} templates, {sources} sources, {lookups} lookups \
({resolved} resolved cleanly): {} findings",
tenant.user,
tenant.findings.len()
)
})
.collect();
lines.push(format!(
"{} tenants, trigger host binds {} imports: {} findings",
self.tenants.len(),
self.trigger_imports,
self.findings().count()
));
lines
fn how(kind: LookupKind) -> &'static str {
match kind {
LookupKind::Account => "account",
LookupKind::Commodity => "commodity",
fn classify(directory: &Directory, kind: LookupKind, key: &str) -> Resolution {
LookupKind::Account => directory.classify_account(key),
LookupKind::Commodity => directory.classify_commodity(key),
/// Why `key` is not a clean reference, or `None` when it resolves by id, path
/// or symbol.
fn defect(kind: LookupKind, key: &str, resolution: &Resolution) -> Option<String> {
let entity = how(kind);
match resolution {
Resolution::Id | Resolution::Path | Resolution::Symbol => None,
Resolution::Bare(path) => Some(format!(
"{entity} '{key}' is a bare name: use the path '{path}' or the id"
)),
Resolution::Ambiguous(total) => {
Some(format!("{entity} '{key}' is ambiguous ({total} matches)"))
Resolution::Unknown => Some(format!("{entity} '{key}' matches no entity of the user")),
/// Why a logical-row key is not an id; the id is suggested when the key
/// resolves by the lookup rules.
fn row_defect(directory: &Directory, kind: LookupKind, key: &str) -> Option<String> {
let resolved = match kind {
LookupKind::Account => directory.account(key),
LookupKind::Commodity => directory.commodity(key),
};
match (Uuid::parse_str(key).is_ok(), resolved) {
(true, Ok(_)) => None,
(false, Ok(id)) => Some(format!(
"row key {entity} '{key}' must be an id: use '{id}'"
_ => Some(format!(
"row key {entity} '{key}' must be the id of an entity of the user"
/// Check every tenant of the directory except the admin; `sources` is the
/// declared directory of source files.
///
/// # Errors
/// [`DBError`] when the directory cannot be listed.
pub async fn check_references(admin: Uuid, sources: Option<&Path>) -> Result<Report, DBError> {
let (trigger_imports, mut findings) = trigger::check();
let (declared, unreadable) = sources.map(sources::load).unwrap_or_default();
findings.extend(unreadable);
let mut report = Report {
trigger_imports,
findings,
..Report::default()
for user in tenants(admin).await? {
report.tenants.push(check_tenant(user, &declared).await);
Ok(report)
/// Check the stored templates and the declared sources of one tenant.
pub async fn check_tenant(user: Uuid, declared: &[Source]) -> TenantReport {
let mut report = TenantReport {
user,
coverage: Coverage::default(),
findings: Vec::new(),
match Directory::load("check-references", user).await {
Ok(directory) => {
templates::check(user, &directory, &mut report).await;
sources::check(user, &directory, declared, &mut report);
Err(err) => report.findings.push(Finding {
user: Some(user),
subject: Subject::Tenant,
reason: format!("{err:#}"),
}),
report