Files
sorsfonalak/services/backend/src/routes/analyses.rs
T

311 lines
11 KiB
Rust
Raw Normal View History

//! Text analyses (LLM) of charts and synastries.
//!
//! A request creates a `pending` analysis and spends credits; the worker
//! writes the text later. A finished analysis with the same cache key (same
//! chart or synastry hash, prompt version, model and language) is copied
//! instead, free of charge, so the same chart is never paid for twice.
//!
//! Every saved chart also gets a free short summary (`summary` kind, written
//! by `SUMMARY_MODEL`); the detailed analyses are paid.
use axum::Json;
use axum::body::Bytes;
use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum_extra::extract::WithRejection;
use serde::Deserialize;
use serde_json::{Value, json};
use sqlx::PgPool;
use time::OffsetDateTime;
use uuid::Uuid;
use super::auth::validate_locale;
use super::charts::{ChartRow, find_chart, owned_chart};
use super::synastries::{load_synastry, visible_synastry};
use super::{IdPath, St};
use crate::AppState;
use crate::auth::AuthUser;
use crate::credits;
use crate::error::{ApiError, ApiResult};
use crate::views::{rfc3339, rfc3339_opt, sha256_hex};
#[derive(Debug, Clone, sqlx::FromRow)]
pub struct AnalysisRow {
pub id: Uuid,
pub kind: String,
pub chart_id: Option<Uuid>,
pub synastry_id: Option<Uuid>,
pub language: String,
pub model: String,
pub prompt_version: String,
pub status: String,
pub content: Option<Value>,
pub error: Option<String>,
pub credits_charged: i32,
pub created_at: OffsetDateTime,
pub completed_at: Option<OffsetDateTime>,
}
const ANALYSIS_COLUMNS: &str = "id, kind, chart_id, synastry_id, language, model, prompt_version, status, content, \
error, credits_charged, created_at, completed_at";
impl AnalysisRow {
pub fn view(&self) -> Value {
json!({
"id": self.id,
"kind": self.kind,
"chart_id": self.chart_id,
"synastry_id": self.synastry_id,
"language": self.language,
"model": self.model,
"prompt_version": self.prompt_version,
"status": self.status,
"content": self.content,
"error": self.error,
"credits_charged": self.credits_charged,
"created_at": rfc3339(self.created_at),
"completed_at": rfc3339_opt(self.completed_at),
})
}
}
pub async fn find_analysis(db: &PgPool, id: Uuid) -> Result<Option<AnalysisRow>, ApiError> {
Ok(sqlx::query_as(&format!("SELECT {ANALYSIS_COLUMNS} FROM analyses WHERE id = $1"))
.bind(id)
.fetch_optional(db)
.await?)
}
/// Whether `user` may read the analysis: the chart's owner, or a member of
/// the synastry.
pub async fn can_see(db: &PgPool, analysis: &AnalysisRow, user: Uuid) -> Result<bool, ApiError> {
if let Some(chart_id) = analysis.chart_id {
return Ok(find_chart(db, chart_id).await?.is_some_and(|c| c.owner_id == user));
}
if let Some(synastry_id) = analysis.synastry_id {
return Ok(load_synastry(db, synastry_id).await?.is_some_and(|s| s.is_member(user)));
}
Ok(false)
}
#[derive(Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct AnalysisRequest {
/// Defaults to the user's locale.
language: Option<String>,
/// One of the configured models; defaults to the first.
model: Option<String>,
}
/// The request body is optional: empty means all defaults.
fn optional_body(body: &[u8]) -> Result<AnalysisRequest, ApiError> {
if body.iter().all(u8::is_ascii_whitespace) {
return Ok(AnalysisRequest::default());
}
serde_json::from_slice(body).map_err(|e| ApiError::BadRequest(format!("invalid request body: {e}")))
}
enum Target {
Natal { chart_id: Uuid, hash: String },
Summary { chart_id: Uuid, hash: String },
Synastry { synastry_id: Uuid, hash: String },
}
async fn request(
state: &AppState,
auth: &AuthUser,
target: Target,
req: AnalysisRequest,
) -> ApiResult<(StatusCode, Json<Value>)> {
let language = validate_locale(state, Some(req.language.as_deref().unwrap_or(&auth.user.locale)))?;
let models = &state.config.llm_models;
let chosen = match &req.model {
None => &models[0],
Some(id) => models.iter().find(|m| &m.id == id).ok_or_else(|| {
let available: Vec<&str> = models.iter().map(|m| m.id.as_str()).collect();
ApiError::BadRequest(format!("unknown model '{id}'; available: {}", available.join(", ")))
})?,
};
if let Some(role) = chosen.role
&& !auth.user.has_access(role)
{
return Err(ApiError::Forbidden(format!("the model '{}' needs the '{}' role", chosen.id, role.as_str())));
}
let cost = chosen.credits;
let (status, row) = queue(state, auth.id(), &target, &language, &chosen.id, cost).await?;
Ok((status, Json(row.view())))
}
/// Returns the existing analysis with the same cache key for this target,
/// copies a finished one from another chart with the same data, or queues a
/// new one (spending `cost` credits). 200, 201 and 202 respectively.
async fn queue(
state: &AppState,
user: Uuid,
target: &Target,
language: &str,
model: &str,
cost: i32,
) -> Result<(StatusCode, AnalysisRow), ApiError> {
let (kind, hash, chart_id, synastry_id) = match target {
Target::Natal { chart_id, hash } => ("natal", hash, Some(*chart_id), None),
Target::Summary { chart_id, hash } => ("summary", hash, Some(*chart_id), None),
Target::Synastry { synastry_id, hash } => ("synastry", hash, None, Some(*synastry_id)),
};
let prompt_version = &state.config.prompt_version;
let cache_key = sha256_hex(&format!("{kind}|{hash}|{prompt_version}|{model}|{language}"));
// Already requested for this chart/synastry: return it.
let existing: Option<AnalysisRow> = sqlx::query_as(&format!(
"SELECT {ANALYSIS_COLUMNS} FROM analyses \
WHERE (chart_id = $1 OR synastry_id = $2) AND cache_key = $3 AND status <> 'failed' \
ORDER BY created_at DESC LIMIT 1"
))
.bind(chart_id)
.bind(synastry_id)
.bind(&cache_key)
.fetch_optional(&state.db)
.await?;
if let Some(row) = existing {
return Ok((StatusCode::OK, row));
}
let insert = format!(
"INSERT INTO analyses (id, kind, chart_id, synastry_id, requested_by, language, model, prompt_version, \
cache_key, status, content, input_tokens, output_tokens, credits_charged, completed_at) \
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15) RETURNING {ANALYSIS_COLUMNS}"
);
let id = Uuid::now_v7();
// The same chart elsewhere (another user, same birth data) was already analysed: copy it.
let cached: Option<(Value, Option<i32>, Option<i32>)> = sqlx::query_as(
"SELECT content, input_tokens, output_tokens FROM analyses WHERE cache_key = $1 AND status = 'done' LIMIT 1",
)
.bind(&cache_key)
.fetch_optional(&state.db)
.await?;
if let Some((content, input_tokens, output_tokens)) = cached {
let row: AnalysisRow = sqlx::query_as(&insert)
.bind(id)
.bind(kind)
.bind(chart_id)
.bind(synastry_id)
.bind(user)
.bind(language)
.bind(model)
.bind(prompt_version)
.bind(&cache_key)
.bind("done")
.bind(content)
.bind(input_tokens)
.bind(output_tokens)
.bind(0)
.bind(OffsetDateTime::now_utc())
.fetch_one(&state.db)
.await?;
return Ok((StatusCode::CREATED, row));
}
// New analysis: spend credits and queue it for the worker.
let mut tx = state.db.begin().await?;
let row: AnalysisRow = sqlx::query_as(&insert)
.bind(id)
.bind(kind)
.bind(chart_id)
.bind(synastry_id)
.bind(user)
.bind(language)
.bind(model)
.bind(prompt_version)
.bind(&cache_key)
.bind("pending")
.bind(None::<Value>)
.bind(None::<i32>)
.bind(None::<i32>)
.bind(cost)
.bind(None::<OffsetDateTime>)
.fetch_one(&mut *tx)
.await?;
if cost > 0 {
credits::spend(&mut tx, user, cost, state.config.monthly_free_credits, "analysis", Some(id)).await?;
}
tx.commit().await?;
Ok((StatusCode::ACCEPTED, row))
}
/// The free short summary of a chart (in the owner's language): queued if
/// it does not exist yet or the last attempt failed.
pub async fn ensure_summary(state: &AppState, owner: &AuthUser, chart: &ChartRow) -> Result<AnalysisRow, ApiError> {
let target = Target::Summary { chart_id: chart.id, hash: chart.chart_hash.clone() };
let model = state.config.summary_model.clone();
Ok(queue(state, owner.id(), &target, &owner.user.locale, &model, 0).await?.1)
}
pub async fn summary_for_chart(
State(state): St,
auth: AuthUser,
WithRejection(Path(id), _): IdPath,
) -> ApiResult<Json<Value>> {
let chart = owned_chart(&state.db, id, auth.id()).await?;
Ok(Json(ensure_summary(&state, &auth, &chart).await?.view()))
}
async fn list_where(db: &PgPool, column: &str, id: Uuid) -> Result<Json<Value>, ApiError> {
let rows: Vec<AnalysisRow> = sqlx::query_as(&format!(
"SELECT {ANALYSIS_COLUMNS} FROM analyses WHERE {column} = $1 ORDER BY created_at DESC"
))
.bind(id)
.fetch_all(db)
.await?;
Ok(Json(json!({ "analyses": rows.iter().map(AnalysisRow::view).collect::<Vec<_>>() })))
}
pub async fn list_for_chart(
State(state): St,
auth: AuthUser,
WithRejection(Path(id), _): IdPath,
) -> ApiResult<Json<Value>> {
owned_chart(&state.db, id, auth.id()).await?;
list_where(&state.db, "chart_id", id).await
}
pub async fn request_for_chart(
State(state): St,
auth: AuthUser,
WithRejection(Path(id), _): IdPath,
body: Bytes,
) -> ApiResult<(StatusCode, Json<Value>)> {
let chart = owned_chart(&state.db, id, auth.id()).await?;
let req = optional_body(&body)?;
request(&state, &auth, Target::Natal { chart_id: chart.id, hash: chart.chart_hash }, req).await
}
pub async fn list_for_synastry(
State(state): St,
auth: AuthUser,
WithRejection(Path(id), _): IdPath,
) -> ApiResult<Json<Value>> {
visible_synastry(&state.db, id, auth.id()).await?;
list_where(&state.db, "synastry_id", id).await
}
pub async fn request_for_synastry(
State(state): St,
auth: AuthUser,
WithRejection(Path(id), _): IdPath,
body: Bytes,
) -> ApiResult<(StatusCode, Json<Value>)> {
let s = visible_synastry(&state.db, id, auth.id()).await?;
let req = optional_body(&body)?;
let target = Target::Synastry { synastry_id: s.synastry.id, hash: s.synastry.synastry_hash };
request(&state, &auth, target, req).await
}
pub async fn get_one(State(state): St, auth: AuthUser, WithRejection(Path(id), _): IdPath) -> ApiResult<Json<Value>> {
let analysis = find_analysis(&state.db, id).await?.ok_or(ApiError::NotFound("analysis"))?;
if !can_see(&state.db, &analysis, auth.id()).await? {
return Err(ApiError::NotFound("analysis"));
}
Ok(Json(analysis.view()))
}