backbone-bucket 0.3.0

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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
//! MultipartUpload flow implementation
//!
//! Generated by metaphor-schema
//!
//! Multipart upload workflow for large files including:
//! - Session initialization
//! - Chunk upload tracking
//! - Progress updates
//! - File assembly
//! - Validation and processing

use serde::{Deserialize, Serialize};
use std::sync::Arc;
use chrono;
use backbone_core::flow::{WorkflowStep, WorkflowContext};

/// Error type for flow execution
#[derive(Debug, Clone, thiserror::Error)]
pub enum FlowError {
    #[error("No current step to execute")]
    NoCurrentStep,

    #[error("Step execution failed: {0}")]
    StepFailed(String),

    #[error("Condition evaluation failed: {0}")]
    ConditionFailed(String),

    #[error("Compensation failed: {0}")]
    CompensationFailed(String),

    #[error("Flow timed out")]
    Timeout,

    #[error("Flow cancelled")]
    Cancelled,

    #[error("Invalid state transition: {from} -> {to}")]
    InvalidTransition { from: String, to: String },
}

/// Execution status for MultipartUpload flow
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MultipartUploadFlowStatus {
    /// Flow is pending execution
    Pending,
    /// Flow is currently running
    Running,
    /// Flow is waiting for an event or condition
    Waiting,
    /// Flow completed successfully
    Completed,
    /// Flow failed
    Failed,
    /// Flow was cancelled
    Cancelled,
    /// Flow is compensating (rolling back)
    Compensating,
}

/// Steps in MultipartUpload flow
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MultipartUploadFlowStep {
    /// load_bucket
    LoadBucket,
    /// check_bucket_accessible
    CheckBucketAccessible,
    /// validate_file_size
    ValidateFileSize,
    /// check_max_file_size
    CheckMaxFileSize,
    /// calculate_chunk_params
    CalculateChunkParams,
    /// validate_mime_type
    ValidateMimeType,
    /// load_quota
    LoadQuota,
    /// create_default_quota
    CreateDefaultQuota,
    /// check_quota_available
    CheckQuotaAvailable,
    /// create_upload_session
    CreateUploadSession,
    /// reserve_quota
    ReserveQuota,
    /// emit_session_created
    EmitSessionCreated,
    /// complete
    Complete,
    /// bucket_not_found
    BucketNotFound,
    /// bucket_not_active
    BucketNotActive,
    /// invalid_file_size
    InvalidFileSize,
    /// file_too_large
    FileTooLarge,
    /// mime_type_not_allowed
    MimeTypeNotAllowed,
    /// quota_exceeded
    QuotaExceeded,
}

/// Instance of MultipartUpload flow execution
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MultipartUploadFlowInstance {
    /// Unique instance ID
    pub id: String,
    /// Current status
    pub status: MultipartUploadFlowStatus,
    /// Current step
    pub current_step: Option<MultipartUploadFlowStep>,
    /// Flow context (variables)
    pub context: serde_json::Value,
    /// Completed steps
    pub completed_steps: Vec<MultipartUploadFlowStep>,
    /// Error if failed
    pub error: Option<String>,
    /// Created timestamp
    pub created_at: chrono::DateTime<chrono::Utc>,
    /// Updated timestamp
    pub updated_at: chrono::DateTime<chrono::Utc>,
}

impl MultipartUploadFlowInstance {
    /// Create a new flow instance
    pub fn new(id: impl Into<String>) -> Self {
        let now = chrono::Utc::now();
        Self {
            id: id.into(),
            status: MultipartUploadFlowStatus::Pending,
            current_step: None,
            context: serde_json::json!({}),
            completed_steps: Vec::new(),
            error: None,
            created_at: now,
            updated_at: now,
        }
    }

    /// Check if flow is complete
    pub fn is_complete(&self) -> bool {
        matches!(
            self.status,
            MultipartUploadFlowStatus::Completed | MultipartUploadFlowStatus::Failed | MultipartUploadFlowStatus::Cancelled
        )
    }

