backbone-bucket 0.4.9

Bucket Bounded Context: File Storage Module for Backbone Framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
//! FileLock 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)
use backbone_auth::middleware::AuthContext;
#[cfg(feature = "auth")]
use backbone_auth::AuthMiddleware;

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

// DTO imports
use crate::presentation::dto::{CreateFileLockDto, UpdateFileLockDto, PatchFileLockDto, FileLockResponseDto};

use crate::domain::state_machine::{FileLockState, FileLockStateMachine, FileLockTransition};

/// Application error type
#[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),
    // Domain-specific errors from hook rules
    #[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()
    }
}

/// Domain-specific error codes for FileLock
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";
}

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

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

/// Create Axum router with only the read (GET) endpoints for FileLock.
///
/// Safe for public, unauthenticated exposure (e.g., reference data).
/// Mutations must be served separately via `create_file_lock_write_routes`,
/// typically wrapped in an auth middleware layer.
pub fn create_file_lock_read_routes(service: Arc<FileLockService>) -> Router {
    BackboneCrudHandler::<FileLockService, FileLock, CreateFileLockDto, UpdateFileLockDto, FileLockResponseDto>::read_routes(
        service,
        "/file_locks",
    )
}

/// Create Axum router with only the write (mutation) endpoints for FileLock.
///
/// 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_lock_write_routes(service: Arc<FileLockService>) -> Router {
    BackboneCrudHandler::<FileLockService, FileLock, CreateFileLockDto, UpdateFileLockDto, FileLockResponseDto>::write_routes(
        service,
        "/file_locks",
    )
}

/// 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_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()
                    }
                }
            }
        }))
}

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

/// Execute expire transition on a FileLock.
///
/// POST /file_locks/:id/transitions/expire
pub async fn expire_transition(
    axum::extract::State(service): axum::extract::State<Arc<FileLockService>>,
    axum::extract::Path(id): axum::extract::Path<String>,
    auth: Option<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::<FileLockResponseDto>::not_found("FileLock", &id))),
        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileLockResponseDto>::error(e.to_string()))),
    };

    // Check permission
    let Some(axum::Extension(auth)) = auth else {
        return (StatusCode::UNAUTHORIZED, Json(ApiResponse::<FileLockResponseDto>::error("A transition needs an authenticated caller")));
    };
    {
        let allowed_roles = FileLockTransition::Expire.allowed_roles();
        let granted = |required: &str| auth.permissions.iter().any(|p| {
            let (have, want): (Vec<&str>, Vec<&str>) = (p.split(':').collect(), required.split(':').collect());
            have.iter().enumerate().all(|(i, h)| *h == "*" || want.get(i) == Some(h))
                && (have.len() == want.len() || (have.len() < want.len() && have.last() == Some(&"*")))
        });
        let has_specific_perm = granted("file_lock:transition:expire");
        let has_update_perm = granted("file_lock:update");
        let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
        if !has_specific_perm && !has_role {
            if !has_update_perm {
                return (StatusCode::FORBIDDEN, Json(ApiResponse::<FileLockResponseDto>::error("Insufficient permissions for expire transition")));
            }
            tracing::warn!(target: "backbone::write_guard", entity = "FileLock", verb = "expire", code = "transition_by_update_permission", "a transition granted only by file_lock:update, running in shadow; it needs file_lock:transition:expire or one of the roles system");
        }
    }

    // Create state machine from entity's actual status and validate transition
    let current_state: FileLockState = match entity.status.to_string().parse() {
        Ok(s) => s,
        Err(_) => return (StatusCode::CONFLICT, Json(ApiResponse::<FileLockResponseDto>::error("The stored state is not a state of this machine"))),
    };
    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")));
    }

    // Guard `expires_at <= now()` not compiled (reads the writer, the time or the row before the write); the transition is not checked against it.
    // 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 backbone_core::write_guard::as_transition("expire", 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()))),
    }
}

