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::db::event::EventDB;
14
15/// A middleware that raises an error  with `ServiceUnavailable` and 503 status code
16/// if a DB schema version mismatch is found the existing `State`.
17pub(crate) struct SchemaVersionValidation;
18
19impl<E: Endpoint> Middleware<E> for SchemaVersionValidation {
20    type Output = SchemaVersionValidationImpl<E>;
21
22    fn transform(&self, ep: E) -> Self::Output {
23        SchemaVersionValidationImpl { ep }
24    }
25}
26
27/// The new endpoint type generated by the `SchemaVersionValidation`.
28pub(crate) struct SchemaVersionValidationImpl<E> {
29    /// Endpoint wrapped by the middleware.
30    ep: E,
31}
32
33impl<E: Endpoint> Endpoint for SchemaVersionValidationImpl<E> {
34    type Output = E::Output;
35
36    async fn call(&self, req: Request) -> Result<Self::Output> {
37        // Check if the inner schema version status is set to `Mismatch`,
38        // if so, return the `StatusCode::SERVICE_UNAVAILABLE` code.
39        if let Err(e) = EventDB::schema_version_check().await {
40            error!("Schema version check error: {e:?}");
41            return Err(StatusCode::SERVICE_UNAVAILABLE.into());
42        }
43        // Calls the endpoint with the request, and returns the response.
44        self.ep.call(req).await
45    }
46}
47
48/// A function that wraps an endpoint with the `SchemaVersionValidation`.
49///
50/// 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
51/// `transform` attribute.
52pub(crate) fn schema_version_validation(ep: impl Endpoint) -> impl Endpoint {
53    ep.with(SchemaVersionValidation)
54}