Skip to main content

tuwunel_service/integrity/
schema.rs

1use 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/// A way the database's schema departs from this build's.
23///
24/// Neither is damage in itself. Each says the rows may not be in the shape this
25/// build reads.
26#[derive(Clone, Copy)]
27pub enum Finding {
28	/// The stored schema version is not this build's.
29	Version {
30		/// The version stored in the database.
31		stored: u64,
32	},
33
34	/// No schema version is stored.
35	Unversioned,
36
37	/// The stored schema version is not eight bytes.
38	Malformed,
39
40	/// A migration has not stamped its marker.
41	Pending {
42		/// The marker of the step, which is also its name.
43		step: &'static str,
44	},
45}
46
47/// Streams each departure of the stored schema from this build's.
48///
49/// A version mismatch comes first. Between it and the pending steps a reader can
50/// tell a database that was never upgraded from one a build abandoned partway,
51/// including after a downgrade. A failed read ends the stream, so an unreadable
52/// record is never reported as a version.
53#[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}