Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(webserver): add endpoint to calculate disk usage #1964

Merged
merged 4 commits into from
Apr 25, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions ee/tabby-webserver/graphql/schema.graphql
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
type StorageStats {
events: DirectoryStat!
indexedRepositories: DirectoryStat!
database: DirectoryStat!
models: DirectoryStat!
}

enum Language {
RUST
PYTHON
Expand Down Expand Up @@ -258,6 +265,7 @@ type Query {
dailyStatsInPastYear(users: [ID!]): [CompletionStats!]!
dailyStats(start: DateTimeUtc!, end: DateTimeUtc!, users: [ID!], languages: [Language!]): [CompletionStats!]!
userEvents(after: String, before: String, first: Int, last: Int, users: [ID!], start: DateTimeUtc!, end: DateTimeUtc!): UserEventConnection!
storageStats: StorageStats!
}

input NetworkSettingInput {
Expand All @@ -280,6 +288,11 @@ type JobRunConnection {
pageInfo: PageInfo!
}

type DirectoryStat {
filePaths: [String!]!
size: Float!
}

type RefreshTokenResponse {
accessToken: String!
refreshToken: String!
Expand Down
2 changes: 1 addition & 1 deletion ee/tabby-webserver/src/path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

use tabby_common::path::tabby_root;

fn tabby_ee_root() -> PathBuf {
pub fn tabby_ee_root() -> PathBuf {

Check warning on line 5 in ee/tabby-webserver/src/path.rs

View check run for this annotation

Codecov / codecov/patch

ee/tabby-webserver/src/path.rs#L5

Added line #L5 was not covered by tests
tabby_root().join("ee")
}

Expand Down
29 changes: 29 additions & 0 deletions ee/tabby-webserver/src/schema/analytic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,33 @@

use crate::schema::Result;

#[derive(GraphQLObject)]

Check warning on line 11 in ee/tabby-webserver/src/schema/analytic.rs

View check run for this annotation

Codecov / codecov/patch

ee/tabby-webserver/src/schema/analytic.rs#L11

Added line #L11 was not covered by tests
pub struct StorageStats {
boxbeam marked this conversation as resolved.
Show resolved Hide resolved
pub events: DirectoryStat,
pub indexed_repositories: DirectoryStat,
pub database: DirectoryStat,
pub models: DirectoryStat,
}

#[derive(GraphQLObject)]

Check warning on line 19 in ee/tabby-webserver/src/schema/analytic.rs

View check run for this annotation

Codecov / codecov/patch

ee/tabby-webserver/src/schema/analytic.rs#L19

Added line #L19 was not covered by tests
pub struct DirectoryStat {
boxbeam marked this conversation as resolved.
Show resolved Hide resolved
pub file_paths: Vec<String>,
pub size: f64,
}

impl DirectoryStat {
pub fn combine(self, other: Self) -> Self {
DirectoryStat {
size: self.size + other.size,
file_paths: self
.file_paths
.into_iter()
.chain(other.file_paths)
.collect(),
}
}

Check warning on line 35 in ee/tabby-webserver/src/schema/analytic.rs

View check run for this annotation

Codecov / codecov/patch

ee/tabby-webserver/src/schema/analytic.rs#L26-L35

Added lines #L26 - L35 were not covered by tests
}

#[derive(GraphQLObject, Debug, Clone)]
pub struct CompletionStats {
pub start: DateTime<Utc>,
Expand Down Expand Up @@ -101,4 +128,6 @@
users: Vec<ID>,
languages: Vec<Language>,
) -> Result<Vec<CompletionStats>>;

async fn storage_stats(&self) -> Result<StorageStats>;
}
8 changes: 7 additions & 1 deletion ee/tabby-webserver/src/schema/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ use validator::{Validate, ValidationErrors};
use worker::{Worker, WorkerService};

use self::{
analytic::{AnalyticService, CompletionStats},
analytic::{AnalyticService, CompletionStats, StorageStats},
auth::{
JWTPayload, OAuthCredential, OAuthProvider, PasswordChangeInput, PasswordResetInput,
RequestInvitationInput, RequestPasswordResetEmailInput, UpdateOAuthCredentialInput,
Expand Down Expand Up @@ -457,6 +457,12 @@ impl Query {
)
.await
}

async fn storage_stats(ctx: &Context) -> Result<StorageStats> {
boxbeam marked this conversation as resolved.
Show resolved Hide resolved
check_admin(ctx).await?;
let storage_stats = ctx.locator.analytic().storage_stats().await?;
Ok(storage_stats)
}
}

#[derive(GraphQLObject)]
Expand Down
40 changes: 38 additions & 2 deletions ee/tabby-webserver/src/service/analytic.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
use std::sync::Arc;
use std::{path::PathBuf, sync::Arc};

use async_trait::async_trait;
use chrono::{DateTime, Utc};
use futures::Future;
use juniper::ID;
use tabby_db::DbConn;
use tracing::warn;

use super::AsRowid;
use crate::schema::{
analytic::{AnalyticService, CompletionStats, Language},
analytic::{AnalyticService, CompletionStats, DirectoryStat, Language, StorageStats},
Result,
};

Expand Down Expand Up @@ -70,6 +71,41 @@
.collect();
Ok(stats)
}

async fn storage_stats(&self) -> Result<StorageStats> {

Check warning on line 75 in ee/tabby-webserver/src/service/analytic.rs

View check run for this annotation

Codecov / codecov/patch

ee/tabby-webserver/src/service/analytic.rs#L75

Added line #L75 was not covered by tests
boxbeam marked this conversation as resolved.
Show resolved Hide resolved
Ok(StorageStats {
events: recursive_dir_size(tabby_common::path::events_dir()).await?,
indexed_repositories: recursive_dir_size(tabby_common::path::dataset_dir())
.await?
.combine(recursive_dir_size(tabby_common::path::index_dir()).await?),
database: recursive_dir_size(crate::path::tabby_ee_root()).await?,
models: recursive_dir_size(tabby_common::path::models_dir()).await?,

Check warning on line 82 in ee/tabby-webserver/src/service/analytic.rs

View check run for this annotation

Codecov / codecov/patch

ee/tabby-webserver/src/service/analytic.rs#L77-L82

Added lines #L77 - L82 were not covered by tests
})
}

Check warning on line 84 in ee/tabby-webserver/src/service/analytic.rs

View check run for this annotation

Codecov / codecov/patch

ee/tabby-webserver/src/service/analytic.rs#L84

Added line #L84 was not covered by tests
}

/// Calculate the size of a directory in kilobytes recursively
fn recursive_dir_size(
boxbeam marked this conversation as resolved.
Show resolved Hide resolved
path: PathBuf,
) -> Box<dyn Future<Output = Result<DirectoryStat, anyhow::Error>> + Unpin + Send> {
Box::new(Box::pin(async move {
let mut size: f64 = 0.0;
if path.exists() {
let mut read_dir = tokio::fs::read_dir(path.clone()).await?;
while let Some(next) = read_dir.next_entry().await? {
let meta = next.metadata().await?;
if meta.is_dir() {
size += recursive_dir_size(next.path()).await?.size;
} else {
size += meta.len() as f64 / 1024.0;
}

Check warning on line 101 in ee/tabby-webserver/src/service/analytic.rs

View check run for this annotation

Codecov / codecov/patch

ee/tabby-webserver/src/service/analytic.rs#L88-L101

Added lines #L88 - L101 were not covered by tests
}
}
Ok(DirectoryStat {
file_paths: vec![path.to_string_lossy().to_string()],
size,
})
}))

Check warning on line 108 in ee/tabby-webserver/src/service/analytic.rs

View check run for this annotation

Codecov / codecov/patch

ee/tabby-webserver/src/service/analytic.rs#L103-L108

Added lines #L103 - L108 were not covered by tests
}

fn convert_ids(ids: Vec<ID>) -> Vec<i64> {
Expand Down
Loading