backbone-bucket 0.2.1

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
431
432
433
434
435
436
437
438
439
440
//! Bucket Module
//!
//! Generated by metaphor-schema. Enhanced with runtime implementations.
//!
//! This module provides:
//! - Domain entities and repositories
//! - Application services
//! - HTTP and gRPC handlers
//! - Route configuration
//! - State machine enforcement
//! - Validation rules runtime
//! - RBAC middleware
//! - Trigger execution system
//! - Computed fields
//! - Workflow orchestrator

#![recursion_limit = "1024"]
#![allow(unused_imports)]

// Generated modules
pub mod domain;
pub mod infrastructure;
pub mod application;
pub mod presentation;
pub mod seeders;
pub mod exports;
// <<< CUSTOM MODULES
pub mod error;
pub mod storage;
pub mod auth;
pub mod config;

// ─── Essential (every consumer wires these) ─────────────────────────────
pub use error::{BucketError, BucketResult};
pub use config::{BucketConfig, ConfigEnvError, S3Config, ServingConfig, ServingMode, StorageConfig};

// ─── Storage backends ───────────────────────────────────────────────────
// `ObjectStorage` is the boundary trait. `LocalStorage` ships always;
// `S3Storage` is gated on the `s3` feature; `InMemoryStorage` on `test-utils`.
pub use storage::{ObjectMeta, ObjectStorage, LocalStorage};
#[cfg(feature = "s3")]
pub use storage::S3Storage;
#[cfg(feature = "test-utils")]
pub use storage::InMemoryStorage;

// ─── Auth slots (consumer-implemented) ──────────────────────────────────
pub use auth::{
    ArcAuthzPolicy, AuthExtractor, AuthzDecision, AuthzPolicy, DefaultOwnerOnlyPolicy, HasOwnerId,
};

// ─── File operations (single-shot programmatic API) ─────────────────────
pub use application::service::{FileMeta, FileService};

// ─── HTTP surfaces (serving + multipart upload) ─────────────────────────
pub use presentation::http::{lookup_by_key as lookup_file_by_key, serving_router, ServingContext};
pub use presentation::http::{
    upload_router, UploadConfig, UploadContext, DEFAULT_CHUNK_BODY_LIMIT, DEFAULT_UPLOAD_BODY_LIMIT,
};
// END CUSTOM

// Re-exports for convenience - Domain entities
pub use domain::entity::*;

// Re-exports - State Machine
pub use domain::state_machine::*;

// Re-exports - Computed Fields
pub use domain::computed::{HasComputedFields, ComputedFieldValues};

// Re-exports - Permissions
pub use domain::permission::{Action, FieldRestriction, PermissionChecker, PermissionError, PermissionResult};

// Re-exports - Infrastructure
pub use infrastructure::persistence::*;

// Re-exports - Application services
pub use application::service::AccessLogService;
pub use application::service::BucketService;
pub use application::service::ContentHashService;
pub use application::service::ConversionJobService;
pub use application::service::FileCommentService;
pub use application::service::FileLockService;
pub use application::service::FileShareService;
pub use application::service::FileVersionService;
pub use application::service::ProcessingJobService;
pub use application::service::StoredFileService;
pub use application::service::ThumbnailService;
pub use application::service::UploadSessionService;
pub use application::service::UserQuotaService;

// <<< CUSTOM - Custom service re-exports
pub use application::service::LockingService;
pub use application::service::DeduplicationService;
pub use application::service::MultipartUploadService;
pub use application::service::ConversionService;
#[allow(deprecated)]
pub use application::service::CdnService;
pub use application::service::VideoThumbnailService;
pub use application::service::DocumentPreviewService;
mod bucket_module; // Phase 6: http_routes() — regeneration-safe BucketModule extensions
pub use bucket_module::RouterOptions;
// END CUSTOM
// Re-exports - Validation
pub use application::validator::{ValidationError, ValidationResult};

// Re-exports - Triggers
pub use application::triggers::*;

// Re-exports - Workflows
pub use application::workflows::*;

use std::sync::Arc;
use axum::Router;
use sqlx::PgPool;

