use axum::{
http::StatusCode,
response::{IntoResponse, Response},
Json,
};
use serde::Serialize;
use std::sync::Arc;
use tracing::error;
use crate::{nsupdate::NsupdateExecutor, rndc::RndcExecutor};
#[derive(Clone)]
pub struct AppState {
pub rndc: Arc<RndcExecutor>,
pub nsupdate: Arc<NsupdateExecutor>,
pub zone_dir: String,
}
#[derive(Serialize)]
pub struct ErrorResponse {
pub error: String,
pub details: Option<String>,
}
#[derive(Debug, thiserror::Error)]
pub enum ApiError {
#[error("Zone file error: {0}")]
ZoneFileError(String),
#[error("RNDC command failed: {0}")]
RndcError(String),
#[error("Invalid request: {0}")]
InvalidRequest(String),
#[error("Zone not found: {0}")]
ZoneNotFound(String),
#[error("Zone already exists: {0}")]
ZoneAlreadyExists(String),
#[error("Internal server error: {0}")]
InternalError(String),
#[error("Dynamic updates not enabled: {0}")]
DynamicUpdatesNotEnabled(String),
#[error("nsupdate command failed: {0}")]
NsupdateError(String),
#[error("Invalid record: {0}")]
InvalidRecord(String),
}
const GENERIC_SERVER_ERROR: &str = "Internal server error";
impl IntoResponse for ApiError {
fn into_response(self) -> Response {
let (status, error_message) = match &self {
ApiError::InvalidRequest(_) => (StatusCode::BAD_REQUEST, self.to_string()),
ApiError::ZoneNotFound(_) => (StatusCode::NOT_FOUND, self.to_string()),
ApiError::ZoneAlreadyExists(_) => (StatusCode::CONFLICT, self.to_string()),
ApiError::DynamicUpdatesNotEnabled(_) => (StatusCode::BAD_REQUEST, self.to_string()),
ApiError::InvalidRecord(_) => (StatusCode::BAD_REQUEST, self.to_string()),
ApiError::ZoneFileError(_)
| ApiError::RndcError(_)
| ApiError::InternalError(_)
| ApiError::NsupdateError(_) => {
error!("returning 500 to client; internal error: {}", self);
(
StatusCode::INTERNAL_SERVER_ERROR,
GENERIC_SERVER_ERROR.to_string(),
)
}
};
let body = Json(ErrorResponse {
error: error_message,
details: None,
});
(status, body).into_response()
}
}