more refactoring

This commit is contained in:
pavel 2026-02-11 01:51:40 +01:00
commit ce5d2c9fb4
10 changed files with 251 additions and 39 deletions

View file

@ -4,9 +4,22 @@ mod entities;
mod error;
mod scheduler;
mod server;
#[cfg(test)]
mod tests;
use tracing::info;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
tracing_subscriber::fmt()
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| "bot=info,axum=info".into()),
)
.init();
info!("Starting Antigravity Agent...");
let config = config::Config::from_env()?;
server::start(config).await?;

View file

@ -1,6 +1,7 @@
use crate::domain::agent::Agent;
use crate::entities::task::Entity as Task;
use crate::entities::task_run;
use crate::error::{AppError, AppResult};
use dashmap::DashMap;
use sea_orm::{DatabaseConnection, EntityTrait, Set};
use std::sync::Arc;
@ -18,9 +19,14 @@ impl Scheduler {
pub async fn new(
db: DatabaseConnection,
config: Arc<crate::config::Config>,
) -> Result<Self, Box<dyn std::error::Error>> {
let scheduler = JobScheduler::new().await?;
scheduler.start().await?;
) -> AppResult<Self> {
let scheduler = JobScheduler::new()
.await
.map_err(|e| AppError::Internal(format!("Failed to create scheduler: {}", e)))?;
scheduler
.start()
.await
.map_err(|e| AppError::Internal(format!("Failed to start scheduler: {}", e)))?;
Ok(Self {
scheduler,
db,
@ -29,11 +35,7 @@ impl Scheduler {
})
}
pub async fn add_task_job(
&self,
task_id: Uuid,
cron_expr: &str,
) -> Result<(), Box<dyn std::error::Error>> {
pub async fn add_task_job(&self, task_id: Uuid, cron_expr: &str) -> AppResult<()> {
// Remove existing job if any
if let Some((_, old_job_id)) = self.tasks_to_jobs.remove(&task_id) {
let _ = self.scheduler.remove(&old_job_id).await;
@ -47,20 +49,28 @@ impl Scheduler {
let config = config.clone();
Box::pin(async move {
if let Err(e) = Self::run_task(db, config, task_id).await {
eprintln!("Error in scheduled task {}: {}", task_id, e);
tracing::error!("Error in scheduled task {}: {}", task_id, e);
}
})
})?;
})
.map_err(|e| AppError::Internal(format!("Failed to create job: {}", e)))?;
let job_id = self.scheduler.add(job).await?;
let job_id = self
.scheduler
.add(job)
.await
.map_err(|e| AppError::Internal(format!("Failed to add job: {}", e)))?;
self.tasks_to_jobs.insert(task_id, job_id);
Ok(())
}
pub async fn remove_task_job(&self, task_id: Uuid) -> Result<(), Box<dyn std::error::Error>> {
pub async fn remove_task_job(&self, task_id: Uuid) -> AppResult<()> {
if let Some((_, job_id)) = self.tasks_to_jobs.remove(&task_id) {
self.scheduler.remove(&job_id).await?;
self.scheduler
.remove(&job_id)
.await
.map_err(|e| AppError::Internal(format!("Failed to remove job: {}", e)))?;
}
Ok(())
}
@ -69,11 +79,12 @@ impl Scheduler {
db: DatabaseConnection,
config: Arc<crate::config::Config>,
task_id: Uuid,
) -> Result<(), Box<dyn std::error::Error>> {
) -> AppResult<()> {
let task = Task::find_by_id(task_id)
.one(&db)
.await?
.ok_or("Task not found")?;
.await
.map_err(AppError::Database)?
.ok_or_else(|| AppError::NotFound("Task not found".into()))?;
// Create a new run entry
let run_id = Uuid::new_v4();
@ -87,7 +98,7 @@ impl Scheduler {
};
use sea_orm::ActiveModelTrait;
run.insert(&db).await?;
run.insert(&db).await.map_err(AppError::Database)?;
// Start agent in background
let mut agent = Agent::new(
@ -114,9 +125,10 @@ impl Scheduler {
..Default::default()
};
if let Err(e) = run_complete.update(&db).await {
eprintln!(
tracing::error!(
"Failed to update scheduled run status for task {}: {}",
task_id, e
task_id,
e
);
}
});

View file

@ -63,7 +63,7 @@ pub async fn start(config: crate::config::Config) -> AppResult<()> {
let listener = tokio::net::TcpListener::bind(&addr)
.await
.map_err(|e| crate::error::AppError::Internal(e.to_string()))?;
println!("Server running on http://localhost:{}", config.port);
tracing::info!("Server running on http://localhost:{}", config.port);
axum::serve(listener, app)
.await
.map_err(|e| crate::error::AppError::Internal(e.to_string()))?;

View file

@ -55,11 +55,22 @@ pub async fn create_task(
State(state): State<Arc<AppState>>,
Json(payload): Json<CreateTaskRequest>,
) -> AppResult<Json<TaskResponse>> {
let task_id = Uuid::new_v4();
if payload.goal.trim().is_empty() {
return Err(crate::error::AppError::InvalidRequest(
"Goal cannot be empty".into(),
));
}
if payload.goal.trim().len() < 5 {
return Err(crate::error::AppError::InvalidRequest(
"Goal is too short (min 5 characters)".into(),
));
}
let task_id = Uuid::new_v4();
let new_task = crate::entities::task::ActiveModel {
id: sea_orm::Set(task_id),
goal: sea_orm::Set(payload.goal.clone()),
goal: sea_orm::Set(payload.goal),
cron: sea_orm::Set(payload.cron.clone()),
created_at: sea_orm::Set(chrono::Utc::now().into()),
};
@ -69,14 +80,9 @@ pub async fn create_task(
if let Some(cron) = &payload.cron {
let _ = state.scheduler.add_task_job(task_id, cron).await;
} else {
let _ = state.scheduler.remove_task_job(task_id).await;
}
tasks::get_task_inner(task_id, &state.db)
.await
.map(Json)
.map_err(|e| crate::error::AppError::Internal(e.to_string()))
tasks::get_task_inner(task_id, &state.db).await.map(Json)
}
pub async fn rerun_task(
@ -107,6 +113,18 @@ pub async fn update_task(
Path(id): Path<Uuid>,
Json(payload): Json<UpdateTaskRequest>,
) -> AppResult<Json<TaskResponse>> {
if payload.goal.trim().is_empty() {
return Err(crate::error::AppError::InvalidRequest(
"Goal cannot be empty".into(),
));
}
if payload.goal.trim().len() < 5 {
return Err(crate::error::AppError::InvalidRequest(
"Goal is too short (min 5 characters)".into(),
));
}
let task: crate::entities::task::ActiveModel = crate::entities::task::Entity::find_by_id(id)
.one(&state.db)
.await?
@ -114,7 +132,7 @@ pub async fn update_task(
.into();
let mut task = task;
task.goal = sea_orm::Set(payload.goal.clone());
task.goal = sea_orm::Set(payload.goal);
task.cron = sea_orm::Set(payload.cron.clone());
use sea_orm::ActiveModelTrait;
@ -126,10 +144,7 @@ pub async fn update_task(
let _ = state.scheduler.remove_task_job(id).await;
}
tasks::get_task_inner(id, &state.db)
.await
.map(Json)
.map_err(|e| crate::error::AppError::Internal(e.to_string()))
tasks::get_task_inner(id, &state.db).await.map(Json)
}
pub async fn get_task(

39
src/tests.rs Normal file
View file

@ -0,0 +1,39 @@
use crate::config::Config;
use crate::error::{AppError, AppResult};
use axum::http::StatusCode;
use axum::response::IntoResponse;
#[test]
fn test_app_error_into_response() {
let err = AppError::NotFound("Resource not found".into());
let response = err.into_response();
assert_eq!(response.status(), StatusCode::NOT_FOUND);
let err = AppError::Unauthorized("Invalid token".into());
let response = err.into_response();
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
let err = AppError::Internal("Server glitch".into());
let response = err.into_response();
assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
}
#[tokio::test]
async fn test_config_validation() {
// We can't easily clear all env vars in multi-threaded tests,
// but we can test that it fails if a required one is missing (if we can ensure it's missing)
// However, for this environment, it's safer to test the mapping logic if it was more complex.
// Instead, let's test a helper if we had one, or just verify AppResult works as expected.
let result: AppResult<Config> = Err(AppError::Config("Missing DATABASE_URL".into()));
assert!(result.is_err());
if let Err(AppError::Config(msg)) = result {
assert_eq!(msg, "Missing DATABASE_URL");
}
}
#[test]
fn test_error_variants() {
let err = AppError::InvalidRequest("Bad input".into());
assert!(err.to_string().contains("Bad input"));
}