use axum::{
extract::{Path, Query, State},
http::StatusCode,
response::IntoResponse,
Json,
};
use chrono::{DateTime, Utc};
use serde::Deserialize;
use serde_json::json;
use std::collections::HashSet;
use crate::{
error::AppError,
git,
hooks::HookJob,
routes::AuthorRequest,
seek::{SeekBody, SeekFilter, SeekOptions},
state::AppState,
util::run_blocking,
validate,
};
#[derive(Deserialize)]
pub struct ListFilesQuery {
pub prefix_path: Option<String>,
pub maximum_depth: Option<u32>,
pub include_hidden_files: Option<bool>,
pub file_name_starts_with: Option<String>,
pub include_date_from: Option<String>,
pub include_date_to: Option<String>,
pub include_date_type: Option<String>,
pub apply_order_index: Option<bool>,
pub page: Option<usize>,
pub per_page: Option<usize>,
}
const DEFAULT_PER_PAGE: usize = 100;
const MAX_PER_PAGE: usize = 500;
#[derive(Deserialize)]
pub struct CountFilesQuery {
pub prefix_path: Option<String>,
pub maximum_depth: Option<u32>,
pub include_hidden_files: Option<bool>,
pub restrict_file_extensions: Option<String>,
}
#[derive(Deserialize)]
pub struct BatchReadFilesRequest {
pub files: Vec<BatchReadFileRequest>,
pub seek: Option<SeekBody>,
}
#[derive(Deserialize)]
#[serde(untagged)]
pub enum BatchReadFileRequest {
Path(String),
Options {
path: String,
seek: Option<SeekBody>,
},
}
impl BatchReadFileRequest {
fn parts(&self) -> (&str, Option<&SeekBody>) {
match self {
Self::Path(path) => (path, None),
Self::Options { path, seek } => (path, seek.as_ref()),
}
}
}
#[derive(Deserialize)]
pub struct FileExistsQuery {
pub check_prefix_path: Option<bool>,
}
#[derive(Deserialize)]
pub struct WriteFileRequest {
pub author: AuthorRequest,
pub content: String,
pub message: Option<String>,
}
#[derive(Deserialize)]
pub struct DeleteFileRequest {
pub author: AuthorRequest,
pub message: Option<String>,
pub allow_prefix_path_recurse: Option<bool>,
}
#[derive(Deserialize)]
pub struct MoveFileRequest {
pub author: AuthorRequest,
pub destination: String,
pub message: Option<String>,
pub allow_prefix_path_recurse: Option<bool>,
}
fn parse_file_name_prefixes(raw: &str) -> Result<Vec<String>, AppError> {
let prefixes = if raw.trim_start().starts_with('[') {
serde_json::from_str::<Vec<String>>(raw).map_err(|_err| AppError::InvalidOperation {
reason:
"file_name_starts_with must be a string or a JSON array of strings, e.g. [\"intro\", \"readme\"]"
.to_string(),
})?
} else {
vec![raw.to_string()]
};
if prefixes.is_empty() {
return Err(AppError::InvalidOperation {
reason: "file_name_starts_with must contain at least one prefix".to_string(),
});
}
if prefixes.iter().any(|prefix| prefix.is_empty()) {
return Err(AppError::InvalidOperation {
reason: "file_name_starts_with must not be empty".to_string(),
});
}
Ok(prefixes)
}
fn parse_rfc3339(raw: &str, parameter: &str) -> Result<DateTime<Utc>, AppError> {
DateTime::parse_from_rfc3339(raw)
.map(|date_time| date_time.with_timezone(&Utc))
.map_err(|_err| AppError::InvalidOperation {
reason: format!(
"{} must be an RFC 3339 date-time, e.g. 2026-06-16T10:00:00Z",
parameter
),
})
}
fn parse_date_filter(
from: Option<&str>,
to: Option<&str>,
date_type: Option<&str>,
) -> Result<Option<git::DateFilter>, AppError> {
let kind = match date_type {
None | Some("updated") => git::DateKind::Updated,
Some("created") => git::DateKind::Created,
Some(other) => {
return Err(AppError::InvalidOperation {
reason: format!(
"include_date_type must be 'updated' or 'created': {}",
other
),
})
}
};
let from = from
.map(|raw| parse_rfc3339(raw, "include_date_from"))
.transpose()?;
let to = to
.map(|raw| parse_rfc3339(raw, "include_date_to"))
.transpose()?;
if from.is_none() && to.is_none() {
return Ok(None);
}
if let (Some(from), Some(to)) = (from, to) {
if from >= to {
return Err(AppError::InvalidOperation {
reason: "include_date_from must be strictly before include_date_to".to_string(),
});
}
}
Ok(Some(git::DateFilter { from, to, kind }))
}
pub async fn list_files(
State(state): State<AppState>,
Path((collection_id, tenant_id)): Path<(String, String)>,
Query(query): Query<ListFilesQuery>,
) -> Result<impl IntoResponse, AppError> {
let collection_id = validate::collection_id(&collection_id)?.to_string();
let tenant_id = validate::tenant_id(&tenant_id)?.to_string();
let path_prefix: Option<String> = query
.prefix_path
.as_deref()
.map(validate::folder_path)
.transpose()?
.filter(|p| !p.is_empty())
.map(|p| p.to_string());
let maximum_depth: Option<usize> = match query.maximum_depth {
Some(0) => {
return Err(AppError::InvalidOperation {
reason: "maximum_depth must be at least 1".to_string(),
})
}
Some(d) => Some(d as usize),
None => None,
};
let include_hidden_files = query.include_hidden_files.unwrap_or(false);
let file_name_starts_with: Option<Vec<String>> = query
.file_name_starts_with
.as_deref()
.map(parse_file_name_prefixes)
.transpose()?;
let date_filter = parse_date_filter(
query.include_date_from.as_deref(),
query.include_date_to.as_deref(),
query.include_date_type.as_deref(),
)?;
let apply_order_index = query.apply_order_index.unwrap_or(false);
let page = query.page.unwrap_or(1).max(1);
let per_page = query
.per_page
.unwrap_or(DEFAULT_PER_PAGE)
.clamp(1, MAX_PER_PAGE);
tracing::debug!(collection_id = %collection_id, tenant_id = %tenant_id, path_prefix = ?path_prefix, maximum_depth = ?maximum_depth, include_hidden_files = include_hidden_files, file_name_starts_with = ?file_name_starts_with, date_filter = ?date_filter, apply_order_index = apply_order_index, page = page, per_page = per_page, "handling list files request");
let repo_path = state
.config
.server
.repos_path
.join(&collection_id)
.join(&tenant_id);
let tenant_id_for_task = tenant_id.clone();
let (tree, has_more) = run_blocking(move || {
git::GitFiles::list_files(
&repo_path,
&tenant_id_for_task,
path_prefix.as_deref(),
maximum_depth,
include_hidden_files,
file_name_starts_with.as_deref(),
date_filter,
apply_order_index,
page,
per_page,
)
})
.await?;
tracing::debug!(tenant_id = %tenant_id, page = page, returned = tree.len(), has_more = has_more, "list files tree response ready");
Ok(Json(json!({
"page": page,
"per_page": per_page,
"has_more": has_more,
"files": tree,
})))
}
pub async fn count_files(
State(state): State<AppState>,
Path((collection_id, tenant_id)): Path<(String, String)>,
Query(query): Query<CountFilesQuery>,
) -> Result<impl IntoResponse, AppError> {
let collection_id = validate::collection_id(&collection_id)?.to_string();
let tenant_id = validate::tenant_id(&tenant_id)?.to_string();
let path_prefix: Option<String> = query
.prefix_path
.as_deref()
.map(validate::folder_path)
.transpose()?
.filter(|p| !p.is_empty())
.map(|p| p.to_string());
let maximum_depth: Option<usize> = match query.maximum_depth {
Some(0) => {
return Err(AppError::InvalidOperation {
reason: "maximum_depth must be at least 1".to_string(),
})
}
Some(d) => Some(d as usize),
None => None,
};
let include_hidden_files = query.include_hidden_files.unwrap_or(false);
let restrict_file_extensions: Option<Vec<String>> = query
.restrict_file_extensions
.as_deref()
.map(parse_restrict_file_extensions)
.transpose()?;
tracing::debug!(collection_id = %collection_id, tenant_id = %tenant_id, path_prefix = ?path_prefix, maximum_depth = ?maximum_depth, include_hidden_files = include_hidden_files, restrict_file_extensions = ?restrict_file_extensions, "handling count files request");
let repo_path = state
.config
.server
.repos_path
.join(&collection_id)
.join(&tenant_id);
let tenant_id_for_task = tenant_id.clone();
let counts = run_blocking(move || {
git::GitFiles::count_files(
&repo_path,
&tenant_id_for_task,
path_prefix.as_deref(),
maximum_depth,
include_hidden_files,
restrict_file_extensions.as_deref(),
)
})
.await?;
tracing::debug!(tenant_id = %tenant_id, files = counts.files, directories = counts.directories, "count files response ready");
Ok(Json(json!({
"files": counts.files,
"directories": counts.directories,
})))
}
fn parse_restrict_file_extensions(raw: &str) -> Result<Vec<String>, AppError> {
let extensions: Vec<String> =
serde_json::from_str(raw).map_err(|_err| AppError::InvalidOperation {
reason:
"restrict_file_extensions must be a JSON array of strings, e.g. [\"md\", \"mdx\"]"
.to_string(),
})?;
if extensions.is_empty() {
return Err(AppError::InvalidOperation {
reason: "restrict_file_extensions must contain at least one extension".to_string(),
});
}
let normalized: Vec<String> = extensions
.iter()
.map(|extension| extension.trim_start_matches('.').to_string())
.collect();
if normalized.iter().any(|extension| extension.is_empty()) {
return Err(AppError::InvalidOperation {
reason: "restrict_file_extensions extensions must not be empty".to_string(),
});
}
Ok(normalized)
}
pub async fn read_file(
State(state): State<AppState>,
Path((collection_id, tenant_id, file_path)): Path<(String, String, String)>,
Query(seek): Query<SeekOptions>,
) -> Result<impl IntoResponse, AppError> {
let collection_id = validate::collection_id(&collection_id)?.to_string();
let tenant_id = validate::tenant_id(&tenant_id)?.to_string();
let file_path = validate::file_path(&file_path)?.to_string();
let seek = seek.parse()?;
tracing::debug!(collection_id = %collection_id, tenant_id = %tenant_id, path = %file_path, seek = ?seek, "handling read file request");
let repo_path = state
.config
.server
.repos_path
.join(&collection_id)
.join(&tenant_id);
let file_path_for_task = file_path.clone();
let tenant_id_for_task = tenant_id.clone();
let content = run_blocking(move || {
git::GitFiles::read_file(&repo_path, &tenant_id_for_task, &file_path_for_task, &seek)
})
.await?;
Ok(Json(json!({
"path": file_path,
"content": content,
})))
}
pub async fn batch_read_files(
State(state): State<AppState>,
Path((collection_id, tenant_id)): Path<(String, String)>,
Json(body): Json<BatchReadFilesRequest>,
) -> Result<impl IntoResponse, AppError> {
let collection_id = validate::collection_id(&collection_id)?.to_string();
let tenant_id = validate::tenant_id(&tenant_id)?.to_string();
if body.files.is_empty() {
return Err(AppError::InvalidOperation {
reason: "files must contain at least one path".to_string(),
});
}
let maximum_files = state.config.limits.batch_read_maximum_files;
if body.files.len() > maximum_files {
return Err(AppError::InvalidOperation {
reason: format!(
"files must not contain more than {} paths ({} requested)",
maximum_files,
body.files.len()
),
});
}
let global_seek = body.seek.unwrap_or_default().parse()?;
let mut seen_paths = HashSet::new();
let mut file_reads: Vec<(String, SeekFilter)> = Vec::with_capacity(body.files.len());
for (index, entry) in body.files.iter().enumerate() {
let (raw_path, entry_seek) = entry.parts();
let file_path = validate::file_path(raw_path)?.to_string();
if !seen_paths.insert(file_path.clone()) {
return Err(AppError::InvalidOperation {
reason: format!("files must be unique: '{}' is requested twice", file_path),
});
}
let seek = match entry_seek {
None => global_seek.clone(),
Some(entry_seek) => entry_seek.parse().map_err(|err| match err {
AppError::InvalidOperation { reason } => AppError::InvalidOperation {
reason: format!("files[{}]: {}", index, reason),
},
other => other,
})?,
};
file_reads.push((file_path, seek));
}
tracing::debug!(collection_id = %collection_id, tenant_id = %tenant_id, count = file_reads.len(), seek = ?global_seek, "handling batch read files request");
let repo_path = state
.config
.server
.repos_path
.join(&collection_id)
.join(&tenant_id);
let file_reads_for_task = file_reads.clone();
let contents = run_blocking(move || {
git::GitFiles::batch_read_files(&repo_path, &tenant_id, &file_reads_for_task)
})
.await?;
let files: Vec<_> = file_reads
.iter()
.zip(contents)
.map(|((path, _seek), content)| {
content.map(|content| json!({ "path": path, "content": content }))
})
.collect();
Ok(Json(json!({ "files": files })))
}
pub async fn file_exists(
State(state): State<AppState>,
Path((collection_id, tenant_id, file_path)): Path<(String, String, String)>,
Query(query): Query<FileExistsQuery>,
) -> Result<impl IntoResponse, AppError> {
let collection_id = validate::collection_id(&collection_id)?.to_string();
let tenant_id = validate::tenant_id(&tenant_id)?.to_string();
let check_prefix_path = query.check_prefix_path.unwrap_or(false);
let file_path = if check_prefix_path {
validate::file_or_folder_path(&file_path)?
} else {
validate::file_path(&file_path)?
}
.to_string();
tracing::debug!(collection_id = %collection_id, tenant_id = %tenant_id, path = %file_path, check_prefix_path = check_prefix_path, "handling file existence request");
let repo_path = state
.config
.server
.repos_path
.join(&collection_id)
.join(&tenant_id);
let file_path_for_task = file_path.clone();
let kind =
run_blocking(move || git::GitFiles::path_kind(&repo_path, &tenant_id, &file_path_for_task))
.await?;
match kind {
git::PathKind::File => Ok(StatusCode::OK),
git::PathKind::Directory if check_prefix_path => Ok(StatusCode::OK),
_ => Err(AppError::FileNotFound { path: file_path }),
}
}
pub async fn write_file(
State(state): State<AppState>,
Path((collection_id, tenant_id, file_path)): Path<(String, String, String)>,
Json(body): Json<WriteFileRequest>,
) -> Result<impl IntoResponse, AppError> {
let collection_id = validate::collection_id(&collection_id)?.to_string();
let tenant_id = validate::tenant_id(&tenant_id)?.to_string();
let file_path = validate::file_path(&file_path)?.to_string();
validate::file_extension(
&file_path,
state.config.limits.allowed_extensions.as_deref(),
)?;
tracing::debug!(collection_id = %collection_id, tenant_id = %tenant_id, path = %file_path, "handling write file 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 WriteFileRequest {
author,
content,
message,
} = body;
let repo_path_for_maintenance = repo_path.clone();
let (commit_sha, file_change) = run_blocking(move || {
git::GitFiles::write_file(
&repo_path,
&file_path,
&content,
message.as_deref(),
&author.name,
&author.email,
)
})
.await?;
let Some(file_change) = file_change else {
tracing::debug!(tenant_id = %tenant_id, sha = %commit_sha, "content unchanged, no commit created");
return Ok((StatusCode::OK, Json(json!({ "commit_sha": commit_sha }))));
};
tracing::debug!(tenant_id = %tenant_id, sha = %commit_sha, "file write committed, enqueuing hook delivery");
state.hook_queue.enqueue(
&lock_key,
HookJob::new(
collection_id,
tenant_id,
commit_sha.clone(),
Utc::now(),
vec![file_change],
),
);
state
.maintenance
.schedule(&lock_key, repo_path_for_maintenance, lock.clone());
Ok((StatusCode::OK, Json(json!({ "commit_sha": commit_sha }))))
}
pub async fn delete_file(
State(state): State<AppState>,
Path((collection_id, tenant_id, file_path)): Path<(String, String, String)>,
Json(body): Json<DeleteFileRequest>,
) -> Result<impl IntoResponse, AppError> {
let collection_id = validate::collection_id(&collection_id)?.to_string();
let tenant_id = validate::tenant_id(&tenant_id)?.to_string();
let allow_prefix_path_recurse = body.allow_prefix_path_recurse.unwrap_or(false);
let file_path = if allow_prefix_path_recurse {
validate::file_or_folder_path(&file_path)?
} else {
validate::file_path(&file_path)?
}
.to_string();
tracing::debug!(collection_id = %collection_id, tenant_id = %tenant_id, path = %file_path, allow_prefix_path_recurse = allow_prefix_path_recurse, "handling delete file 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 DeleteFileRequest {
author,
message,
allow_prefix_path_recurse: _,
} = body;
let repo_path_for_maintenance = repo_path.clone();
let recurse_directory = if allow_prefix_path_recurse {
let repo_path_for_kind = repo_path.clone();
let tenant_id_for_kind = tenant_id.clone();
let file_path_for_kind = file_path.clone();
let kind = run_blocking(move || {
git::GitFiles::path_kind(
&repo_path_for_kind,
&tenant_id_for_kind,
&file_path_for_kind,
)
})
.await?;
kind == git::PathKind::Directory
} else {
false
};
let tenant_id_for_task = tenant_id.clone();
let (commit_sha, file_changes) = if recurse_directory {
run_blocking(move || {
git::GitFiles::delete_directory(
&repo_path,
&tenant_id_for_task,
&file_path,
message.as_deref(),
&author.name,
&author.email,
)
})
.await?
} else {
run_blocking(move || {
git::GitFiles::delete_file(
&repo_path,
&tenant_id_for_task,
&file_path,
message.as_deref(),
&author.name,
&author.email,
)
})
.await?
};
if file_changes.is_empty() {
tracing::debug!(tenant_id = %tenant_id, sha = %commit_sha, "nothing to delete, no commit created");
return Ok((StatusCode::OK, Json(json!({ "commit_sha": commit_sha }))));
}
tracing::debug!(tenant_id = %tenant_id, sha = %commit_sha, file_count = file_changes.len(), "file deletion committed, enqueuing hook delivery");
state.hook_queue.enqueue(
&lock_key,
HookJob::new(
collection_id,
tenant_id,
commit_sha.clone(),
Utc::now(),
file_changes,
),
);
state
.maintenance
.schedule(&lock_key, repo_path_for_maintenance, lock.clone());
Ok((StatusCode::OK, Json(json!({ "commit_sha": commit_sha }))))
}
pub async fn move_file(
State(state): State<AppState>,
Path((collection_id, tenant_id, raw_path)): Path<(String, String, String)>,
Json(body): Json<MoveFileRequest>,
) -> Result<impl IntoResponse, AppError> {
let collection_id = validate::collection_id(&collection_id)?.to_string();
let tenant_id = validate::tenant_id(&tenant_id)?.to_string();
let from_path_raw = raw_path
.strip_suffix("/move")
.ok_or_else(|| AppError::InvalidPath {
reason: "POST on a file path must end with /move".to_string(),
})?;
let allow_prefix_path_recurse = body.allow_prefix_path_recurse.unwrap_or(false);
let (from_path, to_path) = if allow_prefix_path_recurse {
(
validate::file_or_folder_path(from_path_raw)?.to_string(),
validate::file_or_folder_path(&body.destination)?.to_string(),
)
} else {
(
validate::file_path(from_path_raw)?.to_string(),
validate::file_path(&body.destination)?.to_string(),
)
};
if !allow_prefix_path_recurse {
validate::file_extension(&to_path, state.config.limits.allowed_extensions.as_deref())?;
}
tracing::debug!(
collection_id = %collection_id,
tenant_id = %tenant_id,
from_path = %from_path,
to_path = %to_path,
allow_prefix_path_recurse = allow_prefix_path_recurse,
"handling move file 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 MoveFileRequest {
author,
destination: _,
message,
allow_prefix_path_recurse: _,
} = body;
let repo_path_for_maintenance = repo_path.clone();
let recurse_directory = if allow_prefix_path_recurse {
let repo_path_for_kind = repo_path.clone();
let tenant_id_for_kind = tenant_id.clone();
let from_path_for_kind = from_path.clone();
let kind = run_blocking(move || {
git::GitFiles::path_kind(
&repo_path_for_kind,
&tenant_id_for_kind,
&from_path_for_kind,
)
})
.await?;
kind == git::PathKind::Directory
} else {
false
};
if allow_prefix_path_recurse && !recurse_directory {
validate::file_extension(&to_path, state.config.limits.allowed_extensions.as_deref())?;
}
let tenant_id_for_task = tenant_id.clone();
let (commit_sha, file_changes) = if recurse_directory {
run_blocking(move || {
git::GitFiles::move_directory(
&repo_path,
&tenant_id_for_task,
&from_path,
&to_path,
message.as_deref(),
&author.name,
&author.email,
)
})
.await?
} else {
run_blocking(move || {
git::GitFiles::move_file(
&repo_path,
&tenant_id_for_task,
&from_path,
&to_path,
message.as_deref(),
&author.name,
&author.email,
)
})
.await?
};
if file_changes.is_empty() {
tracing::debug!(tenant_id = %tenant_id, sha = %commit_sha, "nothing to move, no commit created");
return Ok((StatusCode::OK, Json(json!({ "commit_sha": commit_sha }))));
}
tracing::debug!(tenant_id = %tenant_id, sha = %commit_sha, file_count = file_changes.len(), "file move committed, enqueuing hook delivery");
state.hook_queue.enqueue(
&lock_key,
HookJob::new(
collection_id,
tenant_id,
commit_sha.clone(),
Utc::now(),
file_changes,
),
);
state
.maintenance
.schedule(&lock_key, repo_path_for_maintenance, lock.clone());
Ok((StatusCode::OK, Json(json!({ "commit_sha": commit_sha }))))
}