    /// Check if flow is running
    pub fn is_running(&self) -> bool {
        matches!(
            self.status,
            MultipartUploadFlowStatus::Running | MultipartUploadFlowStatus::Waiting
        )
    }

    /// Set a context variable
    pub fn set_context(&mut self, key: &str, value: serde_json::Value) {
        if let serde_json::Value::Object(ref mut map) = self.context {
            map.insert(key.to_string(), value);
        }
        self.updated_at = chrono::Utc::now();
    }

    /// Get a context variable
    pub fn get_context(&self, key: &str) -> Option<&serde_json::Value> {
        if let serde_json::Value::Object(ref map) = self.context {
            map.get(key)
        } else {
            None
        }
    }
}

// Phase 1: FlowInstance satisfies backbone_core::flow::WorkflowContext.
// The entity() accessor requires the entity to be carried in the instance;
// add `pub entity: MultipartUpload` in the // <<< CUSTOM section and remove the todo!.
#[allow(unused_variables)]
impl WorkflowContext<MultipartUploadFlowInstance> for MultipartUploadFlowInstance {
    fn entity(&self) -> &MultipartUploadFlowInstance { self }
    fn set_var(&mut self, key: &str, value: serde_json::Value) {
        self.set_context(key, value);
    }
    fn get_var(&self, key: &str) -> Option<&serde_json::Value> {
        self.get_context(key)
    }
}

/// Step handler trait for MultipartUpload flow
#[async_trait::async_trait]
pub trait MultipartUploadStepHandler: Send + Sync {
    /// Handle load_bucket step
    async fn handle_load_bucket(
        &self,
        instance: &mut MultipartUploadFlowInstance,
    ) -> Result<Option<MultipartUploadFlowStep>, FlowError>;

    /// Evaluate condition for check_bucket_accessible step
    async fn evaluate_check_bucket_accessible(
        &self,
        instance: &MultipartUploadFlowInstance,
    ) -> Result<MultipartUploadFlowStep, FlowError>;

    /// Evaluate condition for validate_file_size step
    async fn evaluate_validate_file_size(
        &self,
        instance: &MultipartUploadFlowInstance,
    ) -> Result<MultipartUploadFlowStep, FlowError>;

    /// Evaluate condition for check_max_file_size step
    async fn evaluate_check_max_file_size(
        &self,
        instance: &MultipartUploadFlowInstance,
    ) -> Result<MultipartUploadFlowStep, FlowError>;

    /// Handle calculate_chunk_params step
    async fn handle_calculate_chunk_params(
        &self,
        instance: &mut MultipartUploadFlowInstance,
    ) -> Result<Option<MultipartUploadFlowStep>, FlowError>;

    /// Evaluate condition for validate_mime_type step
    async fn evaluate_validate_mime_type(
        &self,
        instance: &MultipartUploadFlowInstance,
    ) -> Result<MultipartUploadFlowStep, FlowError>;

    /// Handle load_quota step
    async fn handle_load_quota(
        &self,
        instance: &mut MultipartUploadFlowInstance,
    ) -> Result<Option<MultipartUploadFlowStep>, FlowError>;

    /// Handle create_default_quota step
    async fn handle_create_default_quota(
        &self,
        instance: &mut MultipartUploadFlowInstance,
    ) -> Result<Option<MultipartUploadFlowStep>, FlowError>;

    /// Evaluate condition for check_quota_available step
    async fn evaluate_check_quota_available(
        &self,
        instance: &MultipartUploadFlowInstance,
    ) -> Result<MultipartUploadFlowStep, FlowError>;

    /// Handle create_upload_session step
    async fn handle_create_upload_session(
        &self,
        instance: &mut MultipartUploadFlowInstance,
    ) -> Result<Option<MultipartUploadFlowStep>, FlowError>;

