backbone-bucket 0.3.0

Bucket Bounded Context: File Storage Module for Backbone Framework
Documentation
//! FileShare REST handlers
//!
//! Generated by metaphor-schema. Do not edit manually.
//!
//! Uses Axum and backbone-core's BackboneCrudHandler for all 12 CRUD endpoints.

use std::collections::HashMap;
use std::sync::Arc;

use axum::Router;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use chrono::{DateTime, Utc};

// Backbone framework imports
use backbone_core::http::{ApiResponse, BackboneCrudHandler};

// Auth integration (optional)
#[cfg(feature = "auth")]
use backbone_auth::middleware::AuthContext;
#[cfg(feature = "auth")]
use backbone_auth::AuthMiddleware;

// Domain imports
use crate::domain::entity::*;
use crate::application::service::{FileShareService, ServiceError};

// DTO imports
use crate::presentation::dto::{CreateFileShareDto, UpdateFileShareDto, PatchFileShareDto, FileShareResponseDto};

use crate::domain::state_machine::{FileShareState, FileShareStateMachine, FileShareTransition};

/// Application error type
#[derive(Debug, thiserror::Error)]
pub enum FileShareError {
    #[error("Not found: {0}")]
    NotFound(String),
    #[error("Validation error: {0}")]
    Validation(String),
    #[error("Database error: {0}")]
    Database(String),
    #[error("Internal error: {0}")]
    Internal(String),
    // Domain-specific errors from hook rules
    #[error("Share token must be 32-64 characters: {0}")]
    InvalidTokenLength(String),
    #[error("Share token must be alphanumeric: {0}")]
    InvalidTokenChars(String),
    #[error("Cannot share inactive or quarantined files: {0}")]
    FileNotActive(String),
    #[error("Only file owner can create shares: {0}")]
    NotFileOwner(String),
    #[error("Expiration date must be in the future: {0}")]
    ExpiredDate(String),
    #[error("Maximum downloads must be positive: {0}")]
    InvalidMaxDownloads(String),
    #[error("User shares must specify recipients: {0}")]
    MissingRecipients(String),
    #[error("Cannot modify inactive shares: {0}")]
    ShareInactive(String),
}

