use std::collections::HashMap;
use std::sync::Arc;
use axum::Router;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use chrono::{DateTime, Utc};
use backbone_core::http::{ApiResponse, BackboneCrudHandler};
#[cfg(feature = "auth")]
use backbone_auth::middleware::AuthContext;
#[cfg(feature = "auth")]
use backbone_auth::AuthMiddleware;
use crate::domain::entity::*;
use crate::application::service::{FileLockService, ServiceError};
use crate::presentation::dto::{CreateFileLockDto, UpdateFileLockDto, PatchFileLockDto, FileLockResponseDto};
use crate::domain::state_machine::{FileLockState, FileLockStateMachine, FileLockTransition};
#[derive(Debug, thiserror::Error)]
pub enum FileLockError {
#[error("Not found: {0}")]
NotFound(String),
#[error("Validation error: {0}")]
Validation(String),
#[error("Database error: {0}")]
Database(String),
#[error("Internal error: {0}")]
Internal(String),
#[error("File must exist to be locked: {0}")]
FileNotFound(String),
#[error("Only active files can be locked: {0}")]
FileNotActive(String),
#[error("File is already locked by another user: {0}")]
FileAlreadyLocked(String),
#[error("Lock duration must be between 5 minutes and 24 hours: {0}")]
InvalidDuration(String),
#[error("Only lock owner can modify: {0}")]
NotLockOwner(String),
#[error("Cannot modify expired lock: {0}")]
LockExpired(String),
#[error("Can only refresh within 5 minutes of expiration: {0}")]
RefreshTooEarly(String),
}
impl From<ServiceError> for FileLockError {
fn from(err: ServiceError) -> Self {
match err {
ServiceError::NotFound => Self::NotFound(err.to_string()),
ServiceError::Validation(ref msg) => Self::Validation(msg.clone()),
ServiceError::AlreadyExists(ref msg) => Self::Validation(msg.clone()),
ServiceError::Repository(ref e) => Self::Database(e.to_string()),
ServiceError::Internal(ref msg) => Self::Internal(msg.clone()),
ServiceError::Violations(_) => Self::Validation(err.to_string()),
}
}
}
impl axum::response::IntoResponse for FileLockError {
fn into_response(self) -> axum::response::Response {
use axum::http::StatusCode;
use axum::Json;
let (status, code) = match &self {
Self::NotFound(_) => (StatusCode::NOT_FOUND, "FILELOCK_NOT_FOUND"),
Self::Validation(_) => (StatusCode::BAD_REQUEST, "FILELOCK_VALIDATION_ERROR"),
Self::Database(_) => (StatusCode::INTERNAL_SERVER_ERROR, "FILELOCK_DATABASE_ERROR"),
Self::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "FILELOCK_INTERNAL_ERROR"),
Self::FileNotFound(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILELOCK_FILE_NOT_FOUND"),
Self::FileNotActive(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILELOCK_FILE_NOT_ACTIVE"),
Self::FileAlreadyLocked(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILELOCK_FILE_ALREADY_LOCKED"),
Self::InvalidDuration(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILELOCK_INVALID_DURATION"),
Self::NotLockOwner(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILELOCK_NOT_LOCK_OWNER"),
Self::LockExpired(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILELOCK_LOCK_EXPIRED"),
Self::RefreshTooEarly(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILELOCK_REFRESH_TOO_EARLY"),
};
let body = serde_json::json!({
"success": false,
"error": code,
"message": self.to_string(),
});
(status, Json(body)).into_response()
}
}
pub mod file_lock_errors {
pub const FILE_NOT_FOUND: &str = "FILELOCK_FILE_NOT_FOUND";
pub const FILE_NOT_ACTIVE: &str = "FILELOCK_FILE_NOT_ACTIVE";
pub const FILE_ALREADY_LOCKED: &str = "FILELOCK_FILE_ALREADY_LOCKED";
pub const INVALID_DURATION: &str = "FILELOCK_INVALID_DURATION";
pub const NOT_LOCK_OWNER: &str = "FILELOCK_NOT_LOCK_OWNER";
pub const LOCK_EXPIRED: &str = "FILELOCK_LOCK_EXPIRED";
pub const REFRESH_TOO_EARLY: &str = "FILELOCK_REFRESH_TOO_EARLY";
}
pub fn create_file_lock_routes(service: Arc<FileLockService>) -> Router {
BackboneCrudHandler::<FileLockService, FileLock, CreateFileLockDto, UpdateFileLockDto, FileLockResponseDto>::routes(
service,
"/file_locks",
)
}
pub fn create_file_lock_read_routes(service: Arc<FileLockService>) -> Router {
BackboneCrudHandler::<FileLockService, FileLock, CreateFileLockDto, UpdateFileLockDto, FileLockResponseDto>::read_routes(
service,
"/file_locks",
)
}
pub fn create_file_lock_write_routes(service: Arc<FileLockService>) -> Router {
BackboneCrudHandler::<FileLockService, FileLock, CreateFileLockDto, UpdateFileLockDto, FileLockResponseDto>::write_routes(
service,
"/file_locks",
)
}
#[cfg(feature = "auth")]
pub fn create_protected_file_lock_routes<A: AuthMiddleware + Send + Sync + 'static>(
service: Arc<FileLockService>,
auth: Arc<A>,
) -> Router {
use axum::middleware;
use axum::response::IntoResponse;
let auth_layer = auth.clone();
create_file_lock_routes(service)
.layer(middleware::from_fn(move |mut req: axum::extract::Request, next: axum::middleware::Next| {
let auth = auth_layer.clone();
async move {
let token = req.headers()
.get(axum::http::header::AUTHORIZATION)
.and_then(|h| h.to_str().ok())
.and_then(|raw| raw.strip_prefix("Bearer ").or_else(|| raw.strip_prefix("bearer ")))
.unwrap_or("");
match auth.authenticate(token).await {
Ok(ctx) => {
req.extensions_mut().insert(ctx);
next.run(req).await
}
Err(_) => {
(axum::http::StatusCode::UNAUTHORIZED,
axum::Json(serde_json::json!({
"success": false,
"error": "unauthorized",
"message": "Authentication required"
}))
).into_response()
}
}
}
}))
}
pub async fn expire_transition(
axum::extract::State(service): axum::extract::State<Arc<FileLockService>>,
axum::extract::Path(id): axum::extract::Path<String>,
#[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
) -> impl axum::response::IntoResponse {
use axum::{http::StatusCode, Json};
let entity = match service.get_by_id(&id).await {
Ok(Some(e)) => e,
Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<FileLockResponseDto>::not_found("FileLock", &id))),
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileLockResponseDto>::error(e.to_string()))),
};
#[cfg(feature = "auth")]
{
let allowed_roles = FileLockTransition::Expire.allowed_roles();
let has_specific_perm = auth.permissions.iter().any(|p| p == "file_lock:transition:expire");
let has_update_perm = auth.permissions.iter().any(|p| p == "file_lock:update");
let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
if !has_specific_perm && !has_update_perm && !has_role {
return (StatusCode::FORBIDDEN, Json(ApiResponse::<FileLockResponseDto>::error("Insufficient permissions for expire transition")));
}
}
let current_state: FileLockState = entity.status.to_string().parse()
.unwrap_or(FileLockState::default());
let sm = FileLockStateMachine::from_state(current_state);
if !sm.can_transition(FileLockTransition::Expire) {
return (StatusCode::BAD_REQUEST, Json(ApiResponse::<FileLockResponseDto>::error("Transition not allowed from current state")));
}
let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
fields.insert("status".to_string(), serde_json::Value::String("Expired".to_string()));
match service.partial_update(&id, fields).await {
Ok(Some(updated)) => {
let response: FileLockResponseDto = updated.into();
(StatusCode::OK, Json(ApiResponse::ok(response)))
}
Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<FileLockResponseDto>::not_found("FileLock", &id))),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileLockResponseDto>::error(e.to_string()))),
}
}
pub async fn release_transition(
axum::extract::State(service): axum::extract::State<Arc<FileLockService>>,
axum::extract::Path(id): axum::extract::Path<String>,
#[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
) -> impl axum::response::IntoResponse {
use axum::{http::StatusCode, Json};
let entity = match service.get_by_id(&id).await {
Ok(Some(e)) => e,
Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<FileLockResponseDto>::not_found("FileLock", &id))),
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileLockResponseDto>::error(e.to_string()))),
};
#[cfg(feature = "auth")]
{
let allowed_roles = FileLockTransition::Release.allowed_roles();
let has_specific_perm = auth.permissions.iter().any(|p| p == "file_lock:transition:release");
let has_update_perm = auth.permissions.iter().any(|p| p == "file_lock:update");
let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
if !has_specific_perm && !has_update_perm && !has_role {
return (StatusCode::FORBIDDEN, Json(ApiResponse::<FileLockResponseDto>::error("Insufficient permissions for release transition")));
}
}
let current_state: FileLockState = entity.status.to_string().parse()
.unwrap_or(FileLockState::default());
let sm = FileLockStateMachine::from_state(current_state);
if !sm.can_transition(FileLockTransition::Release) {
return (StatusCode::BAD_REQUEST, Json(ApiResponse::<FileLockResponseDto>::error("Transition not allowed from current state")));
}
let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
fields.insert("status".to_string(), serde_json::Value::String("Released".to_string()));
match service.partial_update(&id, fields).await {
Ok(Some(updated)) => {
let response: FileLockResponseDto = updated.into();
(StatusCode::OK, Json(ApiResponse::ok(response)))
}
Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<FileLockResponseDto>::not_found("FileLock", &id))),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileLockResponseDto>::error(e.to_string()))),
}
}
pub async fn refresh_transition(
axum::extract::State(service): axum::extract::State<Arc<FileLockService>>,
axum::extract::Path(id): axum::extract::Path<String>,
#[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
) -> impl axum::response::IntoResponse {
use axum::{http::StatusCode, Json};
let entity = match service.get_by_id(&id).await {
Ok(Some(e)) => e,
Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<FileLockResponseDto>::not_found("FileLock", &id))),
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileLockResponseDto>::error(e.to_string()))),
};
#[cfg(feature = "auth")]
{
let allowed_roles = FileLockTransition::Refresh.allowed_roles();
let has_specific_perm = auth.permissions.iter().any(|p| p == "file_lock:transition:refresh");
let has_update_perm = auth.permissions.iter().any(|p| p == "file_lock:update");
let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
if !has_specific_perm && !has_update_perm && !has_role {
return (StatusCode::FORBIDDEN, Json(ApiResponse::<FileLockResponseDto>::error("Insufficient permissions for refresh transition")));
}
}
let current_state: FileLockState = entity.status.to_string().parse()
.unwrap_or(FileLockState::default());
let sm = FileLockStateMachine::from_state(current_state);
if !sm.can_transition(FileLockTransition::Refresh) {
return (StatusCode::BAD_REQUEST, Json(ApiResponse::<FileLockResponseDto>::error("Transition not allowed from current state")));
}
let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
fields.insert("status".to_string(), serde_json::Value::String("Active".to_string()));
match service.partial_update(&id, fields).await {
Ok(Some(updated)) => {
let response: FileLockResponseDto = updated.into();
(StatusCode::OK, Json(ApiResponse::ok(response)))
}
Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<FileLockResponseDto>::not_found("FileLock", &id))),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileLockResponseDto>::error(e.to_string()))),
}
}
pub fn create_file_lock_transition_routes(service: Arc<FileLockService>) -> Router {
use axum::routing::post;
Router::new()
.route("/file_locks/:id/transitions/expire", post(expire_transition))
.route("/file_locks/:id/transitions/release", post(release_transition))
.route("/file_locks/:id/transitions/refresh", post(refresh_transition))
.with_state(service)
}