    /// Handle reserve_quota step
    async fn handle_reserve_quota(
        &self,
        instance: &mut MultipartUploadFlowInstance,
    ) -> Result<Option<MultipartUploadFlowStep>, FlowError>;

    /// Handle emit_session_created step
    async fn handle_emit_session_created(
        &self,
        instance: &mut MultipartUploadFlowInstance,
    ) -> Result<Option<MultipartUploadFlowStep>, FlowError>;

    /// Handle terminal step complete
    async fn handle_complete(
        &self,
        instance: &mut MultipartUploadFlowInstance,
    ) -> Result<(), FlowError>;

    /// Handle terminal step bucket_not_found
    async fn handle_bucket_not_found(
        &self,
        instance: &mut MultipartUploadFlowInstance,
    ) -> Result<(), FlowError>;

    /// Handle terminal step bucket_not_active
    async fn handle_bucket_not_active(
        &self,
        instance: &mut MultipartUploadFlowInstance,
    ) -> Result<(), FlowError>;

    /// Handle terminal step invalid_file_size
    async fn handle_invalid_file_size(
        &self,
        instance: &mut MultipartUploadFlowInstance,
    ) -> Result<(), FlowError>;

    /// Handle terminal step file_too_large
    async fn handle_file_too_large(
        &self,
        instance: &mut MultipartUploadFlowInstance,
    ) -> Result<(), FlowError>;

    /// Handle terminal step mime_type_not_allowed
    async fn handle_mime_type_not_allowed(
        &self,
        instance: &mut MultipartUploadFlowInstance,
    ) -> Result<(), FlowError>;

    /// Handle terminal step quota_exceeded
    async fn handle_quota_exceeded(
        &self,
        instance: &mut MultipartUploadFlowInstance,
    ) -> Result<(), FlowError>;

}

/// Executor for MultipartUpload flow
pub struct MultipartUploadFlowExecutor<H: MultipartUploadStepHandler> {
    handler: Arc<H>,
}

impl<H: MultipartUploadStepHandler> MultipartUploadFlowExecutor<H> {
    /// Create a new flow executor
    pub fn new(handler: Arc<H>) -> Self {
        Self { handler }
    }

    /// Start a new flow instance
    pub async fn start(&self, instance_id: impl Into<String>) -> Result<MultipartUploadFlowInstance, FlowError> {
        let mut instance = MultipartUploadFlowInstance::new(instance_id);
        instance.status = MultipartUploadFlowStatus::Running;
        instance.current_step = Some(MultipartUploadFlowStep::LoadBucket);
        Ok(instance)
    }

