tuwunel_service/integrity/
schema.rs1use std::fmt;
2
3use futures::{Stream, StreamExt, stream::once};
4use tuwunel_core::{
5 Result,
6 utils::{BoolExt, IterStream, TryReadyExt, u64_from_bytes},
7};
8
9use super::{Check, Report, tally};
10use crate::{
11 Services,
12 migrations::{DATABASE_VERSION, MARKERS, marker_present},
13};
14
15pub(super) static CHECK: Check = Check {
16 name: "schema",
17 about: "The schema version matches this build and a fresh database's markers are stamped",
18 quiescent: false,
19 walk: |services, limit| tally(scan(services), limit),
20};
21
22#[derive(Clone, Copy)]
27pub enum Finding {
28 Version {
30 stored: u64,
32 },
33
34 Unversioned,
36
37 Malformed,
39
40 Pending {
42 step: &'static str,
44 },
45}
46
47#[tracing::instrument(level = "trace", skip_all)]
54pub fn scan(services: &Services) -> impl Stream<Item = Result<Finding>> + Send + '_ {
55 let version = once(version(services)).ready_try_filter_map(Ok);
56
57 let pending = MARKERS
58 .iter()
59 .copied()
60 .stream()
61 .then(async |step| Ok((step, marker_present(services, step).await?)))
62 .ready_try_filter_map(|(step, present)| {
63 Ok(present
64 .is_false()
65 .then_some(Finding::Pending { step }))
66 });
67
68 version.chain(pending)
69}
70
71impl Report for Finding {
72 fn kind(&self) -> &'static str {
73 match self {
74 | Self::Version { .. } => "schema-version",
75 | Self::Unversioned => "missing-version",
76 | Self::Malformed => "malformed-version",
77 | Self::Pending { .. } => "pending-migration",
78 }
79 }
80}
81
82impl fmt::Display for Finding {
83 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84 match self {
85 | Self::Version { stored } => {
86 write!(f, "schema version is {stored}; this build uses {DATABASE_VERSION}")
87 },
88 | Self::Unversioned => write!(f, "no schema version is stored"),
89 | Self::Malformed => write!(f, "the stored schema version does not decode"),
90 | Self::Pending { step } => write!(f, "migration {step} is not stamped"),
91 }
92 }
93}
94
95#[tracing::instrument(level = "debug", skip_all)]
96async fn version(services: &Services) -> Result<Option<Finding>> {
97 match services
98 .globals
99 .db
100 .database_version_record()
101 .await
102 {
103 | Err(error) if error.is_not_found() => Ok(Some(Finding::Unversioned)),
104 | Err(error) => Err(error),
105 | Ok(record) => Ok(match u64_from_bytes(&record) {
106 | Ok(DATABASE_VERSION) => None,
107 | Ok(stored) => Some(Finding::Version { stored }),
108 | Err(_) => Some(Finding::Malformed),
109 }),
110 }
111}