Add total history count to the index API (#1102)

Thought it would be fun to collect some cool stats, maybe put them on
atuin.sh.
This commit is contained in:
Ellie Huxtable 2023-07-14 20:44:47 +01:00 committed by GitHub
parent 97e24d0d41
commit 5786155969
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 27 additions and 2 deletions

View file

@ -67,6 +67,7 @@ pub struct ErrorResponse<'a> {
pub struct IndexResponse {
pub homage: String,
pub version: String,
pub total_history: i64,
}
#[derive(Debug, Serialize, Deserialize)]

View file

@ -52,6 +52,7 @@ pub trait Database: Sized + Clone + Send + Sync + 'static {
async fn add_user(&self, user: &NewUser) -> DbResult<i64>;
async fn delete_user(&self, u: &User) -> DbResult<()>;
async fn total_history(&self) -> DbResult<i64>;
async fn count_history(&self, user: &User) -> DbResult<i64>;
async fn count_history_cached(&self, user: &User) -> DbResult<i64>;

View file

@ -100,6 +100,21 @@ impl Database for Postgres {
Ok(res.0)
}
#[instrument(skip_all)]
async fn total_history(&self) -> DbResult<i64> {
// The cache is new, and the user might not yet have a cache value.
// They will have one as soon as they post up some new history, but handle that
// edge case.
let res: (i64,) = sqlx::query_as("select sum(total) from total_history_count_user")
.fetch_optional(&self.pool)
.await
.map_err(fix_error)?
.unwrap_or((0,));
Ok(res.0)
}
#[instrument(skip_all)]
async fn count_history_cached(&self, user: &User) -> DbResult<i64> {
let res: (i32,) = sqlx::query_as(

View file

@ -1,5 +1,8 @@
use atuin_common::api::{ErrorResponse, IndexResponse};
use axum::{response::IntoResponse, Json};
use atuin_server_database::Database;
use axum::{extract::State, response::IntoResponse, Json};
use crate::router::AppState;
pub mod history;
pub mod record;
@ -8,12 +11,17 @@ pub mod user;
const VERSION: &str = env!("CARGO_PKG_VERSION");
pub async fn index() -> Json<IndexResponse> {
pub async fn index<DB: Database>(state: State<AppState<DB>>) -> Json<IndexResponse> {
let homage = r#""Through the fathomless deeps of space swims the star turtle Great A'Tuin, bearing on its back the four giant elephants who carry on their shoulders the mass of the Discworld." -- Sir Terry Pratchett"#;
// Error with a -1 response
// It's super unlikley this will happen
let count = state.database.total_history().await.unwrap_or(-1);
Json(IndexResponse {
homage: homage.to_string(),
version: VERSION.to_string(),
total_history: count,
})
}