    /// Execute the current step
    pub async fn execute_step(&self, instance: &mut MultipartUploadFlowInstance) -> Result<(), FlowError> {
        let current_step = match instance.current_step {
            Some(step) => step,
            None => return Err(FlowError::NoCurrentStep),
        };

        let next_step = match current_step {
            MultipartUploadFlowStep::LoadBucket => {
                self.handler.handle_load_bucket(instance).await?
            }
            MultipartUploadFlowStep::CheckBucketAccessible => {
                let next = self.handler.evaluate_check_bucket_accessible(instance).await?;
                Some(next)
            }
            MultipartUploadFlowStep::ValidateFileSize => {
                let next = self.handler.evaluate_validate_file_size(instance).await?;
                Some(next)
            }
            MultipartUploadFlowStep::CheckMaxFileSize => {
                let next = self.handler.evaluate_check_max_file_size(instance).await?;
                Some(next)
            }
            MultipartUploadFlowStep::CalculateChunkParams => {
                self.handler.handle_calculate_chunk_params(instance).await?
            }
            MultipartUploadFlowStep::ValidateMimeType => {
                let next = self.handler.evaluate_validate_mime_type(instance).await?;
                Some(next)
            }
            MultipartUploadFlowStep::LoadQuota => {
                self.handler.handle_load_quota(instance).await?
            }
            MultipartUploadFlowStep::CreateDefaultQuota => {
                self.handler.handle_create_default_quota(instance).await?
            }
            MultipartUploadFlowStep::CheckQuotaAvailable => {
                let next = self.handler.evaluate_check_quota_available(instance).await?;
                Some(next)
            }
            MultipartUploadFlowStep::CreateUploadSession => {
                self.handler.handle_create_upload_session(instance).await?
            }
            MultipartUploadFlowStep::ReserveQuota => {
                self.handler.handle_reserve_quota(instance).await?
            }
            MultipartUploadFlowStep::EmitSessionCreated => {
                self.handler.handle_emit_session_created(instance).await?
            }
            MultipartUploadFlowStep::Complete => {
                self.handler.handle_complete(instance).await?;
                None // Terminal step
            }
            MultipartUploadFlowStep::BucketNotFound => {
                self.handler.handle_bucket_not_found(instance).await?;
                None // Terminal step
            }
            MultipartUploadFlowStep::BucketNotActive => {
                self.handler.handle_bucket_not_active(instance).await?;
                None // Terminal step
            }
            MultipartUploadFlowStep::InvalidFileSize => {
                self.handler.handle_invalid_file_size(instance).await?;
                None // Terminal step
            }
            MultipartUploadFlowStep::FileTooLarge => {
                self.handler.handle_file_too_large(instance).await?;
                None // Terminal step
            }
            MultipartUploadFlowStep::MimeTypeNotAllowed => {
                self.handler.handle_mime_type_not_allowed(instance).await?;
                None // Terminal step
            }
            MultipartUploadFlowStep::QuotaExceeded => {
                self.handler.handle_quota_exceeded(instance).await?;
                None // Terminal step
            }
        };

        // Mark current step as completed
        instance.completed_steps.push(current_step);

        // Move to next step
        match next_step {
            Some(next) => {
                instance.current_step = Some(next);
            }
            None => {
                instance.current_step = None;
                instance.status = MultipartUploadFlowStatus::Completed;
            }
        }

        instance.updated_at = chrono::Utc::now();
        Ok(())
    }

    /// Run the flow to completion
    pub async fn run(&self, instance: &mut MultipartUploadFlowInstance) -> Result<(), FlowError> {
        while !instance.is_complete() && instance.status != MultipartUploadFlowStatus::Waiting {
            self.execute_step(instance).await?;
        }
        Ok(())
    }

    /// Cancel the flow
    pub fn cancel(&self, instance: &mut MultipartUploadFlowInstance) {
        instance.status = MultipartUploadFlowStatus::Cancelled;
        instance.updated_at = chrono::Utc::now();
    }

    /// Mark flow as failed
    pub fn fail(&self, instance: &mut MultipartUploadFlowInstance, error: impl Into<String>) {
        instance.status = MultipartUploadFlowStatus::Failed;
        instance.error = Some(error.into());
        instance.updated_at = chrono::Utc::now();
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_flow_instance_creation() {
        let instance = MultipartUploadFlowInstance::new("test-1");
        assert_eq!(instance.id, "test-1");
        assert_eq!(instance.status, MultipartUploadFlowStatus::Pending);
        assert!(!instance.is_complete());
    }

    #[test]
    fn test_flow_context() {
        let mut instance = MultipartUploadFlowInstance::new("test-2");
        instance.set_context("key", serde_json::json!("value"));
        let value = instance.get_context("key");
        assert_eq!(value, Some(&serde_json::json!("value")));
    }

    #[test]
    fn test_flow_status_transitions() {
        let mut instance = MultipartUploadFlowInstance::new("test-3");
        assert!(!instance.is_running());

        instance.status = MultipartUploadFlowStatus::Running;
        assert!(instance.is_running());
        assert!(!instance.is_complete());

        instance.status = MultipartUploadFlowStatus::Completed;
        assert!(instance.is_complete());
        assert!(!instance.is_running());
    }
}