Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
33 changes: 9 additions & 24 deletions crates/server/src/handlers/analytics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use crate::app::AppState;
use crate::handlers::clickhouse_util::ch_client;
use crate::handlers::time_range::{RangeQuery, TimeRange};
use crate::middleware::auth_guard::AuthUser;
use crate::services::analytics_repository as repo;

/// Resolve the caller's analytics scope as a user-id allowlist that
/// ClickHouse's `has(?, user_id)` can bind against.
Expand Down Expand Up @@ -54,12 +55,7 @@ async fn analytics_user_id_filter(
&& !team_ids.is_empty()
{
let team_ids_vec: Vec<uuid::Uuid> = team_ids.into_iter().collect();
let members: Vec<(String,)> = sqlx::query_as(
"SELECT DISTINCT user_id::text FROM team_members WHERE team_id = ANY($1)",
)
.bind(&team_ids_vec)
.fetch_all(pool)
.await?;
let members = repo::members_of_teams(pool, &team_ids_vec).await?;
for (uid,) in members {
visible.insert(uid);
}
Expand All @@ -73,14 +69,11 @@ async fn analytics_user_id_filter(
};

// Team filter requested. Resolve membership and intersect.
let team_members: std::collections::HashSet<String> =
sqlx::query_as::<_, (String,)>("SELECT user_id::text FROM team_members WHERE team_id = $1")
.bind(team_id)
.fetch_all(pool)
.await?
.into_iter()
.map(|(s,)| s)
.collect();
let team_members: std::collections::HashSet<String> = repo::members_of_team(pool, team_id)
.await?
.into_iter()
.map(|(s,)| s)
.collect();

let intersected: Vec<String> = match scope {
None => team_members.into_iter().collect(), // global → just the team
Expand Down Expand Up @@ -1078,11 +1071,7 @@ pub async fn get_costs(
if key_ids.is_empty() {
std::collections::HashMap::new()
} else {
let rows: Vec<(uuid::Uuid, Option<String>)> =
sqlx::query_as("SELECT id, cost_center FROM api_keys WHERE id = ANY($1)")
.bind(&key_ids)
.fetch_all(&state.db)
.await?;
let rows = repo::cost_centers_of_keys(&state.db, &key_ids).await?;
rows.into_iter()
.filter_map(|(id, cc)| cc.map(|c| (id, c)))
.collect()
Expand Down Expand Up @@ -1147,11 +1136,7 @@ pub async fn get_costs(
if ids.is_empty() {
std::collections::HashMap::new()
} else {
let rows: Vec<(uuid::Uuid, String)> =
sqlx::query_as("SELECT id, email FROM users WHERE id = ANY($1)")
.bind(&ids)
.fetch_all(&state.db)
.await?;
let rows = repo::emails_of_users(&state.db, &ids).await?;
rows.into_iter()
.map(|(id, email)| (id.to_string(), email))
.collect()
Expand Down
7 changes: 2 additions & 5 deletions crates/server/src/handlers/chargeback.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ use think_watch_common::errors::AppError;
use crate::app::AppState;
use crate::handlers::clickhouse_util::ch_client;
use crate::middleware::auth_guard::AuthUser;
use crate::services::analytics_repository;

#[derive(Debug, Deserialize)]
pub struct ChargebackQuery {
Expand Down Expand Up @@ -122,11 +123,7 @@ pub async fn export_chargeback_csv(
{
std::collections::HashMap::new()
} else {
let rows: Vec<(uuid::Uuid, Option<String>)> =
sqlx::query_as("SELECT id, cost_center FROM api_keys WHERE id = ANY($1)")
.bind(&referenced_keys)
.fetch_all(&state.db)
.await?;
let rows = analytics_repository::cost_centers_of_keys(&state.db, &referenced_keys).await?;
rows.into_iter()
.filter_map(|(id, cc)| cc.map(|c| (id, c)))
.collect()
Expand Down
21 changes: 3 additions & 18 deletions crates/server/src/handlers/dashboard/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use think_watch_common::errors::AppError;

use crate::app::AppState;
use crate::middleware::auth_guard::AuthUser;
use crate::services::observability_repository as repo;

#[derive(Debug, Serialize, Deserialize, utoipa::ToSchema)]
pub struct DashboardLayout {
Expand All @@ -35,11 +36,7 @@ pub async fn get_dashboard_layout(
auth_user: AuthUser,
State(state): State<AppState>,
) -> Result<Json<DashboardLayout>, AppError> {
let row: Option<(String, serde_json::Value)> =
sqlx::query_as("SELECT name, layout_json FROM user_dashboard_layouts WHERE user_id = $1")
.bind(auth_user.claims.sub)
.fetch_optional(&state.db)
.await?;
let row = repo::get_layout(&state.db, auth_user.claims.sub).await?;

let (name, layout_json) = row.unwrap_or_else(|| ("default".into(), serde_json::Value::Null));
Ok(Json(DashboardLayout { name, layout_json }))
Expand Down Expand Up @@ -86,19 +83,7 @@ pub async fn put_dashboard_layout(
req.name
};

sqlx::query(
"INSERT INTO user_dashboard_layouts (user_id, name, layout_json, updated_at) \
VALUES ($1, $2, $3, now()) \
ON CONFLICT (user_id) DO UPDATE \
SET name = EXCLUDED.name, \
layout_json = EXCLUDED.layout_json, \
updated_at = now()",
)
.bind(auth_user.claims.sub)
.bind(&name)
.bind(&req.layout_json)
.execute(&state.db)
.await?;
repo::upsert_layout(&state.db, auth_user.claims.sub, &name, &req.layout_json).await?;

Ok(Json(serde_json::json!({ "status": "saved" })))
}
25 changes: 5 additions & 20 deletions crates/server/src/handlers/dashboard/live.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use think_watch_common::errors::AppError;
use crate::app::AppState;
use crate::handlers::clickhouse_util::{ch_available, ch_client};
use crate::middleware::auth_guard::AuthUser;
use crate::services::observability_repository as repo;

use super::scope::resolve_dashboard_user_filter;
use super::top_users::{TopActiveUsersResponse, fetch_top_active_users};
Expand Down Expand Up @@ -128,14 +129,7 @@ async fn ai_breaker_states(
state: &AppState,
) -> std::collections::HashMap<String, tw_breaker::State> {
use tw_breaker::State;
let rows: Vec<(uuid::Uuid, String)> = match sqlx::query_as(
"SELECT mr.id, p.name FROM model_routes mr \
JOIN providers p ON p.id = mr.provider_id \
WHERE p.is_active = true AND p.deleted_at IS NULL",
)
.fetch_all(&state.db)
.await
{
let rows = match repo::active_provider_routes(&state.db).await {
Ok(r) => r,
Err(e) => {
tracing::warn!("dashboard: route list for breaker states failed: {e}");
Expand Down Expand Up @@ -175,20 +169,11 @@ pub(super) async fn build_live_snapshot(
// Errors propagate so the dashboard surfaces a real failure instead of
// pretending data is empty when the DB is down.
//
let providers_fut = sqlx::query_as::<_, (String,)>(
"SELECT name FROM providers WHERE is_active = true AND deleted_at IS NULL",
)
.fetch_all(&state.db);
let mcp_servers_fut =
sqlx::query_as::<_, (String, String)>("SELECT name, status FROM mcp_servers")
.fetch_all(&state.db);
let providers_fut = repo::active_provider_names(&state.db);
let mcp_servers_fut = repo::mcp_server_statuses(&state.db);
// Highest per-minute RPM limit across all enabled rules — used as
// a reference line on the request-rate sparkline.
let rpm_limit_fut = sqlx::query_scalar::<_, Option<i64>>(
"SELECT MAX(max_count) FROM rate_limit_rules \
WHERE metric = 'requests' AND window_secs = 60 AND enabled = true",
)
.fetch_one(&state.db);
let rpm_limit_fut = repo::max_enabled_rpm_limit(&state.db);

let (configured_providers, configured_mcp_servers, max_rpm_raw) =
tokio::try_join!(providers_fut, mcp_servers_fut, rpm_limit_fut)
Expand Down
53 changes: 8 additions & 45 deletions crates/server/src/handlers/dashboard/scope.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,62 +17,25 @@

use think_watch_common::errors::AppError;

use crate::services::observability_repository as repo;

pub(super) async fn resolve_dashboard_user_filter(
pool: &sqlx::PgPool,
caller_id: uuid::Uuid,
) -> Result<Option<Vec<String>>, AppError> {
// Global analytics:read_all → no filter.
let has_global_all: bool = sqlx::query_scalar(
"SELECT EXISTS (
SELECT 1 FROM rbac_role_assignments ra
JOIN rbac_roles r ON r.id = ra.role_id
WHERE ra.user_id = $1
AND ra.scope_kind = 'global'
AND EXISTS (
SELECT 1 FROM jsonb_array_elements(r.policy_document->'Statement') AS stmt
WHERE stmt->>'Effect' = 'Allow'
AND (stmt->>'Action' = '*' OR stmt->>'Action' = 'analytics:read_all'
OR (stmt->'Action' @> '\"analytics:read_all\"'::jsonb))
)
)",
)
.bind(caller_id)
.fetch_one(pool)
.await
.map_err(|e| AppError::Internal(anyhow::anyhow!("dashboard scope check failed: {e}")))?;
let has_global_all = repo::has_global_analytics_read_all(pool, caller_id)
.await
.map_err(|e| AppError::Internal(anyhow::anyhow!("dashboard scope check failed: {e}")))?;
if has_global_all {
return Ok(None);
}

// Otherwise build the visible-user set: caller themself + every
// team member of any team the caller holds analytics:read_team
// (or analytics:read_all) for at team scope.
let user_id_strs: Vec<(String,)> = sqlx::query_as(
"SELECT DISTINCT u.id::text
FROM users u
WHERE u.deleted_at IS NULL
AND (u.id = $1
OR EXISTS (
SELECT 1 FROM team_members tm
JOIN rbac_role_assignments ra ON ra.scope_kind = 'team'
AND ra.scope_id = tm.team_id
JOIN rbac_roles r ON r.id = ra.role_id
WHERE tm.user_id = u.id
AND ra.user_id = $1
AND EXISTS (
SELECT 1 FROM jsonb_array_elements(r.policy_document->'Statement') AS stmt
WHERE stmt->>'Effect' = 'Allow'
AND (stmt->>'Action' = '*'
OR stmt->>'Action' = 'analytics:read_team'
OR stmt->>'Action' = 'analytics:read_all'
OR (stmt->'Action' @> '\"analytics:read_team\"'::jsonb)
OR (stmt->'Action' @> '\"analytics:read_all\"'::jsonb))
)
))",
)
.bind(caller_id)
.fetch_all(pool)
.await
.map_err(|e| AppError::Internal(anyhow::anyhow!("dashboard scope query failed: {e}")))?;
let user_id_strs = repo::analytics_team_scope_user_ids(pool, caller_id)
.await
.map_err(|e| AppError::Internal(anyhow::anyhow!("dashboard scope query failed: {e}")))?;
Ok(Some(user_id_strs.into_iter().map(|(s,)| s).collect()))
}
64 changes: 12 additions & 52 deletions crates/server/src/handlers/dashboard/stats.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use think_watch_common::errors::AppError;
use crate::app::AppState;
use crate::handlers::clickhouse_util::{ch_available, ch_client};
use crate::middleware::auth_guard::AuthUser;
use crate::services::observability_repository as repo;

#[derive(Debug, Serialize, utoipa::ToSchema)]
pub struct DashboardStats {
Expand Down Expand Up @@ -104,18 +105,8 @@ pub async fn get_dashboard_stats(
// team manager doesn't see analytics rows for accounts that
// have been removed from the org (those rows linger in CH
// for the 30-day GDPR retention window).
let rows: Vec<(String,)> = sqlx::query_as(
"SELECT DISTINCT u.id::text FROM users u \
WHERE u.deleted_at IS NULL AND (u.id = $1 \
OR EXISTS ( \
SELECT 1 FROM team_members tm \
WHERE tm.user_id = u.id AND tm.team_id = ANY($2) \
))",
)
.bind(caller_id)
.bind(&team_ids_vec)
.fetch_all(&state.db)
.await?;
let rows =
repo::caller_and_team_member_ids(&state.db, caller_id, &team_ids_vec).await?;
Some(rows.into_iter().map(|(s,)| s).collect())
}
};
Expand Down Expand Up @@ -190,16 +181,9 @@ pub async fn get_dashboard_stats(
// matches what the limits engine and the gateway router actually
// see. Without `deleted_at IS NULL` the count silently inflates
// for 30 days after a delete.
let active_providers: Option<i64> = sqlx::query_scalar(
"SELECT COUNT(*) FROM providers WHERE is_active = true AND deleted_at IS NULL",
)
.fetch_one(&state.db)
.await?;
let active_providers = repo::count_active_providers(&state.db).await?;

let connected_mcp_servers: Option<i64> =
sqlx::query_scalar("SELECT COUNT(*) FROM mcp_servers WHERE status = 'connected'")
.fetch_one(&state.db)
.await?;
let connected_mcp_servers = repo::count_connected_mcp_servers(&state.db).await?;

// Active API keys — distinct keys used in the selected window from
// ClickHouse gateway_logs, plus per-bucket counts for the sparkline.
Expand All @@ -226,18 +210,8 @@ pub async fn get_dashboard_stats(
// Same soft-delete filter as the usage scope above —
// keep the two in lockstep so active-key counts and
// usage rollups display a consistent population.
let rows: Vec<(String,)> = sqlx::query_as(
"SELECT DISTINCT u.id::text FROM users u \
WHERE u.deleted_at IS NULL AND (u.id = $1 \
OR EXISTS ( \
SELECT 1 FROM team_members tm \
WHERE tm.user_id = u.id AND tm.team_id = ANY($2) \
))",
)
.bind(caller_id)
.bind(&team_ids_vec)
.fetch_all(&state.db)
.await?;
let rows =
repo::caller_and_team_member_ids(&state.db, caller_id, &team_ids_vec).await?;
Some(rows.into_iter().map(|(s,)| s).collect())
}
};
Expand Down Expand Up @@ -394,14 +368,7 @@ pub async fn get_dashboard_stats(
(count_result as i64, buckets)
} else {
// No ClickHouse — fall back to Postgres last_used_at in the window.
let count: Option<i64> = sqlx::query_scalar(
"SELECT COUNT(DISTINCT id) FROM api_keys \
WHERE is_active = true AND deleted_at IS NULL \
AND last_used_at >= $1",
)
.bind(window_start)
.fetch_one(&state.db)
.await?;
let count = repo::count_api_keys_used_since(&state.db, window_start).await?;
(count.unwrap_or(0), vec![0; range.bucket_count()])
};

Expand Down Expand Up @@ -439,16 +406,9 @@ pub async fn get_dashboard_stats(
.map(|r| r.cnt as i64)
.unwrap_or(0)
} else {
sqlx::query_scalar::<_, Option<i64>>(
"SELECT COUNT(DISTINCT id) FROM api_keys \
WHERE is_active = true AND deleted_at IS NULL \
AND last_used_at >= $1 AND last_used_at < $2",
)
.bind(prev_start)
.bind(prev_end)
.fetch_one(&state.db)
.await?
.unwrap_or(0)
repo::count_api_keys_used_between(&state.db, prev_start, prev_end)
.await?
.unwrap_or(0)
};
(Some(prev_reqs.unwrap_or(0)), Some(prev_keys))
} else {
Expand All @@ -457,7 +417,7 @@ pub async fn get_dashboard_stats(

Ok(Json(DashboardStats {
total_requests: total_requests.unwrap_or(0),
active_providers: active_providers.unwrap_or(0),
active_providers,
active_api_keys,
connected_mcp_servers: connected_mcp_servers.unwrap_or(0),
active_keys_buckets,
Expand Down
11 changes: 4 additions & 7 deletions crates/server/src/handlers/gateway_logs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use think_watch_common::errors::AppError;

use crate::app::AppState;
use crate::middleware::auth_guard::AuthUser;
use crate::services::analytics_repository;

use super::clickhouse_util::*;

Expand Down Expand Up @@ -172,13 +173,9 @@ pub async fn list_gateway_logs(
// letting the empty result speak for itself.
if let Some(ref raw) = params.api_key_id {
let lineage_id = match raw.parse::<uuid::Uuid>() {
Ok(id) => {
sqlx::query_scalar::<_, uuid::Uuid>("SELECT lineage_id FROM api_keys WHERE id = $1")
.bind(id)
.fetch_optional(&state.db)
.await
.map_err(|e| AppError::Internal(anyhow::anyhow!("lineage lookup: {e}")))?
}
Ok(id) => analytics_repository::api_key_lineage_id(&state.db, id)
.await
.map_err(|e| AppError::Internal(anyhow::anyhow!("lineage lookup: {e}")))?,
Err(_) => None,
};
if let Some(lid) = lineage_id {
Expand Down
Loading
Loading