use std::sync::Arc;
use axum::Json;
use axum::extract::State;
use axum::http::StatusCode;
use axum::response::IntoResponse;
use serde::Deserialize;
use super::internal_error;
use crate::AppState;
use crate::maintenance::{DrainRequest, RepairRequest, run_repair};
#[derive(Deserialize, Default)]
pub(super) struct RepairBody {
#[serde(default)]
dry_run: bool,
}
pub(super) async fn maintenance_repair(
State(state): State<Arc<AppState>>,
body: Option<Json<RepairBody>>,
) -> impl IntoResponse {
let dry_run = body.map(|Json(b)| b.dry_run).unwrap_or(false);
let result = tokio::task::spawn_blocking(move || match &state.repair_tx {
Some(tx) => {
let (reply_tx, reply_rx) = std::sync::mpsc::channel();
tx.send(DrainRequest::Repair(RepairRequest {
dry_run,
reply: reply_tx,
}))
.map_err(|_| anyhow::anyhow!("the index drain thread is not running"))?;
reply_rx
.recv_timeout(std::time::Duration::from_secs(3600))
.map_err(|e| anyhow::anyhow!("waiting for the drain thread: {e}"))?
}
None => {
let summary = run_repair(&state.sqlite, None, state.embedder.as_deref(), dry_run)?;
if !dry_run {
let mut guard = match state.maintenance.write() {
Ok(g) => g,
Err(poisoned) => poisoned.into_inner(),
};
*guard = Some(summary.clone());
}
Ok(summary)
}
})
.await;
match result {
Ok(Ok(summary)) => Json(summary).into_response(),
Ok(Err(e)) => internal_error(e),
Err(e) => internal_error(e),
}
}
pub(super) async fn maintenance_vacuum(State(state): State<Arc<AppState>>) -> impl IntoResponse {
let result = tokio::task::spawn_blocking(move || {
crate::store_compaction::vacuum(&state.sqlite, &state.gate, &state.health)
})
.await;
match result {
Ok(Ok((before, after))) => Json(serde_json::json!({
"bytes_before": before,
"bytes_after": after,
}))
.into_response(),
Ok(Err(e)) => internal_error(e),
Err(e) => internal_error(e),
}
}
pub(super) async fn backfill_project_paths(
State(state): State<Arc<AppState>>,
) -> impl IntoResponse {
let store = state.store.clone();
let result = tokio::task::spawn_blocking(move || store.backfill_project_paths()).await;
match result {
Ok(Ok(count)) => Json(serde_json::json!({"backfilled": count})).into_response(),
Ok(Err(e)) => (
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({"error": e.to_string()})),
)
.into_response(),
Err(e) => (
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({"error": e.to_string()})),
)
.into_response(),
}
}