79 lines
2.5 KiB
Rust
79 lines
2.5 KiB
Rust
//! Credit ledger: every LLM call costs credits; users get a free monthly
|
|||
|
|
//! allowance, granted lazily on the first balance query or spend of a month.
|
||
|
|
|
||
|
|
use sqlx::{PgConnection, PgPool};
|
||
|
|
use time::OffsetDateTime;
|
||
|
|
use uuid::Uuid;
|
||
|
|
|
||
|
|
use crate::error::ApiError;
|
||
|
|
|
||
|
|
pub fn current_period() -> String {
|
||
|
|
let now = OffsetDateTime::now_utc();
|
||
|
|
format!("{:04}-{:02}", now.year(), u8::from(now.month()))
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Grants this month's free credits if not granted yet.
|
||
|
|
pub async fn ensure_monthly_grant(conn: &mut PgConnection, user_id: Uuid, amount: i32) -> Result<(), ApiError> {
|
||
|
|
if amount <= 0 {
|
||
|
|
return Ok(());
|
||
|
|
}
|
||
|
|
sqlx::query(
|
||
|
|
"INSERT INTO credit_ledger (id, user_id, delta, reason, period, note) \
|
||
|
|
VALUES ($1, $2, $3, 'monthly_grant', $4, 'monthly free credits') \
|
||
|
|
ON CONFLICT (user_id, period) WHERE reason = 'monthly_grant' DO NOTHING",
|
||
|
|
)
|
||
|
|
.bind(Uuid::now_v7())
|
||
|
|
.bind(user_id)
|
||
|
|
.bind(amount)
|
||
|
|
.bind(current_period())
|
||
|
|
.execute(conn)
|
||
|
|
.await?;
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
|
||
|
|
pub async fn balance_of(conn: &mut PgConnection, user_id: Uuid) -> Result<i64, ApiError> {
|
||
|
|
let (balance,): (i64,) =
|
||
|
|
sqlx::query_as("SELECT COALESCE(SUM(delta), 0)::bigint FROM credit_ledger WHERE user_id = $1")
|
||
|
|
.bind(user_id)
|
||
|
|
.fetch_one(conn)
|
||
|
|
.await?;
|
||
|
|
Ok(balance)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Current balance including this month's allowance.
|
||
|
|
pub async fn balance(pool: &PgPool, user_id: Uuid, monthly: i32) -> Result<i64, ApiError> {
|
||
|
|
let mut conn = pool.acquire().await?;
|
||
|
|
ensure_monthly_grant(&mut conn, user_id, monthly).await?;
|
||
|
|
balance_of(&mut conn, user_id).await
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Spends `cost` credits inside the caller's transaction. The user row is
|
||
|
|
/// locked so concurrent requests cannot overspend.
|
||
|
|
pub async fn spend(
|
||
|
|
tx: &mut PgConnection,
|
||
|
|
user_id: Uuid,
|
||
|
|
cost: i32,
|
||
|
|
monthly: i32,
|
||
|
|
reason: &str,
|
||
|
|
analysis_id: Option<Uuid>,
|
||
|
|
) -> Result<(), ApiError> {
|
||
|
|
if cost <= 0 {
|
||
|
|
return Ok(());
|
||
|
|
}
|
||
|
|
sqlx::query("SELECT id FROM users WHERE id = $1 FOR UPDATE").bind(user_id).execute(&mut *tx).await?;
|
||
|
|
ensure_monthly_grant(tx, user_id, monthly).await?;
|
||
|
|
let balance = balance_of(tx, user_id).await?;
|
||
|
|
if balance < i64::from(cost) {
|
||
|
|
return Err(ApiError::InsufficientCredits { needed: cost, balance });
|
||
|
|
}
|
||
|
|
sqlx::query("INSERT INTO credit_ledger (id, user_id, delta, reason, analysis_id) VALUES ($1, $2, $3, $4, $5)")
|
||
|
|
.bind(Uuid::now_v7())
|
||
|
|
.bind(user_id)
|
||
|
|
.bind(-cost)
|
||
|
|
.bind(reason)
|
||
|
|
.bind(analysis_id)
|
||
|
|
.execute(tx)
|
||
|
|
.await?;
|
||
|
|
Ok(())
|
||
|
|
}
|