Skip to main content

backbone_bucket/
lib.rs

1//! Bucket Module
2//!
3//! Generated by metaphor-schema. Enhanced with runtime implementations.
4//!
5//! This module provides:
6//! - Domain entities and repositories
7//! - Application services
8//! - HTTP and gRPC handlers
9//! - Route configuration
10//! - State machine enforcement
11//! - Validation rules runtime
12//! - RBAC middleware
13//! - Trigger execution system
14//! - Computed fields
15//! - Workflow orchestrator
16
17#![recursion_limit = "1024"]
18#![allow(unused_imports)]
19
20// Generated modules
21pub mod domain;
22pub mod infrastructure;
23pub mod application;
24pub mod presentation;
25pub mod seeders;
26pub mod exports;
27// <<< CUSTOM MODULES
28pub mod error;
29pub mod storage;
30pub mod auth;
31pub mod config;
32
33// ─── Essential (every consumer wires these) ─────────────────────────────
34pub use error::{BucketError, BucketResult};
35pub use config::{BucketConfig, ConfigEnvError, S3Config, ServingConfig, ServingMode, StorageConfig};
36
37// ─── Storage backends ───────────────────────────────────────────────────
38// `ObjectStorage` is the boundary trait. `LocalStorage` ships always;
39// `S3Storage` is gated on the `s3` feature; `InMemoryStorage` on `test-utils`.
40pub use storage::{ObjectMeta, ObjectStorage, LocalStorage};
41#[cfg(feature = "s3")]
42pub use storage::S3Storage;
43#[cfg(feature = "test-utils")]
44pub use storage::InMemoryStorage;
45
46// ─── Auth slots (consumer-implemented) ──────────────────────────────────
47pub use auth::{
48    ArcAuthzPolicy, AuthExtractor, AuthzDecision, AuthzPolicy, DefaultOwnerOnlyPolicy, HasOwnerId,
49};
50
51// ─── File operations (single-shot programmatic API) ─────────────────────
52pub use application::service::{FileMeta, FileService};
53
54// ─── HTTP surfaces (serving + multipart upload) ─────────────────────────
55pub use presentation::http::{lookup_by_key as lookup_file_by_key, serving_router, ServingContext};
56pub use presentation::http::{
57    upload_router, UploadConfig, UploadContext, DEFAULT_CHUNK_BODY_LIMIT, DEFAULT_UPLOAD_BODY_LIMIT,
58};
59// END CUSTOM
60
61// Re-exports for convenience - Domain entities
62pub use domain::entity::*;
63
64// Re-exports - State Machine
65pub use domain::state_machine::*;
66
67// Re-exports - Computed Fields
68pub use domain::computed::{HasComputedFields, ComputedFieldValues};
69
70// Re-exports - Permissions
71pub use domain::permission::{Action, FieldRestriction, PermissionChecker, PermissionError, PermissionResult};
72
73// Re-exports - Infrastructure
74pub use infrastructure::persistence::*;
75
76// Re-exports - Application services
77pub use application::service::AccessLogService;
78pub use application::service::BucketService;
79pub use application::service::ContentHashService;
80pub use application::service::ConversionJobService;
81pub use application::service::FileCommentService;
82pub use application::service::FileLockService;
83pub use application::service::FileShareService;
84pub use application::service::FileVersionService;
85pub use application::service::ProcessingJobService;
86pub use application::service::StoredFileService;
87pub use application::service::ThumbnailService;
88pub use application::service::UploadSessionService;
89pub use application::service::UserQuotaService;
90
91// <<< CUSTOM - Custom service re-exports
92pub use application::service::LockingService;
93pub use application::service::MultipartUploadService;
94pub use application::service::ConversionService;
95#[allow(deprecated)]
96pub use application::service::CdnService;
97pub use application::service::VideoThumbnailService;
98pub use application::service::DocumentPreviewService;
99mod bucket_module; // Phase 6: http_routes() — regeneration-safe BucketModule extensions
100pub use bucket_module::RouterOptions;
101// END CUSTOM
102// Re-exports - Validation
103pub use application::validator::{ValidationError, ValidationResult};
104
105// Re-exports - Triggers
106pub use application::triggers::*;
107
108// Re-exports - Workflows
109pub use application::workflows::*;
110
111use std::sync::Arc;
112use axum::Router;
113use sqlx::PgPool;
114
115/// Bucket module configuration
116///
117/// Use the builder pattern to configure and register this module:
118///
119/// ```text
120/// let bucket = BucketModule::builder()
121///     .with_database(pool.clone())
122///     .build()?;
123///
124/// // Unguarded full CRUD (trusted/admin); compose a guarded router for production.
125/// let router = bucket.all_crud_routes();
126/// ```
127pub struct BucketModule {
128    #[allow(dead_code)]
129    pub(crate) access_log_service: Arc<AccessLogService>,
130    pub(crate) bucket_service: Arc<BucketService>,
131    pub(crate) content_hash_service: Arc<ContentHashService>,
132    pub(crate) conversion_job_service: Arc<ConversionJobService>,
133    pub(crate) file_comment_service: Arc<FileCommentService>,
134    pub(crate) file_lock_service: Arc<FileLockService>,
135    pub(crate) file_share_service: Arc<FileShareService>,
136    #[allow(dead_code)]
137    pub(crate) file_version_service: Arc<FileVersionService>,
138    pub(crate) processing_job_service: Arc<ProcessingJobService>,
139    pub(crate) stored_file_service: Arc<StoredFileService>,
140    #[allow(dead_code)]
141    pub(crate) thumbnail_service: Arc<ThumbnailService>,
142    pub(crate) upload_session_service: Arc<UploadSessionService>,
143    pub(crate) user_quota_service: Arc<UserQuotaService>,
144    // <<< CUSTOM FIELDS
145    // Custom business logic services
146    pub locking_service: Arc<LockingService>,
147    pub multipart_upload_service: Arc<MultipartUploadService>,
148    pub conversion_service: Arc<ConversionService>,
149    #[allow(deprecated)]
150    pub cdn_service: Arc<CdnService>,
151    pub video_thumbnail_service: Arc<VideoThumbnailService>,
152    pub document_preview_service: Arc<DocumentPreviewService>,
153    /// Storage backend (mode-B serving + uploads). None until `.with_storage()` is called.
154    pub storage: Option<Arc<dyn ObjectStorage>>,
155    /// Bucket-module config (storage + serving). None until `.with_config()` is called.
156    pub bucket_config: Option<Arc<BucketConfig>>,
157    /// High-level file operations service, wired when both `storage` and `bucket_config` are set.
158    pub file_service: Option<Arc<FileService>>,
159    /// Direct handle to the StoredFile repository — used by the mode-B
160    /// serving handler to look up files by `storage_key`.
161    pub stored_file_repository: Arc<infrastructure::persistence::StoredFileRepository>,
162    // END CUSTOM
163}
164
165impl BucketModule {
166    /// Create a new module builder
167    pub fn builder() -> BucketModuleBuilder {
168        BucketModuleBuilder::new()
169    }
170
171    /// Mount ALL generated CRUD endpoints (12 per entity) with NO domain
172    /// validation — the fully **unguarded** surface. A well-formed request can
173    /// create invalid rows or soft-delete a referenced master out from under its
174    /// dependents. Prefer a guarded composition (read + validated writes) for any
175    /// real deployment; use this only in trusted/admin/seeding contexts.
176    pub fn all_crud_routes(&self) -> Router {
177        use presentation::http::{
178            create_bucket_routes,
179            create_content_hash_routes,
180            create_conversion_job_routes,
181            create_file_comment_routes,
182            create_file_lock_routes,
183            create_file_share_routes,
184            create_processing_job_routes,
185            create_stored_file_routes,
186            create_upload_session_routes,
187            create_user_quota_routes,
188        };
189
190        Router::new()
191            .merge(create_bucket_routes(self.bucket_service.clone()))
192            .merge(create_content_hash_routes(self.content_hash_service.clone()))
193            .merge(create_conversion_job_routes(self.conversion_job_service.clone()))
194            .merge(create_file_comment_routes(self.file_comment_service.clone()))
195            .merge(create_file_lock_routes(self.file_lock_service.clone()))
196            .merge(create_file_share_routes(self.file_share_service.clone()))
197            .merge(create_processing_job_routes(self.processing_job_service.clone()))
198            .merge(create_stored_file_routes(self.stored_file_service.clone()))
199            .merge(create_upload_session_routes(self.upload_session_service.clone()))
200            .merge(create_user_quota_routes(self.user_quota_service.clone()))
201    }
202
203    /// Deprecated alias for [`Self::all_crud_routes`]. `routes()` reads like
204    /// "the routes" but mounts UNVALIDATED generic CRUD on every entity — a naive
205    /// mount exposes unguarded writes. Compose a guarded router (read + validated
206    /// writes) for production, or call `all_crud_routes()` to opt into the full
207    /// unguarded surface explicitly.
208    #[deprecated(note = "mounts unvalidated generic CRUD; prefer readonly_routes() + validated writes, or all_crud_routes() for the full/unguarded surface")]
209    pub fn routes(&self) -> Router {
210        self.all_crud_routes()
211    }
212
213    /// Read-only routes for every entity (GET endpoints only) — the safe base.
214    ///
215    /// Generic mutation can't reach here, so this surface cannot bypass a
216    /// validated write service's invariants. Use this as the production base and
217    /// merge validated write routes (or a write service's HTTP layer) onto it.
218    pub fn readonly_routes(&self) -> Router {
219        use presentation::http::{
220            create_bucket_read_routes,
221            create_content_hash_read_routes,
222            create_conversion_job_read_routes,
223            create_file_comment_read_routes,
224            create_file_lock_read_routes,
225            create_file_share_read_routes,
226            create_processing_job_read_routes,
227            create_stored_file_read_routes,
228            create_upload_session_read_routes,
229            create_user_quota_read_routes,
230        };
231
232        Router::new()
233            .merge(create_bucket_read_routes(self.bucket_service.clone()))
234            .merge(create_content_hash_read_routes(self.content_hash_service.clone()))
235            .merge(create_conversion_job_read_routes(self.conversion_job_service.clone()))
236            .merge(create_file_comment_read_routes(self.file_comment_service.clone()))
237            .merge(create_file_lock_read_routes(self.file_lock_service.clone()))
238            .merge(create_file_share_read_routes(self.file_share_service.clone()))
239            .merge(create_processing_job_read_routes(self.processing_job_service.clone()))
240            .merge(create_stored_file_read_routes(self.stored_file_service.clone()))
241            .merge(create_upload_session_read_routes(self.upload_session_service.clone()))
242            .merge(create_user_quota_read_routes(self.user_quota_service.clone()))
243    }
244
245    // <<< CUSTOM METHODS
246    /// What [`upload_router`] needs, built from this module's own services.
247    ///
248    /// `None` until the module has both a storage backend and a config (the
249    /// file service is wired only then). A host mounts uploads with
250    /// `upload_router::<I>(bucket.upload_context()?, config)` and never holds
251    /// the generic bucket service itself.
252    pub fn upload_context(&self) -> Option<UploadContext> {
253        Some(UploadContext {
254            file_service: self.file_service.clone()?,
255            multipart_service: self.multipart_upload_service.clone(),
256            bucket_service: self.bucket_service.clone(),
257            storage: self.storage.clone()?,
258        })
259    }
260    // END CUSTOM
261}
262
263/// Builder for BucketModule
264pub struct BucketModuleBuilder {
265    db_pool: Option<PgPool>,
266    // <<< CUSTOM BUILDER FIELDS
267    // bucket-serving fields (see docs/serving.md)
268    storage: Option<Arc<dyn ObjectStorage>>,
269    bucket_config: Option<BucketConfig>,
270    // END CUSTOM
271}
272
273impl BucketModuleBuilder {
274    /// Create a new builder
275    pub fn new() -> Self {
276        Self {
277            db_pool: None,
278            // <<< CUSTOM BUILDER DEFAULTS
279            storage: None,
280            bucket_config: None,
281            // END CUSTOM
282        }
283    }
284
285    /// Set the database connection pool
286    pub fn with_database(mut self, pool: PgPool) -> Self {
287        self.db_pool = Some(pool);
288        self
289    }
290
291    // <<< CUSTOM - custom builder methods
292    // Bucket-serving builder methods (see docs/serving.md)
293
294    /// Attach the bucket-module runtime config (storage + serving).
295    pub fn with_config(mut self, config: BucketConfig) -> Self {
296        self.bucket_config = Some(config);
297        self
298    }
299
300    /// Attach the object-storage backend (`LocalStorage`, `S3Storage`, …).
301    pub fn with_storage(mut self, storage: Arc<dyn ObjectStorage>) -> Self {
302        self.storage = Some(storage);
303        self
304    }
305
306    // END CUSTOM
307
308    /// Build the module with configured dependencies
309    pub fn build(self) -> anyhow::Result<BucketModule> {
310        let db_pool = self.db_pool
311            .ok_or_else(|| anyhow::anyhow!("Database pool not configured"))?;
312
313        // AccessLog service
314        let access_log_repository = Arc::new(AccessLogRepository::new(db_pool.clone()));
315        let access_log_service = Arc::new(AccessLogService::with_repository(access_log_repository.clone()));
316
317        // Bucket service
318        let bucket_repository = Arc::new(BucketRepository::new(db_pool.clone()));
319        let bucket_service = Arc::new(BucketService::with_repository(bucket_repository.clone()));
320
321        // ContentHash service
322        let content_hash_repository = Arc::new(ContentHashRepository::new(db_pool.clone()));
323        let content_hash_service = Arc::new(ContentHashService::with_repository(content_hash_repository.clone()));
324
325        // ConversionJob service
326        let conversion_job_repository = Arc::new(ConversionJobRepository::new(db_pool.clone()));
327        let conversion_job_service = Arc::new(ConversionJobService::with_repository(conversion_job_repository.clone()));
328
329        // FileComment service
330        let file_comment_repository = Arc::new(FileCommentRepository::new(db_pool.clone()));
331        let file_comment_service = Arc::new(FileCommentService::with_repository(file_comment_repository.clone()));
332
333        // FileLock service
334        let file_lock_repository = Arc::new(FileLockRepository::new(db_pool.clone()));
335        let file_lock_service = Arc::new(FileLockService::with_repository(file_lock_repository.clone()));
336
337        // FileShare service
338        let file_share_repository = Arc::new(FileShareRepository::new(db_pool.clone()));
339        let file_share_service = Arc::new(FileShareService::with_repository(file_share_repository.clone()));
340
341        // FileVersion service
342        let file_version_repository = Arc::new(FileVersionRepository::new(db_pool.clone()));
343        let file_version_service = Arc::new(FileVersionService::with_repository(file_version_repository.clone()));
344
345        // ProcessingJob service
346        let processing_job_repository = Arc::new(ProcessingJobRepository::new(db_pool.clone()));
347        let processing_job_service = Arc::new(ProcessingJobService::with_repository(processing_job_repository.clone()));
348
349        // StoredFile service
350        let stored_file_repository = Arc::new(StoredFileRepository::new(db_pool.clone()));
351        let stored_file_service = Arc::new(StoredFileService::with_repository(stored_file_repository.clone()));
352
353        // Thumbnail service
354        let thumbnail_repository = Arc::new(ThumbnailRepository::new(db_pool.clone()));
355        let thumbnail_service = Arc::new(ThumbnailService::with_repository(thumbnail_repository.clone()));
356
357        // UploadSession service
358        let upload_session_repository = Arc::new(UploadSessionRepository::new(db_pool.clone()));
359        let upload_session_service = Arc::new(UploadSessionService::with_repository(upload_session_repository.clone()));
360
361        // UserQuota service
362        let user_quota_repository = Arc::new(UserQuotaRepository::new(db_pool.clone()));
363        let user_quota_service = Arc::new(UserQuotaService::with_repository(user_quota_repository.clone()));
364
365        // <<< CUSTOM
366        // Custom business logic services
367        let locking_service = Arc::new(LockingService::new(
368            file_lock_repository, stored_file_repository.clone(),
369        ));
370        let multipart_upload_service = Arc::new(MultipartUploadService::new(
371            upload_session_repository, bucket_repository.clone(), user_quota_repository,
372        ));
373        let conversion_service = Arc::new(ConversionService::new(
374            conversion_job_repository, stored_file_repository.clone(),
375        ));
376        #[allow(deprecated)]
377        let cdn_service = Arc::new(CdnService::new(
378            stored_file_repository.clone(), bucket_repository,
379        ));
380        let video_thumbnail_service = Arc::new(VideoThumbnailService::new(
381            processing_job_repository.clone(), thumbnail_repository.clone(), stored_file_repository.clone(),
382        ));
383        let document_preview_service = Arc::new(DocumentPreviewService::new(
384            processing_job_repository, thumbnail_repository, stored_file_repository.clone(),
385        ));
386
387        // Bucket-serving wiring (see docs/serving.md)
388        let bucket_config = self.bucket_config.map(Arc::new);
389        let storage = self.storage;
390        let file_service = match (&storage, &bucket_config) {
391            (Some(s), Some(c)) => Some(Arc::new(FileService::new(
392                s.clone(),
393                stored_file_repository.clone(),
394                c.clone(),
395            ))),
396            _ => None,
397        };
398        // END CUSTOM
399
400        Ok(BucketModule {
401            access_log_service,
402            bucket_service,
403            content_hash_service,
404            conversion_job_service,
405            file_comment_service,
406            file_lock_service,
407            file_share_service,
408            file_version_service,
409            processing_job_service,
410            stored_file_service,
411            thumbnail_service,
412            upload_session_service,
413            user_quota_service,
414            // <<< CUSTOM
415            locking_service,
416            multipart_upload_service,
417            conversion_service,
418            cdn_service,
419            video_thumbnail_service,
420            document_preview_service,
421            storage,
422            bucket_config,
423            file_service,
424            stored_file_repository,
425            // END CUSTOM
426        })
427    }
428}
429
430impl Default for BucketModuleBuilder {
431    fn default() -> Self {
432        Self::new()
433    }
434}