use axum::{ Json, response::{IntoResponse, Response}, }; use reqwest::StatusCode; use serde_json::json; use tracing::error; #[derive(Debug)] pub(crate) enum XrpcError { InvalidRequest(String), RepoNotFound { detail: String }, RefNotFound { rev: String, detail: String }, RevisionNotFound { rev: String }, CompareError(String), FileNotFound { path: String }, BlameTooLarge, BlameTimeout, MergeConflict(Vec), PushRejected(String), Unauthorized(String), Internal(String), } impl IntoResponse for XrpcError { fn into_response(self) -> Response { let (status, error, message) = match self { Self::InvalidRequest(m) => (StatusCode::BAD_REQUEST, "InvalidRequest", m), Self::RepoNotFound { detail } => { error!(error = %detail, "repo not found"); ( StatusCode::NOT_FOUND, "RepoNotFound", "repository not found".to_owned(), ) } Self::RefNotFound { rev, detail } => { error!(error = %detail, rev = %rev, "revision not found"); ( StatusCode::NOT_FOUND, "RefNotFound", format!("revision not found: {rev}"), ) } Self::RevisionNotFound { rev } => ( StatusCode::NOT_FOUND, "RevisionNotFound", format!("commit not found: {rev}"), ), Self::CompareError(m) => { error!(error = %m, "compare failed"); ( StatusCode::INTERNAL_SERVER_ERROR, "CompareError", "failed to compare revisions".to_owned(), ) } Self::FileNotFound { path } => ( StatusCode::NOT_FOUND, "FileNotFound", format!("file not found: {path}"), ), Self::BlameTooLarge => ( StatusCode::PAYLOAD_TOO_LARGE, "BlameTooLarge", "blame exceeds resource limits".to_owned(), ), Self::BlameTimeout => ( StatusCode::GATEWAY_TIMEOUT, "BlameTimeout", "blame computation timed out".to_owned(), ), Self::MergeConflict(paths) => ( StatusCode::CONFLICT, "MergeConflict", format!("merge produced conflicts in {}", paths.join(", ")), ), Self::PushRejected(detail) => { error!(error = %detail, "push rejected"); ( StatusCode::CONFLICT, "PushRejected", "knot rejected the push".to_owned(), ) } Self::Unauthorized(detail) => { error!(error = %detail, "authentication failed"); (StatusCode::UNAUTHORIZED, "AuthenticationRequired", detail) } Self::Internal(m) => { error!(error = %m, "xrpc request failed"); ( StatusCode::INTERNAL_SERVER_ERROR, "InternalServerError", "internal error".to_owned(), ) } }; (status, Json(json!({ "error": error, "message": message }))).into_response() } } impl From for XrpcError { fn from(e: gitmirror_git::layout::Error) -> Self { match e { gitmirror_git::layout::Error::RepoNotFound => Self::RepoNotFound { detail: e.to_string(), }, _ => Self::Internal(e.to_string()), } } }