/// Bucket module configuration
///
/// Use the builder pattern to configure and register this module:
///
/// ```text
/// let bucket = BucketModule::builder()
///     .with_database(pool.clone())
///     .build()?;
///
/// // Unguarded full CRUD (trusted/admin); compose a guarded router for production.
/// let router = bucket.all_crud_routes();
/// ```
pub struct BucketModule {
    #[allow(dead_code)]
    pub(crate) access_log_service: Arc<AccessLogService>,
    pub(crate) bucket_service: Arc<BucketService>,
    pub(crate) content_hash_service: Arc<ContentHashService>,
    pub(crate) conversion_job_service: Arc<ConversionJobService>,
    pub(crate) file_comment_service: Arc<FileCommentService>,
    pub(crate) file_lock_service: Arc<FileLockService>,
    pub(crate) file_share_service: Arc<FileShareService>,
    #[allow(dead_code)]
    pub(crate) file_version_service: Arc<FileVersionService>,
    pub(crate) processing_job_service: Arc<ProcessingJobService>,
    pub(crate) stored_file_service: Arc<StoredFileService>,
    #[allow(dead_code)]
    pub(crate) thumbnail_service: Arc<ThumbnailService>,
    pub(crate) upload_session_service: Arc<UploadSessionService>,
    pub(crate) user_quota_service: Arc<UserQuotaService>,
    // <<< CUSTOM FIELDS
    // Custom business logic services
    pub locking_service: Arc<LockingService>,
    pub deduplication_service: Arc<DeduplicationService>,
    pub multipart_upload_service: Arc<MultipartUploadService>,
    pub conversion_service: Arc<ConversionService>,
    #[allow(deprecated)]
    pub cdn_service: Arc<CdnService>,
    pub video_thumbnail_service: Arc<VideoThumbnailService>,
    pub document_preview_service: Arc<DocumentPreviewService>,
    /// Storage backend (mode-B serving + uploads). None until `.with_storage()` is called.
    pub storage: Option<Arc<dyn ObjectStorage>>,
    /// Bucket-module config (storage + serving). None until `.with_config()` is called.
    pub bucket_config: Option<Arc<BucketConfig>>,
    /// High-level file operations service, wired when both `storage` and `bucket_config` are set.
    pub file_service: Option<Arc<FileService>>,
    /// Direct handle to the StoredFile repository — used by the mode-B
    /// serving handler to look up files by `storage_key`.
    pub stored_file_repository: Arc<infrastructure::persistence::StoredFileRepository>,
    // END CUSTOM
}

impl BucketModule {
    /// Create a new module builder
    pub fn builder() -> BucketModuleBuilder {
        BucketModuleBuilder::new()
    }

    /// Mount ALL generated CRUD endpoints (12 per entity) with NO domain
    /// validation — the fully **unguarded** surface. A well-formed request can
    /// create invalid rows or soft-delete a referenced master out from under its
    /// dependents. Prefer a guarded composition (read + validated writes) for any
    /// real deployment; use this only in trusted/admin/seeding contexts.
    pub fn all_crud_routes(&self) -> Router {
        use presentation::http::{
            create_bucket_routes,
            create_content_hash_routes,
            create_conversion_job_routes,
            create_file_comment_routes,
            create_file_lock_routes,
            create_file_share_routes,
            create_processing_job_routes,
            create_stored_file_routes,
            create_upload_session_routes,
            create_user_quota_routes,
        };

        Router::new()
            .merge(create_bucket_routes(self.bucket_service.clone()))
            .merge(create_content_hash_routes(self.content_hash_service.clone()))
            .merge(create_conversion_job_routes(self.conversion_job_service.clone()))
            .merge(create_file_comment_routes(self.file_comment_service.clone()))
            .merge(create_file_lock_routes(self.file_lock_service.clone()))
            .merge(create_file_share_routes(self.file_share_service.clone()))
            .merge(create_processing_job_routes(self.processing_job_service.clone()))
            .merge(create_stored_file_routes(self.stored_file_service.clone()))
            .merge(create_upload_session_routes(self.upload_session_service.clone()))
            .merge(create_user_quota_routes(self.user_quota_service.clone()))
    }

    /// Deprecated alias for [`Self::all_crud_routes`]. `routes()` reads like
    /// "the routes" but mounts UNVALIDATED generic CRUD on every entity — a naive
    /// mount exposes unguarded writes. Compose a guarded router (read + validated
    /// writes) for production, or call `all_crud_routes()` to opt into the full
    /// unguarded surface explicitly.
    #[deprecated(note = "mounts unvalidated generic CRUD; prefer readonly_routes() + validated writes, or all_crud_routes() for the full/unguarded surface")]
    pub fn routes(&self) -> Router {
        self.all_crud_routes()
    }

