cat_gateway/db/event/config/
mod.rs

1//! Configuration query
2
3use jsonschema::BasicOutput;
4use key::ConfigKey;
5use serde_json::Value;
6use tracing::error;
7
8use crate::db::event::EventDB;
9
10pub(crate) mod key;
11
12/// Configuration struct
13pub(crate) struct Config {}
14
15/// SQL get configuration.
16const GET_CONFIG: &str = include_str!("sql/get.sql");
17/// SQL update if exist or else insert configuration.
18const UPSERT_CONFIG: &str = include_str!("sql/upsert.sql");
19
20impl Config {
21    /// Retrieve configuration based on the given `ConfigKey`.
22    ///
23    /// # Returns
24    ///
25    /// - A JSON value of the configuration, if not found or error, returns the default
26    ///   value.
27    /// - Error if the query fails.
28    pub(crate) async fn get(id: ConfigKey) -> anyhow::Result<Value> {
29        let (id1, id2, id3) = id.to_id();
30        let rows = EventDB::query(GET_CONFIG, &[&id1, &id2, &id3]).await?;
31
32        if let Some(row) = rows.first() {
33            let value: Value = row.get(0);
34            match id.validate(&value) {
35                BasicOutput::Valid(_) => return Ok(value),
36                BasicOutput::Invalid(errors) => {
37                    // This should not happen, expecting the schema to be valid
38                    error!(id=%id, error=?errors, "Get Config, schema validation failed, defaulting.");
39                },
40            }
41        }
42        // Return the default config value as a fallback
43        Ok(id.default())
44    }
45
46    /// Set the configuration for the given `ConfigKey`.
47    ///
48    /// # Returns
49    ///
50    /// - A `BasicOutput` of the validation result, which can be valid or invalid.
51    /// - Error if the query fails.
52    pub(crate) async fn set(id: ConfigKey, value: Value) -> anyhow::Result<BasicOutput<'static>> {
53        let validate = id.validate(&value);
54        // Validate schema failed, return immediately with JSON schema error
55        if !validate.is_valid() {
56            return Ok(validate);
57        }
58
59        let (id1, id2, id3) = id.to_id();
60        EventDB::query(UPSERT_CONFIG, &[&id1, &id2, &id3, &value]).await?;
61
62        Ok(validate)
63    }
64}