use axum::{
extract::{Path, Query, State},
http::StatusCode,
response::IntoResponse,
Json,
};
use chrono::{DateTime, Utc};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::HashSet;
use std::time::Duration;
use crate::{
error::AppError,
git,
hooks::HookJob,
order, reserved,
routes::AuthorRequest,
seek::{SeekBody, SeekFilter, SeekOptions},
state::AppState,
util::{run_blocking, run_tenant_read},
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 file_paths: 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 implicit_order_default_index: Option<i64>,
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>,
pub include: Option<BatchReadIncludeBody>,
}
#[derive(Default, Deserialize)]
pub struct BatchReadIncludeBody {
pub updated_at: Option<bool>,
pub created_at: Option<bool>,
}
#[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 ReadFileQuery {
pub seek_from_line_starts_with: Option<String>,
pub seek_to_line_starts_with: Option<String>,
pub seek_lines_maximum: Option<usize>,
pub include_updated_at: Option<bool>,
pub include_created_at: Option<bool>,
}
#[derive(Serialize)]
struct ReadFileResponse {
path: String,
content: String,
position: i64,
#[serde(skip_serializing_if = "Option::is_none")]
updated_at: Option<Option<DateTime<Utc>>>,
#[serde(skip_serializing_if = "Option::is_none")]
created_at: Option<Option<DateTime<Utc>>>,
}
#[derive(Serialize)]
struct BatchReadFileResponse {
path: String,
content: String,
#[serde(skip_serializing_if = "Option::is_none")]
updated_at: Option<Option<DateTime<Utc>>>,
#[serde(skip_serializing_if = "Option::is_none")]
created_at: Option<Option<DateTime<Utc>>>,
}
#[derive(Serialize)]
struct BatchReadFilesResponse {
files: Vec<Option<BatchReadFileResponse>>,
}
#[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>,
}
#[derive(Deserialize)]
pub struct ReorderFileRequest {
pub author: AuthorRequest,
pub position: i64,
pub implicit_order_default_index: Option<i64>,
pub implicit_allow_hidden_files: Option<bool>,
pub message: Option<String>,
pub allow_prefix_path: 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_file_paths(raw: &str) -> Result<Vec<String>, AppError> {
let paths = if raw.trim_start().starts_with('[') {
serde_json::from_str::<Vec<String>>(raw).map_err(|_err| AppError::InvalidOperation {
reason:
"file_paths must be a string or a JSON array of strings, e.g. [\"intro.md\", \"docs/setup.md\"]"
.to_string(),
})?
} else {
vec![raw.to_string()]
};
if paths.is_empty() {
return Err(AppError::InvalidOperation {
reason: "file_paths must contain at least one path".to_string(),
});
}
paths
.iter()
.map(|path| validate::file_or_folder_path(path).map(str::to_string))
.collect()
}
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>,
budget: Option<Duration>,
) -> 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,
budget,
}))
}
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()?;
if query.file_name_starts_with.is_some() && query.file_paths.is_some() {
return Err(AppError::InvalidOperation {
reason: "file_name_starts_with and file_paths must not be combined".to_string(),
});
}
let file_paths: Option<Vec<String>> = query
.file_paths
.as_deref()
.map(parse_file_paths)
.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(),
match state.config.limits.date_filter_maximum_ms {
0 => None,
maximum => Some(Duration::from_millis(maximum)),
},
)?;
let order_options: Option<git::OrderOptions> = query
.apply_order_index
.unwrap_or(false)
.then_some(git::OrderOptions {
implicit_default_index: query.implicit_order_default_index,
});
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, file_paths = ?file_paths, date_filter = ?date_filter, order_options = ?order_options, 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 listing = run_tenant_read(&repo_path.clone(), &tenant_id, 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(),
file_paths.as_deref(),
date_filter,
order_options,
page,
per_page,
)
})
.await?;
tracing::debug!(tenant_id = %tenant_id, page = page, returned = listing.nodes.len(), has_more = listing.has_more, partial = listing.partial, "list files tree response ready");
Ok(Json(json!({
"page": page,
"per_page": per_page,
"has_more": listing.has_more,
"partial": listing.partial,
"files": listing.nodes,
})))
}
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_tenant_read(&repo_path.clone(), &tenant_id, 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(query): Query<ReadFileQuery>,
) -> 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 = SeekOptions {
seek_from_line_starts_with: query.seek_from_line_starts_with,
seek_to_line_starts_with: query.seek_to_line_starts_with,
seek_lines_maximum: query.seek_lines_maximum,
}
.parse()?;
let dates = git::FileDateOptions {
updated: query.include_updated_at.unwrap_or(false),
created: query.include_created_at.unwrap_or(false),
};
tracing::debug!(collection_id = %collection_id, tenant_id = %tenant_id, path = %file_path, seek = ?seek, dates = ?dates, "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 file = run_tenant_read(&repo_path.clone(), &tenant_id, move || {
git::GitFiles::read_file(
&repo_path,
&tenant_id_for_task,
&file_path_for_task,
&seek,
dates,
)
})
.await?;
Ok(Json(ReadFileResponse {
path: file_path,
content: file.content,
position: file.position,
updated_at: dates.updated.then_some(file.updated_at),
created_at: dates.created.then_some(file.created_at),
}))
}
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));
}
let include = body.include.unwrap_or_default();
let dates = git::FileDateOptions {
updated: include.updated_at.unwrap_or(false),
created: include.created_at.unwrap_or(false),
};
tracing::debug!(collection_id = %collection_id, tenant_id = %tenant_id, count = file_reads.len(), seek = ?global_seek, dates = ?dates, "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 tenant_id_for_task = tenant_id.clone();
let contents = run_tenant_read(&repo_path.clone(), &tenant_id, move || {
git::GitFiles::batch_read_files(
&repo_path,
&tenant_id_for_task,
&file_reads_for_task,
dates,
)
})
.await?;
let files: Vec<Option<BatchReadFileResponse>> = file_reads
.into_iter()
.zip(contents)
.map(|((path, _seek), read)| {
read.map(|(content, found)| BatchReadFileResponse {
path,
content,
updated_at: dates.updated.then_some(found.updated_at),
created_at: dates.created.then_some(found.created_at),
})
})
.collect();
Ok(Json(BatchReadFilesResponse { 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 tenant_id_for_task = tenant_id.clone();
let kind = run_tenant_read(&repo_path.clone(), &tenant_id, move || {
git::GitFiles::path_kind(&repo_path, &tenant_id_for_task, &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 checkout_files = state.config.server.checkout_files;
let (commit_sha, file_change) = run_blocking(move || {
git::GitFiles::write_file(
&repo_path,
&file_path,
&content,
message.as_deref(),
&author.name,
&author.email,
checkout_files,
)
})
.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
.replication
.repository_updated(&collection_id, &tenant_id, &commit_sha);
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 checkout_files = state.config.server.checkout_files;
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,
checkout_files,
)
})
.await?
} else {
run_blocking(move || {
git::GitFiles::delete_file(
&repo_path,
&tenant_id_for_task,
&file_path,
message.as_deref(),
&author.name,
&author.email,
checkout_files,
)
})
.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
.replication
.repository_updated(&collection_id, &tenant_id, &commit_sha);
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 post_file(
State(state): State<AppState>,
Path((collection_id, tenant_id, raw_path)): Path<(String, String, String)>,
Json(body): Json<Value>,
) -> Result<(StatusCode, Json<Value>), AppError> {
if let Some(from_path_raw) = raw_path.strip_suffix("/move") {
return move_file(
state,
collection_id,
tenant_id,
from_path_raw,
parse_body(body)?,
)
.await;
}
if let Some(file_path_raw) = raw_path.strip_suffix("/reorder") {
return reorder_file(
state,
collection_id,
tenant_id,
file_path_raw,
parse_body(body)?,
)
.await;
}
Err(AppError::InvalidPath {
reason: "POST on a file path must end with /move or /reorder".to_string(),
})
}
fn parse_body<T: DeserializeOwned>(body: Value) -> Result<T, AppError> {
serde_json::from_value(body).map_err(|err| AppError::InvalidOperation {
reason: format!("invalid request body: {}", err),
})
}
async fn move_file(
state: AppState,
collection_id: String,
tenant_id: String,
from_path_raw: &str,
body: MoveFileRequest,
) -> 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 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 checkout_files = state.config.server.checkout_files;
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,
checkout_files,
)
})
.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,
checkout_files,
)
})
.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
.replication
.repository_updated(&collection_id, &tenant_id, &commit_sha);
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 }))))
}
async fn reorder_file(
state: AppState,
collection_id: String,
tenant_id: String,
entry_path_raw: &str,
body: ReorderFileRequest,
) -> 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 allow_prefix_path = body.allow_prefix_path.unwrap_or(false);
let entry_path = if allow_prefix_path {
validate::file_or_folder_path(entry_path_raw)?
} else {
validate::file_path(entry_path_raw)?
}
.to_string();
let position = match body.position {
position if position >= 0 => git::OrderPosition::At(position as usize),
order::UNLISTED_POSITION => git::OrderPosition::Unlisted,
position => {
return Err(AppError::InvalidOperation {
reason: format!(
"position must be zero or greater, or {} to drop the entry from the index: {}",
order::UNLISTED_POSITION,
position
),
})
}
};
let implicit_allow_hidden_files = body.implicit_allow_hidden_files.unwrap_or(false);
if matches!(position, git::OrderPosition::At(_))
&& !implicit_allow_hidden_files
&& order::is_hidden(reserved::split_parent(&entry_path).1)
{
return Err(AppError::InvalidOperation {
reason: format!(
"entry is a hidden file; set implicit_allow_hidden_files to give it a position: {}",
entry_path
),
});
}
tracing::debug!(collection_id = %collection_id, tenant_id = %tenant_id, path = %entry_path, position = ?position, implicit_order_default_index = ?body.implicit_order_default_index, implicit_allow_hidden_files = implicit_allow_hidden_files, allow_prefix_path = allow_prefix_path, "handling reorder 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 ReorderFileRequest {
author,
position: _,
implicit_order_default_index,
implicit_allow_hidden_files: _,
message,
allow_prefix_path: _,
} = body;
let repo_path_for_maintenance = repo_path.clone();
let tenant_id_for_task = tenant_id.clone();
let checkout_files = state.config.server.checkout_files;
let (commit_sha, change) = run_blocking(move || {
git::GitOrder::reorder_entry(
&repo_path,
&tenant_id_for_task,
&entry_path,
position,
implicit_order_default_index,
implicit_allow_hidden_files,
allow_prefix_path,
message.as_deref(),
&author.name,
&author.email,
checkout_files,
)
})
.await?;
let Some(change) = change else {
tracing::debug!(tenant_id = %tenant_id, sha = %commit_sha, "order unchanged, no commit created");
return Ok((StatusCode::OK, Json(json!({ "commit_sha": commit_sha }))));
};
tracing::debug!(tenant_id = %tenant_id, sha = %commit_sha, "order reorder committed, enqueuing hook delivery");
state
.replication
.repository_updated(&collection_id, &tenant_id, &commit_sha);
state.hook_queue.enqueue(
&lock_key,
HookJob::new(
collection_id,
tenant_id,
commit_sha.clone(),
Utc::now(),
vec![change],
),
);
state
.maintenance
.schedule(&lock_key, repo_path_for_maintenance, lock.clone());
Ok((StatusCode::OK, Json(json!({ "commit_sha": commit_sha }))))
}