The platform for continuously improving AI agents.
use std::{
collections::HashMap,
path::{Path, PathBuf},
};
use serde::{Deserialize, Serialize};
use thiserror::Error;
use uuid::Uuid;
#[derive(Debug, Error)]
pub enum ControlPlaneError {
#[error("invalid argument: {0}")]
InvalidArgument(String),
#[error("unauthorized: {0}")]
Unauthorized(String),
#[error("forbidden: {0}")]
Forbidden(String),
#[error("not found: {0}")]
NotFound(String),
#[error("conflict: {0}")]
Conflict(String),
#[error("storage error: {0}")]
Storage(#[from] anyhow::Error),
}
pub type Result<T> = std::result::Result<T, ControlPlaneError>;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct User {
pub id: i64,
pub email: String,
pub is_guest: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Project {
pub id: Uuid,
pub slug: String,
pub name: String,
}
/// Mirrors a row of Django's `eval_matrix` table.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct PgEvalMatrixRow {
pub id: Uuid,
pub project_id: Uuid,
pub capability_id: Option<Uuid>,
pub name: String,
pub row_type: String,
pub source: String,
pub span_type: String,
pub span_name: String,
pub enabled: bool,
}
#[derive(Debug, Clone, Default)]
pub struct PgProjectEvalConfig {
pub enabled_rows: Vec<PgEvalMatrixRow>,
pub has_any_rows: bool,
pub capability_descriptions: HashMap<Uuid, String>,
}
/// A Django `APIToken` after the hash, expiry, IP and membership checks.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct VerifiedApiKey {
pub key_id: Uuid,
pub user_id: i64,
pub is_guest: bool,
/// `scope.scope == "account"`: every membership is reachable.
pub account_scoped: bool,
/// Memberships this key may act on. One entry for a project-scoped key.
pub project_ids: Vec<Uuid>,
pub can_read: bool,
pub can_write: bool,
}
pub fn new_project_id() -> String {
Uuid::new_v4().to_string()
}
/// Accepts any `Uuid::parse_str` form and returns the hyphenated lowercase id Django stores.
pub fn normalize_uuid(raw: &str) -> Result<Uuid> {
let trimmed = raw.trim();
Uuid::parse_str(trimmed)
.map_err(|_| ControlPlaneError::InvalidArgument(format!("invalid project id: {trimmed}")))
}
/// `<data_dir>/projects/<uuid>.duckdb`. Rejects anything that is not a UUID.
pub fn project_db_path(data_dir: impl AsRef<Path>, project_id: &str) -> Result<PathBuf> {
let id = normalize_uuid(project_id)?;
Ok(data_dir
.as_ref()
.join("projects")
.join(format!("{id}.duckdb")))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn uuid_path_rejects_traversal_and_canonicalises() {
let id = "550E8400-E29B-41D4-A716-446655440000";
let path = project_db_path("/data", id).unwrap();
assert_eq!(
path,
PathBuf::from("/data/projects/550e8400-e29b-41d4-a716-446655440000.duckdb")
);
assert!(project_db_path("/data", "../etc/passwd").is_err());
assert!(project_db_path("/data", "01ARZ3NDEKTSV4RRFFQ69G5FAV").is_err());
}
}