diff --git a/crates/server/src/handlers/analytics.rs b/crates/server/src/handlers/analytics.rs index 97f77a3d..c058328e 100644 --- a/crates/server/src/handlers/analytics.rs +++ b/crates/server/src/handlers/analytics.rs @@ -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. @@ -54,12 +55,7 @@ async fn analytics_user_id_filter( && !team_ids.is_empty() { let team_ids_vec: Vec = 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); } @@ -73,14 +69,11 @@ async fn analytics_user_id_filter( }; // Team filter requested. Resolve membership and intersect. - let team_members: std::collections::HashSet = - 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 = repo::members_of_team(pool, team_id) + .await? + .into_iter() + .map(|(s,)| s) + .collect(); let intersected: Vec = match scope { None => team_members.into_iter().collect(), // global → just the team @@ -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)> = - 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() @@ -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() diff --git a/crates/server/src/handlers/chargeback.rs b/crates/server/src/handlers/chargeback.rs index c2a11c26..03394b91 100644 --- a/crates/server/src/handlers/chargeback.rs +++ b/crates/server/src/handlers/chargeback.rs @@ -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 { @@ -122,11 +123,7 @@ pub async fn export_chargeback_csv( { std::collections::HashMap::new() } else { - let rows: Vec<(uuid::Uuid, Option)> = - 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() diff --git a/crates/server/src/handlers/dashboard/layout.rs b/crates/server/src/handlers/dashboard/layout.rs index f33044aa..55845fbc 100644 --- a/crates/server/src/handlers/dashboard/layout.rs +++ b/crates/server/src/handlers/dashboard/layout.rs @@ -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 { @@ -35,11 +36,7 @@ pub async fn get_dashboard_layout( auth_user: AuthUser, State(state): State, ) -> Result, 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 })) @@ -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" }))) } diff --git a/crates/server/src/handlers/dashboard/live.rs b/crates/server/src/handlers/dashboard/live.rs index 6493b19a..936b7ad0 100644 --- a/crates/server/src/handlers/dashboard/live.rs +++ b/crates/server/src/handlers/dashboard/live.rs @@ -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}; @@ -128,14 +129,7 @@ async fn ai_breaker_states( state: &AppState, ) -> std::collections::HashMap { 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}"); @@ -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>( - "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) diff --git a/crates/server/src/handlers/dashboard/scope.rs b/crates/server/src/handlers/dashboard/scope.rs index fda66aa8..17bc6134 100644 --- a/crates/server/src/handlers/dashboard/scope.rs +++ b/crates/server/src/handlers/dashboard/scope.rs @@ -17,29 +17,16 @@ 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>, 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); } @@ -47,32 +34,8 @@ pub(super) async fn resolve_dashboard_user_filter( // 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())) } diff --git a/crates/server/src/handlers/dashboard/stats.rs b/crates/server/src/handlers/dashboard/stats.rs index 1ae8351c..4123e3c8 100644 --- a/crates/server/src/handlers/dashboard/stats.rs +++ b/crates/server/src/handlers/dashboard/stats.rs @@ -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 { @@ -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()) } }; @@ -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 = 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 = - 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. @@ -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()) } }; @@ -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 = 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()]) }; @@ -439,16 +406,9 @@ pub async fn get_dashboard_stats( .map(|r| r.cnt as i64) .unwrap_or(0) } else { - sqlx::query_scalar::<_, Option>( - "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 { @@ -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, diff --git a/crates/server/src/handlers/gateway_logs.rs b/crates/server/src/handlers/gateway_logs.rs index acccc37f..03272781 100644 --- a/crates/server/src/handlers/gateway_logs.rs +++ b/crates/server/src/handlers/gateway_logs.rs @@ -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::*; @@ -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::() { - 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 { diff --git a/crates/server/src/handlers/health.rs b/crates/server/src/handlers/health.rs index 1404a787..de65f9b5 100644 --- a/crates/server/src/handlers/health.rs +++ b/crates/server/src/handlers/health.rs @@ -6,6 +6,7 @@ use serde::Serialize; use serde_json::{Value, json}; use crate::app::AppState; +use crate::services::observability_repository as repo; pub async fn health_check() -> Json { Json(json!({ @@ -31,10 +32,7 @@ pub async fn liveness() -> Json { /// 4. At least one active, non-deleted provider configured /// (without this, every `/v1/*` request would 502 at runtime) pub async fn readiness(State(state): State) -> Response { - let pg_ok = sqlx::query_scalar::<_, i32>("SELECT 1") - .fetch_one(&state.db) - .await - .is_ok(); + let pg_ok = repo::ping(&state.db).await.is_ok(); let redis_ok: bool = { use fred::interfaces::ClientLike; @@ -54,12 +52,7 @@ pub async fn readiness(State(state): State) -> Response { // otherwise the lookup itself would fail and we'd double-count // the same outage. let providers_ready = if pg_ok { - let count: i64 = sqlx::query_scalar( - "SELECT COUNT(*) FROM providers WHERE is_active = true AND deleted_at IS NULL", - ) - .fetch_one(&state.db) - .await - .unwrap_or(0); + let count: i64 = repo::count_active_providers(&state.db).await.unwrap_or(0); count > 0 } else { false @@ -130,10 +123,7 @@ pub struct ServiceHealth { pub async fn api_health_check(State(state): State) -> Response { // PostgreSQL let pg_start = std::time::Instant::now(); - let pg_ok = sqlx::query_scalar::<_, i32>("SELECT 1") - .fetch_one(&state.db) - .await - .is_ok(); + let pg_ok = repo::ping(&state.db).await.is_ok(); let pg_latency = pg_start.elapsed().as_millis() as i64; // Redis diff --git a/crates/server/src/handlers/limits.rs b/crates/server/src/handlers/limits.rs index e624251a..c0d5ad92 100644 --- a/crates/server/src/handlers/limits.rs +++ b/crates/server/src/handlers/limits.rs @@ -43,6 +43,7 @@ use think_watch_common::limits::{ use crate::app::AppState; use crate::middleware::auth_guard::AuthUser; +use crate::services::analytics_repository; /// Hard ceiling on how far into the future a temporary override can /// extend. Anything longer is almost certainly a "permanent" change @@ -110,11 +111,7 @@ async fn resolve_subject_id(pool: &sqlx::PgPool, kind: &str, id: Uuid) -> Result if kind != "api_key" { return Ok(id); } - let lineage_id: Option = - sqlx::query_scalar("SELECT lineage_id FROM api_keys WHERE id = $1") - .bind(id) - .fetch_optional(pool) - .await?; + let lineage_id = analytics_repository::api_key_lineage_id(pool, id).await?; lineage_id.ok_or_else(|| AppError::NotFound(format!("api_key {id} not found"))) } diff --git a/crates/server/src/handlers/limits_bulk.rs b/crates/server/src/handlers/limits_bulk.rs index ea0f700d..9f84f245 100644 --- a/crates/server/src/handlers/limits_bulk.rs +++ b/crates/server/src/handlers/limits_bulk.rs @@ -34,6 +34,7 @@ use think_watch_common::limits::{ use super::limits::validate_override_meta_pub; use crate::app::AppState; use crate::middleware::auth_guard::AuthUser; +use crate::services::limits_repository; // ---------------------------------------------------------------------------- // Request shapes @@ -543,12 +544,6 @@ async fn run_bulk_id_op( let mut outcomes = Vec::with_capacity(ids.len()); let mut success = 0usize; let mut errors = 0usize; - let mutate_sql = match op { - BulkIdOp::Disable => { - format!("UPDATE {table} SET enabled = FALSE, updated_at = now() WHERE id = $1") - } - BulkIdOp::Delete => format!("DELETE FROM {table} WHERE id = $1"), - }; // SECURITY: pre-flight scope check per row. The single-row // `delete_rule` / `delete_cap` handlers take `(kind, subject_id)` // in their URL path and call `assert_scope_for_subject` against @@ -557,14 +552,8 @@ async fn run_bulk_id_op( // Without this, a team-scoped caller with `rate_limits:write` can // pass arbitrary ids and disable / delete rows for users outside // their scope. - let lookup_sql = format!("SELECT subject_kind, subject_id FROM {table} WHERE id = $1"); - for id in ids { - let subject: Option<(String, Uuid)> = match sqlx::query_as(&lookup_sql) - .bind(id) - .fetch_optional(&state.db) - .await - { + let subject = match limits_repository::subject_of(&state.db, table, *id).await { Ok(row) => row, Err(e) => { errors += 1; @@ -598,9 +587,12 @@ async fn run_bulk_id_op( continue; } - let result = sqlx::query(&mutate_sql).bind(id).execute(&state.db).await; + let result = match &op { + BulkIdOp::Disable => limits_repository::disable(&state.db, table, *id).await, + BulkIdOp::Delete => limits_repository::delete(&state.db, table, *id).await, + }; match result { - Ok(r) if r.rows_affected() > 0 => { + Ok(rows) if rows > 0 => { success += 1; state.audit.log(audit(*id)); outcomes.push(BulkIdsOutcome { diff --git a/crates/server/src/handlers/log_forwarders.rs b/crates/server/src/handlers/log_forwarders.rs index 86050567..8f73db72 100644 --- a/crates/server/src/handlers/log_forwarders.rs +++ b/crates/server/src/handlers/log_forwarders.rs @@ -8,6 +8,7 @@ use think_watch_common::models::LogForwarder; use crate::app::AppState; use crate::middleware::auth_guard::AuthUser; +use crate::services::log_forwarder_repository as repo; // --- List all forwarders --- @@ -35,11 +36,7 @@ pub async fn list_forwarders( // or test fixture leak that creates thousands of rows would // serialize a multi-MB JSON payload synchronously and risk OOM. // Add tiebreaker on id so the truncation is at least stable. - let forwarders = sqlx::query_as::<_, LogForwarder>( - "SELECT * FROM log_forwarders ORDER BY created_at DESC, id DESC LIMIT 500", - ) - .fetch_all(&state.db) - .await?; + let forwarders = repo::list(&state.db).await?; Ok(Json(forwarders)) } @@ -114,16 +111,14 @@ pub async fn create_forwarder( } let enabled = req.enabled.unwrap_or(true); - let forwarder = sqlx::query_as::<_, LogForwarder>( - r#"INSERT INTO log_forwarders (name, forwarder_type, config, enabled, log_types) - VALUES ($1, $2, $3, $4, $5) RETURNING *"#, + let forwarder = repo::create( + &state.db, + &req.name, + &req.forwarder_type, + &req.config, + enabled, + &log_types, ) - .bind(&req.name) - .bind(&req.forwarder_type) - .bind(&req.config) - .bind(enabled) - .bind(&log_types) - .fetch_one(&state.db) .await?; state.audit.reload_forwarders().await; @@ -173,9 +168,7 @@ pub async fn update_forwarder( auth_user .require_global_permission(&state.db, "log_forwarders:write") .await?; - let existing = sqlx::query_as::<_, LogForwarder>("SELECT * FROM log_forwarders WHERE id = $1") - .bind(id) - .fetch_optional(&state.db) + let existing = repo::find(&state.db, id) .await? .ok_or_else(|| AppError::NotFound("Forwarder not found".into()))?; @@ -202,17 +195,7 @@ pub async fn update_forwarder( let config = req.config.as_ref().unwrap_or(&existing.config); let enabled = req.enabled.unwrap_or(existing.enabled); - let updated = sqlx::query_as::<_, LogForwarder>( - r#"UPDATE log_forwarders SET name = $2, config = $3, enabled = $4, log_types = $5, updated_at = now() - WHERE id = $1 RETURNING *"#, - ) - .bind(id) - .bind(name) - .bind(config) - .bind(enabled) - .bind(&log_types) - .fetch_one(&state.db) - .await?; + let updated = repo::update(&state.db, id, name, config, enabled, &log_types).await?; state.audit.reload_forwarders().await; @@ -244,12 +227,7 @@ pub async fn delete_forwarder( auth_user .require_global_permission(&state.db, "log_forwarders:write") .await?; - let result = sqlx::query("DELETE FROM log_forwarders WHERE id = $1") - .bind(id) - .execute(&state.db) - .await?; - - if result.rows_affected() == 0 { + if repo::delete(&state.db, id).await? == 0 { return Err(AppError::NotFound("Forwarder not found".into())); } @@ -306,15 +284,9 @@ pub async fn toggle_forwarder( // Idempotent: SET enabled = $2, not NOT enabled. A retry of the // same request leaves the row in the same final state and emits // the same audit action. - let updated = sqlx::query_as::<_, LogForwarder>( - r#"UPDATE log_forwarders SET enabled = $2, updated_at = now() - WHERE id = $1 RETURNING *"#, - ) - .bind(id) - .bind(req.enabled) - .fetch_optional(&state.db) - .await? - .ok_or_else(|| AppError::NotFound("Forwarder not found".into()))?; + let updated = repo::set_enabled(&state.db, id, req.enabled) + .await? + .ok_or_else(|| AppError::NotFound("Forwarder not found".into()))?; state.audit.reload_forwarders().await; @@ -357,14 +329,9 @@ pub async fn reset_stats( auth_user .require_global_permission(&state.db, "log_forwarders:write") .await?; - let updated = sqlx::query_as::<_, LogForwarder>( - r#"UPDATE log_forwarders SET sent_count = 0, error_count = 0, last_error = NULL, updated_at = now() - WHERE id = $1 RETURNING *"#, - ) - .bind(id) - .fetch_optional(&state.db) - .await? - .ok_or_else(|| AppError::NotFound("Forwarder not found".into()))?; + let updated = repo::reset_stats(&state.db, id) + .await? + .ok_or_else(|| AppError::NotFound("Forwarder not found".into()))?; Ok(Json(updated)) } @@ -409,9 +376,7 @@ pub async fn test_forwarder( "log_forwarder", ) .await?; - let forwarder = sqlx::query_as::<_, LogForwarder>("SELECT * FROM log_forwarders WHERE id = $1") - .bind(id) - .fetch_optional(&state.db) + let forwarder = repo::find(&state.db, id) .await? .ok_or_else(|| AppError::NotFound("Forwarder not found".into()))?; diff --git a/crates/server/src/handlers/route_observability.rs b/crates/server/src/handlers/route_observability.rs index 884b7750..5ce1ef53 100644 --- a/crates/server/src/handlers/route_observability.rs +++ b/crates/server/src/handlers/route_observability.rs @@ -3,6 +3,7 @@ use crate::app::AppState; use crate::middleware::auth_guard::AuthUser; +use crate::services::observability_repository as repo; use axum::{ Json, extract::{Path, State}, @@ -43,27 +44,7 @@ pub async fn list_route_health( .require_global_permission(&state.db, "models:read") .await?; - #[derive(sqlx::FromRow)] - struct Row { - route_id: Uuid, - provider_id: Uuid, - provider_name: String, - upstream_model: String, - weight: i32, - enabled: bool, - } - let rows: Vec = sqlx::query_as( - r#"SELECT mr.id AS route_id, mr.provider_id, - p.name AS provider_name, - mr.upstream_model, mr.weight, mr.enabled - FROM model_routes mr - JOIN providers p ON p.id = mr.provider_id - WHERE mr.model_id = $1 AND p.deleted_at IS NULL - ORDER BY mr.weight DESC"#, - ) - .bind(&model_id) - .fetch_all(&state.db) - .await?; + let rows = repo::model_routes(&state.db, &model_id).await?; // Reuse the gateway's HealthTracker — same Redis instance, same // window — so the UI sees the exact view the breaker uses to diff --git a/crates/server/src/handlers/webhook_outbox.rs b/crates/server/src/handlers/webhook_outbox.rs index de367b69..981f96a9 100644 --- a/crates/server/src/handlers/webhook_outbox.rs +++ b/crates/server/src/handlers/webhook_outbox.rs @@ -11,7 +11,6 @@ use axum::Json; use axum::extract::{Path, Query, State}; -use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; use uuid::Uuid; @@ -19,27 +18,7 @@ use think_watch_common::errors::AppError; use crate::app::AppState; use crate::middleware::auth_guard::AuthUser; - -#[derive(Debug, Serialize, sqlx::FromRow, utoipa::ToSchema)] -pub struct WebhookOutboxRow { - pub id: Uuid, - pub forwarder_id: Uuid, - /// Looked up at list time so the UI can render a name without a - /// second round-trip. `None` means the forwarder was deleted — - /// the FK CASCADE should normally clean those up but a row could - /// linger if the worker is mid-iteration. - pub forwarder_name: Option, - /// URL the delivery is targeting, extracted from the forwarder - /// config. Lets the operator debug a stuck row without jumping - /// to the forwarder-admin page to cross-reference. `None` when - /// the forwarder was deleted or the config is somehow missing - /// the `url` field (defensive). - pub forwarder_url: Option, - pub attempts: i32, - pub next_attempt_at: DateTime, - pub last_error: Option, - pub created_at: DateTime, -} +use crate::services::webhook_outbox_repository::{self as repo, WebhookOutboxRow}; #[derive(Debug, Serialize, utoipa::ToSchema)] pub struct WebhookOutboxListResponse { @@ -88,32 +67,8 @@ pub async fn list_outbox( .require_global_permission(&state.db, "log_forwarders:write") .await?; - // `$1::uuid IS NULL OR o.forwarder_id = $1` lets one prepared - // statement serve both the "show everything" and "only this - // forwarder" calls. `->>` returns TEXT for the URL column — - // safer than a second materialised column that'd drift from the - // forwarder's canonical config. - let items: Vec = sqlx::query_as( - "SELECT o.id, o.forwarder_id, f.name AS forwarder_name, \ - (f.config->>'url')::text AS forwarder_url, \ - o.attempts, o.next_attempt_at, o.last_error, o.created_at \ - FROM webhook_outbox o \ - LEFT JOIN log_forwarders f ON f.id = o.forwarder_id \ - WHERE $1::uuid IS NULL OR o.forwarder_id = $1 \ - ORDER BY o.next_attempt_at ASC \ - LIMIT 200", - ) - .bind(q.forwarder_id) - .fetch_all(&state.db) - .await?; - - let total: i64 = sqlx::query_scalar( - "SELECT COUNT(*) FROM webhook_outbox \ - WHERE $1::uuid IS NULL OR forwarder_id = $1", - ) - .bind(q.forwarder_id) - .fetch_one(&state.db) - .await?; + let items = repo::list(&state.db, q.forwarder_id).await?; + let total = repo::count(&state.db, q.forwarder_id).await?; Ok(Json(WebhookOutboxListResponse { items, total })) } @@ -153,15 +108,7 @@ pub async fn outbox_counts( // endpoints can't return a multi-megabyte JSON body. Sorted by // backlog desc so operators see the biggest offenders first; the // tail (rare in practice) is dropped silently. - let rows: Vec<(Uuid, i64)> = sqlx::query_as( - "SELECT forwarder_id, COUNT(*) AS count \ - FROM webhook_outbox \ - GROUP BY forwarder_id \ - ORDER BY count DESC \ - LIMIT 500", - ) - .fetch_all(&state.db) - .await?; + let rows = repo::counts_by_forwarder(&state.db).await?; Ok(Json( rows.into_iter() .map(|(forwarder_id, count)| WebhookOutboxCount { @@ -199,12 +146,7 @@ pub async fn delete_outbox_row( .require_global_permission(&state.db, "log_forwarders:write") .await?; - let result = sqlx::query("DELETE FROM webhook_outbox WHERE id = $1") - .bind(id) - .execute(&state.db) - .await?; - - if result.rows_affected() == 0 { + if repo::delete(&state.db, id).await? == 0 { return Err(AppError::NotFound("Outbox row not found".into())); } @@ -245,12 +187,7 @@ pub async fn retry_outbox_row( .require_global_permission(&state.db, "log_forwarders:write") .await?; - let result = sqlx::query("UPDATE webhook_outbox SET next_attempt_at = now() WHERE id = $1") - .bind(id) - .execute(&state.db) - .await?; - - if result.rows_affected() == 0 { + if repo::retry_now(&state.db, id).await? == 0 { return Err(AppError::NotFound("Outbox row not found".into())); } diff --git a/crates/server/src/services/analytics_repository.rs b/crates/server/src/services/analytics_repository.rs new file mode 100644 index 00000000..a045cb2b --- /dev/null +++ b/crates/server/src/services/analytics_repository.rs @@ -0,0 +1,65 @@ +//! Analytics repository — the Postgres lookups the ClickHouse-backed +//! reports lean on: who is in a team, which cost center an API key +//! carries, a user's email, and an API key's rotation lineage. + +use sqlx::PgPool; +use think_watch_common::errors::AppError; +use uuid::Uuid; + +/// Distinct members (as text) of any of the given teams. +pub async fn members_of_teams( + pool: &PgPool, + team_ids: &[Uuid], +) -> Result, AppError> { + Ok( + sqlx::query_as("SELECT DISTINCT user_id::text FROM team_members WHERE team_id = ANY($1)") + .bind(team_ids) + .fetch_all(pool) + .await?, + ) +} + +/// Members (as text) of one team. +pub async fn members_of_team(pool: &PgPool, team_id: Uuid) -> Result, AppError> { + Ok( + sqlx::query_as::<_, (String,)>("SELECT user_id::text FROM team_members WHERE team_id = $1") + .bind(team_id) + .fetch_all(pool) + .await?, + ) +} + +/// Each key's cost center, `None` where it has none. +pub async fn cost_centers_of_keys( + pool: &PgPool, + key_ids: &[Uuid], +) -> Result)>, AppError> { + Ok( + sqlx::query_as("SELECT id, cost_center FROM api_keys WHERE id = ANY($1)") + .bind(key_ids) + .fetch_all(pool) + .await?, + ) +} + +/// Each user's email. +pub async fn emails_of_users( + pool: &PgPool, + user_ids: &[Uuid], +) -> Result, AppError> { + Ok( + sqlx::query_as("SELECT id, email FROM users WHERE id = ANY($1)") + .bind(user_ids) + .fetch_all(pool) + .await?, + ) +} + +/// The rotation lineage of an API key, `None` when no such key exists. +/// Returns the raw `sqlx::Error`: callers word the failure themselves. +pub async fn api_key_lineage_id(pool: &PgPool, key_id: Uuid) -> Result, sqlx::Error> { + sqlx::query_scalar::<_, Uuid>("SELECT lineage_id FROM api_keys WHERE id = $1") + .bind(key_id) + .fetch_optional(pool) + .await +} diff --git a/crates/server/src/services/limits_repository.rs b/crates/server/src/services/limits_repository.rs new file mode 100644 index 00000000..c572234d --- /dev/null +++ b/crates/server/src/services/limits_repository.rs @@ -0,0 +1,37 @@ +//! Limits repository — row-by-id access to the two limit side tables, +//! `rate_limit_rules` and `budget_caps`, for the bulk endpoints. +//! +//! `table` is always one of those two names, fixed by the caller, never +//! user input. Errors are returned as `sqlx::Error`: the bulk endpoints +//! report each row's failure in their own words. + +use sqlx::PgPool; +use uuid::Uuid; + +/// The row's `(subject_kind, subject_id)`; `None` when there is no such +/// row. +pub async fn subject_of( + pool: &PgPool, + table: &'static str, + id: Uuid, +) -> Result, sqlx::Error> { + let lookup_sql = format!("SELECT subject_kind, subject_id FROM {table} WHERE id = $1"); + sqlx::query_as(&lookup_sql) + .bind(id) + .fetch_optional(pool) + .await +} + +/// Turn the row off. Returns the number of rows touched (0 or 1). +pub async fn disable(pool: &PgPool, table: &'static str, id: Uuid) -> Result { + let sql = format!("UPDATE {table} SET enabled = FALSE, updated_at = now() WHERE id = $1"); + let result = sqlx::query(&sql).bind(id).execute(pool).await?; + Ok(result.rows_affected()) +} + +/// Returns the number of rows deleted (0 or 1). +pub async fn delete(pool: &PgPool, table: &'static str, id: Uuid) -> Result { + let sql = format!("DELETE FROM {table} WHERE id = $1"); + let result = sqlx::query(&sql).bind(id).execute(pool).await?; + Ok(result.rows_affected()) +} diff --git a/crates/server/src/services/log_forwarder_repository.rs b/crates/server/src/services/log_forwarder_repository.rs new file mode 100644 index 00000000..c5b88704 --- /dev/null +++ b/crates/server/src/services/log_forwarder_repository.rs @@ -0,0 +1,105 @@ +//! Log forwarder repository — the `log_forwarders` table: the +//! destinations audit and gateway logs are shipped to. + +use sqlx::PgPool; +use think_watch_common::errors::AppError; +use think_watch_common::models::LogForwarder; +use uuid::Uuid; + +/// Newest first, capped at 500. +pub async fn list(pool: &PgPool) -> Result, AppError> { + Ok(sqlx::query_as::<_, LogForwarder>( + "SELECT * FROM log_forwarders ORDER BY created_at DESC, id DESC LIMIT 500", + ) + .fetch_all(pool) + .await?) +} + +pub async fn find(pool: &PgPool, id: Uuid) -> Result, AppError> { + Ok( + sqlx::query_as::<_, LogForwarder>("SELECT * FROM log_forwarders WHERE id = $1") + .bind(id) + .fetch_optional(pool) + .await?, + ) +} + +pub async fn create( + pool: &PgPool, + name: &str, + forwarder_type: &str, + config: &serde_json::Value, + enabled: bool, + log_types: &[String], +) -> Result { + Ok(sqlx::query_as::<_, LogForwarder>( + r#"INSERT INTO log_forwarders (name, forwarder_type, config, enabled, log_types) + VALUES ($1, $2, $3, $4, $5) RETURNING *"#, + ) + .bind(name) + .bind(forwarder_type) + .bind(config) + .bind(enabled) + .bind(log_types) + .fetch_one(pool) + .await?) +} + +/// Overwrite the editable fields of an existing forwarder. +pub async fn update( + pool: &PgPool, + id: Uuid, + name: &str, + config: &serde_json::Value, + enabled: bool, + log_types: &[String], +) -> Result { + Ok(sqlx::query_as::<_, LogForwarder>( + r#"UPDATE log_forwarders SET name = $2, config = $3, enabled = $4, log_types = $5, updated_at = now() + WHERE id = $1 RETURNING *"#, + ) + .bind(id) + .bind(name) + .bind(config) + .bind(enabled) + .bind(log_types) + .fetch_one(pool) + .await?) +} + +/// Returns the number of rows deleted (0 or 1). +pub async fn delete(pool: &PgPool, id: Uuid) -> Result { + let result = sqlx::query("DELETE FROM log_forwarders WHERE id = $1") + .bind(id) + .execute(pool) + .await?; + Ok(result.rows_affected()) +} + +/// `None` when no such forwarder exists. +pub async fn set_enabled( + pool: &PgPool, + id: Uuid, + enabled: bool, +) -> Result, AppError> { + Ok(sqlx::query_as::<_, LogForwarder>( + r#"UPDATE log_forwarders SET enabled = $2, updated_at = now() + WHERE id = $1 RETURNING *"#, + ) + .bind(id) + .bind(enabled) + .fetch_optional(pool) + .await?) +} + +/// Zero the sent / error counters and clear the last error. `None` when +/// no such forwarder exists. +pub async fn reset_stats(pool: &PgPool, id: Uuid) -> Result, AppError> { + Ok(sqlx::query_as::<_, LogForwarder>( + r#"UPDATE log_forwarders SET sent_count = 0, error_count = 0, last_error = NULL, updated_at = now() + WHERE id = $1 RETURNING *"#, + ) + .bind(id) + .fetch_optional(pool) + .await?) +} diff --git a/crates/server/src/services/mod.rs b/crates/server/src/services/mod.rs index 49e3a154..cd49e0db 100644 --- a/crates/server/src/services/mod.rs +++ b/crates/server/src/services/mod.rs @@ -25,8 +25,12 @@ //! [`REVIEW_PLAN_2026-04-20.md`] (gitignored). Not every handler has //! a service yet; the migration is iterative. +pub mod analytics_repository; pub mod auth_lockout; +pub mod limits_repository; +pub mod log_forwarder_repository; pub mod model_repository; +pub mod observability_repository; pub mod pricing_repository; pub mod provider_repository; pub mod rbac_service; @@ -34,3 +38,4 @@ pub mod refresh_blacklist; pub mod session_service; pub mod totp_service; pub mod user_repository; +pub mod webhook_outbox_repository; diff --git a/crates/server/src/services/observability_repository.rs b/crates/server/src/services/observability_repository.rs new file mode 100644 index 00000000..812cc39f --- /dev/null +++ b/crates/server/src/services/observability_repository.rs @@ -0,0 +1,272 @@ +//! Observability repository — the Postgres reads behind the dashboard +//! tiles, the live snapshot, the health probes and the per-model route +//! health view, plus the per-user dashboard layout. +//! +//! Functions whose callers map database errors themselves (a custom +//! message, or a best-effort fallback) return `sqlx::Error` unchanged. + +use sqlx::PgPool; +use think_watch_common::errors::AppError; +use uuid::Uuid; + +// --------------------------------------------------------------------------- +// Health probes +// --------------------------------------------------------------------------- + +/// `SELECT 1` — is Postgres answering? +pub async fn ping(pool: &PgPool) -> Result { + sqlx::query_scalar::<_, i32>("SELECT 1") + .fetch_one(pool) + .await +} + +/// Active, non-deleted providers — the readiness check and the +/// dashboard tile. +pub async fn count_active_providers(pool: &PgPool) -> Result { + sqlx::query_scalar( + "SELECT COUNT(*) FROM providers WHERE is_active = true AND deleted_at IS NULL", + ) + .fetch_one(pool) + .await +} + +// --------------------------------------------------------------------------- +// Dashboard scope +// --------------------------------------------------------------------------- + +/// Does the user hold `analytics:read_all` through a global role? +pub async fn has_global_analytics_read_all( + pool: &PgPool, + user_id: Uuid, +) -> Result { + 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(user_id) + .fetch_one(pool) + .await +} + +/// Ids (as text) of the user plus every live member of any team the +/// user holds `analytics:read_team` or `analytics:read_all` for at team +/// scope. +pub async fn analytics_team_scope_user_ids( + pool: &PgPool, + user_id: Uuid, +) -> Result, sqlx::Error> { + 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(user_id) + .fetch_all(pool) + .await +} + +// --------------------------------------------------------------------------- +// Dashboard stats +// --------------------------------------------------------------------------- + +/// Ids (as text) of the caller plus every live member of the given +/// teams. +pub async fn caller_and_team_member_ids( + pool: &PgPool, + caller_id: Uuid, + team_ids: &[Uuid], +) -> Result, AppError> { + Ok(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) + .fetch_all(pool) + .await?) +} + +/// MCP servers whose status is `connected`. +pub async fn count_connected_mcp_servers(pool: &PgPool) -> Result, AppError> { + Ok( + sqlx::query_scalar("SELECT COUNT(*) FROM mcp_servers WHERE status = 'connected'") + .fetch_one(pool) + .await?, + ) +} + +/// Active keys used since `since` — the fallback when ClickHouse is off. +pub async fn count_api_keys_used_since( + pool: &PgPool, + since: chrono::DateTime, +) -> Result, AppError> { + Ok(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(since) + .fetch_one(pool) + .await?) +} + +/// Active keys last used in `[start, end)`. +pub async fn count_api_keys_used_between( + pool: &PgPool, + start: chrono::DateTime, + end: chrono::DateTime, +) -> Result, AppError> { + Ok(sqlx::query_scalar::<_, Option>( + "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(start) + .bind(end) + .fetch_one(pool) + .await?) +} + +// --------------------------------------------------------------------------- +// Dashboard live snapshot +// --------------------------------------------------------------------------- + +/// Every route of an active provider, with that provider's name. +pub async fn active_provider_routes(pool: &PgPool) -> Result, sqlx::Error> { + 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(pool) + .await +} + +/// Names of the active, non-deleted providers. +pub async fn active_provider_names(pool: &PgPool) -> Result, sqlx::Error> { + sqlx::query_as::<_, (String,)>( + "SELECT name FROM providers WHERE is_active = true AND deleted_at IS NULL", + ) + .fetch_all(pool) + .await +} + +/// Every MCP server's name and status. +pub async fn mcp_server_statuses(pool: &PgPool) -> Result, sqlx::Error> { + sqlx::query_as::<_, (String, String)>("SELECT name, status FROM mcp_servers") + .fetch_all(pool) + .await +} + +/// Highest per-minute request limit across the enabled rules. +pub async fn max_enabled_rpm_limit(pool: &PgPool) -> Result, sqlx::Error> { + sqlx::query_scalar::<_, Option>( + "SELECT MAX(max_count) FROM rate_limit_rules \ + WHERE metric = 'requests' AND window_secs = 60 AND enabled = true", + ) + .fetch_one(pool) + .await +} + +// --------------------------------------------------------------------------- +// Dashboard layout +// --------------------------------------------------------------------------- + +/// The user's saved layout: `(name, layout_json)`. +pub async fn get_layout( + pool: &PgPool, + user_id: Uuid, +) -> Result, AppError> { + Ok( + sqlx::query_as("SELECT name, layout_json FROM user_dashboard_layouts WHERE user_id = $1") + .bind(user_id) + .fetch_optional(pool) + .await?, + ) +} + +/// Insert or replace the user's layout. +pub async fn upsert_layout( + pool: &PgPool, + user_id: Uuid, + name: &str, + layout_json: &serde_json::Value, +) -> Result<(), AppError> { + 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(user_id) + .bind(name) + .bind(layout_json) + .execute(pool) + .await?; + Ok(()) +} + +// --------------------------------------------------------------------------- +// Route health +// --------------------------------------------------------------------------- + +/// One route of a model, as the route-health view lists it. +#[derive(sqlx::FromRow)] +pub struct ModelRouteRow { + pub route_id: Uuid, + pub provider_id: Uuid, + pub provider_name: String, + pub upstream_model: String, + pub weight: i32, + pub enabled: bool, +} + +/// The model's routes on non-deleted providers, heaviest first. +pub async fn model_routes(pool: &PgPool, model_id: &str) -> Result, AppError> { + Ok(sqlx::query_as( + r#"SELECT mr.id AS route_id, mr.provider_id, + p.name AS provider_name, + mr.upstream_model, mr.weight, mr.enabled + FROM model_routes mr + JOIN providers p ON p.id = mr.provider_id + WHERE mr.model_id = $1 AND p.deleted_at IS NULL + ORDER BY mr.weight DESC"#, + ) + .bind(model_id) + .fetch_all(pool) + .await?) +} diff --git a/crates/server/src/services/webhook_outbox_repository.rs b/crates/server/src/services/webhook_outbox_repository.rs new file mode 100644 index 00000000..4b1a7c0e --- /dev/null +++ b/crates/server/src/services/webhook_outbox_repository.rs @@ -0,0 +1,97 @@ +//! Webhook outbox repository — the admin view of `webhook_outbox`: +//! webhook deliveries waiting for (another) attempt. + +use chrono::{DateTime, Utc}; +use serde::Serialize; +use sqlx::PgPool; +use think_watch_common::errors::AppError; +use uuid::Uuid; + +#[derive(Debug, Serialize, sqlx::FromRow, utoipa::ToSchema)] +pub struct WebhookOutboxRow { + pub id: Uuid, + pub forwarder_id: Uuid, + /// Looked up at list time so the UI can render a name without a + /// second round-trip. `None` means the forwarder was deleted — + /// the FK CASCADE should normally clean those up but a row could + /// linger if the worker is mid-iteration. + pub forwarder_name: Option, + /// URL the delivery is targeting, extracted from the forwarder + /// config. Lets the operator debug a stuck row without jumping + /// to the forwarder-admin page to cross-reference. `None` when + /// the forwarder was deleted or the config is somehow missing + /// the `url` field (defensive). + pub forwarder_url: Option, + pub attempts: i32, + pub next_attempt_at: DateTime, + pub last_error: Option, + pub created_at: DateTime, +} + +/// Pending rows, next due first, capped at 200; every forwarder's when +/// `forwarder_id` is `None`. +pub async fn list( + pool: &PgPool, + forwarder_id: Option, +) -> Result, AppError> { + // `$1::uuid IS NULL OR o.forwarder_id = $1` lets one prepared + // statement serve both the "show everything" and "only this + // forwarder" calls. `->>` returns TEXT for the URL column — + // safer than a second materialised column that'd drift from the + // forwarder's canonical config. + Ok(sqlx::query_as( + "SELECT o.id, o.forwarder_id, f.name AS forwarder_name, \ + (f.config->>'url')::text AS forwarder_url, \ + o.attempts, o.next_attempt_at, o.last_error, o.created_at \ + FROM webhook_outbox o \ + LEFT JOIN log_forwarders f ON f.id = o.forwarder_id \ + WHERE $1::uuid IS NULL OR o.forwarder_id = $1 \ + ORDER BY o.next_attempt_at ASC \ + LIMIT 200", + ) + .bind(forwarder_id) + .fetch_all(pool) + .await?) +} + +/// Pending rows in total; every forwarder's when `forwarder_id` is `None`. +pub async fn count(pool: &PgPool, forwarder_id: Option) -> Result { + Ok(sqlx::query_scalar( + "SELECT COUNT(*) FROM webhook_outbox \ + WHERE $1::uuid IS NULL OR forwarder_id = $1", + ) + .bind(forwarder_id) + .fetch_one(pool) + .await?) +} + +/// `(forwarder_id, pending rows)`, biggest backlog first, capped at 500. +pub async fn counts_by_forwarder(pool: &PgPool) -> Result, AppError> { + Ok(sqlx::query_as( + "SELECT forwarder_id, COUNT(*) AS count \ + FROM webhook_outbox \ + GROUP BY forwarder_id \ + ORDER BY count DESC \ + LIMIT 500", + ) + .fetch_all(pool) + .await?) +} + +/// Returns the number of rows deleted (0 or 1). +pub async fn delete(pool: &PgPool, id: Uuid) -> Result { + let result = sqlx::query("DELETE FROM webhook_outbox WHERE id = $1") + .bind(id) + .execute(pool) + .await?; + Ok(result.rows_affected()) +} + +/// Make the row due now. Returns the number of rows touched (0 or 1). +pub async fn retry_now(pool: &PgPool, id: Uuid) -> Result { + let result = sqlx::query("UPDATE webhook_outbox SET next_attempt_at = now() WHERE id = $1") + .bind(id) + .execute(pool) + .await?; + Ok(result.rows_affected()) +} diff --git a/crates/test-support/tests/admin_observability.rs b/crates/test-support/tests/admin_observability.rs new file mode 100644 index 00000000..a7b922c6 --- /dev/null +++ b/crates/test-support/tests/admin_observability.rs @@ -0,0 +1,855 @@ +//! The observability and limits endpoints end to end: dashboard tiles, +//! live snapshot and layout, health probes, route health, analytics +//! scoping, log forwarders, the webhook outbox, and API-key limit +//! subjects. +//! +//! Several of these were only reached through the UI before; this file +//! pins what each one reads and writes, so moving their SQL around +//! (into `services::*_repository`) is checked rather than assumed. + +use chrono::{Duration, Utc}; +use serde_json::Value; +use think_watch_test_support::prelude::*; +use wiremock::matchers::method; +use wiremock::{Mock, MockServer, ResponseTemplate}; + +async fn get(con: &TestClient, path: &str) -> Value { + let resp = con.get(path).await.unwrap(); + resp.assert_ok(); + resp.json().unwrap() +} + +async fn login(app: &TestApp, user: &fixtures::SeededUser) -> TestClient { + let con = app.console_client(); + con.post( + "/api/auth/login", + json!({"email": user.user.email, "password": user.plaintext_password}), + ) + .await + .unwrap() + .assert_ok(); + con +} + +async fn create_team(app: &TestApp) -> Uuid { + sqlx::query_scalar("INSERT INTO teams (name, description) VALUES ($1, 'obs') RETURNING id") + .bind(unique_name("obs-team")) + .fetch_one(&app.db) + .await + .unwrap() +} + +async fn add_member(app: &TestApp, team_id: Uuid, user_id: Uuid) { + sqlx::query("INSERT INTO team_members (user_id, team_id) VALUES ($1, $2)") + .bind(user_id) + .bind(team_id) + .execute(&app.db) + .await + .unwrap(); +} + +/// A user whose only role is `team_manager` scoped to `team_id` — no +/// global developer role, so every permission it has is team-scoped. +async fn create_team_manager(app: &TestApp, team_id: Uuid) -> fixtures::SeededUser { + let user = fixtures::create_user(&app.db, &unique_email(), "Manager", "MgrPwd_1234567!") + .await + .unwrap(); + sqlx::query( + r#"INSERT INTO rbac_role_assignments (user_id, role_id, scope_kind, scope_id, assigned_by) + SELECT $1, id, 'team', $2, $1 FROM rbac_roles WHERE name = 'team_manager'"#, + ) + .bind(user.user.id) + .bind(team_id) + .execute(&app.db) + .await + .unwrap(); + user +} + +async fn api_key(app: &TestApp, user_id: Uuid) -> fixtures::SeededApiKey { + fixtures::create_api_key( + &app.db, + user_id, + &unique_name("obs-key"), + &["ai_gateway"], + None, + None, + ) + .await + .unwrap() +} + +async fn set_last_used(app: &TestApp, key_id: Uuid, at: chrono::DateTime) { + sqlx::query("UPDATE api_keys SET last_used_at = $2 WHERE id = $1") + .bind(key_id) + .bind(at) + .execute(&app.db) + .await + .unwrap(); +} + +async fn create_mcp_server_with_status(app: &TestApp, status: &str) -> String { + let short = Uuid::new_v4().simple().to_string()[..12].to_string(); + let name = format!("obs-mcp-{short}"); + let id = fixtures::create_mcp_server( + &app.db, + &name, + &format!("obs_{short}"), + "http://127.0.0.1:9/mcp", + ) + .await + .unwrap(); + sqlx::query("UPDATE mcp_servers SET status = $2 WHERE id = $1") + .bind(id) + .bind(status) + .execute(&app.db) + .await + .unwrap(); + name +} + +// --------------------------------------------------------------------------- +// Dashboard +// --------------------------------------------------------------------------- + +#[ignore = "integration test — run via `make test-it`"] +#[tokio::test] +async fn dashboard_stats_count_from_postgres_without_clickhouse() { + let app = TestApp::spawn().await; + let (con, admin) = admin_session_with_user(&app).await; + + let upstream = MockProvider::openai_chat_ok("obs-model").await; + fixtures::create_provider( + &app.db, + &unique_name("live"), + "openai", + &upstream.uri(), + None, + ) + .await + .unwrap(); + let off = fixtures::create_provider( + &app.db, + &unique_name("off"), + "openai", + &upstream.uri(), + None, + ) + .await + .unwrap(); + sqlx::query("UPDATE providers SET is_active = false WHERE id = $1") + .bind(off.id) + .execute(&app.db) + .await + .unwrap(); + create_mcp_server_with_status(&app, "connected").await; + create_mcp_server_with_status(&app, "disconnected").await; + + // One key used in the current 24h window, one in the window before, + // one used now but inactive. + let now = Utc::now(); + let current = api_key(&app, admin.user.id).await; + set_last_used(&app, current.row.id, now - Duration::hours(1)).await; + let previous = api_key(&app, admin.user.id).await; + set_last_used(&app, previous.row.id, now - Duration::hours(30)).await; + let inactive = api_key(&app, admin.user.id).await; + set_last_used(&app, inactive.row.id, now - Duration::minutes(5)).await; + sqlx::query("UPDATE api_keys SET is_active = false WHERE id = $1") + .bind(inactive.row.id) + .execute(&app.db) + .await + .unwrap(); + + let stats = get(&con, "/api/dashboard/stats?range=24h&compare=true").await; + assert_eq!(stats["range"], "24h", "{stats}"); + assert_eq!(stats["active_providers"], 1, "{stats}"); + assert_eq!(stats["connected_mcp_servers"], 1, "{stats}"); + assert_eq!(stats["active_api_keys"], 1, "{stats}"); + assert_eq!(stats["prev_active_api_keys"], 1, "{stats}"); + assert_eq!(stats["total_requests"], 0, "{stats}"); + assert_eq!(stats["prev_total_requests"], 0, "{stats}"); + assert_eq!(stats["active_keys_buckets"].as_array().unwrap().len(), 24); + + // Without `compare` the previous-window fields are left out; a 7d + // window takes in the 30h-old key too. + let week = get(&con, "/api/dashboard/stats?range=7d").await; + assert_eq!(week["active_api_keys"], 2, "{week}"); + assert!(week.get("prev_active_api_keys").is_none(), "{week}"); + assert_eq!(week["active_keys_buckets"].as_array().unwrap().len(), 7); + + // A team-scoped caller gets the same platform-wide tiles. + let team = create_team(&app).await; + let manager = create_team_manager(&app, team).await; + let scoped = get(&login(&app, &manager).await, "/api/dashboard/stats").await; + assert_eq!(scoped["active_providers"], 1, "{scoped}"); + assert_eq!(scoped["total_requests"], 0, "{scoped}"); +} + +#[ignore = "integration test — run via `make test-it`"] +#[tokio::test] +async fn dashboard_live_lists_configured_providers_servers_and_rpm_limit() { + let app = TestApp::spawn().await; + let (con, admin) = admin_session_with_user(&app).await; + + let upstream = MockProvider::openai_chat_ok("obs-model").await; + let live_name = unique_name("live"); + fixtures::create_provider(&app.db, &live_name, "openai", &upstream.uri(), None) + .await + .unwrap(); + let off_name = unique_name("off"); + let off = fixtures::create_provider(&app.db, &off_name, "openai", &upstream.uri(), None) + .await + .unwrap(); + sqlx::query("UPDATE providers SET deleted_at = now() WHERE id = $1") + .bind(off.id) + .execute(&app.db) + .await + .unwrap(); + let up = create_mcp_server_with_status(&app, "connected").await; + let down = create_mcp_server_with_status(&app, "disconnected").await; + + // No per-minute request rule yet → no reference line. + let live = get(&con, "/api/dashboard/live").await; + assert!(live["max_rpm_limit"].is_null(), "{live}"); + + fixtures::create_rate_limit_rule( + &app.db, + "user", + admin.user.id, + "ai_gateway", + "requests", + 60, + 250, + ) + .await + .unwrap(); + let disabled = fixtures::create_rate_limit_rule( + &app.db, + "user", + admin.user.id, + "mcp_gateway", + "requests", + 60, + 900, + ) + .await + .unwrap(); + sqlx::query("UPDATE rate_limit_rules SET enabled = false WHERE id = $1") + .bind(disabled) + .execute(&app.db) + .await + .unwrap(); + fixtures::create_rate_limit_rule( + &app.db, + "user", + admin.user.id, + "ai_gateway", + "requests", + 3600, + 5000, + ) + .await + .unwrap(); + + let live = get(&con, "/api/dashboard/live").await; + assert_eq!(live["max_rpm_limit"], 250, "{live}"); + assert_eq!(live["rpm_buckets"].as_array().unwrap().len(), 30); + let rows = live["providers"].as_array().unwrap(); + let row = |name: &str| rows.iter().find(|r| r["provider"] == name); + let ai = row(&live_name).unwrap_or_else(|| panic!("no {live_name}: {live}")); + assert_eq!(ai["kind"], "ai"); + assert!( + row(&off_name).is_none(), + "a deleted provider is not listed: {live}" + ); + let up_row = row(&up).unwrap_or_else(|| panic!("no {up}: {live}")); + assert_eq!(up_row["kind"], "mcp"); + assert!(up_row["success_rate"].is_null(), "{up_row}"); + let down_row = row(&down).unwrap_or_else(|| panic!("no {down}: {live}")); + assert_eq!(down_row["success_rate"], 0.0, "{down_row}"); + + // A team-scoped caller resolves a user filter first; without + // ClickHouse the snapshot is the same. + let team = create_team(&app).await; + let manager = create_team_manager(&app, team).await; + let scoped = get(&login(&app, &manager).await, "/api/dashboard/live").await; + assert_eq!(scoped["max_rpm_limit"], 250, "{scoped}"); + assert_eq!( + scoped["providers"].as_array().unwrap().len(), + rows.len(), + "{scoped}" + ); +} + +#[ignore = "integration test — run via `make test-it`"] +#[tokio::test] +async fn dashboard_layout_is_saved_per_user() { + let app = TestApp::spawn().await; + let con = admin_session(&app).await; + + let layout = get(&con, "/api/dashboard/layout").await; + assert_eq!(layout["name"], "default", "{layout}"); + assert!(layout["layout_json"].is_null(), "{layout}"); + + con.put( + "/api/dashboard/layout", + json!({"name": "ops", "layout_json": {"cards": ["a", "b"]}}), + ) + .await + .unwrap() + .assert_ok(); + let layout = get(&con, "/api/dashboard/layout").await; + assert_eq!(layout["name"], "ops", "{layout}"); + assert_eq!(layout["layout_json"], json!({"cards": ["a", "b"]})); + + // Saving again replaces the row; an empty name saves as "default". + con.put( + "/api/dashboard/layout", + json!({"name": "", "layout_json": {"cards": ["c"]}}), + ) + .await + .unwrap() + .assert_ok(); + let layout = get(&con, "/api/dashboard/layout").await; + assert_eq!(layout["name"], "default", "{layout}"); + assert_eq!(layout["layout_json"], json!({"cards": ["c"]})); + let rows: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM user_dashboard_layouts") + .fetch_one(&app.db) + .await + .unwrap(); + assert_eq!(rows, 1); + + // Another user still sees the built-in default. + let other = admin_session(&app).await; + let layout = get(&other, "/api/dashboard/layout").await; + assert!(layout["layout_json"].is_null(), "{layout}"); + + let big = "x".repeat(17 * 1024); + con.put( + "/api/dashboard/layout", + json!({"name": "big", "layout_json": {"blob": big}}), + ) + .await + .unwrap() + .assert_status(400); +} + +/// Two users call the gateway, one of them in a team; the team's manager +/// sees only that member's traffic on the dashboard and in the cost +/// breakdown, an admin sees both. +#[ignore = "integration test — run via `make test-it`"] +#[tokio::test] +async fn team_scoped_dashboard_and_cost_breakdowns_with_clickhouse() { + let app = TestApp::spawn_with_clickhouse().await; + let admin = admin_session(&app).await; + + let upstream = MockProvider::openai_chat_ok("obs-model").await; + let provider = fixtures::create_provider( + &app.db, + &unique_name("obs"), + "openai", + &upstream.uri(), + None, + ) + .await + .unwrap(); + fixtures::create_model_and_route(&app.db, provider.id, "obs-model") + .await + .unwrap(); + app.rebuild_gateway_router().await; + + let team = create_team(&app).await; + let member = fixtures::create_random_user(&app.db).await.unwrap(); + add_member(&app, team, member.user.id).await; + let outsider = fixtures::create_random_user(&app.db).await.unwrap(); + let manager = create_team_manager(&app, team).await; + + let member_key = api_key(&app, member.user.id).await; + sqlx::query("UPDATE api_keys SET cost_center = 'eng' WHERE id = $1") + .bind(member_key.row.id) + .execute(&app.db) + .await + .unwrap(); + let outsider_key = api_key(&app, outsider.user.id).await; + for key in [&member_key, &outsider_key] { + let gw = app.gateway_client(); + gw.set_bearer(&key.plaintext); + gw.post( + "/v1/chat/completions", + json!({"model": "obs-model", "messages": [{"role": "user", "content": "x"}]}), + ) + .await + .unwrap() + .assert_ok(); + } + + // The audit pipeline writes to ClickHouse asynchronously. + let mut stats = Value::Null; + for _ in 0..200 { + stats = get(&admin, "/api/dashboard/stats").await; + if stats["total_requests"] == 2 { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + } + assert_eq!(stats["total_requests"], 2, "{stats}"); + assert_eq!(stats["active_api_keys"], 2, "{stats}"); + + let mgr = login(&app, &manager).await; + let scoped = get(&mgr, "/api/dashboard/stats").await; + assert_eq!(scoped["total_requests"], 1, "{scoped}"); + assert_eq!(scoped["active_api_keys"], 1, "{scoped}"); + + let rpm_sum = |live: &Value| -> u64 { + live["rpm_buckets"] + .as_array() + .unwrap() + .iter() + .map(|v| v.as_u64().unwrap()) + .sum() + }; + let live = get(&admin, "/api/dashboard/live").await; + assert_eq!(rpm_sum(&live), 2, "{live}"); + let live = get(&mgr, "/api/dashboard/live").await; + assert_eq!(rpm_sum(&live), 1, "{live}"); + + // Costs by user show emails; the manager sees the member only. + let users_of = |body: &Value| -> Vec { + let mut v: Vec = body["items"] + .as_array() + .unwrap() + .iter() + .map(|i| i["dimensions"]["user"].as_str().unwrap().to_string()) + .collect(); + v.sort(); + v + }; + let all = get(&admin, "/api/analytics/costs?group_by=user&range=24h").await; + let mut both = vec![member.user.email.clone(), outsider.user.email.clone()]; + both.sort(); + assert_eq!(users_of(&all), both, "{all}"); + let mine = get(&mgr, "/api/analytics/costs?group_by=user&range=24h").await; + assert_eq!(users_of(&mine), vec![member.user.email.clone()], "{mine}"); + let by_team = get( + &admin, + &format!("/api/analytics/costs?group_by=user&range=24h&team_id={team}"), + ) + .await; + assert_eq!( + users_of(&by_team), + vec![member.user.email.clone()], + "{by_team}" + ); + + // Costs by cost center label each key by its tag. + let cc = get( + &admin, + "/api/analytics/costs?group_by=cost_center&range=24h", + ) + .await; + let mut labels: Vec = cc["items"] + .as_array() + .unwrap() + .iter() + .map(|i| i["dimensions"]["cost_center"].as_str().unwrap().to_string()) + .collect(); + labels.sort(); + assert_eq!(labels, vec!["(untagged)", "eng"], "{cc}"); + + // Usage stats go through the same scope resolution. + let usage = get(&mgr, "/api/analytics/usage/stats?range=24h").await; + assert!(usage.is_object(), "{usage}"); +} + +// --------------------------------------------------------------------------- +// Health and route health +// --------------------------------------------------------------------------- + +#[ignore = "integration test — run via `make test-it`"] +#[tokio::test] +async fn health_probes_check_postgres_and_providers() { + let app = TestApp::spawn().await; + let public = app.console_client(); + + let resp = public.get("/health/ready").await.unwrap(); + resp.assert_status(503); + let body: Value = resp.json().unwrap(); + assert_eq!(body["postgres"], true, "{body}"); + assert_eq!(body["providers"], false, "{body}"); + + let upstream = MockProvider::openai_chat_ok("obs-model").await; + fixtures::create_provider( + &app.db, + &unique_name("ready"), + "openai", + &upstream.uri(), + None, + ) + .await + .unwrap(); + let resp = public.get("/health/ready").await.unwrap(); + resp.assert_ok(); + let body: Value = resp.json().unwrap(); + assert_eq!(body["status"], "ready", "{body}"); + + let con = admin_session(&app).await; + let health = get(&con, "/api/health").await; + assert_eq!(health["postgres"], true, "{health}"); + assert!(health["pg_latency_ms"].is_i64(), "{health}"); +} + +#[ignore = "integration test — run via `make test-it`"] +#[tokio::test] +async fn route_health_lists_a_models_routes_heaviest_first() { + let app = TestApp::spawn().await; + let con = admin_session(&app).await; + let model = unique_name("obs-model"); + + let upstream = MockProvider::openai_chat_ok(&model).await; + let light_name = unique_name("light"); + let light = fixtures::create_provider(&app.db, &light_name, "openai", &upstream.uri(), None) + .await + .unwrap(); + let heavy_name = unique_name("heavy"); + let heavy = fixtures::create_provider(&app.db, &heavy_name, "openai", &upstream.uri(), None) + .await + .unwrap(); + let gone = fixtures::create_provider( + &app.db, + &unique_name("gone"), + "openai", + &upstream.uri(), + None, + ) + .await + .unwrap(); + fixtures::create_model_route(&app.db, light.id, &model, 10) + .await + .unwrap(); + fixtures::create_model_route(&app.db, heavy.id, &model, 90) + .await + .unwrap(); + fixtures::create_model_route(&app.db, gone.id, &model, 50) + .await + .unwrap(); + sqlx::query("UPDATE providers SET deleted_at = now() WHERE id = $1") + .bind(gone.id) + .execute(&app.db) + .await + .unwrap(); + + let routes = get(&con, &format!("/api/admin/models/{model}/route-health")).await; + let routes = routes.as_array().unwrap(); + assert_eq!(routes.len(), 2, "{routes:?}"); + assert_eq!(routes[0]["provider_name"], heavy_name.as_str()); + assert_eq!(routes[0]["weight"], 90); + assert_eq!(routes[0]["provider_id"], heavy.id.to_string()); + assert_eq!(routes[0]["upstream_model"], model.as_str()); + assert_eq!(routes[0]["enabled"], true); + assert!(routes[0]["health"].is_object(), "{:?}", routes[0]); + assert_eq!(routes[1]["provider_name"], light_name.as_str()); + + let none = get(&con, "/api/admin/models/no-such-model/route-health").await; + assert_eq!(none, json!([])); +} + +// --------------------------------------------------------------------------- +// Limits on an API key +// --------------------------------------------------------------------------- + +#[ignore = "integration test — run via `make test-it`"] +#[tokio::test] +async fn api_key_limits_are_stored_on_the_key_lineage() { + let app = TestApp::spawn().await; + let (con, admin) = admin_session_with_user(&app).await; + + let root = api_key(&app, admin.user.id).await; + let rotated = api_key(&app, admin.user.id).await; + sqlx::query("UPDATE api_keys SET lineage_id = $2 WHERE id = $1") + .bind(rotated.row.id) + .bind(root.row.id) + .execute(&app.db) + .await + .unwrap(); + + // Written through the rotated key's id, stored on the lineage root. + let resp = con + .post( + &format!("/api/admin/limits/api_key/{}/rules", rotated.row.id), + json!({"surface": "ai_gateway", "metric": "requests", "window_secs": 60, "max_count": 42}), + ) + .await + .unwrap(); + resp.assert_ok(); + let rule: Value = resp.json().unwrap(); + assert_eq!(rule["subject_id"], root.row.id.to_string(), "{rule}"); + + let listed = get( + &con, + &format!("/api/admin/limits/api_key/{}/rules", root.row.id), + ) + .await; + assert_eq!(listed["items"].as_array().unwrap().len(), 1, "{listed}"); + assert_eq!(listed["items"][0]["max_count"], 42); + + con.get(&format!( + "/api/admin/limits/api_key/{}/rules", + Uuid::new_v4() + )) + .await + .unwrap() + .assert_status(404); +} + +// --------------------------------------------------------------------------- +// Log forwarders and the webhook outbox +// --------------------------------------------------------------------------- + +#[ignore = "integration test — run via `make test-it`"] +#[tokio::test] +async fn a_log_forwarder_is_created_edited_tested_and_removed() { + let app = TestApp::spawn_reaching_loopback().await; + let con = admin_session(&app).await; + let receiver = MockServer::start().await; + Mock::given(method("POST")) + .respond_with(ResponseTemplate::new(200)) + .mount(&receiver) + .await; + + con.post( + "/api/admin/log-forwarders", + json!({"name": "bad", "forwarder_type": "webhook", "config": {"url": receiver.uri()}, + "log_types": ["platform"]}), + ) + .await + .unwrap() + .assert_status(400); + + let name = unique_name("fwd"); + let resp = con + .post( + "/api/admin/log-forwarders", + json!({"name": name, "forwarder_type": "webhook", + "config": {"url": receiver.uri()}, "enabled": false}), + ) + .await + .unwrap(); + resp.assert_ok(); + let created: Value = resp.json().unwrap(); + let id = created["id"].as_str().unwrap().to_string(); + assert_eq!(created["enabled"], false, "{created}"); + assert_eq!(created["log_types"], json!(["audit"]), "{created}"); + + let list = get(&con, "/api/admin/log-forwarders").await; + assert!( + list.as_array() + .unwrap() + .iter() + .any(|f| f["id"] == id.as_str()), + "{list}" + ); + + // PATCH keeps what it isn't given. + let resp = con + .patch( + &format!("/api/admin/log-forwarders/{id}"), + json!({"name": "renamed", "log_types": ["audit", "gateway"]}), + ) + .await + .unwrap(); + resp.assert_ok(); + let updated: Value = resp.json().unwrap(); + assert_eq!(updated["name"], "renamed"); + assert_eq!(updated["log_types"], json!(["audit", "gateway"])); + assert_eq!(updated["config"]["url"], receiver.uri()); + assert_eq!(updated["enabled"], false); + con.patch( + &format!("/api/admin/log-forwarders/{}", Uuid::new_v4()), + json!({"name": "x"}), + ) + .await + .unwrap() + .assert_status(404); + + // Pause / resume sets the state it is given. + for enabled in [true, true, false] { + let resp = con + .post( + &format!("/api/admin/log-forwarders/{id}/toggle"), + json!({"enabled": enabled}), + ) + .await + .unwrap(); + resp.assert_ok(); + let body: Value = resp.json().unwrap(); + assert_eq!(body["enabled"], enabled, "{body}"); + } + con.post( + &format!("/api/admin/log-forwarders/{}/toggle", Uuid::new_v4()), + json!({"enabled": true}), + ) + .await + .unwrap() + .assert_status(404); + + sqlx::query( + "UPDATE log_forwarders SET sent_count = 5, error_count = 2, last_error = 'boom' \ + WHERE id = $1::uuid", + ) + .bind(&id) + .execute(&app.db) + .await + .unwrap(); + let resp = con + .post_empty(&format!("/api/admin/log-forwarders/{id}/reset-stats")) + .await + .unwrap(); + resp.assert_ok(); + let reset: Value = resp.json().unwrap(); + assert_eq!(reset["sent_count"], 0, "{reset}"); + assert_eq!(reset["error_count"], 0, "{reset}"); + assert!(reset["last_error"].is_null(), "{reset}"); + con.post_empty(&format!( + "/api/admin/log-forwarders/{}/reset-stats", + Uuid::new_v4() + )) + .await + .unwrap() + .assert_status(404); + + let resp = con + .post_empty(&format!("/api/admin/log-forwarders/{id}/test")) + .await + .unwrap(); + resp.assert_ok(); + let tested: Value = resp.json().unwrap(); + assert_eq!(tested["success"], true, "{tested}"); + assert!(!receiver.received_requests().await.unwrap().is_empty()); + con.post_empty(&format!( + "/api/admin/log-forwarders/{}/test", + Uuid::new_v4() + )) + .await + .unwrap() + .assert_status(404); + + con.delete(&format!("/api/admin/log-forwarders/{id}")) + .await + .unwrap() + .assert_ok(); + con.delete(&format!("/api/admin/log-forwarders/{id}")) + .await + .unwrap() + .assert_status(404); + let list = get(&con, "/api/admin/log-forwarders").await; + assert!( + !list + .as_array() + .unwrap() + .iter() + .any(|f| f["id"] == id.as_str()), + "{list}" + ); +} + +async fn install_forwarder(app: &TestApp, name: &str, url: &str) -> Uuid { + sqlx::query_scalar( + r#"INSERT INTO log_forwarders (name, forwarder_type, config, log_types, enabled) + VALUES ($1, 'webhook', $2, ARRAY['audit']::text[], false) RETURNING id"#, + ) + .bind(name) + .bind(json!({"url": url})) + .fetch_one(&app.db) + .await + .unwrap() +} + +/// An outbox row that is not due for a while, so the background drain +/// leaves it alone. +async fn enqueue(app: &TestApp, forwarder_id: Uuid, due_in_hours: i64) -> Uuid { + sqlx::query_scalar( + "INSERT INTO webhook_outbox (forwarder_id, payload, next_attempt_at, last_error) \ + VALUES ($1, '{}'::jsonb, now() + make_interval(hours => $2::int), 'HTTP 500') \ + RETURNING id", + ) + .bind(forwarder_id) + .bind(due_in_hours as i32) + .fetch_one(&app.db) + .await + .unwrap() +} + +#[ignore = "integration test — run via `make test-it`"] +#[tokio::test] +async fn the_webhook_outbox_is_listed_counted_retried_and_pruned() { + let app = TestApp::spawn().await; + let con = admin_session(&app).await; + + let a_name = unique_name("outbox-a"); + let a = install_forwarder(&app, &a_name, "http://127.0.0.1:9/a").await; + let b = install_forwarder(&app, &unique_name("outbox-b"), "http://127.0.0.1:9/b").await; + let a_late = enqueue(&app, a, 48).await; + let a_soon = enqueue(&app, a, 24).await; + let b_row = enqueue(&app, b, 36).await; + + let all = get(&con, "/api/admin/webhook-outbox").await; + assert_eq!(all["total"], 3, "{all}"); + let ids: Vec<&str> = all["items"] + .as_array() + .unwrap() + .iter() + .map(|r| r["id"].as_str().unwrap()) + .collect(); + let expected = [a_soon.to_string(), b_row.to_string(), a_late.to_string()]; + assert_eq!(ids, expected, "next due first: {all}"); + let first = &all["items"][0]; + assert_eq!(first["forwarder_id"], a.to_string()); + assert_eq!(first["forwarder_name"], a_name.as_str()); + assert_eq!(first["forwarder_url"], "http://127.0.0.1:9/a"); + assert_eq!(first["attempts"], 0); + assert_eq!(first["last_error"], "HTTP 500"); + + let only_a = get(&con, &format!("/api/admin/webhook-outbox?forwarder_id={a}")).await; + assert_eq!(only_a["total"], 2, "{only_a}"); + assert_eq!(only_a["items"].as_array().unwrap().len(), 2); + + let counts = get(&con, "/api/admin/webhook-outbox/counts").await; + assert_eq!( + counts, + json!([{"forwarder_id": a, "count": 2}, {"forwarder_id": b, "count": 1}]) + ); + + con.delete(&format!("/api/admin/webhook-outbox/{a_late}")) + .await + .unwrap() + .assert_ok(); + con.delete(&format!("/api/admin/webhook-outbox/{a_late}")) + .await + .unwrap() + .assert_status(404); + let only_a = get(&con, &format!("/api/admin/webhook-outbox?forwarder_id={a}")).await; + assert_eq!(only_a["total"], 1, "{only_a}"); + + // Retry makes the row due now; whatever the drain then does with + // it, it is no longer a day out. + con.post_empty(&format!("/api/admin/webhook-outbox/{b_row}/retry")) + .await + .unwrap() + .assert_ok(); + let due: Option> = + sqlx::query_scalar("SELECT next_attempt_at FROM webhook_outbox WHERE id = $1") + .bind(b_row) + .fetch_optional(&app.db) + .await + .unwrap(); + if let Some(due) = due { + assert!(due < Utc::now() + Duration::hours(1), "{due}"); + } + con.post_empty(&format!( + "/api/admin/webhook-outbox/{}/retry", + Uuid::new_v4() + )) + .await + .unwrap() + .assert_status(404); +}