use std::time::Duration;
use acton_service::agents::TaskStatus;
use acton_service::prelude::*;
async fn hello() -> &'static str {
"Hello from background-worker example!"
}
async fn start_task(
State(state): State<AppState>,
) -> std::result::Result<Json<serde_json::Value>, StatusCode> {
let worker = state
.background_worker()
.ok_or(StatusCode::SERVICE_UNAVAILABLE)?;
worker
.submit("handler-task", || async {
tracing::info!("Handler-submitted task running");
tokio::time::sleep(Duration::from_secs(2)).await;
tracing::info!("Handler-submitted task completed");
Ok(())
})
.await;
Ok(Json(serde_json::json!({ "status": "started" })))
}
async fn check_status(
State(state): State<AppState>,
Path(task_id): Path<String>,
) -> std::result::Result<Json<serde_json::Value>, StatusCode> {
let worker = state
.background_worker()
.ok_or(StatusCode::SERVICE_UNAVAILABLE)?;
let status = worker.get_task_status(&task_id).await;
let status_str = match &status {
TaskStatus::Pending => "pending",
TaskStatus::Running => "running",
TaskStatus::Completed => "completed",
TaskStatus::Failed(_) => "failed",
TaskStatus::Cancelled => "cancelled",
};
Ok(Json(
serde_json::json!({ "task_id": task_id, "status": status_str }),
))
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let routes = VersionedApiBuilder::new()
.add_version(ApiVersion::V1, |router| {
router
.route("/hello", get(hello))
.route("/tasks/start", post(start_task))
.route("/tasks/{task_id}/status", get(check_status))
})
.build_routes();
let service = ServiceBuilder::new().with_routes(routes).build();
if let Some(worker) = service.state().background_worker() {
worker
.submit("startup-cache-warm", || async {
tracing::info!("Warming caches at startup...");
tokio::time::sleep(Duration::from_secs(1)).await;
tracing::info!("Cache warming complete");
Ok(())
})
.await;
worker
.submit("startup-data-sync", || async {
tracing::info!("Syncing data at startup...");
tokio::time::sleep(Duration::from_secs(2)).await;
tracing::info!("Data sync complete");
Ok(())
})
.await;
tracing::info!("Submitted {} startup tasks", worker.task_count());
}
service.serve().await?;
Ok(())
}