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(&self, ep: E) -> Self::Output {
26 SchemaVersionValidationImpl { ep }
27 }
28}
29
30/// The new endpoint type generated by the `SchemaVersionValidation`.
31pub(crate) struct SchemaVersionValidationImpl<E> {
32 /// Endpoint wrapped by the middleware.
33 ep: E,
34}
35
36impl<E: Endpoint> Endpoint for SchemaVersionValidationImpl<E> {
37 type Output = E::Output;
38
39 async fn call(&self, req: Request) -> Result<Self::Output> {
40 // Check if the inner schema version status is set to `Mismatch`,
41 // if so, return the `StatusCode::SERVICE_UNAVAILABLE` code.
42 if let Err(e) = EventDB::schema_version_check().await {
43 if e.is::<EventDBConnectionError>() {
44 set_event_db_liveness(false);
45 error!("Event DB is disconnected. Liveness set to false");
46 } else {
47 error!("Schema version check error: {e:?}");
48 }
49 return Err(StatusCode::SERVICE_UNAVAILABLE.into());
50 }
51 // Calls the endpoint with the request, and returns the response.
52 self.ep.call(req).await
53 }
54}
55
56/// A function that wraps an endpoint with the `SchemaVersionValidation`.
57///
58/// 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
59/// `transform` attribute.
60pub(crate) fn schema_version_validation(ep: impl Endpoint) -> impl Endpoint {
61 ep.with(SchemaVersionValidation)
62}