cat_gateway/service/utilities/middleware/
schema_validation.rs

1//! Middleware to verify the status of the last DB schema version validation.
2//!
3//! If a mismatch is detected, the middleware returns an error with `ServiceUnavailable`
4//! status code (503). Otherwise, the middleware calls and returns the wrapped endpoint's
5//! response.
6//!
7//! This middleware checks the `State.schema_version_status` value, if it is Ok,
8//! the wrapped endpoint is called and its response is returned.
9
10use poem::{http::StatusCode, Endpoint, EndpointExt, Middleware, Request, Result};
11use tracing::error;
12
13use crate::{
14    db::event::{EventDB, EventDBConnectionError},
15    service::utilities::health::set_event_db_liveness,
16};
17
18/// A middleware that raises an error  with `ServiceUnavailable` and 503 status code
19/// if a DB schema version mismatch is found the existing `State`.
20pub(crate) struct SchemaVersionValidation;
21
22impl<E: Endpoint> Middleware<E> for SchemaVersionValidation {
23    type Output = SchemaVersionValidationImpl<E>;
24
25    fn transform(
26        &self,
27        ep: E,
28    ) -> Self::Output {
29        SchemaVersionValidationImpl { ep }
30    }
31}
32
33/// The new endpoint type generated by the `SchemaVersionValidation`.
34pub(crate) struct SchemaVersionValidationImpl<E> {
35    /// Endpoint wrapped by the middleware.
36    ep: E,
37}
38
39impl<E: Endpoint> Endpoint for SchemaVersionValidationImpl<E> {
40    type Output = E::Output;
41
42    async fn call(
43        &self,
44        req: Request,
45    ) -> Result<Self::Output> {
46        // Check if the inner schema version status is set to `Mismatch`,
47        // if so, return the `StatusCode::SERVICE_UNAVAILABLE` code.
48        if let Err(e) = EventDB::schema_version_check().await {
49            if e.is::<EventDBConnectionError>() {
50                set_event_db_liveness(false);
51                error!("Event DB is disconnected. Liveness set to false");
52            } else {
53                error!("Schema version check error: {e:?}");
54            }
55            return Err(StatusCode::SERVICE_UNAVAILABLE.into());
56        }
57        // Calls the endpoint with the request, and returns the response.
58        self.ep.call(req).await
59    }
60}
61
62/// A function that wraps an endpoint with the `SchemaVersionValidation`.
63///
64/// This function is convenient to use with `poem-openapi` [operation parameters](https://docs.rs/poem-openapi/latest/poem_openapi/attr.OpenApi.html#operation-parameters) via the
65/// `transform` attribute.
66pub(crate) fn schema_version_validation(ep: impl Endpoint) -> impl Endpoint {
67    ep.with(SchemaVersionValidation)
68}