impl From<ServiceError> for FileShareError {
    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 FileShareError {
    fn into_response(self) -> axum::response::Response {
        use axum::http::StatusCode;
        use axum::Json;

        let (status, code) = match &self {
            Self::NotFound(_) => (StatusCode::NOT_FOUND, "FILESHARE_NOT_FOUND"),
            Self::Validation(_) => (StatusCode::BAD_REQUEST, "FILESHARE_VALIDATION_ERROR"),
            Self::Database(_) => (StatusCode::INTERNAL_SERVER_ERROR, "FILESHARE_DATABASE_ERROR"),
            Self::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "FILESHARE_INTERNAL_ERROR"),
            Self::InvalidTokenLength(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILESHARE_INVALID_TOKEN_LENGTH"),
            Self::InvalidTokenChars(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILESHARE_INVALID_TOKEN_CHARS"),
            Self::FileNotActive(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILESHARE_FILE_NOT_ACTIVE"),
            Self::NotFileOwner(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILESHARE_NOT_FILE_OWNER"),
            Self::ExpiredDate(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILESHARE_EXPIRED_DATE"),
            Self::InvalidMaxDownloads(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILESHARE_INVALID_MAX_DOWNLOADS"),
            Self::MissingRecipients(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILESHARE_MISSING_RECIPIENTS"),
            Self::ShareInactive(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILESHARE_SHARE_INACTIVE"),
        };

        let body = serde_json::json!({
            "success": false,
            "error": code,
            "message": self.to_string(),
        });

        (status, Json(body)).into_response()
    }
}

/// Domain-specific error codes for FileShare
pub mod file_share_errors {
    pub const INVALID_TOKEN_LENGTH: &str = "FILESHARE_INVALID_TOKEN_LENGTH";
    pub const INVALID_TOKEN_CHARS: &str = "FILESHARE_INVALID_TOKEN_CHARS";
    pub const FILE_NOT_ACTIVE: &str = "FILESHARE_FILE_NOT_ACTIVE";
    pub const NOT_FILE_OWNER: &str = "FILESHARE_NOT_FILE_OWNER";
    pub const EXPIRED_DATE: &str = "FILESHARE_EXPIRED_DATE";
    pub const INVALID_MAX_DOWNLOADS: &str = "FILESHARE_INVALID_MAX_DOWNLOADS";
    pub const MISSING_RECIPIENTS: &str = "FILESHARE_MISSING_RECIPIENTS";
    pub const SHARE_INACTIVE: &str = "FILESHARE_SHARE_INACTIVE";
}

// =============================================================================
// Route Configuration
// =============================================================================

/// Create Axum router with all 16 Backbone endpoints for FileShare.
///
/// # Routes
///
/// | Method | Path | Description |
/// |--------|------|-------------|
/// | GET | /file_shares | List with pagination |
/// | POST | /file_shares | Create new |
/// | GET | /file_shares/:id | Get by ID |
/// | PUT | /file_shares/:id | Full update |
/// | PATCH | /file_shares/:id | Partial update |
/// | DELETE | /file_shares/:id | Soft delete |
/// | POST | /file_shares/bulk | Bulk create |
/// | POST | /file_shares/upsert | Upsert |
/// | GET | /file_shares/trash | List deleted |
/// | POST | /file_shares/:id/restore | Restore |
/// | DELETE | /file_shares/empty | Empty trash |
/// | GET | /file_shares/:id/deleted | Get deleted by ID |
/// | DELETE | /file_shares/trash/:id | Permanent delete from trash |
/// | GET | /file_shares/count | Count active entities |
/// | GET | /file_shares/trash/count | Count deleted entities |
///
/// # Example
///
/// ```text
/// let service = Arc::new(FileShareService::with_repository(repository));
/// let router = create_file_share_routes(service);
/// ```
pub fn create_file_share_routes(service: Arc<FileShareService>) -> Router {
    BackboneCrudHandler::<FileShareService, FileShare, CreateFileShareDto, UpdateFileShareDto, FileShareResponseDto>::routes(
        service,
        "/file_shares",
    )
}

/// Create Axum router with only the read (GET) endpoints for FileShare.
///
/// Safe for public, unauthenticated exposure (e.g., reference data).
/// Mutations must be served separately via `create_file_share_write_routes`,
/// typically wrapped in an auth middleware layer.
pub fn create_file_share_read_routes(service: Arc<FileShareService>) -> Router {
    BackboneCrudHandler::<FileShareService, FileShare, CreateFileShareDto, UpdateFileShareDto, FileShareResponseDto>::read_routes(
        service,
        "/file_shares",
    )
}

/// Create Axum router with only the write (mutation) endpoints for FileShare.
///
/// These routes must NOT be publicly exposed. Wrap them with an auth
/// middleware before nesting into the application router.
///
/// # This is unguarded generic CRUD, not a validated write path
///
/// These are plain create/update/patch/delete mutations over the entity row —
/// they bypass all business invariants. If the module exposes a validated write
/// service (e.g. a command router over its domain engine), serve THAT instead
/// for any mutation that must respect domain rules.
pub fn create_file_share_write_routes(service: Arc<FileShareService>) -> Router {
    BackboneCrudHandler::<FileShareService, FileShare, CreateFileShareDto, UpdateFileShareDto, FileShareResponseDto>::write_routes(
        service,
        "/file_shares",
    )
}

/// Create authenticated routes with auth middleware.
///
/// Requires the `auth` feature flag. The `AuthMiddleware` implementation
/// is responsible for extracting and validating tokens, then providing
/// an `AuthContext` via request extensions.
#[cfg(feature = "auth")]
pub fn create_protected_file_share_routes<A: AuthMiddleware + Send + Sync + 'static>(
    service: Arc<FileShareService>,
    auth: Arc<A>,
) -> Router {
    use axum::middleware;
    use axum::response::IntoResponse;

    let auth_layer = auth.clone();
    create_file_share_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()
                    }
                }
            }
        }))
}

// =============================================================================
// State Transition Handlers
// =============================================================================

/// Execute expire transition on a FileShare.
///
/// POST /file_shares/:id/transitions/expire
pub async fn expire_transition(
    axum::extract::State(service): axum::extract::State<Arc<FileShareService>>,
    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};

    // Get current entity
    let entity = match service.get_by_id(&id).await {
        Ok(Some(e)) => e,
        Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<FileShareResponseDto>::not_found("FileShare", &id))),
        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileShareResponseDto>::error(e.to_string()))),
    };

    // Check permission (if auth enabled)
    #[cfg(feature = "auth")]
    {
        let allowed_roles = FileShareTransition::Expire.allowed_roles();
        let has_specific_perm = auth.permissions.iter().any(|p| p == "file_share:transition:expire");
        let has_update_perm = auth.permissions.iter().any(|p| p == "file_share: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::<FileShareResponseDto>::error("Insufficient permissions for expire transition")));
        }
    }

    // Create state machine from entity's actual status and validate transition
    let current_state: FileShareState = entity.status.to_string().parse()
        .unwrap_or(FileShareState::default());
    let sm = FileShareStateMachine::from_state(current_state);
    if !sm.can_transition(FileShareTransition::Expire) {
        return (StatusCode::BAD_REQUEST, Json(ApiResponse::<FileShareResponseDto>::error("Transition not allowed from current state")));
    }

    // Apply transition via partial update
    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: FileShareResponseDto = updated.into();
            (StatusCode::OK, Json(ApiResponse::ok(response)))
        }
        Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<FileShareResponseDto>::not_found("FileShare", &id))),
        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileShareResponseDto>::error(e.to_string()))),
    }
}

