use axum::{extract::Path as AxumPath, extract::State, http::StatusCode, Json};
use chrono::Utc;
use serde::Deserialize;
use serde_json::{json, Value};
use std::collections::HashSet;
use crate::{
error::AppError,
git,
hooks::{HookJob, ReplayJob, ReplayKind},
order,
state::AppState,
util::run_blocking,
validate,
};
const MAX_DELAY_MS: u64 = 60_000;
#[derive(Deserialize, Clone, Copy, Debug)]
#[serde(rename_all = "lowercase")]
pub enum ReplayDirection {
Delete,
Create,
}
impl ReplayDirection {
fn keeps_present(self) -> bool {
matches!(self, ReplayDirection::Create)
}
fn replay_kind(self) -> ReplayKind {
match self {
ReplayDirection::Delete => ReplayKind::Deleted,
ReplayDirection::Create => ReplayKind::Created,
}
}
}
#[derive(Deserialize)]
pub struct ReplayHookRequest {
direction: ReplayDirection,
#[serde(default)]
files: Option<Vec<String>>,
#[serde(default)]
prefix_path: Option<String>,
#[serde(default)]
include_hidden_files: bool,
#[serde(default)]
delay_ms: Option<u64>,
}
pub async fn replay_hook(
State(state): State<AppState>,
AxumPath((collection_id, tenant_id)): AxumPath<(String, String)>,
Json(body): Json<ReplayHookRequest>,
) -> Result<(StatusCode, Json<Value>), AppError> {
let collection_id = validate::collection_id(&collection_id)?.to_string();
let tenant_id = validate::tenant_id(&tenant_id)?.to_string();
let delay_ms = validate_delay(body.delay_ms)?;
let prefix_path = match &body.prefix_path {
Some(raw) => Some(validate::folder_path(raw)?.to_string()),
None => None,
};
let files = match &body.files {
Some(raw_files) => Some(sanitize_files(raw_files, prefix_path.as_deref())?),
None => None,
};
require_hook_receiver(&state)?;
let direction = body.direction;
tracing::debug!(collection_id = %collection_id, tenant_id = %tenant_id, direction = ?direction, given_count = ?files.as_ref().map(Vec::len), prefix_path = ?prefix_path, "handling hook replay request");
let repo_path = state
.config
.server
.repos_path
.join(&collection_id)
.join(&tenant_id);
let lock_key = format!("{}/{}", collection_id, tenant_id);
let lock = state.get_repo_lock(&lock_key);
let _lock_guard = lock.lock().await;
let repo_path_for_task = repo_path.clone();
let tenant_id_for_task = tenant_id.clone();
let prefix_for_task = prefix_path.clone();
let include_hidden_files = files.is_some() || body.include_hidden_files;
let (head_sha, present_paths) = run_blocking(move || {
git::GitFiles::list_all_file_paths(
&repo_path_for_task,
&tenant_id_for_task,
prefix_for_task.as_deref(),
include_hidden_files,
)
})
.await?;
let present: HashSet<&str> = present_paths.iter().map(String::as_str).collect();
let candidates: &[String] = files.as_deref().unwrap_or(&present_paths);
let keeps_present = direction.keeps_present();
let affected: Vec<String> = candidates
.iter()
.filter(|path| present.contains(path.as_str()) == keeps_present)
.cloned()
.collect();
let file_count = affected.len();
let scheduled = file_count > 0;
tracing::info!(collection_id = %collection_id, tenant_id = %tenant_id, direction = ?direction, candidate_count = candidates.len(), present_count = present.len(), file_count, "computed hook replay set");
if scheduled {
state.hook_queue.enqueue(
&lock_key,
HookJob::replay(
collection_id,
tenant_id,
head_sha.clone(),
Utc::now(),
ReplayJob {
repo_path,
kind: direction.replay_kind(),
paths: affected,
delay_ms,
},
),
);
}
Ok((
StatusCode::OK,
Json(json!({
"commit_sha": head_sha,
"files": file_count,
})),
))
}
fn require_hook_receiver(state: &AppState) -> Result<(), AppError> {
if state.config.hooks.is_none() {
return Err(AppError::InvalidOperation {
reason: "no webhook receiver is configured; a replay would deliver nothing".to_string(),
});
}
Ok(())
}
fn validate_delay(delay_ms: Option<u64>) -> Result<Option<u64>, AppError> {
if let Some(delay_ms) = delay_ms {
if delay_ms > MAX_DELAY_MS {
return Err(AppError::InvalidOperation {
reason: format!(
"delay_ms must not exceed {} milliseconds, got {}",
MAX_DELAY_MS, delay_ms
),
});
}
}
Ok(delay_ms)
}
fn sanitize_files(
raw_files: &[String],
prefix_path: Option<&str>,
) -> Result<Vec<String>, AppError> {
if raw_files.is_empty() {
return Err(AppError::InvalidOperation {
reason:
"files must contain at least one path; omit it entirely to default to every file"
.to_string(),
});
}
let mut sanitized: Vec<String> = Vec::with_capacity(raw_files.len());
let mut seen: HashSet<&str> = HashSet::with_capacity(raw_files.len());
for raw_file in raw_files {
let path = validate::file_path(raw_file)?;
if order::is_order_file(path) {
return Err(AppError::InvalidOperation {
reason: format!(
"files must not reference an order index: {}; file order is a separate resource under /order",
raw_file
),
});
}
if let Some(prefix) = prefix_path.filter(|prefix| !prefix.is_empty()) {
let inside = path
.strip_prefix(prefix)
.and_then(|rest| rest.strip_prefix('/'))
.is_some_and(|rest| !rest.is_empty());
if !inside {
return Err(AppError::InvalidOperation {
reason: format!(
"files entry '{}' must sit under prefix_path '{}'",
raw_file, prefix
),
});
}
}
if !seen.insert(path) {
return Err(AppError::InvalidOperation {
reason: format!("files must be unique: '{}' is listed twice", path),
});
}
sanitized.push(path.to_string());
}
Ok(sanitized)
}