From 73a1ae0fb51422a835bb2e58cf28e60d98cf55a4 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Thu, 24 Sep 2026 16:13:03 +0800 Subject: [PATCH] refactor(server): move the catalog's SQL into repositories The models, routes, providers and platform-pricing handlers no longer carry SQL: services::{model,provider,pricing}_repository hold every statement, verbatim, one function per statement or transaction. The handlers keep validation, audit and the router / cache refresh. The row types those queries return (ModelRow, ModelIdRow, ModelRouteRow, PlatformPricing) move with them. No behaviour change. admin_catalog.rs pins the endpoints that had no integration test (route PATCH/delete, the flat route listing, batch weights and toggles, bulk model operations, the unrouted cleanup, provider edit and delete, pricing); it passes against both the old and the new code. Co-Authored-By: Claude Opus 5.5 --- crates/server/src/handlers/models.rs | 699 +++-------------- .../server/src/handlers/platform_pricing.rs | 37 +- crates/server/src/handlers/providers.rs | 96 +-- crates/server/src/openapi.rs | 3 +- crates/server/src/services/mod.rs | 3 + .../server/src/services/model_repository.rs | 707 ++++++++++++++++++ .../server/src/services/pricing_repository.rs | 49 ++ .../src/services/provider_repository.rs | 111 +++ crates/test-support/tests/admin_catalog.rs | 404 ++++++++++ 9 files changed, 1423 insertions(+), 686 deletions(-) create mode 100644 crates/server/src/services/model_repository.rs create mode 100644 crates/server/src/services/pricing_repository.rs create mode 100644 crates/server/src/services/provider_repository.rs create mode 100644 crates/test-support/tests/admin_catalog.rs diff --git a/crates/server/src/handlers/models.rs b/crates/server/src/handlers/models.rs index e1889ca0..7f5a7fd1 100644 --- a/crates/server/src/handlers/models.rs +++ b/crates/server/src/handlers/models.rs @@ -25,51 +25,11 @@ use think_watch_gateway::output_guardrails::{MAX_LENGTH_CAP_CEILING, OutputGuard use super::serde_util::deserialize_some; use crate::app::AppState; use crate::middleware::auth_guard::AuthUser; - -/// Row shape returned by `GET /api/admin/models`. Route counts are -/// joined in so the UI can show "active / draft / unrouted" status -/// without a second round-trip. -#[derive(Debug, Serialize, sqlx::FromRow, utoipa::ToSchema)] -pub struct ModelRow { - pub id: Uuid, - pub model_id: String, - pub display_name: String, - #[schema(value_type = f64)] - pub input_weight: Decimal, - #[schema(value_type = f64)] - pub output_weight: Decimal, - /// Cache weights as stored. `None` ⇒ derived from `input_weight`. - #[schema(value_type = Option)] - pub cache_read_weight: Option, - #[schema(value_type = Option)] - pub cache_write_weight: Option, - #[schema(value_type = Option)] - pub cache_write_1h_weight: Option, - pub route_count: i64, - pub enabled_route_count: i64, - /// Model-level kill switch. FALSE ⇒ all routes are skipped at - /// router-bootstrap (gateway behaves as if the model has no routes). - /// Independent of per-route `enabled` so flipping back restores the - /// previous traffic split exactly. - pub enabled: bool, - /// Provider display names (or `name` if display_name is null) for - /// every route attached to the model, ordered by weight DESC. Lets - /// the list table show "who serves this?" without an extra fetch. - pub providers: Vec, - /// Per-model routing override. `None` ⇒ inherit - /// `gateway.default_routing_strategy`. The detail drawer reads this - /// to label the strategy picker — without it, refetch-after-PATCH - /// can't reflect the new value. - pub routing_strategy: Option, - pub affinity_mode: Option, - pub affinity_ttl_secs: Option, - /// Output guardrails as stored in JSONB. The list endpoint returns - /// the raw `Value` (rather than `Vec`) so the UI - /// can render unrecognised future variants without breaking. The - /// shape is `[{ "type": "max_length", "max_chars": N }, ...]`. - #[schema(value_type = serde_json::Value)] - pub output_guardrails: serde_json::Value, -} +use crate::services::model_repository::{ + self as repo, ModelFields, ModelIdRow, ModelRouteRow, ModelRow, NewRoute, RouteImport, + RouteUpdate, +}; +use crate::services::provider_repository; /// `status` filter accepted by `GET /api/admin/models`: /// @@ -119,84 +79,9 @@ pub async fn list_models( let page = query.page.unwrap_or(1).max(1); let offset = (page - 1) * page_size; let search = query.q.as_deref().unwrap_or("").trim(); - let search_pattern = format!("%{search}%"); let status = query.status.as_deref().unwrap_or(""); - - // Unified query with `$1='' OR ...` to combine optional search + - // status filter. `status_filter`: - // 'active' — m.enabled = true AND enabled_route_count > 0 - // 'disabled' — m.enabled = false, OR - // (m.enabled = true AND route_count > 0 AND enabled_route_count = 0) - // 'unrouted' — route_count = 0 - // otherwise — no filter - // - // We compute `route_count` / `enabled_route_count` via `LATERAL` - // subquery so the filter happens on the joined shape; PG rewrites - // this to a HashAggregate over `model_routes`. - let status_filter_sql = match status { - "active" => "AND m.enabled = true AND rc.enabled_route_count > 0", - "disabled" => { - "AND (m.enabled = false OR (rc.route_count > 0 AND rc.enabled_route_count = 0))" - } - "unrouted" => "AND rc.route_count = 0", - _ => "", - }; - - let total_sql = format!( - r#"SELECT COUNT(*) FROM models m - LEFT JOIN LATERAL ( - SELECT COUNT(*) AS route_count, - COUNT(*) FILTER (WHERE mr.enabled = true) AS enabled_route_count - FROM model_routes mr - JOIN providers p ON p.id = mr.provider_id AND p.deleted_at IS NULL - WHERE mr.model_id = m.model_id - ) rc ON true - WHERE ($1 = '' OR m.model_id ILIKE $2 OR m.display_name ILIKE $2) - {status_filter_sql}"#, - ); - let list_sql = format!( - r#"SELECT m.id, m.model_id, m.display_name, - m.input_weight, m.output_weight, - m.cache_read_weight, m.cache_write_weight, m.cache_write_1h_weight, - COALESCE(rc.route_count, 0) AS route_count, - COALESCE(rc.enabled_route_count, 0) AS enabled_route_count, - m.enabled, - COALESCE(rc.providers, '{{}}'::text[]) AS providers, - m.routing_strategy, m.affinity_mode, m.affinity_ttl_secs, - m.output_guardrails - FROM models m - LEFT JOIN LATERAL ( - SELECT COUNT(*) AS route_count, - COUNT(*) FILTER (WHERE mr.enabled = true) AS enabled_route_count, - array_agg(COALESCE(p.display_name, p.name) - ORDER BY mr.weight DESC, p.name) AS providers - FROM model_routes mr - JOIN providers p ON p.id = mr.provider_id AND p.deleted_at IS NULL - WHERE mr.model_id = m.model_id - ) rc ON true - WHERE ($1 = '' OR m.model_id ILIKE $2 OR m.display_name ILIKE $2) - {status_filter_sql} - ORDER BY m.model_id - LIMIT $3 OFFSET $4"#, - ); - - let total: Option = sqlx::query_scalar(&total_sql) - .bind(search) - .bind(&search_pattern) - .fetch_one(&state.db) - .await?; - let rows = sqlx::query_as::<_, ModelRow>(&list_sql) - .bind(search) - .bind(&search_pattern) - .bind(page_size) - .bind(offset) - .fetch_all(&state.db) - .await?; - - Ok(Json(ModelListResponse { - items: rows, - total: total.unwrap_or(0), - })) + let (total, items) = repo::list(&state.db, search, status, page_size, offset).await?; + Ok(Json(ModelListResponse { items, total })) } #[derive(Debug, Deserialize, utoipa::ToSchema)] @@ -291,31 +176,21 @@ pub async fn create_model( let guardrails_json = serde_json::to_value(&guardrails) .map_err(|e| AppError::BadRequest(format!("failed to serialize output_guardrails: {e}")))?; - let model = sqlx::query_as::<_, Model>( - r#"INSERT INTO models - (model_id, display_name, input_weight, output_weight, - routing_strategy, affinity_mode, affinity_ttl_secs, tags, - output_guardrails, - cache_read_weight, cache_write_weight, cache_write_1h_weight) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) - RETURNING id, model_id, display_name, input_weight, output_weight, - cache_read_weight, cache_write_weight, cache_write_1h_weight, - routing_strategy, affinity_mode, affinity_ttl_secs, tags, enabled, - output_guardrails"#, + let model = repo::insert( + &state.db, + &req.model_id, + &ModelFields { + display_name: &req.display_name, + input_weight: in_w, + output_weight: out_w, + routing_strategy: req.routing_strategy.as_deref(), + affinity_mode: req.affinity_mode.as_deref(), + affinity_ttl_secs: req.affinity_ttl_secs, + tags: req.tags.as_deref(), + output_guardrails: &guardrails_json, + cache_weights: cache, + }, ) - .bind(&req.model_id) - .bind(&req.display_name) - .bind(in_w) - .bind(out_w) - .bind(&req.routing_strategy) - .bind(&req.affinity_mode) - .bind(req.affinity_ttl_secs) - .bind(req.tags.as_deref()) - .bind(&guardrails_json) - .bind(cache[0]) - .bind(cache[1]) - .bind(cache[2]) - .fetch_one(&state.db) .await?; state.audit.log( @@ -467,17 +342,9 @@ pub async fn update_model( auth_user .require_global_permission(&state.db, "models:write") .await?; - let existing = sqlx::query_as::<_, Model>( - r#"SELECT id, model_id, display_name, input_weight, output_weight, - cache_read_weight, cache_write_weight, cache_write_1h_weight, - routing_strategy, affinity_mode, affinity_ttl_secs, tags, enabled, - output_guardrails - FROM models WHERE id = $1"#, - ) - .bind(id) - .fetch_optional(&state.db) - .await? - .ok_or_else(|| AppError::NotFound("Model not found".into()))?; + let existing = repo::find(&state.db, id) + .await? + .ok_or_else(|| AppError::NotFound("Model not found".into()))?; let new_in_w = req.input_weight.unwrap_or(existing.input_weight); let new_out_w = req.output_weight.unwrap_or(existing.output_weight); @@ -530,44 +397,25 @@ pub async fn update_model( new_affinity_ttl, )?; - let updated = sqlx::query_as::<_, Model>( - r#"UPDATE models SET - display_name = $2, - input_weight = $3, - output_weight = $4, - routing_strategy = $5, - affinity_mode = $6, - affinity_ttl_secs = $7, - tags = $8, - enabled = $9, - output_guardrails = $10, - cache_read_weight = $11, - cache_write_weight = $12, - cache_write_1h_weight = $13 - WHERE id = $1 - RETURNING id, model_id, display_name, input_weight, output_weight, - cache_read_weight, cache_write_weight, cache_write_1h_weight, - routing_strategy, affinity_mode, affinity_ttl_secs, tags, enabled, - output_guardrails"#, - ) - .bind(id) - .bind( - req.display_name - .as_deref() - .unwrap_or(&existing.display_name), + let updated = repo::update( + &state.db, + id, + &ModelFields { + display_name: req + .display_name + .as_deref() + .unwrap_or(&existing.display_name), + input_weight: new_in_w, + output_weight: new_out_w, + routing_strategy: new_strategy.as_deref(), + affinity_mode: new_affinity_mode.as_deref(), + affinity_ttl_secs: new_affinity_ttl, + tags: new_tags.as_deref(), + output_guardrails: &new_guardrails_json, + cache_weights: cache, + }, + req.enabled.unwrap_or(existing.enabled), ) - .bind(new_in_w) - .bind(new_out_w) - .bind(&new_strategy) - .bind(&new_affinity_mode) - .bind(new_affinity_ttl) - .bind(new_tags.as_deref()) - .bind(req.enabled.unwrap_or(existing.enabled)) - .bind(&new_guardrails_json) - .bind(cache[0]) - .bind(cache[1]) - .bind(cache[2]) - .fetch_one(&state.db) .await?; state.audit.log( @@ -612,14 +460,8 @@ pub async fn delete_model( auth_user .require_global_permission(&state.db, "models:write") .await?; - let model_id: Option = sqlx::query_scalar("SELECT model_id FROM models WHERE id = $1") - .bind(id) - .fetch_optional(&state.db) - .await?; - sqlx::query("DELETE FROM models WHERE id = $1") - .bind(id) - .execute(&state.db) - .await?; + let model_id = repo::model_id_of(&state.db, id).await?; + repo::delete(&state.db, id).await?; state.audit.log( auth_user .audit("model.deleted") @@ -635,12 +477,6 @@ pub async fn delete_model( // Lightweight list of every exposed model_id // --------------------------------------------------------------------------- -#[derive(Debug, Serialize, sqlx::FromRow, utoipa::ToSchema)] -pub struct ModelIdRow { - pub model_id: String, - pub display_name: String, -} - /// GET /api/admin/models/ids /// /// Minimal catalog listing used by the batch-import dialog's "attach to @@ -656,12 +492,7 @@ pub async fn list_model_ids( .require_global_permission(&state.db, "models:read") .await?; - let rows = sqlx::query_as::<_, ModelIdRow>( - "SELECT model_id, display_name FROM models ORDER BY model_id", - ) - .fetch_all(&state.db) - .await?; - Ok(Json(rows)) + Ok(Json(repo::list_ids(&state.db).await?)) } // --------------------------------------------------------------------------- @@ -685,18 +516,7 @@ pub async fn delete_unrouted_models( .require_global_permission(&state.db, "models:write") .await?; - let result = sqlx::query( - r#"DELETE FROM models - WHERE model_id NOT IN ( - SELECT DISTINCT mr.model_id - FROM model_routes mr - JOIN providers p ON p.id = mr.provider_id AND p.deleted_at IS NULL - )"#, - ) - .execute(&state.db) - .await?; - - let deleted = result.rows_affected() as i64; + let deleted = repo::delete_unrouted(&state.db).await? as i64; state.audit.log( auth_user @@ -733,12 +553,7 @@ pub async fn bulk_delete_models( return Err(AppError::BadRequest("ids is empty".into())); } - let result = sqlx::query("DELETE FROM models WHERE id = ANY($1)") - .bind(&req.ids) - .execute(&state.db) - .await?; - - let deleted = result.rows_affected() as i64; + let deleted = repo::delete_many(&state.db, &req.ids).await? as i64; state.audit.log( auth_user @@ -783,18 +598,7 @@ pub async fn bulk_set_enabled_models( return Err(AppError::BadRequest("ids is empty".into())); } - let result = sqlx::query( - r#"UPDATE models - SET enabled = $2 - WHERE id = ANY($1) - AND enabled IS DISTINCT FROM $2"#, - ) - .bind(&req.ids) - .bind(req.enabled) - .execute(&state.db) - .await?; - - let updated = result.rows_affected() as i64; + let updated = repo::set_enabled_many(&state.db, &req.ids, req.enabled).await? as i64; state.audit.log( auth_user @@ -816,30 +620,6 @@ pub async fn bulk_set_enabled_models( // Model Routes CRUD // --------------------------------------------------------------------------- -#[derive(Debug, Serialize, sqlx::FromRow, utoipa::ToSchema)] -pub struct ModelRouteRow { - pub id: Uuid, - pub model_id: String, - pub provider_id: Uuid, - pub provider_name: String, - pub upstream_model: String, - pub weight: i32, - pub enabled: bool, - /// Optional human-readable identifier (e.g. "EU-primary"). Pure - /// metadata for the admin UI; ignored by the routing layer. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub label: Option, - /// Free-form note. Surfaced in the edit dialog only. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub notes: Option, - /// Per-route RPM cap. NULL = unlimited. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub rpm_cap: Option, - /// Per-route TPM cap. NULL = unlimited. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub tpm_cap: Option, -} - /// GET /api/admin/models/{model_id}/routes pub async fn list_model_routes( auth_user: AuthUser, @@ -850,24 +630,7 @@ pub async fn list_model_routes( .require_global_permission(&state.db, "models:read") .await?; - // Order by creation time so the routes table and the traffic-share - // sliders stay in the same place when admins drag weights — sorting - // by weight DESC made rows jump around as soon as you adjusted the - // ratios, which the operator UI shouldn't do. - let rows = sqlx::query_as::<_, ModelRouteRow>( - r#"SELECT mr.id, mr.model_id, mr.provider_id, p.name AS provider_name, - mr.upstream_model, mr.weight, mr.enabled, - mr.label, mr.notes, mr.rpm_cap, mr.tpm_cap - 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.created_at, mr.id"#, - ) - .bind(&model_id) - .fetch_all(&state.db) - .await?; - - Ok(Json(rows)) + Ok(Json(repo::routes_of(&state.db, &model_id).await?)) } #[derive(Debug, Deserialize, utoipa::ToSchema)] @@ -906,24 +669,12 @@ pub async fn create_model_route( .require_global_permission(&state.db, "models:write") .await?; - // Verify model exists - let model_exists: Option = - sqlx::query_scalar("SELECT model_id FROM models WHERE model_id = $1") - .bind(&model_id) - .fetch_optional(&state.db) - .await?; - if model_exists.is_none() { + if !repo::exists(&state.db, &model_id).await? { return Err(AppError::NotFound("Model not found".into())); } - - // Verify provider exists - let provider = sqlx::query_as::<_, think_watch_common::models::Provider>( - "SELECT * FROM providers WHERE id = $1 AND deleted_at IS NULL", - ) - .bind(req.provider_id) - .fetch_optional(&state.db) - .await? - .ok_or_else(|| AppError::BadRequest("Provider not found".into()))?; + let provider = provider_repository::find_live(&state.db, req.provider_id) + .await? + .ok_or_else(|| AppError::BadRequest("Provider not found".into()))?; let weight = req.weight.unwrap_or(100); let upstream_model = req @@ -938,18 +689,7 @@ pub async fn create_model_route( // Uniqueness is on (model_id, provider_id, upstream_model), so the // dup check has to match — same provider with a different upstream // is a legal second route. - let existing: Option = sqlx::query_scalar( - r#"SELECT id FROM model_routes - WHERE model_id = $1 - AND provider_id = $2 - AND upstream_model = $3"#, - ) - .bind(&model_id) - .bind(req.provider_id) - .bind(&upstream_model) - .fetch_optional(&state.db) - .await?; - if existing.is_some() { + if repo::route_exists(&state.db, &model_id, req.provider_id, &upstream_model).await? { return Err(AppError::BadRequest( "A route for this model+provider+upstream already exists".into(), )); @@ -986,27 +726,21 @@ pub async fn create_model_route( } let upstream_protocol = verdict.protocol().map(|p| p.as_str().to_string()); - let row = sqlx::query_as::<_, ModelRouteRow>( - r#"INSERT INTO model_routes - (model_id, provider_id, upstream_model, weight, enabled, - label, notes, rpm_cap, tpm_cap, upstream_protocol) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) - RETURNING id, model_id, provider_id, - (SELECT name FROM providers WHERE id = provider_id) AS provider_name, - upstream_model, weight, enabled, - label, notes, rpm_cap, tpm_cap"#, + let row = repo::insert_route( + &state.db, + &NewRoute { + model_id: &model_id, + provider_id: req.provider_id, + upstream_model: &upstream_model, + weight, + enabled: req.enabled.unwrap_or(true), + label: req.label.as_deref().filter(|s| !s.is_empty()), + notes: req.notes.as_deref().filter(|s| !s.is_empty()), + rpm_cap: req.rpm_cap, + tpm_cap: req.tpm_cap, + upstream_protocol: upstream_protocol.as_deref(), + }, ) - .bind(&model_id) - .bind(req.provider_id) - .bind(&upstream_model) - .bind(weight) - .bind(req.enabled.unwrap_or(true)) - .bind(req.label.as_deref().filter(|s| !s.is_empty())) - .bind(req.notes.as_deref().filter(|s| !s.is_empty())) - .bind(req.rpm_cap) - .bind(req.tpm_cap) - .bind(&upstream_protocol) - .fetch_one(&state.db) .await?; state.audit.log( @@ -1067,61 +801,33 @@ pub async fn update_model_route( "upstream_model cannot be empty".into(), )); } - let (label_set, label_value) = match &req.label { - None => (false, None), - Some(inner) => (true, inner.as_deref().filter(|s| !s.is_empty())), - }; - let (notes_set, notes_value) = match &req.notes { - None => (false, None), - Some(inner) => (true, inner.as_deref().filter(|s| !s.is_empty())), - }; - let (rpm_set, rpm_value) = match req.rpm_cap { - None => (false, None), - Some(inner) => (true, inner), - }; - let (tpm_set, tpm_value) = match req.tpm_cap { - None => (false, None), - Some(inner) => (true, inner), - }; - if let Some(c) = rpm_value + if let Some(Some(c)) = req.rpm_cap && c <= 0 { return Err(AppError::BadRequest("rpm_cap must be > 0".into())); } - if let Some(c) = tpm_value + if let Some(Some(c)) = req.tpm_cap && c <= 0 { return Err(AppError::BadRequest("tpm_cap must be > 0".into())); } - let row = sqlx::query_as::<_, ModelRouteRow>( - r#"UPDATE model_routes SET - upstream_model = COALESCE($2, upstream_model), - weight = COALESCE($3, weight), - enabled = COALESCE($4, enabled), - label = CASE WHEN $6 THEN $5 ELSE label END, - notes = CASE WHEN $8 THEN $7 ELSE notes END, - rpm_cap = CASE WHEN $10 THEN $9 ELSE rpm_cap END, - tpm_cap = CASE WHEN $12 THEN $11 ELSE tpm_cap END - WHERE id = $1 - RETURNING id, model_id, provider_id, - (SELECT name FROM providers WHERE id = provider_id) AS provider_name, - upstream_model, weight, enabled, - label, notes, rpm_cap, tpm_cap"#, + fn non_empty(v: &Option) -> Option<&str> { + v.as_deref().filter(|s| !s.is_empty()) + } + let row = repo::update_route( + &state.db, + route_id, + &RouteUpdate { + upstream_model: upstream_value, + weight: req.weight, + enabled: req.enabled, + label: req.label.as_ref().map(non_empty), + notes: req.notes.as_ref().map(non_empty), + rpm_cap: req.rpm_cap, + tpm_cap: req.tpm_cap, + }, ) - .bind(route_id) - .bind(upstream_value) - .bind(req.weight) - .bind(req.enabled) - .bind(label_value) - .bind(label_set) - .bind(notes_value) - .bind(notes_set) - .bind(rpm_value) - .bind(rpm_set) - .bind(tpm_value) - .bind(tpm_set) - .fetch_optional(&state.db) .await? .ok_or_else(|| AppError::NotFound("Route not found".into()))?; @@ -1147,12 +853,7 @@ pub async fn delete_model_route( .require_global_permission(&state.db, "models:write") .await?; - let result = sqlx::query("DELETE FROM model_routes WHERE id = $1") - .bind(route_id) - .execute(&state.db) - .await?; - - if result.rows_affected() == 0 { + if !repo::delete_route(&state.db, route_id).await? { return Err(AppError::NotFound("Route not found".into())); } @@ -1207,63 +908,8 @@ pub async fn list_all_routes( let page = q.page.unwrap_or(1).max(1); let offset = (page - 1) * page_size; let search = q.q.as_deref().unwrap_or("").trim(); - let search_pattern = format!("%{search}%"); - - let (rows, total) = if search.is_empty() && q.provider_id.is_none() { - let total: Option = sqlx::query_scalar( - "SELECT COUNT(*) FROM model_routes mr JOIN providers p ON p.id = mr.provider_id WHERE p.deleted_at IS NULL", - ) - .fetch_one(&state.db) - .await?; - let rows = sqlx::query_as::<_, ModelRouteRow>( - r#"SELECT mr.id, mr.model_id, mr.provider_id, p.name AS provider_name, - mr.upstream_model, mr.weight, mr.enabled, - mr.label, mr.notes, mr.rpm_cap, mr.tpm_cap - FROM model_routes mr - JOIN providers p ON p.id = mr.provider_id - WHERE p.deleted_at IS NULL - ORDER BY mr.model_id, mr.weight DESC - LIMIT $1 OFFSET $2"#, - ) - .bind(page_size) - .bind(offset) - .fetch_all(&state.db) - .await?; - (rows, total.unwrap_or(0)) - } else { - let total: Option = sqlx::query_scalar( - r#"SELECT COUNT(*) FROM model_routes mr - JOIN providers p ON p.id = mr.provider_id - WHERE p.deleted_at IS NULL - AND ($1 = '' OR mr.model_id ILIKE $2 OR p.name ILIKE $2) - AND ($3::UUID IS NULL OR mr.provider_id = $3)"#, - ) - .bind(search) - .bind(&search_pattern) - .bind(q.provider_id) - .fetch_one(&state.db) - .await?; - let rows = sqlx::query_as::<_, ModelRouteRow>( - r#"SELECT mr.id, mr.model_id, mr.provider_id, p.name AS provider_name, - mr.upstream_model, mr.weight, mr.enabled, - mr.label, mr.notes, mr.rpm_cap, mr.tpm_cap - FROM model_routes mr - JOIN providers p ON p.id = mr.provider_id - WHERE p.deleted_at IS NULL - AND ($1 = '' OR mr.model_id ILIKE $2 OR p.name ILIKE $2) - AND ($3::UUID IS NULL OR mr.provider_id = $3) - ORDER BY mr.model_id, mr.weight DESC - LIMIT $4 OFFSET $5"#, - ) - .bind(search) - .bind(&search_pattern) - .bind(q.provider_id) - .bind(page_size) - .bind(offset) - .fetch_all(&state.db) - .await?; - (rows, total.unwrap_or(0)) - }; + let (total, rows) = + repo::list_routes(&state.db, search, q.provider_id, page_size, offset).await?; Ok(Json(RouteListResponse { items: rows, total })) } @@ -1325,13 +971,9 @@ pub async fn batch_create_routes( return Err(AppError::BadRequest("items is empty".into())); } - let provider = sqlx::query_as::<_, think_watch_common::models::Provider>( - "SELECT * FROM providers WHERE id = $1 AND deleted_at IS NULL", - ) - .bind(req.provider_id) - .fetch_optional(&state.db) - .await? - .ok_or_else(|| AppError::BadRequest("Provider not found".into()))?; + let provider = provider_repository::find_live(&state.db, req.provider_id) + .await? + .ok_or_else(|| AppError::BadRequest("Provider not found".into()))?; // Split the request into the two flows. Each flow is one bulk // INSERT via UNNEST so we stay at O(1) round trips regardless of N. @@ -1370,12 +1012,7 @@ pub async fn batch_create_routes( }) .collect(); - let mut new_exposed: Vec = Vec::new(); - let mut new_upstreams: Vec = Vec::new(); - let mut new_protocols: Vec> = Vec::new(); - let mut attach_targets: Vec = Vec::new(); - let mut attach_upstreams: Vec = Vec::new(); - let mut attach_protocols: Vec> = Vec::new(); + let mut import = RouteImport::default(); for it in &req.items { let verdict = verdicts.get(&it.upstream); @@ -1397,89 +1034,22 @@ pub async fn batch_create_routes( .filter(|s| !s.is_empty()) .unwrap_or(&it.upstream) .to_string(); - new_exposed.push(exposed); - new_upstreams.push(it.upstream.clone()); - new_protocols.push(protocol); + import.new_exposed.push(exposed); + import.new_upstreams.push(it.upstream.clone()); + import.new_protocols.push(protocol); } Some(target) => { - attach_targets.push(target.clone()); - attach_upstreams.push(it.upstream.clone()); - attach_protocols.push(protocol); + import.attach_targets.push(target.clone()); + import.attach_upstreams.push(it.upstream.clone()); + import.attach_protocols.push(protocol); } } } - let mut tx = state.db.begin().await?; - - // --- "new" items ----------------------------------------------- - // - // Catalog insert is idempotent. Route insert counts rows via the - // RETURNING/CTE pattern so the response's `created` count reflects - // only rows that actually landed (skipping ON CONFLICT dupes). - let new_inserted: i64 = if new_exposed.is_empty() { - 0 - } else { - sqlx::query( - r#"INSERT INTO models (model_id, display_name) - SELECT exposed, exposed - FROM UNNEST($1::TEXT[]) AS t(exposed) - ON CONFLICT (model_id) DO NOTHING"#, - ) - .bind(&new_exposed) - .execute(&mut *tx) - .await?; - - sqlx::query_scalar::<_, i64>( - r#"WITH ins AS ( - INSERT INTO model_routes - (model_id, provider_id, upstream_model, weight, upstream_protocol) - SELECT exposed, $3, upstream, 100, protocol - FROM UNNEST($1::TEXT[], $2::TEXT[], $4::TEXT[]) - AS t(exposed, upstream, protocol) - ON CONFLICT (model_id, provider_id, upstream_model) DO NOTHING - RETURNING 1 - ) - SELECT COUNT(*) FROM ins"#, - ) - .bind(&new_exposed) - .bind(&new_upstreams) - .bind(req.provider_id) - .bind(&new_protocols) - .fetch_one(&mut *tx) - .await? - }; - - // --- "attach" items -------------------------------------------- - // - // Targets that don't exist in `models` are silently skipped - // (EXISTS guard below) to avoid a FK failure on a typo. The audit - // log records the discrepancy via the created/requested deltas. - let attach_inserted: i64 = if attach_targets.is_empty() { - 0 - } else { - sqlx::query_scalar::<_, i64>( - r#"WITH ins AS ( - INSERT INTO model_routes - (model_id, provider_id, upstream_model, weight, upstream_protocol) - SELECT t.target, $3, t.upstream, 100, t.protocol - FROM UNNEST($1::TEXT[], $2::TEXT[], $4::TEXT[]) - AS t(target, upstream, protocol) - WHERE EXISTS (SELECT 1 FROM models m WHERE m.model_id = t.target) - ON CONFLICT (model_id, provider_id, upstream_model) DO NOTHING - RETURNING 1 - ) - SELECT COUNT(*) FROM ins"#, - ) - .bind(&attach_targets) - .bind(&attach_upstreams) - .bind(req.provider_id) - .bind(&attach_protocols) - .fetch_one(&mut *tx) - .await? - }; - - tx.commit().await?; - let created = new_inserted + attach_inserted; + // Imported routes that already exist, or attach to a catalog entry + // that does not, are skipped; the audit row records the discrepancy + // via the created/requested deltas. + let created = repo::import_routes(&state.db, req.provider_id, &import).await?; state.audit.log( auth_user @@ -1487,8 +1057,8 @@ pub async fn batch_create_routes( .resource("model_routes") .detail(serde_json::json!({ "provider_id": req.provider_id, - "new": new_exposed.len(), - "attach": attach_targets.len(), + "new": import.new_exposed.len(), + "attach": import.attach_targets.len(), "created": created, })), ); @@ -1532,12 +1102,7 @@ pub async fn batch_delete_routes( return Err(AppError::BadRequest("ids is empty".into())); } - let result = sqlx::query("DELETE FROM model_routes WHERE id = ANY($1)") - .bind(&req.ids) - .execute(&state.db) - .await?; - - let deleted = result.rows_affected() as i64; + let deleted = repo::delete_routes(&state.db, &req.ids).await? as i64; state.audit.log( auth_user @@ -1601,17 +1166,8 @@ pub async fn batch_update_route_weights( // One transaction so partial failures roll back — admins shouldn't // see "1/3 of my drag landed". - let mut tx = state.db.begin().await?; - let mut updated = 0i64; - for u in &req.updates { - let result = sqlx::query("UPDATE model_routes SET weight = $1 WHERE id = $2") - .bind(u.weight) - .bind(u.id) - .execute(&mut *tx) - .await?; - updated += result.rows_affected() as i64; - } - tx.commit().await?; + let weights: Vec<(Uuid, i32)> = req.updates.iter().map(|u| (u.id, u.weight)).collect(); + let updated = repo::set_route_weights(&state.db, &weights).await? as i64; state.audit.log( auth_user @@ -1698,16 +1254,9 @@ pub async fn get_route_history( // and the log table records the resolved (model, provider name, // upstream_model) tuple instead. Look those up here so the CH // query can filter on what it actually has. - let route = sqlx::query_as::<_, (String, String, String)>( - "SELECT mr.model_id, p.name, mr.upstream_model \ - FROM model_routes mr \ - JOIN providers p ON p.id = mr.provider_id AND p.deleted_at IS NULL \ - WHERE mr.id = $1", - ) - .bind(q.route_id) - .fetch_optional(&state.db) - .await - .map_err(|e| AppError::Internal(anyhow::anyhow!("route lookup: {e}")))?; + let route = repo::route_log_identity(&state.db, q.route_id) + .await + .map_err(|e| AppError::Internal(anyhow::anyhow!("route lookup: {e}")))?; let Some((model_id, provider_name, upstream_model)) = route else { // Route was deleted between page load and refresh — return // an empty history so the sparkline stays blank rather than @@ -1795,13 +1344,7 @@ pub async fn batch_update_routes( return Err(AppError::BadRequest("ids is empty".into())); } - let result = sqlx::query("UPDATE model_routes SET enabled = $1 WHERE id = ANY($2)") - .bind(req.enabled) - .bind(&req.ids) - .execute(&state.db) - .await?; - - let updated = result.rows_affected() as i64; + let updated = repo::set_routes_enabled(&state.db, &req.ids, req.enabled).await? as i64; state.audit.log( auth_user @@ -1831,13 +1374,9 @@ pub async fn list_remote_models( ) -> Result>, AppError> { auth_user.require_permission("models:read")?; - let provider = sqlx::query_as::<_, think_watch_common::models::Provider>( - "SELECT * FROM providers WHERE id = $1 AND deleted_at IS NULL", - ) - .bind(provider_id) - .fetch_optional(&state.db) - .await? - .ok_or(AppError::NotFound("Provider not found".into()))?; + let provider = provider_repository::find_live(&state.db, provider_id) + .await? + .ok_or(AppError::NotFound("Provider not found".into()))?; // Stored header values are `{"$enc": …}` envelopes, so they have to // be decrypted here — deserializing them straight into @@ -1906,13 +1445,9 @@ pub async fn recheck_provider_models( .require_global_permission(&state.db, "models:write") .await?; - let provider = sqlx::query_as::<_, think_watch_common::models::Provider>( - "SELECT * FROM providers WHERE id = $1 AND deleted_at IS NULL", - ) - .bind(provider_id) - .fetch_optional(&state.db) - .await? - .ok_or(AppError::NotFound("Provider not found".into()))?; + let provider = provider_repository::find_live(&state.db, provider_id) + .await? + .ok_or(AppError::NotFound("Provider not found".into()))?; let headers = super::providers::decrypt_headers_from_config( &provider.config_json, diff --git a/crates/server/src/handlers/platform_pricing.rs b/crates/server/src/handlers/platform_pricing.rs index 08b79d48..0e8d059f 100644 --- a/crates/server/src/handlers/platform_pricing.rs +++ b/crates/server/src/handlers/platform_pricing.rs @@ -14,21 +14,13 @@ use axum::Json; use axum::extract::State; use rust_decimal::Decimal; -use serde::{Deserialize, Serialize}; +use serde::Deserialize; 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 PlatformPricing { - #[schema(value_type = f64)] - pub input_price_per_token: Decimal, - #[schema(value_type = f64)] - pub output_price_per_token: Decimal, - pub currency: String, -} +use crate::services::pricing_repository::{self as repo, PlatformPricing}; #[derive(Debug, Deserialize, utoipa::ToSchema)] pub struct UpdatePlatformPricingRequest { @@ -54,13 +46,7 @@ pub async fn get_platform_pricing( State(state): State, ) -> Result, AppError> { auth_user.require_permission("settings:read")?; - let row = sqlx::query_as::<_, PlatformPricing>( - "SELECT input_price_per_token, output_price_per_token, currency \ - FROM platform_pricing WHERE id = 1", - ) - .fetch_one(&state.db) - .await?; - Ok(Json(row)) + Ok(Json(repo::get(&state.db).await?)) } #[utoipa::path( @@ -99,19 +85,12 @@ pub async fn update_platform_pricing( )); } - let updated = sqlx::query_as::<_, PlatformPricing>( - r#"UPDATE platform_pricing SET - input_price_per_token = COALESCE($1, input_price_per_token), - output_price_per_token = COALESCE($2, output_price_per_token), - currency = COALESCE($3, currency), - updated_at = now() - WHERE id = 1 - RETURNING input_price_per_token, output_price_per_token, currency"#, + let updated = repo::update( + &state.db, + req.input_price_per_token, + req.output_price_per_token, + req.currency.as_deref(), ) - .bind(req.input_price_per_token) - .bind(req.output_price_per_token) - .bind(req.currency.as_ref()) - .fetch_one(&state.db) .await?; state.audit.log( diff --git a/crates/server/src/handlers/providers.rs b/crates/server/src/handlers/providers.rs index b254f0ef..19d9762d 100644 --- a/crates/server/src/handlers/providers.rs +++ b/crates/server/src/handlers/providers.rs @@ -8,6 +8,7 @@ use think_watch_common::models::Provider; use crate::app::AppState; use crate::middleware::auth_guard::AuthUser; +use crate::services::provider_repository as repo; // --------------------------------------------------------------------------- // At-rest encryption for provider secrets stored in `providers.config_json`. @@ -219,11 +220,7 @@ pub async fn list_providers( auth_user .require_global_permission(&state.db, "providers:read") .await?; - let mut providers = sqlx::query_as::<_, Provider>( - "SELECT * FROM providers WHERE deleted_at IS NULL ORDER BY created_at DESC", - ) - .fetch_all(&state.db) - .await?; + let mut providers = repo::list_live(&state.db).await?; providers.iter_mut().for_each(redact_provider_secrets); Ok(Json(providers)) @@ -265,16 +262,14 @@ pub async fn create_provider( encrypt_aws_secret_in_config(&mut config, &state.config.encryption_key)?; config["headers"] = encrypt_headers_for_storage(&req.headers, &state.config.encryption_key)?; - let mut provider = sqlx::query_as::<_, Provider>( - r#"INSERT INTO providers (name, display_name, provider_type, base_url, config_json) - VALUES ($1, $2, $3, $4, $5) RETURNING *"#, + let mut provider = repo::insert( + &state.db, + &req.name, + &req.display_name, + &req.provider_type, + &req.base_url, + &config, ) - .bind(&req.name) - .bind(&req.display_name) - .bind(&req.provider_type) - .bind(&req.base_url) - .bind(&config) - .fetch_one(&state.db) .await?; state.audit.log( @@ -324,13 +319,9 @@ pub async fn update_provider( auth_user .require_global_permission(&state.db, "providers:update") .await?; - let existing = sqlx::query_as::<_, Provider>( - "SELECT * FROM providers WHERE id = $1 AND deleted_at IS NULL", - ) - .bind(id) - .fetch_optional(&state.db) - .await? - .ok_or(AppError::NotFound("Provider not found".into()))?; + let existing = repo::find_live(&state.db, id) + .await? + .ok_or(AppError::NotFound("Provider not found".into()))?; let display_name = req .display_name @@ -362,16 +353,7 @@ pub async fn update_provider( config }; - let mut updated = sqlx::query_as::<_, Provider>( - r#"UPDATE providers SET display_name = $2, base_url = $3, config_json = $4 - WHERE id = $1 RETURNING *"#, - ) - .bind(id) - .bind(display_name) - .bind(base_url) - .bind(&config_json) - .fetch_one(&state.db) - .await?; + let mut updated = repo::update(&state.db, id, display_name, base_url, &config_json).await?; // A new base URL or credential can mean an entirely different // upstream, so every dialect we learned for this provider's routes @@ -379,14 +361,7 @@ pub async fn update_provider( // them and let the runtime relearn on first use — stale beats // wrong, and the relearn is invisible to the caller. if req.base_url.is_some() || req.headers.is_some() { - let cleared: u64 = sqlx::query( - "UPDATE model_routes SET upstream_protocol = NULL - WHERE provider_id = $1 AND upstream_protocol IS NOT NULL", - ) - .bind(id) - .execute(&state.db) - .await? - .rows_affected(); + let cleared = repo::clear_learned_protocols(&state.db, id).await?; // Same reasoning for the probe cache: "this upstream refuses // model X" described the old endpoint. Dropping it is also the // path back for an operator who fixed access upstream and @@ -438,13 +413,9 @@ pub async fn get_provider( auth_user .require_global_permission(&state.db, "providers:read") .await?; - let mut provider = sqlx::query_as::<_, Provider>( - "SELECT * FROM providers WHERE id = $1 AND deleted_at IS NULL", - ) - .bind(id) - .fetch_optional(&state.db) - .await? - .ok_or(AppError::NotFound("Provider not found".into()))?; + let mut provider = repo::find_live(&state.db, id) + .await? + .ok_or(AppError::NotFound("Provider not found".into()))?; redact_provider_secrets(&mut provider); Ok(Json(provider)) @@ -472,27 +443,8 @@ pub async fn delete_provider( auth_user .require_global_permission(&state.db, "providers:delete") .await?; - let name: Option = sqlx::query_scalar("SELECT name FROM providers WHERE id = $1") - .bind(id) - .fetch_optional(&state.db) - .await?; - - // Soft-delete + drop routes in one transaction. The `model_routes` - // FK is `ON DELETE CASCADE`, but since we only flip `deleted_at` - // the cascade doesn't fire — hence the explicit DELETE below. - // Orphaned routes would otherwise show up in the Models page with - // a raw provider UUID and no way to edit them. - let mut tx = state.db.begin().await?; - sqlx::query("UPDATE providers SET deleted_at = now() WHERE id = $1 AND deleted_at IS NULL") - .bind(id) - .execute(&mut *tx) - .await?; - let routes_deleted = sqlx::query("DELETE FROM model_routes WHERE provider_id = $1") - .bind(id) - .execute(&mut *tx) - .await? - .rows_affected(); - tx.commit().await?; + let name = repo::name_of(&state.db, id).await?; + let routes_deleted = repo::soft_delete(&state.db, id).await?; state.audit.log( auth_user @@ -569,13 +521,9 @@ pub async fn test_provider( let mut req = req; if let Some(provider_id) = req.provider_id { - let provider = sqlx::query_as::<_, Provider>( - "SELECT * FROM providers WHERE id = $1 AND deleted_at IS NULL", - ) - .bind(provider_id) - .fetch_optional(&state.db) - .await? - .ok_or(AppError::NotFound("Provider not found".into()))?; + let provider = repo::find_live(&state.db, provider_id) + .await? + .ok_or(AppError::NotFound("Provider not found".into()))?; let stored = decrypt_headers_from_config( &provider.config_json, &state.config.encryption_key, diff --git a/crates/server/src/openapi.rs b/crates/server/src/openapi.rs index f169b8b0..7768cb6b 100644 --- a/crates/server/src/openapi.rs +++ b/crates/server/src/openapi.rs @@ -29,7 +29,7 @@ use crate::handlers::{ }, mcp_tools::{McpToolListResponse, McpToolRow}, models::{ - BatchWeightUpdate, BatchWeightsRequest, CreateModelRequest, ModelRow, RouteHistoryBucket, + BatchWeightUpdate, BatchWeightsRequest, CreateModelRequest, RouteHistoryBucket, RouteHistoryResponse, UpdateModelRequest, }, providers::{TestProviderRequest, TestProviderResponse, UpdateProviderRequest}, @@ -46,6 +46,7 @@ use crate::handlers::{ ResetCounterResponse, UsageDay, }, }; +use crate::services::model_repository::ModelRow; /// OpenAPI document covering the ThinkWatch console API (port 3001). /// diff --git a/crates/server/src/services/mod.rs b/crates/server/src/services/mod.rs index ce12f2f7..49e3a154 100644 --- a/crates/server/src/services/mod.rs +++ b/crates/server/src/services/mod.rs @@ -26,6 +26,9 @@ //! a service yet; the migration is iterative. pub mod auth_lockout; +pub mod model_repository; +pub mod pricing_repository; +pub mod provider_repository; pub mod rbac_service; pub mod refresh_blacklist; pub mod session_service; diff --git a/crates/server/src/services/model_repository.rs b/crates/server/src/services/model_repository.rs new file mode 100644 index 00000000..d354880e --- /dev/null +++ b/crates/server/src/services/model_repository.rs @@ -0,0 +1,707 @@ +//! Model catalog repository — the `models` table (what clients see on +//! `/v1/models`) and `model_routes` (which provider serves each one). +//! +//! Thin wrappers over sqlx, one statement (or one transaction) per +//! function; validation, audit and the router / weight-cache refresh stay +//! in `handlers::models`. + +use rust_decimal::Decimal; +use serde::Serialize; +use sqlx::PgPool; +use think_watch_common::errors::AppError; +use think_watch_common::models::Model; +use uuid::Uuid; + +/// Row shape returned by `GET /api/admin/models`. Route counts are +/// joined in so the UI can show "active / draft / unrouted" status +/// without a second round-trip. +#[derive(Debug, Serialize, sqlx::FromRow, utoipa::ToSchema)] +pub struct ModelRow { + pub id: Uuid, + pub model_id: String, + pub display_name: String, + #[schema(value_type = f64)] + pub input_weight: Decimal, + #[schema(value_type = f64)] + pub output_weight: Decimal, + /// Cache weights as stored. `None` ⇒ derived from `input_weight`. + #[schema(value_type = Option)] + pub cache_read_weight: Option, + #[schema(value_type = Option)] + pub cache_write_weight: Option, + #[schema(value_type = Option)] + pub cache_write_1h_weight: Option, + pub route_count: i64, + pub enabled_route_count: i64, + /// Model-level kill switch. FALSE ⇒ all routes are skipped at + /// router-bootstrap (gateway behaves as if the model has no routes). + /// Independent of per-route `enabled` so flipping back restores the + /// previous traffic split exactly. + pub enabled: bool, + /// Provider display names (or `name` if display_name is null) for + /// every route attached to the model, ordered by weight DESC. Lets + /// the list table show "who serves this?" without an extra fetch. + pub providers: Vec, + /// Per-model routing override. `None` ⇒ inherit + /// `gateway.default_routing_strategy`. The detail drawer reads this + /// to label the strategy picker — without it, refetch-after-PATCH + /// can't reflect the new value. + pub routing_strategy: Option, + pub affinity_mode: Option, + pub affinity_ttl_secs: Option, + /// Output guardrails as stored in JSONB. The list endpoint returns + /// the raw `Value` (rather than `Vec`) so the UI + /// can render unrecognised future variants without breaking. The + /// shape is `[{ "type": "max_length", "max_chars": N }, ...]`. + #[schema(value_type = serde_json::Value)] + pub output_guardrails: serde_json::Value, +} + +#[derive(Debug, Serialize, sqlx::FromRow, utoipa::ToSchema)] +pub struct ModelIdRow { + pub model_id: String, + pub display_name: String, +} + +#[derive(Debug, Serialize, sqlx::FromRow, utoipa::ToSchema)] +pub struct ModelRouteRow { + pub id: Uuid, + pub model_id: String, + pub provider_id: Uuid, + pub provider_name: String, + pub upstream_model: String, + pub weight: i32, + pub enabled: bool, + /// Optional human-readable identifier (e.g. "EU-primary"). Pure + /// metadata for the admin UI; ignored by the routing layer. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub label: Option, + /// Free-form note. Surfaced in the edit dialog only. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub notes: Option, + /// Per-route RPM cap. NULL = unlimited. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub rpm_cap: Option, + /// Per-route TPM cap. NULL = unlimited. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tpm_cap: Option, +} + +// --------------------------------------------------------------------------- +// models +// --------------------------------------------------------------------------- + +/// The columns a `Model` is read with. +const MODEL_COLUMNS: &str = "id, model_id, display_name, input_weight, output_weight, \ + cache_read_weight, cache_write_weight, cache_write_1h_weight, \ + routing_strategy, affinity_mode, affinity_ttl_secs, tags, enabled, \ + output_guardrails"; + +/// One page of the catalog, and the total matching `search` / `status`. +/// +/// `status`: +/// 'active' — m.enabled = true AND enabled_route_count > 0 +/// 'disabled' — m.enabled = false, OR +/// (m.enabled = true AND route_count > 0 AND enabled_route_count = 0) +/// 'unrouted' — route_count = 0 +/// otherwise — no filter +/// +/// `route_count` / `enabled_route_count` come from a `LATERAL` subquery so +/// the filter happens on the joined shape; PG rewrites this to a +/// HashAggregate over `model_routes`. +pub async fn list( + pool: &PgPool, + search: &str, + status: &str, + limit: i64, + offset: i64, +) -> Result<(i64, Vec), AppError> { + let search_pattern = format!("%{search}%"); + let status_filter_sql = match status { + "active" => "AND m.enabled = true AND rc.enabled_route_count > 0", + "disabled" => { + "AND (m.enabled = false OR (rc.route_count > 0 AND rc.enabled_route_count = 0))" + } + "unrouted" => "AND rc.route_count = 0", + _ => "", + }; + + let total_sql = format!( + r#"SELECT COUNT(*) FROM models m + LEFT JOIN LATERAL ( + SELECT COUNT(*) AS route_count, + COUNT(*) FILTER (WHERE mr.enabled = true) AS enabled_route_count + FROM model_routes mr + JOIN providers p ON p.id = mr.provider_id AND p.deleted_at IS NULL + WHERE mr.model_id = m.model_id + ) rc ON true + WHERE ($1 = '' OR m.model_id ILIKE $2 OR m.display_name ILIKE $2) + {status_filter_sql}"#, + ); + let list_sql = format!( + r#"SELECT m.id, m.model_id, m.display_name, + m.input_weight, m.output_weight, + m.cache_read_weight, m.cache_write_weight, m.cache_write_1h_weight, + COALESCE(rc.route_count, 0) AS route_count, + COALESCE(rc.enabled_route_count, 0) AS enabled_route_count, + m.enabled, + COALESCE(rc.providers, '{{}}'::text[]) AS providers, + m.routing_strategy, m.affinity_mode, m.affinity_ttl_secs, + m.output_guardrails + FROM models m + LEFT JOIN LATERAL ( + SELECT COUNT(*) AS route_count, + COUNT(*) FILTER (WHERE mr.enabled = true) AS enabled_route_count, + array_agg(COALESCE(p.display_name, p.name) + ORDER BY mr.weight DESC, p.name) AS providers + FROM model_routes mr + JOIN providers p ON p.id = mr.provider_id AND p.deleted_at IS NULL + WHERE mr.model_id = m.model_id + ) rc ON true + WHERE ($1 = '' OR m.model_id ILIKE $2 OR m.display_name ILIKE $2) + {status_filter_sql} + ORDER BY m.model_id + LIMIT $3 OFFSET $4"#, + ); + + let total: Option = sqlx::query_scalar(&total_sql) + .bind(search) + .bind(&search_pattern) + .fetch_one(pool) + .await?; + let rows = sqlx::query_as::<_, ModelRow>(&list_sql) + .bind(search) + .bind(&search_pattern) + .bind(limit) + .bind(offset) + .fetch_all(pool) + .await?; + Ok((total.unwrap_or(0), rows)) +} + +/// Every column a new catalog entry is written with. +pub struct ModelFields<'a> { + pub display_name: &'a str, + pub input_weight: Decimal, + pub output_weight: Decimal, + pub routing_strategy: Option<&'a str>, + pub affinity_mode: Option<&'a str>, + pub affinity_ttl_secs: Option, + pub tags: Option<&'a [String]>, + pub output_guardrails: &'a serde_json::Value, + /// Read, 5-minute write, 1-hour write. + pub cache_weights: [Option; 3], +} + +pub async fn insert(pool: &PgPool, model_id: &str, f: &ModelFields<'_>) -> Result { + let sql = format!( + r#"INSERT INTO models + (model_id, display_name, input_weight, output_weight, + routing_strategy, affinity_mode, affinity_ttl_secs, tags, + output_guardrails, + cache_read_weight, cache_write_weight, cache_write_1h_weight) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) + RETURNING {MODEL_COLUMNS}"# + ); + Ok(sqlx::query_as::<_, Model>(&sql) + .bind(model_id) + .bind(f.display_name) + .bind(f.input_weight) + .bind(f.output_weight) + .bind(f.routing_strategy) + .bind(f.affinity_mode) + .bind(f.affinity_ttl_secs) + .bind(f.tags) + .bind(f.output_guardrails) + .bind(f.cache_weights[0]) + .bind(f.cache_weights[1]) + .bind(f.cache_weights[2]) + .fetch_one(pool) + .await?) +} + +pub async fn find(pool: &PgPool, id: Uuid) -> Result, AppError> { + let sql = format!("SELECT {MODEL_COLUMNS} FROM models WHERE id = $1"); + Ok(sqlx::query_as::<_, Model>(&sql) + .bind(id) + .fetch_optional(pool) + .await?) +} + +/// Overwrite every editable column of one catalog entry. +pub async fn update( + pool: &PgPool, + id: Uuid, + f: &ModelFields<'_>, + enabled: bool, +) -> Result { + let sql = format!( + r#"UPDATE models SET + display_name = $2, + input_weight = $3, + output_weight = $4, + routing_strategy = $5, + affinity_mode = $6, + affinity_ttl_secs = $7, + tags = $8, + enabled = $9, + output_guardrails = $10, + cache_read_weight = $11, + cache_write_weight = $12, + cache_write_1h_weight = $13 + WHERE id = $1 + RETURNING {MODEL_COLUMNS}"# + ); + Ok(sqlx::query_as::<_, Model>(&sql) + .bind(id) + .bind(f.display_name) + .bind(f.input_weight) + .bind(f.output_weight) + .bind(f.routing_strategy) + .bind(f.affinity_mode) + .bind(f.affinity_ttl_secs) + .bind(f.tags) + .bind(enabled) + .bind(f.output_guardrails) + .bind(f.cache_weights[0]) + .bind(f.cache_weights[1]) + .bind(f.cache_weights[2]) + .fetch_one(pool) + .await?) +} + +/// The exposed `model_id` of a catalog row, by its primary key. +pub async fn model_id_of(pool: &PgPool, id: Uuid) -> Result, AppError> { + Ok( + sqlx::query_scalar("SELECT model_id FROM models WHERE id = $1") + .bind(id) + .fetch_optional(pool) + .await?, + ) +} + +pub async fn exists(pool: &PgPool, model_id: &str) -> Result { + let found: Option = + sqlx::query_scalar("SELECT model_id FROM models WHERE model_id = $1") + .bind(model_id) + .fetch_optional(pool) + .await?; + Ok(found.is_some()) +} + +pub async fn delete(pool: &PgPool, id: Uuid) -> Result<(), AppError> { + sqlx::query("DELETE FROM models WHERE id = $1") + .bind(id) + .execute(pool) + .await?; + Ok(()) +} + +/// Every exposed id with its display name, unpaginated. +pub async fn list_ids(pool: &PgPool) -> Result, AppError> { + Ok(sqlx::query_as::<_, ModelIdRow>( + "SELECT model_id, display_name FROM models ORDER BY model_id", + ) + .fetch_all(pool) + .await?) +} + +/// Delete catalog entries with no route to a live provider. Returns how +/// many went. +/// +/// `model_routes.provider_id` has `ON DELETE CASCADE`, so soft-deleted +/// providers still count as "having a route" unless filtered by the +/// provider's `deleted_at IS NULL`. +pub async fn delete_unrouted(pool: &PgPool) -> Result { + let result = sqlx::query( + r#"DELETE FROM models + WHERE model_id NOT IN ( + SELECT DISTINCT mr.model_id + FROM model_routes mr + JOIN providers p ON p.id = mr.provider_id AND p.deleted_at IS NULL + )"#, + ) + .execute(pool) + .await?; + Ok(result.rows_affected()) +} + +/// Delete catalog entries by id (routes cascade). Returns how many went. +pub async fn delete_many(pool: &PgPool, ids: &[Uuid]) -> Result { + let result = sqlx::query("DELETE FROM models WHERE id = ANY($1)") + .bind(ids) + .execute(pool) + .await?; + Ok(result.rows_affected()) +} + +/// Flip the model-level kill switch. Returns how many rows changed. +pub async fn set_enabled_many(pool: &PgPool, ids: &[Uuid], enabled: bool) -> Result { + let result = sqlx::query( + r#"UPDATE models + SET enabled = $2 + WHERE id = ANY($1) + AND enabled IS DISTINCT FROM $2"#, + ) + .bind(ids) + .bind(enabled) + .execute(pool) + .await?; + Ok(result.rows_affected()) +} + +// --------------------------------------------------------------------------- +// model_routes +// --------------------------------------------------------------------------- + +/// A model's routes to live providers, in creation order — so the routes +/// table and the traffic-share sliders stay in place while admins drag +/// weights. +pub async fn routes_of(pool: &PgPool, model_id: &str) -> Result, AppError> { + Ok(sqlx::query_as::<_, ModelRouteRow>( + r#"SELECT mr.id, mr.model_id, mr.provider_id, p.name AS provider_name, + mr.upstream_model, mr.weight, mr.enabled, + mr.label, mr.notes, mr.rpm_cap, mr.tpm_cap + 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.created_at, mr.id"#, + ) + .bind(model_id) + .fetch_all(pool) + .await?) +} + +/// Is there already a route for this (model, provider, upstream model)? +/// That triple is the uniqueness key: the same provider with a different +/// upstream is a legal second route. +pub async fn route_exists( + pool: &PgPool, + model_id: &str, + provider_id: Uuid, + upstream_model: &str, +) -> Result { + let existing: Option = sqlx::query_scalar( + r#"SELECT id FROM model_routes + WHERE model_id = $1 + AND provider_id = $2 + AND upstream_model = $3"#, + ) + .bind(model_id) + .bind(provider_id) + .bind(upstream_model) + .fetch_optional(pool) + .await?; + Ok(existing.is_some()) +} + +pub struct NewRoute<'a> { + pub model_id: &'a str, + pub provider_id: Uuid, + pub upstream_model: &'a str, + pub weight: i32, + pub enabled: bool, + pub label: Option<&'a str>, + pub notes: Option<&'a str>, + pub rpm_cap: Option, + pub tpm_cap: Option, + pub upstream_protocol: Option<&'a str>, +} + +pub async fn insert_route(pool: &PgPool, r: &NewRoute<'_>) -> Result { + Ok(sqlx::query_as::<_, ModelRouteRow>( + r#"INSERT INTO model_routes + (model_id, provider_id, upstream_model, weight, enabled, + label, notes, rpm_cap, tpm_cap, upstream_protocol) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) + RETURNING id, model_id, provider_id, + (SELECT name FROM providers WHERE id = provider_id) AS provider_name, + upstream_model, weight, enabled, + label, notes, rpm_cap, tpm_cap"#, + ) + .bind(r.model_id) + .bind(r.provider_id) + .bind(r.upstream_model) + .bind(r.weight) + .bind(r.enabled) + .bind(r.label) + .bind(r.notes) + .bind(r.rpm_cap) + .bind(r.tpm_cap) + .bind(r.upstream_protocol) + .fetch_one(pool) + .await?) +} + +/// A PATCH to one route. `None` leaves a column alone; for the clearable +/// ones, `Some(None)` clears it. +pub struct RouteUpdate<'a> { + pub upstream_model: Option<&'a str>, + pub weight: Option, + pub enabled: Option, + pub label: Option>, + pub notes: Option>, + pub rpm_cap: Option>, + pub tpm_cap: Option>, +} + +/// `None` when there is no such route. +pub async fn update_route( + pool: &PgPool, + route_id: Uuid, + u: &RouteUpdate<'_>, +) -> Result, AppError> { + Ok(sqlx::query_as::<_, ModelRouteRow>( + r#"UPDATE model_routes SET + upstream_model = COALESCE($2, upstream_model), + weight = COALESCE($3, weight), + enabled = COALESCE($4, enabled), + label = CASE WHEN $6 THEN $5 ELSE label END, + notes = CASE WHEN $8 THEN $7 ELSE notes END, + rpm_cap = CASE WHEN $10 THEN $9 ELSE rpm_cap END, + tpm_cap = CASE WHEN $12 THEN $11 ELSE tpm_cap END + WHERE id = $1 + RETURNING id, model_id, provider_id, + (SELECT name FROM providers WHERE id = provider_id) AS provider_name, + upstream_model, weight, enabled, + label, notes, rpm_cap, tpm_cap"#, + ) + .bind(route_id) + .bind(u.upstream_model) + .bind(u.weight) + .bind(u.enabled) + .bind(u.label.flatten()) + .bind(u.label.is_some()) + .bind(u.notes.flatten()) + .bind(u.notes.is_some()) + .bind(u.rpm_cap.flatten()) + .bind(u.rpm_cap.is_some()) + .bind(u.tpm_cap.flatten()) + .bind(u.tpm_cap.is_some()) + .fetch_optional(pool) + .await?) +} + +/// Returns whether the route existed. +pub async fn delete_route(pool: &PgPool, route_id: Uuid) -> Result { + let result = sqlx::query("DELETE FROM model_routes WHERE id = $1") + .bind(route_id) + .execute(pool) + .await?; + Ok(result.rows_affected() > 0) +} + +/// One page of every route to a live provider, filtered by a search over +/// model id and provider name and by provider, and the total matching. +pub async fn list_routes( + pool: &PgPool, + search: &str, + provider_id: Option, + limit: i64, + offset: i64, +) -> Result<(i64, Vec), AppError> { + if search.is_empty() && provider_id.is_none() { + let total: Option = sqlx::query_scalar( + "SELECT COUNT(*) FROM model_routes mr JOIN providers p ON p.id = mr.provider_id WHERE p.deleted_at IS NULL", + ) + .fetch_one(pool) + .await?; + let rows = sqlx::query_as::<_, ModelRouteRow>( + r#"SELECT mr.id, mr.model_id, mr.provider_id, p.name AS provider_name, + mr.upstream_model, mr.weight, mr.enabled, + mr.label, mr.notes, mr.rpm_cap, mr.tpm_cap + FROM model_routes mr + JOIN providers p ON p.id = mr.provider_id + WHERE p.deleted_at IS NULL + ORDER BY mr.model_id, mr.weight DESC + LIMIT $1 OFFSET $2"#, + ) + .bind(limit) + .bind(offset) + .fetch_all(pool) + .await?; + return Ok((total.unwrap_or(0), rows)); + } + let search_pattern = format!("%{search}%"); + let total: Option = sqlx::query_scalar( + r#"SELECT COUNT(*) FROM model_routes mr + JOIN providers p ON p.id = mr.provider_id + WHERE p.deleted_at IS NULL + AND ($1 = '' OR mr.model_id ILIKE $2 OR p.name ILIKE $2) + AND ($3::UUID IS NULL OR mr.provider_id = $3)"#, + ) + .bind(search) + .bind(&search_pattern) + .bind(provider_id) + .fetch_one(pool) + .await?; + let rows = sqlx::query_as::<_, ModelRouteRow>( + r#"SELECT mr.id, mr.model_id, mr.provider_id, p.name AS provider_name, + mr.upstream_model, mr.weight, mr.enabled, + mr.label, mr.notes, mr.rpm_cap, mr.tpm_cap + FROM model_routes mr + JOIN providers p ON p.id = mr.provider_id + WHERE p.deleted_at IS NULL + AND ($1 = '' OR mr.model_id ILIKE $2 OR p.name ILIKE $2) + AND ($3::UUID IS NULL OR mr.provider_id = $3) + ORDER BY mr.model_id, mr.weight DESC + LIMIT $4 OFFSET $5"#, + ) + .bind(search) + .bind(&search_pattern) + .bind(provider_id) + .bind(limit) + .bind(offset) + .fetch_all(pool) + .await?; + Ok((total.unwrap_or(0), rows)) +} + +/// Routes to create for one provider in a batch import. The vectors of +/// each half are parallel. +#[derive(Default)] +pub struct RouteImport { + /// New catalog entries: the exposed id, the provider's name for it, + /// and the protocol the probe found (if any). + pub new_exposed: Vec, + pub new_upstreams: Vec, + pub new_protocols: Vec>, + /// Routes onto existing catalog entries. + pub attach_targets: Vec, + pub attach_upstreams: Vec, + pub attach_protocols: Vec>, +} + +/// Create a batch import's catalog entries and routes in one transaction, +/// one bulk statement per half. Returns how many routes landed (existing +/// ones are skipped, as are attach targets that do not exist). +pub async fn import_routes( + pool: &PgPool, + provider_id: Uuid, + import: &RouteImport, +) -> Result { + let mut tx = pool.begin().await?; + + // Catalog insert is idempotent. Route insert counts rows via the + // RETURNING/CTE pattern so the count reflects only rows that actually + // landed (skipping ON CONFLICT dupes). + let new_inserted: i64 = if import.new_exposed.is_empty() { + 0 + } else { + sqlx::query( + r#"INSERT INTO models (model_id, display_name) + SELECT exposed, exposed + FROM UNNEST($1::TEXT[]) AS t(exposed) + ON CONFLICT (model_id) DO NOTHING"#, + ) + .bind(&import.new_exposed) + .execute(&mut *tx) + .await?; + + sqlx::query_scalar::<_, i64>( + r#"WITH ins AS ( + INSERT INTO model_routes + (model_id, provider_id, upstream_model, weight, upstream_protocol) + SELECT exposed, $3, upstream, 100, protocol + FROM UNNEST($1::TEXT[], $2::TEXT[], $4::TEXT[]) + AS t(exposed, upstream, protocol) + ON CONFLICT (model_id, provider_id, upstream_model) DO NOTHING + RETURNING 1 + ) + SELECT COUNT(*) FROM ins"#, + ) + .bind(&import.new_exposed) + .bind(&import.new_upstreams) + .bind(provider_id) + .bind(&import.new_protocols) + .fetch_one(&mut *tx) + .await? + }; + + // Targets that don't exist in `models` are silently skipped (EXISTS + // guard) to avoid a FK failure on a typo. + let attach_inserted: i64 = if import.attach_targets.is_empty() { + 0 + } else { + sqlx::query_scalar::<_, i64>( + r#"WITH ins AS ( + INSERT INTO model_routes + (model_id, provider_id, upstream_model, weight, upstream_protocol) + SELECT t.target, $3, t.upstream, 100, t.protocol + FROM UNNEST($1::TEXT[], $2::TEXT[], $4::TEXT[]) + AS t(target, upstream, protocol) + WHERE EXISTS (SELECT 1 FROM models m WHERE m.model_id = t.target) + ON CONFLICT (model_id, provider_id, upstream_model) DO NOTHING + RETURNING 1 + ) + SELECT COUNT(*) FROM ins"#, + ) + .bind(&import.attach_targets) + .bind(&import.attach_upstreams) + .bind(provider_id) + .bind(&import.attach_protocols) + .fetch_one(&mut *tx) + .await? + }; + + tx.commit().await?; + Ok(new_inserted + attach_inserted) +} + +/// Returns how many routes went. +pub async fn delete_routes(pool: &PgPool, ids: &[Uuid]) -> Result { + let result = sqlx::query("DELETE FROM model_routes WHERE id = ANY($1)") + .bind(ids) + .execute(pool) + .await?; + Ok(result.rows_affected()) +} + +/// Set many routes' weights in one transaction, so a partial failure +/// rolls back. Returns how many rows changed. +pub async fn set_route_weights(pool: &PgPool, weights: &[(Uuid, i32)]) -> Result { + let mut tx = pool.begin().await?; + let mut updated = 0; + for (id, weight) in weights { + let result = sqlx::query("UPDATE model_routes SET weight = $1 WHERE id = $2") + .bind(weight) + .bind(id) + .execute(&mut *tx) + .await?; + updated += result.rows_affected(); + } + tx.commit().await?; + Ok(updated) +} + +/// Returns how many routes changed. +pub async fn set_routes_enabled( + pool: &PgPool, + ids: &[Uuid], + enabled: bool, +) -> Result { + let result = sqlx::query("UPDATE model_routes SET enabled = $1 WHERE id = ANY($2)") + .bind(enabled) + .bind(ids) + .execute(pool) + .await?; + Ok(result.rows_affected()) +} + +/// What `gateway_logs` records for a route — (model id, provider name, +/// upstream model) — since the log has no route id. `None` when the route +/// is gone or its provider deleted. +pub async fn route_log_identity( + pool: &PgPool, + route_id: Uuid, +) -> Result, sqlx::Error> { + sqlx::query_as::<_, (String, String, String)>( + "SELECT mr.model_id, p.name, mr.upstream_model \ + FROM model_routes mr \ + JOIN providers p ON p.id = mr.provider_id AND p.deleted_at IS NULL \ + WHERE mr.id = $1", + ) + .bind(route_id) + .fetch_optional(pool) + .await +} diff --git a/crates/server/src/services/pricing_repository.rs b/crates/server/src/services/pricing_repository.rs new file mode 100644 index 00000000..5d1bf5b0 --- /dev/null +++ b/crates/server/src/services/pricing_repository.rs @@ -0,0 +1,49 @@ +//! Platform pricing repository — the single-row `platform_pricing` table +//! (PK fixed at 1): the baseline price per token the model weights +//! multiply. + +use rust_decimal::Decimal; +use serde::Serialize; +use sqlx::PgPool; +use think_watch_common::errors::AppError; + +#[derive(Debug, Serialize, sqlx::FromRow, utoipa::ToSchema)] +pub struct PlatformPricing { + #[schema(value_type = f64)] + pub input_price_per_token: Decimal, + #[schema(value_type = f64)] + pub output_price_per_token: Decimal, + pub currency: String, +} + +pub async fn get(pool: &PgPool) -> Result { + Ok(sqlx::query_as::<_, PlatformPricing>( + "SELECT input_price_per_token, output_price_per_token, currency \ + FROM platform_pricing WHERE id = 1", + ) + .fetch_one(pool) + .await?) +} + +/// Set whichever of the three are given; the others keep their value. +pub async fn update( + pool: &PgPool, + input_price_per_token: Option, + output_price_per_token: Option, + currency: Option<&str>, +) -> Result { + Ok(sqlx::query_as::<_, PlatformPricing>( + r#"UPDATE platform_pricing SET + input_price_per_token = COALESCE($1, input_price_per_token), + output_price_per_token = COALESCE($2, output_price_per_token), + currency = COALESCE($3, currency), + updated_at = now() + WHERE id = 1 + RETURNING input_price_per_token, output_price_per_token, currency"#, + ) + .bind(input_price_per_token) + .bind(output_price_per_token) + .bind(currency) + .fetch_one(pool) + .await?) +} diff --git a/crates/server/src/services/provider_repository.rs b/crates/server/src/services/provider_repository.rs new file mode 100644 index 00000000..03a07e96 --- /dev/null +++ b/crates/server/src/services/provider_repository.rs @@ -0,0 +1,111 @@ +//! Provider repository — the `providers` table. Rows are soft-deleted +//! (`deleted_at`); "live" means not deleted. +//! +//! Secrets in `config_json` are stored encrypted; encrypting on the way in +//! and redacting on the way out stay in `handlers::providers`. + +use sqlx::PgPool; +use think_watch_common::errors::AppError; +use think_watch_common::models::Provider; +use uuid::Uuid; + +/// Every live provider, newest first. +pub async fn list_live(pool: &PgPool) -> Result, AppError> { + Ok(sqlx::query_as::<_, Provider>( + "SELECT * FROM providers WHERE deleted_at IS NULL ORDER BY created_at DESC", + ) + .fetch_all(pool) + .await?) +} + +pub async fn find_live(pool: &PgPool, id: Uuid) -> Result, AppError> { + Ok(sqlx::query_as::<_, Provider>( + "SELECT * FROM providers WHERE id = $1 AND deleted_at IS NULL", + ) + .bind(id) + .fetch_optional(pool) + .await?) +} + +/// A provider's name, deleted or not. +pub async fn name_of(pool: &PgPool, id: Uuid) -> Result, AppError> { + Ok( + sqlx::query_scalar("SELECT name FROM providers WHERE id = $1") + .bind(id) + .fetch_optional(pool) + .await?, + ) +} + +pub async fn insert( + pool: &PgPool, + name: &str, + display_name: &str, + provider_type: &str, + base_url: &str, + config_json: &serde_json::Value, +) -> Result { + Ok(sqlx::query_as::<_, Provider>( + r#"INSERT INTO providers (name, display_name, provider_type, base_url, config_json) + VALUES ($1, $2, $3, $4, $5) RETURNING *"#, + ) + .bind(name) + .bind(display_name) + .bind(provider_type) + .bind(base_url) + .bind(config_json) + .fetch_one(pool) + .await?) +} + +pub async fn update( + pool: &PgPool, + id: Uuid, + display_name: &str, + base_url: &str, + config_json: &serde_json::Value, +) -> Result { + Ok(sqlx::query_as::<_, Provider>( + r#"UPDATE providers SET display_name = $2, base_url = $3, config_json = $4 + WHERE id = $1 RETURNING *"#, + ) + .bind(id) + .bind(display_name) + .bind(base_url) + .bind(config_json) + .fetch_one(pool) + .await?) +} + +/// Forget the protocol learned for each of a provider's routes. Returns +/// how many routes had one. +pub async fn clear_learned_protocols(pool: &PgPool, id: Uuid) -> Result { + Ok(sqlx::query( + "UPDATE model_routes SET upstream_protocol = NULL + WHERE provider_id = $1 AND upstream_protocol IS NOT NULL", + ) + .bind(id) + .execute(pool) + .await? + .rows_affected()) +} + +/// Soft-delete a provider and drop its routes, in one transaction. The +/// `model_routes` FK cascades on a real DELETE, not on flipping +/// `deleted_at`, so the routes are deleted explicitly — orphans would show +/// up on the Models page with a raw provider id and no way to edit them. +/// Returns how many routes went. +pub async fn soft_delete(pool: &PgPool, id: Uuid) -> Result { + let mut tx = pool.begin().await?; + sqlx::query("UPDATE providers SET deleted_at = now() WHERE id = $1 AND deleted_at IS NULL") + .bind(id) + .execute(&mut *tx) + .await?; + let routes_deleted = sqlx::query("DELETE FROM model_routes WHERE provider_id = $1") + .bind(id) + .execute(&mut *tx) + .await? + .rows_affected(); + tx.commit().await?; + Ok(routes_deleted) +} diff --git a/crates/test-support/tests/admin_catalog.rs b/crates/test-support/tests/admin_catalog.rs new file mode 100644 index 00000000..c5477c69 --- /dev/null +++ b/crates/test-support/tests/admin_catalog.rs @@ -0,0 +1,404 @@ +//! The admin catalog endpoints end to end: models, routes, providers and +//! the platform price baseline. +//! +//! Most 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 serde_json::Value; +use think_watch_test_support::prelude::*; + +/// An admin session and a live provider backed by a mock that answers +/// the route-creation probe. +async fn setup(app: &TestApp) -> (TestClient, MockProvider, Uuid) { + let (con, _) = admin_session_with_user(app).await; + let upstream = MockProvider::openai_chat_ok("catalog-upstream").await; + let provider = fixtures::create_provider( + &app.db, + &unique_name("catalog-prov"), + "openai", + &upstream.uri(), + None, + ) + .await + .unwrap(); + (con, upstream, provider.id) +} + +async fn create_model(con: &TestClient, model_id: &str) -> String { + let created: Value = con + .post( + "/api/admin/models", + json!({"model_id": model_id, "display_name": model_id}), + ) + .await + .unwrap() + .json() + .unwrap(); + created["id"].as_str().expect("model id").to_string() +} + +async fn get(con: &TestClient, path: &str) -> Value { + let resp = con.get(path).await.unwrap(); + resp.assert_ok(); + resp.json().unwrap() +} + +#[ignore = "integration test — run via `make test-it`"] +#[tokio::test] +async fn a_route_is_created_edited_listed_and_removed() { + let app = TestApp::spawn().await; + let (con, _upstream, provider_id) = setup(&app).await; + let model = unique_name("catalog-model"); + create_model(&con, &model).await; + + let resp = con + .post( + &format!("/api/admin/models/{model}/routes"), + json!({"provider_id": provider_id, "weight": 10, "label": "eu", "notes": ""}), + ) + .await + .unwrap(); + resp.assert_ok(); + let route: Value = resp.json().unwrap(); + let route_id = route["id"].as_str().unwrap().to_string(); + assert_eq!(route["upstream_model"], model.as_str(), "{route}"); + assert_eq!(route["weight"], 10); + assert_eq!(route["label"], "eu"); + assert!( + route.get("notes").is_none(), + "an empty note is no note: {route}" + ); + assert!(route["provider_name"].is_string(), "{route}"); + + // Same (model, provider, upstream) twice is refused; an unknown + // model or provider too. + con.post( + &format!("/api/admin/models/{model}/routes"), + json!({"provider_id": provider_id}), + ) + .await + .unwrap() + .assert_status(400); + con.post( + &format!("/api/admin/models/{}/routes", unique_name("nope")), + json!({"provider_id": provider_id}), + ) + .await + .unwrap() + .assert_status(404); + con.post( + &format!("/api/admin/models/{model}/routes"), + json!({"provider_id": Uuid::new_v4(), "upstream_model": "other"}), + ) + .await + .unwrap() + .assert_status(400); + + let routes = get(&con, &format!("/api/admin/models/{model}/routes")).await; + assert_eq!(routes.as_array().unwrap().len(), 1, "{routes}"); + + // PATCH: a JSON null clears, an absent field is left alone. + let resp = con + .patch( + &format!("/api/admin/model-routes/{route_id}"), + json!({"label": null, "weight": 20, "rpm_cap": 5}), + ) + .await + .unwrap(); + resp.assert_ok(); + let patched: Value = resp.json().unwrap(); + assert!(patched.get("label").is_none(), "{patched}"); + assert_eq!(patched["weight"], 20); + assert_eq!(patched["rpm_cap"], 5); + assert_eq!(patched["enabled"], true); + con.patch( + &format!("/api/admin/model-routes/{route_id}"), + json!({"rpm_cap": 0}), + ) + .await + .unwrap() + .assert_status(400); + con.patch( + &format!("/api/admin/model-routes/{}", Uuid::new_v4()), + json!({"weight": 1}), + ) + .await + .unwrap() + .assert_status(404); + + // The flat listing, unfiltered and filtered both ways. + let all = get(&con, "/api/admin/model-routes?page_size=200").await; + assert!(all["total"].as_i64().unwrap() >= 1, "{all}"); + let by_search = get(&con, &format!("/api/admin/model-routes?q={model}")).await; + assert_eq!(by_search["total"], 1, "{by_search}"); + assert_eq!(by_search["items"][0]["id"], route_id.as_str()); + let by_provider = get( + &con, + &format!("/api/admin/model-routes?provider_id={provider_id}"), + ) + .await; + assert_eq!(by_provider["total"], 1, "{by_provider}"); + + // Batch weights and the batch enable toggle. + let r: Value = con + .patch( + "/api/admin/model-routes/batch-weights", + json!({"updates": [{"id": route_id, "weight": 7}]}), + ) + .await + .unwrap() + .json() + .unwrap(); + assert_eq!(r["updated"], 1, "{r}"); + let r: Value = con + .post( + "/api/admin/model-routes/batch-update", + json!({"ids": [route_id], "enabled": false}), + ) + .await + .unwrap() + .json() + .unwrap(); + assert_eq!(r["updated"], 1, "{r}"); + let routes = get(&con, &format!("/api/admin/models/{model}/routes")).await; + assert_eq!(routes[0]["weight"], 7, "{routes}"); + assert_eq!(routes[0]["enabled"], false, "{routes}"); + + // A model whose routes are all off lists as disabled. + let disabled = get( + &con, + &format!("/api/admin/models?status=disabled&q={model}"), + ) + .await; + assert_eq!(disabled["total"], 1, "{disabled}"); + assert_eq!(disabled["items"][0]["route_count"], 1); + assert_eq!(disabled["items"][0]["enabled_route_count"], 0); + + let r: Value = con + .post( + "/api/admin/model-routes/batch-delete", + json!({"ids": [route_id]}), + ) + .await + .unwrap() + .json() + .unwrap(); + assert_eq!(r["deleted"], 1, "{r}"); + let unrouted = get( + &con, + &format!("/api/admin/models?status=unrouted&q={model}"), + ) + .await; + assert_eq!(unrouted["total"], 1, "{unrouted}"); + con.delete(&format!("/api/admin/model-routes/{route_id}")) + .await + .unwrap() + .assert_status(404); +} + +#[ignore = "integration test — run via `make test-it`"] +#[tokio::test] +async fn models_are_listed_toggled_and_deleted_in_bulk() { + let app = TestApp::spawn().await; + let (con, _upstream, provider_id) = setup(&app).await; + let routed = unique_name("bulk-routed"); + let a = unique_name("bulk-a"); + let b = unique_name("bulk-b"); + let c = unique_name("bulk-c"); + create_model(&con, &routed).await; + let a_id = create_model(&con, &a).await; + create_model(&con, &b).await; + let c_id = create_model(&con, &c).await; + con.post( + &format!("/api/admin/models/{routed}/routes"), + json!({"provider_id": provider_id}), + ) + .await + .unwrap() + .assert_ok(); + + let active = get(&con, &format!("/api/admin/models?status=active&q={routed}")).await; + assert_eq!(active["total"], 1, "{active}"); + assert_eq!(active["items"][0]["providers"].as_array().unwrap().len(), 1); + + let ids = get(&con, "/api/admin/models/ids").await; + let listed: Vec<&str> = ids + .as_array() + .unwrap() + .iter() + .filter_map(|r| r["model_id"].as_str()) + .collect(); + for m in [&routed, &a, &b, &c] { + assert!(listed.contains(&m.as_str()), "{m} missing from {ids}"); + } + + // Only rows that actually change count. + for expected in [1, 0] { + let r: Value = con + .post( + "/api/admin/models/bulk-set-enabled", + json!({"ids": [a_id], "enabled": false}), + ) + .await + .unwrap() + .json() + .unwrap(); + assert_eq!(r["updated"], expected, "{r}"); + } + let off = get(&con, &format!("/api/admin/models?status=disabled&q={a}")).await; + assert_eq!(off["items"][0]["enabled"], false, "{off}"); + + let r: Value = con + .post("/api/admin/models/bulk-delete", json!({"ids": [a_id]})) + .await + .unwrap() + .json() + .unwrap(); + assert_eq!(r["deleted"], 1, "{r}"); + + let r: Value = con + .delete(&format!("/api/admin/models/{c_id}")) + .await + .unwrap() + .json() + .unwrap(); + assert_eq!(r["status"], "deleted", "{r}"); + + // `b` has no route; `routed` does and survives. + let r: Value = con + .delete("/api/admin/models/unrouted") + .await + .unwrap() + .json() + .unwrap(); + assert!(r["deleted"].as_i64().unwrap() >= 1, "{r}"); + let left = get(&con, "/api/admin/models/ids").await; + let left: Vec<&str> = left + .as_array() + .unwrap() + .iter() + .filter_map(|r| r["model_id"].as_str()) + .collect(); + assert!(left.contains(&routed.as_str())); + for gone in [&a, &b, &c] { + assert!(!left.contains(&gone.as_str()), "{gone} still listed"); + } +} + +#[ignore = "integration test — run via `make test-it`"] +#[tokio::test] +async fn a_provider_edit_forgets_learned_protocols_and_a_delete_drops_its_routes() { + // The new base URL is the loopback mock again. + let app = TestApp::spawn_reaching_loopback().await; + let (con, upstream, provider_id) = setup(&app).await; + let model = unique_name("prov-model"); + create_model(&con, &model).await; + con.post( + &format!("/api/admin/models/{model}/routes"), + json!({"provider_id": provider_id}), + ) + .await + .unwrap() + .assert_ok(); + let protocol = || async { + sqlx::query_scalar::<_, Option>( + "SELECT upstream_protocol FROM model_routes WHERE model_id = $1", + ) + .bind(&model) + .fetch_one(&app.db) + .await + .unwrap() + }; + assert!(protocol().await.is_some(), "the probe recorded a protocol"); + + let one = get(&con, &format!("/api/admin/providers/{provider_id}")).await; + assert_eq!(one["id"], provider_id.to_string()); + let all = get(&con, "/api/admin/providers").await; + assert!( + all.as_array() + .unwrap() + .iter() + .any(|p| p["id"] == provider_id.to_string()), + "{all}" + ); + + // A display-name change keeps what was learned. + let resp = con + .patch( + &format!("/api/admin/providers/{provider_id}"), + json!({"display_name": "Renamed"}), + ) + .await + .unwrap(); + resp.assert_ok(); + let renamed: Value = resp.json().unwrap(); + assert_eq!(renamed["display_name"], "Renamed"); + assert!(protocol().await.is_some()); + + // A new base URL may be a different upstream. + con.patch( + &format!("/api/admin/providers/{provider_id}"), + json!({"base_url": upstream.uri()}), + ) + .await + .unwrap() + .assert_ok(); + assert_eq!(protocol().await, None); + + con.delete(&format!("/api/admin/providers/{provider_id}")) + .await + .unwrap() + .assert_ok(); + let routes: i64 = + sqlx::query_scalar("SELECT COUNT(*) FROM model_routes WHERE provider_id = $1") + .bind(provider_id) + .fetch_one(&app.db) + .await + .unwrap(); + assert_eq!(routes, 0); + con.get(&format!("/api/admin/providers/{provider_id}")) + .await + .unwrap() + .assert_status(404); +} + +#[ignore = "integration test — run via `make test-it`"] +#[tokio::test] +async fn the_platform_price_baseline_is_read_and_patched() { + let app = TestApp::spawn().await; + let (con, _) = admin_session_with_user(&app).await; + + let before = get(&con, "/api/admin/platform-pricing").await; + assert!(before["currency"].is_string(), "{before}"); + + let resp = con + .patch( + "/api/admin/platform-pricing", + json!({"input_price_per_token": 0.000002}), + ) + .await + .unwrap(); + resp.assert_ok(); + let after: Value = resp.json().unwrap(); + assert_eq!( + after["input_price_per_token"] + .as_str() + .map(|s| s.parse::().unwrap()), + Some(0.000002), + "{after}" + ); + assert_eq!( + after["output_price_per_token"], + before["output_price_per_token"] + ); + assert_eq!(after["currency"], before["currency"]); + + con.patch( + "/api/admin/platform-pricing", + json!({"output_price_per_token": -1}), + ) + .await + .unwrap() + .assert_status(400); +}