Skip to main content

backbone_bucket/presentation/http/
bucket_handler.rs

1//! Bucket REST handlers
2//!
3//! Generated by metaphor-schema. Do not edit manually.
4//!
5//! Uses Axum and backbone-core's BackboneCrudHandler for all 12 CRUD endpoints.
6
7use std::collections::HashMap;
8use std::sync::Arc;
9
10use axum::Router;
11use serde::{Deserialize, Serialize};
12use uuid::Uuid;
13
14// Backbone framework imports
15use backbone_core::http::{ApiResponse, BackboneCrudHandler};
16
17// Auth integration (optional)
18#[cfg(feature = "auth")]
19use backbone_auth::middleware::AuthContext;
20#[cfg(feature = "auth")]
21use backbone_auth::AuthMiddleware;
22
23// Domain imports
24use crate::domain::entity::*;
25use crate::application::service::{BucketService, ServiceError};
26
27// DTO imports
28use crate::presentation::dto::{CreateBucketDto, UpdateBucketDto, PatchBucketDto, BucketResponseDto};
29
30use crate::domain::state_machine::{BucketState, BucketStateMachine, BucketTransition};
31
32/// Application error type
33#[derive(Debug, thiserror::Error)]
34pub enum BucketError {
35    #[error("Not found: {0}")]
36    NotFound(String),
37    #[error("Validation error: {0}")]
38    Validation(String),
39    #[error("Database error: {0}")]
40    Database(String),
41    #[error("Internal error: {0}")]
42    Internal(String),
43    // Domain-specific errors from hook rules
44    #[error("Bucket name must be 1-255 characters: {0}")]
45    InvalidNameLength(String),
46    #[error("Bucket name must contain only alphanumeric characters, underscores, and hyphens: {0}")]
47    InvalidNameChars(String),
48    #[error("Bucket slug must be 1-255 characters: {0}")]
49    InvalidSlugLength(String),
50    #[error("Bucket slug must be lowercase with hyphens only: {0}")]
51    InvalidSlugChars(String),
52    #[error("Root path too long: {0}")]
53    PathTooLong(String),
54    #[error("Path traversal not allowed in root path: {0}")]
55    PathTraversal(String),
56    #[error("Cannot modify deleted buckets: {0}")]
57    BucketDeleted(String),
58    #[error("Bucket slug is already taken: {0}")]
59    SlugExists(String),
60}
61
62impl From<ServiceError> for BucketError {
63    fn from(err: ServiceError) -> Self {
64        match err {
65            ServiceError::NotFound => Self::NotFound(err.to_string()),
66            ServiceError::Validation(ref msg) => Self::Validation(msg.clone()),
67            ServiceError::AlreadyExists(ref msg) => Self::Validation(msg.clone()),
68            ServiceError::Repository(ref e) => Self::Database(e.to_string()),
69            ServiceError::Internal(ref msg) => Self::Internal(msg.clone()),
70            ServiceError::Violations(_) => Self::Validation(err.to_string()),
71        }
72    }
73}
74
75impl axum::response::IntoResponse for BucketError {
76    fn into_response(self) -> axum::response::Response {
77        use axum::http::StatusCode;
78        use axum::Json;
79
80        let (status, code) = match &self {
81            Self::NotFound(_) => (StatusCode::NOT_FOUND, "BUCKET_NOT_FOUND"),
82            Self::Validation(_) => (StatusCode::BAD_REQUEST, "BUCKET_VALIDATION_ERROR"),
83            Self::Database(_) => (StatusCode::INTERNAL_SERVER_ERROR, "BUCKET_DATABASE_ERROR"),
84            Self::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "BUCKET_INTERNAL_ERROR"),
85            Self::InvalidNameLength(_) => (StatusCode::UNPROCESSABLE_ENTITY, "BUCKET_INVALID_NAME_LENGTH"),
86            Self::InvalidNameChars(_) => (StatusCode::UNPROCESSABLE_ENTITY, "BUCKET_INVALID_NAME_CHARS"),
87            Self::InvalidSlugLength(_) => (StatusCode::UNPROCESSABLE_ENTITY, "BUCKET_INVALID_SLUG_LENGTH"),
88            Self::InvalidSlugChars(_) => (StatusCode::UNPROCESSABLE_ENTITY, "BUCKET_INVALID_SLUG_CHARS"),
89            Self::PathTooLong(_) => (StatusCode::UNPROCESSABLE_ENTITY, "BUCKET_PATH_TOO_LONG"),
90            Self::PathTraversal(_) => (StatusCode::UNPROCESSABLE_ENTITY, "BUCKET_PATH_TRAVERSAL"),
91            Self::BucketDeleted(_) => (StatusCode::UNPROCESSABLE_ENTITY, "BUCKET_BUCKET_DELETED"),
92            Self::SlugExists(_) => (StatusCode::UNPROCESSABLE_ENTITY, "BUCKET_SLUG_EXISTS"),
93        };
94
95        let body = serde_json::json!({
96            "success": false,
97            "error": code,
98            "message": self.to_string(),
99        });
100
101        (status, Json(body)).into_response()
102    }
103}
104
105/// Domain-specific error codes for Bucket
106pub mod bucket_errors {
107    pub const INVALID_NAME_LENGTH: &str = "BUCKET_INVALID_NAME_LENGTH";
108    pub const INVALID_NAME_CHARS: &str = "BUCKET_INVALID_NAME_CHARS";
109    pub const INVALID_SLUG_LENGTH: &str = "BUCKET_INVALID_SLUG_LENGTH";
110    pub const INVALID_SLUG_CHARS: &str = "BUCKET_INVALID_SLUG_CHARS";
111    pub const PATH_TOO_LONG: &str = "BUCKET_PATH_TOO_LONG";
112    pub const PATH_TRAVERSAL: &str = "BUCKET_PATH_TRAVERSAL";
113    pub const BUCKET_DELETED: &str = "BUCKET_BUCKET_DELETED";
114    pub const SLUG_EXISTS: &str = "BUCKET_SLUG_EXISTS";
115}
116
117// =============================================================================
118// Route Configuration
119// =============================================================================
120
121/// Create Axum router with all 16 Backbone endpoints for Bucket.
122///
123/// # Routes
124///
125/// | Method | Path | Description |
126/// |--------|------|-------------|
127/// | GET | /buckets | List with pagination |
128/// | POST | /buckets | Create new |
129/// | GET | /buckets/:id | Get by ID |
130/// | PUT | /buckets/:id | Full update |
131/// | PATCH | /buckets/:id | Partial update |
132/// | DELETE | /buckets/:id | Soft delete |
133/// | POST | /buckets/bulk | Bulk create |
134/// | POST | /buckets/upsert | Upsert |
135/// | GET | /buckets/trash | List deleted |
136/// | POST | /buckets/:id/restore | Restore |
137/// | DELETE | /buckets/empty | Empty trash |
138/// | GET | /buckets/:id/deleted | Get deleted by ID |
139/// | DELETE | /buckets/trash/:id | Permanent delete from trash |
140/// | GET | /buckets/count | Count active entities |
141/// | GET | /buckets/trash/count | Count deleted entities |
142///
143/// # Example
144///
145/// ```text
146/// let service = Arc::new(BucketService::with_repository(repository));
147/// let router = create_bucket_routes(service);
148/// ```
149pub fn create_bucket_routes(service: Arc<BucketService>) -> Router {
150    BackboneCrudHandler::<BucketService, Bucket, CreateBucketDto, UpdateBucketDto, BucketResponseDto>::routes(
151        service,
152        "/buckets",
153    )
154}
155
156/// Create Axum router with only the read (GET) endpoints for Bucket.
157///
158/// Safe for public, unauthenticated exposure (e.g., reference data).
159/// Mutations must be served separately via `create_bucket_write_routes`,
160/// typically wrapped in an auth middleware layer.
161pub fn create_bucket_read_routes(service: Arc<BucketService>) -> Router {
162    BackboneCrudHandler::<BucketService, Bucket, CreateBucketDto, UpdateBucketDto, BucketResponseDto>::read_routes(
163        service,
164        "/buckets",
165    )
166}
167
168/// Create Axum router with only the write (mutation) endpoints for Bucket.
169///
170/// These routes must NOT be publicly exposed. Wrap them with an auth
171/// middleware before nesting into the application router.
172///
173/// # This is unguarded generic CRUD, not a validated write path
174///
175/// These are plain create/update/patch/delete mutations over the entity row —
176/// they bypass all business invariants. If the module exposes a validated write
177/// service (e.g. a command router over its domain engine), serve THAT instead
178/// for any mutation that must respect domain rules.
179pub fn create_bucket_write_routes(service: Arc<BucketService>) -> Router {
180    BackboneCrudHandler::<BucketService, Bucket, CreateBucketDto, UpdateBucketDto, BucketResponseDto>::write_routes(
181        service,
182        "/buckets",
183    )
184}
185
186/// Create authenticated routes with auth middleware.
187///
188/// Requires the `auth` feature flag. The `AuthMiddleware` implementation
189/// is responsible for extracting and validating tokens, then providing
190/// an `AuthContext` via request extensions.
191#[cfg(feature = "auth")]
192pub fn create_protected_bucket_routes<A: AuthMiddleware + Send + Sync + 'static>(
193    service: Arc<BucketService>,
194    auth: Arc<A>,
195) -> Router {
196    use axum::middleware;
197    use axum::response::IntoResponse;
198
199    let auth_layer = auth.clone();
200    create_bucket_routes(service)
201        .layer(middleware::from_fn(move |mut req: axum::extract::Request, next: axum::middleware::Next| {
202            let auth = auth_layer.clone();
203            async move {
204                let token = req.headers()
205                    .get(axum::http::header::AUTHORIZATION)
206                    .and_then(|h| h.to_str().ok())
207                    .and_then(|raw| raw.strip_prefix("Bearer ").or_else(|| raw.strip_prefix("bearer ")))
208                    .unwrap_or("");
209                match auth.authenticate(token).await {
210                    Ok(ctx) => {
211                        req.extensions_mut().insert(ctx);
212                        next.run(req).await
213                    }
214                    Err(_) => {
215                        (axum::http::StatusCode::UNAUTHORIZED,
216                         axum::Json(serde_json::json!({
217                             "success": false,
218                             "error": "unauthorized",
219                             "message": "Authentication required"
220                         }))
221                        ).into_response()
222                    }
223                }
224            }
225        }))
226}
227
228// =============================================================================
229// State Transition Handlers
230// =============================================================================
231
232/// Execute lock transition on a Bucket.
233///
234/// POST /buckets/:id/transitions/lock
235pub async fn lock_transition(
236    axum::extract::State(service): axum::extract::State<Arc<BucketService>>,
237    axum::extract::Path(id): axum::extract::Path<String>,
238    #[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
239) -> impl axum::response::IntoResponse {
240    use axum::{http::StatusCode, Json};
241
242    // Get current entity
243    let entity = match service.get_by_id(&id).await {
244        Ok(Some(e)) => e,
245        Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<BucketResponseDto>::not_found("Bucket", &id))),
246        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BucketResponseDto>::error(e.to_string()))),
247    };
248
249    // Check permission (if auth enabled)
250    #[cfg(feature = "auth")]
251    {
252        let allowed_roles = BucketTransition::Lock.allowed_roles();
253        let has_specific_perm = auth.permissions.iter().any(|p| p == "bucket:transition:lock");
254        let has_update_perm = auth.permissions.iter().any(|p| p == "bucket:update");
255        let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
256        if !has_specific_perm && !has_update_perm && !has_role {
257            return (StatusCode::FORBIDDEN, Json(ApiResponse::<BucketResponseDto>::error("Insufficient permissions for lock transition")));
258        }
259    }
260
261    // Create state machine from entity's actual status and validate transition
262    let current_state: BucketState = entity.status.to_string().parse()
263        .unwrap_or(BucketState::default());
264    let sm = BucketStateMachine::from_state(current_state);
265    if !sm.can_transition(BucketTransition::Lock) {
266        return (StatusCode::BAD_REQUEST, Json(ApiResponse::<BucketResponseDto>::error("Transition not allowed from current state")));
267    }
268
269    // Apply transition via partial update
270    let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
271    fields.insert("status".to_string(), serde_json::Value::String("Readonly".to_string()));
272
273    match service.partial_update(&id, fields).await {
274        Ok(Some(updated)) => {
275            let response: BucketResponseDto = updated.into();
276            (StatusCode::OK, Json(ApiResponse::ok(response)))
277        }
278        Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<BucketResponseDto>::not_found("Bucket", &id))),
279        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BucketResponseDto>::error(e.to_string()))),
280    }
281}
282
283/// Execute unlock transition on a Bucket.
284///
285/// POST /buckets/:id/transitions/unlock
286pub async fn unlock_transition(
287    axum::extract::State(service): axum::extract::State<Arc<BucketService>>,
288    axum::extract::Path(id): axum::extract::Path<String>,
289    #[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
290) -> impl axum::response::IntoResponse {
291    use axum::{http::StatusCode, Json};
292
293    // Get current entity
294    let entity = match service.get_by_id(&id).await {
295        Ok(Some(e)) => e,
296        Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<BucketResponseDto>::not_found("Bucket", &id))),
297        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BucketResponseDto>::error(e.to_string()))),
298    };
299
300    // Check permission (if auth enabled)
301    #[cfg(feature = "auth")]
302    {
303        let allowed_roles = BucketTransition::Unlock.allowed_roles();
304        let has_specific_perm = auth.permissions.iter().any(|p| p == "bucket:transition:unlock");
305        let has_update_perm = auth.permissions.iter().any(|p| p == "bucket:update");
306        let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
307        if !has_specific_perm && !has_update_perm && !has_role {
308            return (StatusCode::FORBIDDEN, Json(ApiResponse::<BucketResponseDto>::error("Insufficient permissions for unlock transition")));
309        }
310    }
311
312    // Create state machine from entity's actual status and validate transition
313    let current_state: BucketState = entity.status.to_string().parse()
314        .unwrap_or(BucketState::default());
315    let sm = BucketStateMachine::from_state(current_state);
316    if !sm.can_transition(BucketTransition::Unlock) {
317        return (StatusCode::BAD_REQUEST, Json(ApiResponse::<BucketResponseDto>::error("Transition not allowed from current state")));
318    }
319
320    // Apply transition via partial update
321    let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
322    fields.insert("status".to_string(), serde_json::Value::String("Active".to_string()));
323
324    match service.partial_update(&id, fields).await {
325        Ok(Some(updated)) => {
326            let response: BucketResponseDto = updated.into();
327            (StatusCode::OK, Json(ApiResponse::ok(response)))
328        }
329        Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<BucketResponseDto>::not_found("Bucket", &id))),
330        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BucketResponseDto>::error(e.to_string()))),
331    }
332}
333
334/// Execute archive transition on a Bucket.
335///
336/// POST /buckets/:id/transitions/archive
337pub async fn archive_transition(
338    axum::extract::State(service): axum::extract::State<Arc<BucketService>>,
339    axum::extract::Path(id): axum::extract::Path<String>,
340    #[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
341) -> impl axum::response::IntoResponse {
342    use axum::{http::StatusCode, Json};
343
344    // Get current entity
345    let entity = match service.get_by_id(&id).await {
346        Ok(Some(e)) => e,
347        Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<BucketResponseDto>::not_found("Bucket", &id))),
348        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BucketResponseDto>::error(e.to_string()))),
349    };
350
351    // Check permission (if auth enabled)
352    #[cfg(feature = "auth")]
353    {
354        let allowed_roles = BucketTransition::Archive.allowed_roles();
355        let has_specific_perm = auth.permissions.iter().any(|p| p == "bucket:transition:archive");
356        let has_update_perm = auth.permissions.iter().any(|p| p == "bucket:update");
357        let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
358        if !has_specific_perm && !has_update_perm && !has_role {
359            return (StatusCode::FORBIDDEN, Json(ApiResponse::<BucketResponseDto>::error("Insufficient permissions for archive transition")));
360        }
361    }
362
363    // Create state machine from entity's actual status and validate transition
364    let current_state: BucketState = entity.status.to_string().parse()
365        .unwrap_or(BucketState::default());
366    let sm = BucketStateMachine::from_state(current_state);
367    if !sm.can_transition(BucketTransition::Archive) {
368        return (StatusCode::BAD_REQUEST, Json(ApiResponse::<BucketResponseDto>::error("Transition not allowed from current state")));
369    }
370
371    // Apply transition via partial update
372    let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
373    fields.insert("status".to_string(), serde_json::Value::String("Archived".to_string()));
374
375    match service.partial_update(&id, fields).await {
376        Ok(Some(updated)) => {
377            let response: BucketResponseDto = updated.into();
378            (StatusCode::OK, Json(ApiResponse::ok(response)))
379        }
380        Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<BucketResponseDto>::not_found("Bucket", &id))),
381        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BucketResponseDto>::error(e.to_string()))),
382    }
383}
384
385/// Execute restore transition on a Bucket.
386///
387/// POST /buckets/:id/transitions/restore
388pub async fn restore_transition(
389    axum::extract::State(service): axum::extract::State<Arc<BucketService>>,
390    axum::extract::Path(id): axum::extract::Path<String>,
391    #[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
392) -> impl axum::response::IntoResponse {
393    use axum::{http::StatusCode, Json};
394
395    // Get current entity
396    let entity = match service.get_by_id(&id).await {
397        Ok(Some(e)) => e,
398        Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<BucketResponseDto>::not_found("Bucket", &id))),
399        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BucketResponseDto>::error(e.to_string()))),
400    };
401
402    // Check permission (if auth enabled)
403    #[cfg(feature = "auth")]
404    {
405        let allowed_roles = BucketTransition::Restore.allowed_roles();
406        let has_specific_perm = auth.permissions.iter().any(|p| p == "bucket:transition:restore");
407        let has_update_perm = auth.permissions.iter().any(|p| p == "bucket:update");
408        let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
409        if !has_specific_perm && !has_update_perm && !has_role {
410            return (StatusCode::FORBIDDEN, Json(ApiResponse::<BucketResponseDto>::error("Insufficient permissions for restore transition")));
411        }
412    }
413
414    // Create state machine from entity's actual status and validate transition
415    let current_state: BucketState = entity.status.to_string().parse()
416        .unwrap_or(BucketState::default());
417    let sm = BucketStateMachine::from_state(current_state);
418    if !sm.can_transition(BucketTransition::Restore) {
419        return (StatusCode::BAD_REQUEST, Json(ApiResponse::<BucketResponseDto>::error("Transition not allowed from current state")));
420    }
421
422    // Apply transition via partial update
423    let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
424    fields.insert("status".to_string(), serde_json::Value::String("Active".to_string()));
425
426    match service.partial_update(&id, fields).await {
427        Ok(Some(updated)) => {
428            let response: BucketResponseDto = updated.into();
429            (StatusCode::OK, Json(ApiResponse::ok(response)))
430        }
431        Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<BucketResponseDto>::not_found("Bucket", &id))),
432        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BucketResponseDto>::error(e.to_string()))),
433    }
434}
435
436/// Execute delete transition on a Bucket.
437///
438/// POST /buckets/:id/transitions/delete
439pub async fn delete_transition(
440    axum::extract::State(service): axum::extract::State<Arc<BucketService>>,
441    axum::extract::Path(id): axum::extract::Path<String>,
442    #[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
443) -> impl axum::response::IntoResponse {
444    use axum::{http::StatusCode, Json};
445
446    // Get current entity
447    let entity = match service.get_by_id(&id).await {
448        Ok(Some(e)) => e,
449        Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<BucketResponseDto>::not_found("Bucket", &id))),
450        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BucketResponseDto>::error(e.to_string()))),
451    };
452
453    // Check permission (if auth enabled)
454    #[cfg(feature = "auth")]
455    {
456        let allowed_roles = BucketTransition::Delete.allowed_roles();
457        let has_specific_perm = auth.permissions.iter().any(|p| p == "bucket:transition:delete");
458        let has_update_perm = auth.permissions.iter().any(|p| p == "bucket:update");
459        let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
460        if !has_specific_perm && !has_update_perm && !has_role {
461            return (StatusCode::FORBIDDEN, Json(ApiResponse::<BucketResponseDto>::error("Insufficient permissions for delete transition")));
462        }
463    }
464
465    // Create state machine from entity's actual status and validate transition
466    let current_state: BucketState = entity.status.to_string().parse()
467        .unwrap_or(BucketState::default());
468    let sm = BucketStateMachine::from_state(current_state);
469    if !sm.can_transition(BucketTransition::Delete) {
470        return (StatusCode::BAD_REQUEST, Json(ApiResponse::<BucketResponseDto>::error("Transition not allowed from current state")));
471    }
472
473    // Apply transition via partial update
474    let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
475    fields.insert("status".to_string(), serde_json::Value::String("Deleted".to_string()));
476
477    match service.partial_update(&id, fields).await {
478        Ok(Some(updated)) => {
479            let response: BucketResponseDto = updated.into();
480            (StatusCode::OK, Json(ApiResponse::ok(response)))
481        }
482        Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<BucketResponseDto>::not_found("Bucket", &id))),
483        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BucketResponseDto>::error(e.to_string()))),
484    }
485}
486
487/// Create routes for state transitions.
488pub fn create_bucket_transition_routes(service: Arc<BucketService>) -> Router {
489    use axum::routing::post;
490
491    Router::new()
492        .route("/buckets/:id/transitions/lock", post(lock_transition))
493        .route("/buckets/:id/transitions/unlock", post(unlock_transition))
494        .route("/buckets/:id/transitions/archive", post(archive_transition))
495        .route("/buckets/:id/transitions/restore", post(restore_transition))
496        .route("/buckets/:id/transitions/delete", post(delete_transition))
497        .with_state(service)
498}