    /// Read-only routes for every entity (GET endpoints only) — the safe base.
    ///
    /// Generic mutation can't reach here, so this surface cannot bypass a
    /// validated write service's invariants. Use this as the production base and
    /// merge validated write routes (or a write service's HTTP layer) onto it.
    pub fn readonly_routes(&self) -> Router {
        use presentation::http::{
            create_bucket_read_routes,
            create_content_hash_read_routes,
            create_conversion_job_read_routes,
            create_file_comment_read_routes,
            create_file_lock_read_routes,
            create_file_share_read_routes,
            create_processing_job_read_routes,
            create_stored_file_read_routes,
            create_upload_session_read_routes,
            create_user_quota_read_routes,
        };

        Router::new()
            .merge(create_bucket_read_routes(self.bucket_service.clone()))
            .merge(create_content_hash_read_routes(self.content_hash_service.clone()))
            .merge(create_conversion_job_read_routes(self.conversion_job_service.clone()))
            .merge(create_file_comment_read_routes(self.file_comment_service.clone()))
            .merge(create_file_lock_read_routes(self.file_lock_service.clone()))
            .merge(create_file_share_read_routes(self.file_share_service.clone()))
            .merge(create_processing_job_read_routes(self.processing_job_service.clone()))
            .merge(create_stored_file_read_routes(self.stored_file_service.clone()))
            .merge(create_upload_session_read_routes(self.upload_session_service.clone()))
            .merge(create_user_quota_read_routes(self.user_quota_service.clone()))
    }

    // <<< CUSTOM METHODS
    /// What [`upload_router`] needs, built from this module's own services.
    ///
    /// `None` until the module has both a storage backend and a config (the
    /// file service is wired only then). A host mounts uploads with
    /// `upload_router::<I>(bucket.upload_context()?, config)` and never holds
    /// the generic bucket service itself.
    pub fn upload_context(&self) -> Option<UploadContext> {
        Some(UploadContext {
            file_service: self.file_service.clone()?,
            multipart_service: self.multipart_upload_service.clone(),
            bucket_service: self.bucket_service.clone(),
            storage: self.storage.clone()?,
        })
    }
    // END CUSTOM
}

/// Builder for BucketModule
pub struct BucketModuleBuilder {
    db_pool: Option<PgPool>,
    // <<< CUSTOM BUILDER FIELDS
    // bucket-serving fields (see docs/serving.md)
    storage: Option<Arc<dyn ObjectStorage>>,
    bucket_config: Option<BucketConfig>,
    // END CUSTOM
}

impl BucketModuleBuilder {
    /// Create a new builder
    pub fn new() -> Self {
        Self {
            db_pool: None,
            // <<< CUSTOM BUILDER DEFAULTS
            storage: None,
            bucket_config: None,
            // END CUSTOM
        }
    }

    /// Set the database connection pool
    pub fn with_database(mut self, pool: PgPool) -> Self {
        self.db_pool = Some(pool);
        self
    }

    // <<< CUSTOM - custom builder methods
    // Bucket-serving builder methods (see docs/serving.md)

    /// Attach the bucket-module runtime config (storage + serving).
    pub fn with_config(mut self, config: BucketConfig) -> Self {
        self.bucket_config = Some(config);
        self
    }

    /// Attach the object-storage backend (`LocalStorage`, `S3Storage`, …).
    pub fn with_storage(mut self, storage: Arc<dyn ObjectStorage>) -> Self {
        self.storage = Some(storage);
        self
    }

    // END CUSTOM