/// Execute release transition on a FileLock.
///
/// POST /file_locks/:id/transitions/release
pub async fn release_transition(
    axum::extract::State(service): axum::extract::State<Arc<FileLockService>>,
    axum::extract::Path(id): axum::extract::Path<String>,
    auth: Option<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::<FileLockResponseDto>::not_found("FileLock", &id))),
        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileLockResponseDto>::error(e.to_string()))),
    };

    // Check permission
    let Some(axum::Extension(auth)) = auth else {
        return (StatusCode::UNAUTHORIZED, Json(ApiResponse::<FileLockResponseDto>::error("A transition needs an authenticated caller")));
    };
    {
        let allowed_roles = FileLockTransition::Release.allowed_roles();
        let granted = |required: &str| auth.permissions.iter().any(|p| {
            let (have, want): (Vec<&str>, Vec<&str>) = (p.split(':').collect(), required.split(':').collect());
            have.iter().enumerate().all(|(i, h)| *h == "*" || want.get(i) == Some(h))
                && (have.len() == want.len() || (have.len() < want.len() && have.last() == Some(&"*")))
        });
        let has_specific_perm = granted("file_lock:transition:release");
        let has_update_perm = granted("file_lock:update");
        let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
        if !has_specific_perm && !has_role {
            if !has_update_perm {
                return (StatusCode::FORBIDDEN, Json(ApiResponse::<FileLockResponseDto>::error("Insufficient permissions for release transition")));
            }
            tracing::warn!(target: "backbone::write_guard", entity = "FileLock", verb = "release", code = "transition_by_update_permission", "a transition granted only by file_lock:update, running in shadow; it needs file_lock:transition:release or one of the roles owner, admin");
        }
    }

    // Create state machine from entity's actual status and validate transition
    let current_state: FileLockState = match entity.status.to_string().parse() {
        Ok(s) => s,
        Err(_) => return (StatusCode::CONFLICT, Json(ApiResponse::<FileLockResponseDto>::error("The stored state is not a state of this machine"))),
    };
    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")));
    }

    // Guard `$actor.id == user_id || $actor.has_role('admin')` not compiled (reads the writer, the time or the row before the write); the transition is not checked against it.
    // Apply transition via partial update
    let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
    fields.insert("status".to_string(), serde_json::Value::String("released".to_string()));

    match backbone_core::write_guard::as_transition("release", 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()))),
    }
}

/// Execute refresh transition on a FileLock.
///
/// POST /file_locks/:id/transitions/refresh
pub async fn refresh_transition(
    axum::extract::State(service): axum::extract::State<Arc<FileLockService>>,
    axum::extract::Path(id): axum::extract::Path<String>,
    auth: Option<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::<FileLockResponseDto>::not_found("FileLock", &id))),
        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileLockResponseDto>::error(e.to_string()))),
    };

    // Check permission
    let Some(axum::Extension(auth)) = auth else {
        return (StatusCode::UNAUTHORIZED, Json(ApiResponse::<FileLockResponseDto>::error("A transition needs an authenticated caller")));
    };
    {
        let allowed_roles = FileLockTransition::Refresh.allowed_roles();
        let granted = |required: &str| auth.permissions.iter().any(|p| {
            let (have, want): (Vec<&str>, Vec<&str>) = (p.split(':').collect(), required.split(':').collect());
            have.iter().enumerate().all(|(i, h)| *h == "*" || want.get(i) == Some(h))
                && (have.len() == want.len() || (have.len() < want.len() && have.last() == Some(&"*")))
        });
        let has_specific_perm = granted("file_lock:transition:refresh");
        let has_update_perm = granted("file_lock:update");
        let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
        if !has_specific_perm && !has_role {
            if !has_update_perm {
                return (StatusCode::FORBIDDEN, Json(ApiResponse::<FileLockResponseDto>::error("Insufficient permissions for refresh transition")));
            }
            tracing::warn!(target: "backbone::write_guard", entity = "FileLock", verb = "refresh", code = "transition_by_update_permission", "a transition granted only by file_lock:update, running in shadow; it needs file_lock:transition:refresh or one of the roles owner");
        }
    }

    // Create state machine from entity's actual status and validate transition
    let current_state: FileLockState = match entity.status.to_string().parse() {
        Ok(s) => s,
        Err(_) => return (StatusCode::CONFLICT, Json(ApiResponse::<FileLockResponseDto>::error("The stored state is not a state of this machine"))),
    };
    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")));
    }

    // Guard `$actor.id == user_id && expires_at > now()` not compiled (reads the writer, the time or the row before the write); the transition is not checked against it.
    // Apply transition via partial update
    let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
    fields.insert("status".to_string(), serde_json::Value::String("active".to_string()));

    match backbone_core::write_guard::as_transition("refresh", 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()))),
    }
}

/// Create routes for state transitions.
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)
}