Skip to main content

apalis_postgres/queries/
metrics.rs

1use std::str::FromStr;
2
3use apalis_core::backend::{Backend, Metrics, StatType, Statistic};
4
5use crate::{PostgresStorage, error::Error};
6
7struct StatisticRow {
8    priority: Option<i32>,
9    r#type: Option<String>,
10    statistic: Option<String>,
11    value: Option<f32>,
12}
13
14impl<Args> Metrics for PostgresStorage<Args>
15where
16    PostgresStorage<Args>: Backend<Error = Error>,
17{
18    fn global(&self) -> impl Future<Output = Result<Vec<Statistic>, Self::Error>> + Send {
19        let pool = self.persistence.pool.clone();
20
21        async move {
22            let rec = sqlx::query_file_as!(StatisticRow, "queries/backend/overview.sql")
23                .fetch_all(&pool)
24                .await?
25                .into_iter()
26                .map(|r| Statistic {
27                    priority: Some(r.priority.unwrap_or_default() as u64),
28                    stat_type: StatType::from_str(&r.r#type.unwrap_or_default())
29                        .unwrap_or_default(),
30                    title: r.statistic.unwrap_or_default(),
31                    value: r.value.unwrap_or_default().to_string(),
32                })
33                .collect();
34            Ok(rec)
35        }
36    }
37    fn fetch_by_queue(&self) -> impl Future<Output = Result<Vec<Statistic>, Self::Error>> + Send {
38        let pool = self.persistence.pool.clone();
39        let queue_id = self.persistence.config.queue.to_string();
40        async move {
41            let rec = sqlx::query_file_as!(
42                StatisticRow,
43                "queries/backend/overview_by_queue.sql",
44                queue_id
45            )
46            .fetch_all(&pool)
47            .await?
48            .into_iter()
49            .map(|r| Statistic {
50                priority: Some(r.priority.unwrap_or_default() as u64),
51                stat_type: StatType::from_str(&r.r#type.unwrap_or_default()).unwrap_or_default(),
52                title: r.statistic.unwrap_or_default(),
53                value: r.value.unwrap_or_default().to_string(),
54            })
55            .collect();
56            Ok(rec)
57        }
58    }
59}