Skip to content

Commit

Permalink
Add stats endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
xSke committed Feb 11, 2024
1 parent c17c0bd commit 1627df3
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
11 changes: 11 additions & 0 deletions src/db.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::ImageKind;
use s3::creds::time::OffsetDateTime;
use serde::Serialize;
use sqlx::{Executor, FromRow, PgPool, Postgres, Transaction};

#[derive(FromRow)]
Expand All @@ -19,6 +20,12 @@ pub struct ImageMeta {
pub uploaded_by_account: Option<i64>,
}

#[derive(FromRow, Serialize)]
pub struct Stats {
pub total_images: i64,
pub total_file_size: i64
}

#[derive(FromRow)]
pub struct ImageQueueEntry {
pub itemid: i32,
Expand Down Expand Up @@ -65,6 +72,10 @@ pub async fn get_queue_length(pool: &PgPool) -> anyhow::Result<i64> {
Ok(sqlx::query_scalar("select count(*) from image_queue").fetch_one(pool).await?)
}

pub async fn get_stats(pool: &PgPool) -> anyhow::Result<Stats> {
Ok(sqlx::query_as("select count(*) as total_images, sum(file_size) as total_file_size from images").fetch_one(pool).await?)
}

pub async fn add_image(pool: &PgPool, meta: ImageMeta) -> anyhow::Result<bool> {
let kind_str = match meta.kind {
ImageKind::Avatar => "avatar",
Expand Down
11 changes: 10 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,10 @@ use config::FileFormat;
use serde::{Deserialize, Serialize};
use sqlx::PgPool;
use std::sync::Arc;
use axum::routing::get;
use thiserror::Error;
use tracing::{error, info};
use crate::db::Stats;

#[derive(Error, Debug)]
pub enum PKAvatarError {
Expand Down Expand Up @@ -142,6 +144,10 @@ async fn pull(
}))
}

pub async fn stats(State(state): State<AppState>) -> Result<Json<Stats>, PKAvatarError> {
Ok(Json(db::get_stats(&state.pool).await?))
}

fn load_config() -> anyhow::Result<Config> {
config::ConfigBuilder::<DefaultState>::default()
.add_source(config::File::new("config", FileFormat::Toml).required(false))
Expand Down Expand Up @@ -181,7 +187,10 @@ async fn main() -> anyhow::Result<()> {

migrate::spawn_migrate_workers(Arc::new(state.clone()), state.config.migrate_worker_count);

let app = Router::new().route("/pull", post(pull)).with_state(state);
let app = Router::new()
.route("/pull", post(pull))
.route("/stats", get(stats))
.with_state(state);

let host = "0.0.0.0:3000";
info!("starting server on {}!", host);
Expand Down

0 comments on commit 1627df3

Please sign in to comment.