/// Execute exhaust transition on a FileShare.
///
/// POST /file_shares/:id/transitions/exhaust
pub async fn exhaust_transition(
    axum::extract::State(service): axum::extract::State<Arc<FileShareService>>,
    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};

    // Get current entity
    let entity = match service.get_by_id(&id).await {
        Ok(Some(e)) => e,
        Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<FileShareResponseDto>::not_found("FileShare", &id))),
        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileShareResponseDto>::error(e.to_string()))),
    };

    // Check permission (if auth enabled)
    #[cfg(feature = "auth")]
    {
        let allowed_roles = FileShareTransition::Exhaust.allowed_roles();
        let has_specific_perm = auth.permissions.iter().any(|p| p == "file_share:transition:exhaust");
        let has_update_perm = auth.permissions.iter().any(|p| p == "file_share: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::<FileShareResponseDto>::error("Insufficient permissions for exhaust transition")));
        }
    }

    // Create state machine from entity's actual status and validate transition
    let current_state: FileShareState = entity.status.to_string().parse()
        .unwrap_or(FileShareState::default());
    let sm = FileShareStateMachine::from_state(current_state);
    if !sm.can_transition(FileShareTransition::Exhaust) {
        return (StatusCode::BAD_REQUEST, Json(ApiResponse::<FileShareResponseDto>::error("Transition not allowed from current state")));
    }

    // Apply transition via partial update
    let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
    fields.insert("status".to_string(), serde_json::Value::String("Exhausted".to_string()));

    match service.partial_update(&id, fields).await {
        Ok(Some(updated)) => {
            let response: FileShareResponseDto = updated.into();
            (StatusCode::OK, Json(ApiResponse::ok(response)))
        }
        Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<FileShareResponseDto>::not_found("FileShare", &id))),
        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileShareResponseDto>::error(e.to_string()))),
    }
}

/// Execute revoke transition on a FileShare.
///
/// POST /file_shares/:id/transitions/revoke
pub async fn revoke_transition(
    axum::extract::State(service): axum::extract::State<Arc<FileShareService>>,
    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};

    // Get current entity
    let entity = match service.get_by_id(&id).await {
        Ok(Some(e)) => e,
        Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<FileShareResponseDto>::not_found("FileShare", &id))),
        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileShareResponseDto>::error(e.to_string()))),
    };

    // Check permission (if auth enabled)
    #[cfg(feature = "auth")]
    {
        let allowed_roles = FileShareTransition::Revoke.allowed_roles();
        let has_specific_perm = auth.permissions.iter().any(|p| p == "file_share:transition:revoke");
        let has_update_perm = auth.permissions.iter().any(|p| p == "file_share: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::<FileShareResponseDto>::error("Insufficient permissions for revoke transition")));
        }
    }

    // Create state machine from entity's actual status and validate transition
    let current_state: FileShareState = entity.status.to_string().parse()
        .unwrap_or(FileShareState::default());
    let sm = FileShareStateMachine::from_state(current_state);
    if !sm.can_transition(FileShareTransition::Revoke) {
        return (StatusCode::BAD_REQUEST, Json(ApiResponse::<FileShareResponseDto>::error("Transition not allowed from current state")));
    }

    // Apply transition via partial update
    let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
    fields.insert("status".to_string(), serde_json::Value::String("Revoked".to_string()));

    match service.partial_update(&id, fields).await {
        Ok(Some(updated)) => {
            let response: FileShareResponseDto = updated.into();
            (StatusCode::OK, Json(ApiResponse::ok(response)))
        }
        Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<FileShareResponseDto>::not_found("FileShare", &id))),
        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileShareResponseDto>::error(e.to_string()))),
    }
}

/// Create routes for state transitions.
pub fn create_file_share_transition_routes(service: Arc<FileShareService>) -> Router {
    use axum::routing::post;

    Router::new()
        .route("/file_shares/:id/transitions/expire", post(expire_transition))
        .route("/file_shares/:id/transitions/exhaust", post(exhaust_transition))
        .route("/file_shares/:id/transitions/revoke", post(revoke_transition))
        .with_state(service)
}