    /// Build the module with configured dependencies
    pub fn build(self) -> anyhow::Result<BucketModule> {
        let db_pool = self.db_pool
            .ok_or_else(|| anyhow::anyhow!("Database pool not configured"))?;

        // AccessLog service
        let access_log_repository = Arc::new(AccessLogRepository::new(db_pool.clone()));
        let access_log_service = Arc::new(AccessLogService::with_repository(access_log_repository.clone()));

        // Bucket service
        let bucket_repository = Arc::new(BucketRepository::new(db_pool.clone()));
        let bucket_service = Arc::new(BucketService::with_repository(bucket_repository.clone()));

        // ContentHash service
        let content_hash_repository = Arc::new(ContentHashRepository::new(db_pool.clone()));
        let content_hash_service = Arc::new(ContentHashService::with_repository(content_hash_repository.clone()));

        // ConversionJob service
        let conversion_job_repository = Arc::new(ConversionJobRepository::new(db_pool.clone()));
        let conversion_job_service = Arc::new(ConversionJobService::with_repository(conversion_job_repository.clone()));

        // FileComment service
        let file_comment_repository = Arc::new(FileCommentRepository::new(db_pool.clone()));
        let file_comment_service = Arc::new(FileCommentService::with_repository(file_comment_repository.clone()));

        // FileLock service
        let file_lock_repository = Arc::new(FileLockRepository::new(db_pool.clone()));
        let file_lock_service = Arc::new(FileLockService::with_repository(file_lock_repository.clone()));

        // FileShare service
        let file_share_repository = Arc::new(FileShareRepository::new(db_pool.clone()));
        let file_share_service = Arc::new(FileShareService::with_repository(file_share_repository.clone()));

        // FileVersion service
        let file_version_repository = Arc::new(FileVersionRepository::new(db_pool.clone()));
        let file_version_service = Arc::new(FileVersionService::with_repository(file_version_repository.clone()));

        // ProcessingJob service
        let processing_job_repository = Arc::new(ProcessingJobRepository::new(db_pool.clone()));
        let processing_job_service = Arc::new(ProcessingJobService::with_repository(processing_job_repository.clone()));

        // StoredFile service
        let stored_file_repository = Arc::new(StoredFileRepository::new(db_pool.clone()));
        let stored_file_service = Arc::new(StoredFileService::with_repository(stored_file_repository.clone()));

        // Thumbnail service
        let thumbnail_repository = Arc::new(ThumbnailRepository::new(db_pool.clone()));
        let thumbnail_service = Arc::new(ThumbnailService::with_repository(thumbnail_repository.clone()));

        // UploadSession service
        let upload_session_repository = Arc::new(UploadSessionRepository::new(db_pool.clone()));
        let upload_session_service = Arc::new(UploadSessionService::with_repository(upload_session_repository.clone()));

        // UserQuota service
        let user_quota_repository = Arc::new(UserQuotaRepository::new(db_pool.clone()));
        let user_quota_service = Arc::new(UserQuotaService::with_repository(user_quota_repository.clone()));

        // <<< CUSTOM
        // Custom business logic services
        let locking_service = Arc::new(LockingService::new(
            file_lock_repository, stored_file_repository.clone(),
        ));
        let deduplication_service = Arc::new(DeduplicationService::new(
            content_hash_repository, stored_file_repository.clone(),
        ));
        let multipart_upload_service = Arc::new(MultipartUploadService::new(
            upload_session_repository, bucket_repository.clone(), user_quota_repository,
        ));
        let conversion_service = Arc::new(ConversionService::new(
            conversion_job_repository, stored_file_repository.clone(),
        ));
        #[allow(deprecated)]
        let cdn_service = Arc::new(CdnService::new(
            stored_file_repository.clone(), bucket_repository,
        ));
        let video_thumbnail_service = Arc::new(VideoThumbnailService::new(
            processing_job_repository.clone(), thumbnail_repository.clone(), stored_file_repository.clone(),
        ));
        let document_preview_service = Arc::new(DocumentPreviewService::new(
            processing_job_repository, thumbnail_repository, stored_file_repository.clone(),
        ));

        // Bucket-serving wiring (see docs/serving.md)
        let bucket_config = self.bucket_config.map(Arc::new);
        let storage = self.storage;
        let file_service = match (&storage, &bucket_config) {
            (Some(s), Some(c)) => Some(Arc::new(FileService::new(
                s.clone(),
                stored_file_repository.clone(),
                c.clone(),
            ))),
            _ => None,
        };
        // END CUSTOM

        Ok(BucketModule {
            access_log_service,
            bucket_service,
            content_hash_service,
            conversion_job_service,
            file_comment_service,
            file_lock_service,
            file_share_service,
            file_version_service,
            processing_job_service,
            stored_file_service,
            thumbnail_service,
            upload_session_service,
            user_quota_service,
            // <<< CUSTOM
            locking_service,
            deduplication_service,
            multipart_upload_service,
            conversion_service,
            cdn_service,
            video_thumbnail_service,
            document_preview_service,
            storage,
            bucket_config,
            file_service,
            stored_file_repository,
            // END CUSTOM
        })
    }
}

impl Default for BucketModuleBuilder {
    fn default() -> Self {
        Self::new()
    }
}