backbone-bucket 0.2.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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
//! FileProcessing flow implementation
//!
//! Generated by metaphor-schema
//!
//! Async file processing workflow including:
//! - Image thumbnail generation
//! - Video thumbnail generation
//! - Document preview generation
//! - File compression
//! - Virus scanning
//! - Content deduplication checking
//! - CDN URL generation

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 FileProcessing flow
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FileProcessingFlowStatus {
    /// 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 FileProcessing flow
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FileProcessingFlowStep {
    /// load_job
    LoadJob,
    /// mark_running
    MarkRunning,
    /// load_file
    LoadFile,
    /// load_bucket
    LoadBucket,
    /// route_by_job_type
    RouteByJobType,
    /// process_image_thumbnail
    ProcessImageThumbnail,
    /// store_image_thumbnail
    StoreImageThumbnail,
    /// update_file_thumbnail
    UpdateFileThumbnail,
    /// process_video_thumbnail
    ProcessVideoThumbnail,
    /// store_video_thumbnail
    StoreVideoThumbnail,
    /// update_file_video_thumbnail
    UpdateFileVideoThumbnail,
    /// process_document_preview
    ProcessDocumentPreview,
    /// store_document_preview
    StoreDocumentPreview,
    /// update_file_document_preview
    UpdateFileDocumentPreview,
    /// process_compression
    ProcessCompression,
    /// store_compressed_file
    StoreCompressedFile,
    /// update_file_compression
    UpdateFileCompression,
    /// update_bucket_compression_stats
    UpdateBucketCompressionStats,
    /// process_virus_scan
    ProcessVirusScan,
    /// check_threat_level
    CheckThreatLevel,
    /// update_scan_safe
    UpdateScanSafe,
    /// update_scan_warning
    UpdateScanWarning,
    /// notify_scan_warning
    NotifyScanWarning,
    /// update_scan_threat
    UpdateScanThreat,
    /// notify_threat_detected
    NotifyThreatDetected,
    /// process_deduplication
    ProcessDeduplication,
    /// check_existing_hash
    CheckExistingHash,
    /// update_existing_hash
    UpdateExistingHash,
    /// link_file_hash
    LinkFileHash,
    /// create_new_hash
    CreateNewHash,
    /// mark_complete
    MarkComplete,
    /// emit_complete_event
    EmitCompleteEvent,
    /// complete
    Complete,
    /// retry_or_fail
    RetryOrFail,
    /// schedule_retry
    ScheduleRetry,
    /// retry_terminal
    RetryTerminal,
    /// mark_failed
    MarkFailed,
    /// emit_failed_event
    EmitFailedEvent,
    /// failed_terminal
    FailedTerminal,
    /// job_not_found
    JobNotFound,
    /// file_not_found
    FileNotFound,
    /// unknown_job_type
    UnknownJobType,
}

/// Instance of FileProcessing flow execution
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileProcessingFlowInstance {
    /// Unique instance ID
    pub id: String,
    /// Current status
    pub status: FileProcessingFlowStatus,
    /// Current step
    pub current_step: Option<FileProcessingFlowStep>,
    /// Flow context (variables)
    pub context: serde_json::Value,
    /// Completed steps
    pub completed_steps: Vec<FileProcessingFlowStep>,
    /// 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 FileProcessingFlowInstance {
    /// Create a new flow instance
    pub fn new(id: impl Into<String>) -> Self {
        let now = chrono::Utc::now();
        Self {
            id: id.into(),
            status: FileProcessingFlowStatus::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,
            FileProcessingFlowStatus::Completed | FileProcessingFlowStatus::Failed | FileProcessingFlowStatus::Cancelled
        )
    }

    /// Check if flow is running
    pub fn is_running(&self) -> bool {
        matches!(
            self.status,
            FileProcessingFlowStatus::Running | FileProcessingFlowStatus::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: FileProcessing` in the // <<< CUSTOM section and remove the todo!.
#[allow(unused_variables)]
impl WorkflowContext<FileProcessingFlowInstance> for FileProcessingFlowInstance {
    fn entity(&self) -> &FileProcessingFlowInstance { 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 FileProcessing flow
#[async_trait::async_trait]
pub trait FileProcessingStepHandler: Send + Sync {
    /// Handle load_job step
    async fn handle_load_job(
        &self,
        instance: &mut FileProcessingFlowInstance,
    ) -> Result<Option<FileProcessingFlowStep>, FlowError>;

    /// Handle mark_running step
    async fn handle_mark_running(
        &self,
        instance: &mut FileProcessingFlowInstance,
    ) -> Result<Option<FileProcessingFlowStep>, FlowError>;

    /// Handle load_file step
    async fn handle_load_file(
        &self,
        instance: &mut FileProcessingFlowInstance,
    ) -> Result<Option<FileProcessingFlowStep>, FlowError>;

    /// Handle load_bucket step
    async fn handle_load_bucket(
        &self,
        instance: &mut FileProcessingFlowInstance,
    ) -> Result<Option<FileProcessingFlowStep>, FlowError>;

    /// Evaluate condition for route_by_job_type step
    async fn evaluate_route_by_job_type(
        &self,
        instance: &FileProcessingFlowInstance,
    ) -> Result<FileProcessingFlowStep, FlowError>;

    /// Handle process_image_thumbnail step
    async fn handle_process_image_thumbnail(
        &self,
        instance: &mut FileProcessingFlowInstance,
    ) -> Result<Option<FileProcessingFlowStep>, FlowError>;

    /// Handle store_image_thumbnail step
    async fn handle_store_image_thumbnail(
        &self,
        instance: &mut FileProcessingFlowInstance,
    ) -> Result<Option<FileProcessingFlowStep>, FlowError>;

    /// Handle update_file_thumbnail step
    async fn handle_update_file_thumbnail(
        &self,
        instance: &mut FileProcessingFlowInstance,
    ) -> Result<Option<FileProcessingFlowStep>, FlowError>;

    /// Handle process_video_thumbnail step
    async fn handle_process_video_thumbnail(
        &self,
        instance: &mut FileProcessingFlowInstance,
    ) -> Result<Option<FileProcessingFlowStep>, FlowError>;

    /// Handle store_video_thumbnail step
    async fn handle_store_video_thumbnail(
        &self,
        instance: &mut FileProcessingFlowInstance,
    ) -> Result<Option<FileProcessingFlowStep>, FlowError>;

    /// Handle update_file_video_thumbnail step
    async fn handle_update_file_video_thumbnail(
        &self,
        instance: &mut FileProcessingFlowInstance,
    ) -> Result<Option<FileProcessingFlowStep>, FlowError>;

    /// Handle process_document_preview step
    async fn handle_process_document_preview(
        &self,
        instance: &mut FileProcessingFlowInstance,
    ) -> Result<Option<FileProcessingFlowStep>, FlowError>;

    /// Handle store_document_preview step
    async fn handle_store_document_preview(
        &self,
        instance: &mut FileProcessingFlowInstance,
    ) -> Result<Option<FileProcessingFlowStep>, FlowError>;

    /// Handle update_file_document_preview step
    async fn handle_update_file_document_preview(
        &self,
        instance: &mut FileProcessingFlowInstance,
    ) -> Result<Option<FileProcessingFlowStep>, FlowError>;

    /// Handle process_compression step
    async fn handle_process_compression(
        &self,
        instance: &mut FileProcessingFlowInstance,
    ) -> Result<Option<FileProcessingFlowStep>, FlowError>;

    /// Handle store_compressed_file step
    async fn handle_store_compressed_file(
        &self,
        instance: &mut FileProcessingFlowInstance,
    ) -> Result<Option<FileProcessingFlowStep>, FlowError>;

    /// Handle update_file_compression step
    async fn handle_update_file_compression(
        &self,
        instance: &mut FileProcessingFlowInstance,
    ) -> Result<Option<FileProcessingFlowStep>, FlowError>;

    /// Handle update_bucket_compression_stats step
    async fn handle_update_bucket_compression_stats(
        &self,
        instance: &mut FileProcessingFlowInstance,
    ) -> Result<Option<FileProcessingFlowStep>, FlowError>;

    /// Handle process_virus_scan step
    async fn handle_process_virus_scan(
        &self,
        instance: &mut FileProcessingFlowInstance,
    ) -> Result<Option<FileProcessingFlowStep>, FlowError>;

    /// Evaluate condition for check_threat_level step
    async fn evaluate_check_threat_level(
        &self,
        instance: &FileProcessingFlowInstance,
    ) -> Result<FileProcessingFlowStep, FlowError>;

    /// Handle update_scan_safe step
    async fn handle_update_scan_safe(
        &self,
        instance: &mut FileProcessingFlowInstance,
    ) -> Result<Option<FileProcessingFlowStep>, FlowError>;

    /// Handle update_scan_warning step
    async fn handle_update_scan_warning(
        &self,
        instance: &mut FileProcessingFlowInstance,
    ) -> Result<Option<FileProcessingFlowStep>, FlowError>;

    /// Handle notify_scan_warning step
    async fn handle_notify_scan_warning(
        &self,
        instance: &mut FileProcessingFlowInstance,
    ) -> Result<Option<FileProcessingFlowStep>, FlowError>;

    /// Handle update_scan_threat step
    async fn handle_update_scan_threat(
        &self,
        instance: &mut FileProcessingFlowInstance,
    ) -> Result<Option<FileProcessingFlowStep>, FlowError>;

    /// Handle notify_threat_detected step
    async fn handle_notify_threat_detected(
        &self,
        instance: &mut FileProcessingFlowInstance,
    ) -> Result<Option<FileProcessingFlowStep>, FlowError>;

    /// Handle process_deduplication step
    async fn handle_process_deduplication(
        &self,
        instance: &mut FileProcessingFlowInstance,
    ) -> Result<Option<FileProcessingFlowStep>, FlowError>;

    /// Handle check_existing_hash step
    async fn handle_check_existing_hash(
        &self,
        instance: &mut FileProcessingFlowInstance,
    ) -> Result<Option<FileProcessingFlowStep>, FlowError>;

    /// Handle update_existing_hash step
    async fn handle_update_existing_hash(
        &self,
        instance: &mut FileProcessingFlowInstance,
    ) -> Result<Option<FileProcessingFlowStep>, FlowError>;

    /// Handle link_file_hash step
    async fn handle_link_file_hash(
        &self,
        instance: &mut FileProcessingFlowInstance,
    ) -> Result<Option<FileProcessingFlowStep>, FlowError>;

    /// Handle create_new_hash step
    async fn handle_create_new_hash(
        &self,
        instance: &mut FileProcessingFlowInstance,
    ) -> Result<Option<FileProcessingFlowStep>, FlowError>;

    /// Handle mark_complete step
    async fn handle_mark_complete(
        &self,
        instance: &mut FileProcessingFlowInstance,
    ) -> Result<Option<FileProcessingFlowStep>, FlowError>;

    /// Handle emit_complete_event step
    async fn handle_emit_complete_event(
        &self,
        instance: &mut FileProcessingFlowInstance,
    ) -> Result<Option<FileProcessingFlowStep>, FlowError>;

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

    /// Evaluate condition for retry_or_fail step
    async fn evaluate_retry_or_fail(
        &self,
        instance: &FileProcessingFlowInstance,
    ) -> Result<FileProcessingFlowStep, FlowError>;

    /// Handle schedule_retry step
    async fn handle_schedule_retry(
        &self,
        instance: &mut FileProcessingFlowInstance,
    ) -> Result<Option<FileProcessingFlowStep>, FlowError>;

    /// Handle terminal step retry_terminal
    async fn handle_retry_terminal(
        &self,
        instance: &mut FileProcessingFlowInstance,
    ) -> Result<(), FlowError>;

    /// Handle mark_failed step
    async fn handle_mark_failed(
        &self,
        instance: &mut FileProcessingFlowInstance,
    ) -> Result<Option<FileProcessingFlowStep>, FlowError>;

    /// Handle emit_failed_event step
    async fn handle_emit_failed_event(
        &self,
        instance: &mut FileProcessingFlowInstance,
    ) -> Result<Option<FileProcessingFlowStep>, FlowError>;

    /// Handle terminal step failed_terminal
    async fn handle_failed_terminal(
        &self,
        instance: &mut FileProcessingFlowInstance,
    ) -> Result<(), FlowError>;

    /// Handle terminal step job_not_found
    async fn handle_job_not_found(
        &self,
        instance: &mut FileProcessingFlowInstance,
    ) -> Result<(), FlowError>;

    /// Handle terminal step file_not_found
    async fn handle_file_not_found(
        &self,
        instance: &mut FileProcessingFlowInstance,
    ) -> Result<(), FlowError>;

    /// Handle terminal step unknown_job_type
    async fn handle_unknown_job_type(
        &self,
        instance: &mut FileProcessingFlowInstance,
    ) -> Result<(), FlowError>;

    /// Execute compensation (rollback)
    async fn compensate(
        &self,
        instance: &mut FileProcessingFlowInstance,
    ) -> Result<(), FlowError>;

}

/// Executor for FileProcessing flow
pub struct FileProcessingFlowExecutor<H: FileProcessingStepHandler> {
    handler: Arc<H>,
}

impl<H: FileProcessingStepHandler> FileProcessingFlowExecutor<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<FileProcessingFlowInstance, FlowError> {
        let mut instance = FileProcessingFlowInstance::new(instance_id);
        instance.status = FileProcessingFlowStatus::Running;
        instance.current_step = Some(FileProcessingFlowStep::LoadJob);
        Ok(instance)
    }

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

        let next_step = match current_step {
            FileProcessingFlowStep::LoadJob => {
                self.handler.handle_load_job(instance).await?
            }
            FileProcessingFlowStep::MarkRunning => {
                self.handler.handle_mark_running(instance).await?
            }
            FileProcessingFlowStep::LoadFile => {
                self.handler.handle_load_file(instance).await?
            }
            FileProcessingFlowStep::LoadBucket => {
                self.handler.handle_load_bucket(instance).await?
            }
            FileProcessingFlowStep::RouteByJobType => {
                let next = self.handler.evaluate_route_by_job_type(instance).await?;
                Some(next)
            }
            FileProcessingFlowStep::ProcessImageThumbnail => {
                self.handler.handle_process_image_thumbnail(instance).await?
            }
            FileProcessingFlowStep::StoreImageThumbnail => {
                self.handler.handle_store_image_thumbnail(instance).await?
            }
            FileProcessingFlowStep::UpdateFileThumbnail => {
                self.handler.handle_update_file_thumbnail(instance).await?
            }
            FileProcessingFlowStep::ProcessVideoThumbnail => {
                self.handler.handle_process_video_thumbnail(instance).await?
            }
            FileProcessingFlowStep::StoreVideoThumbnail => {
                self.handler.handle_store_video_thumbnail(instance).await?
            }
            FileProcessingFlowStep::UpdateFileVideoThumbnail => {
                self.handler.handle_update_file_video_thumbnail(instance).await?
            }
            FileProcessingFlowStep::ProcessDocumentPreview => {
                self.handler.handle_process_document_preview(instance).await?
            }
            FileProcessingFlowStep::StoreDocumentPreview => {
                self.handler.handle_store_document_preview(instance).await?
            }
            FileProcessingFlowStep::UpdateFileDocumentPreview => {
                self.handler.handle_update_file_document_preview(instance).await?
            }
            FileProcessingFlowStep::ProcessCompression => {
                self.handler.handle_process_compression(instance).await?
            }
            FileProcessingFlowStep::StoreCompressedFile => {
                self.handler.handle_store_compressed_file(instance).await?
            }
            FileProcessingFlowStep::UpdateFileCompression => {
                self.handler.handle_update_file_compression(instance).await?
            }
            FileProcessingFlowStep::UpdateBucketCompressionStats => {
                self.handler.handle_update_bucket_compression_stats(instance).await?
            }
            FileProcessingFlowStep::ProcessVirusScan => {
                self.handler.handle_process_virus_scan(instance).await?
            }
            FileProcessingFlowStep::CheckThreatLevel => {
                let next = self.handler.evaluate_check_threat_level(instance).await?;
                Some(next)
            }
            FileProcessingFlowStep::UpdateScanSafe => {
                self.handler.handle_update_scan_safe(instance).await?
            }
            FileProcessingFlowStep::UpdateScanWarning => {
                self.handler.handle_update_scan_warning(instance).await?
            }
            FileProcessingFlowStep::NotifyScanWarning => {
                self.handler.handle_notify_scan_warning(instance).await?
            }
            FileProcessingFlowStep::UpdateScanThreat => {
                self.handler.handle_update_scan_threat(instance).await?
            }
            FileProcessingFlowStep::NotifyThreatDetected => {
                self.handler.handle_notify_threat_detected(instance).await?
            }
            FileProcessingFlowStep::ProcessDeduplication => {
                self.handler.handle_process_deduplication(instance).await?
            }
            FileProcessingFlowStep::CheckExistingHash => {
                self.handler.handle_check_existing_hash(instance).await?
            }
            FileProcessingFlowStep::UpdateExistingHash => {
                self.handler.handle_update_existing_hash(instance).await?
            }
            FileProcessingFlowStep::LinkFileHash => {
                self.handler.handle_link_file_hash(instance).await?
            }
            FileProcessingFlowStep::CreateNewHash => {
                self.handler.handle_create_new_hash(instance).await?
            }
            FileProcessingFlowStep::MarkComplete => {
                self.handler.handle_mark_complete(instance).await?
            }
            FileProcessingFlowStep::EmitCompleteEvent => {
                self.handler.handle_emit_complete_event(instance).await?
            }
            FileProcessingFlowStep::Complete => {
                self.handler.handle_complete(instance).await?;
                None // Terminal step
            }
            FileProcessingFlowStep::RetryOrFail => {
                let next = self.handler.evaluate_retry_or_fail(instance).await?;
                Some(next)
            }
            FileProcessingFlowStep::ScheduleRetry => {
                self.handler.handle_schedule_retry(instance).await?
            }
            FileProcessingFlowStep::RetryTerminal => {
                self.handler.handle_retry_terminal(instance).await?;
                None // Terminal step
            }
            FileProcessingFlowStep::MarkFailed => {
                self.handler.handle_mark_failed(instance).await?
            }
            FileProcessingFlowStep::EmitFailedEvent => {
                self.handler.handle_emit_failed_event(instance).await?
            }
            FileProcessingFlowStep::FailedTerminal => {
                self.handler.handle_failed_terminal(instance).await?;
                None // Terminal step
            }
            FileProcessingFlowStep::JobNotFound => {
                self.handler.handle_job_not_found(instance).await?;
                None // Terminal step
            }
            FileProcessingFlowStep::FileNotFound => {
                self.handler.handle_file_not_found(instance).await?;
                None // Terminal step
            }
            FileProcessingFlowStep::UnknownJobType => {
                self.handler.handle_unknown_job_type(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 = FileProcessingFlowStatus::Completed;
            }
        }

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

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

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

    /// Mark flow as failed
    pub fn fail(&self, instance: &mut FileProcessingFlowInstance, error: impl Into<String>) {
        instance.status = FileProcessingFlowStatus::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 = FileProcessingFlowInstance::new("test-1");
        assert_eq!(instance.id, "test-1");
        assert_eq!(instance.status, FileProcessingFlowStatus::Pending);
        assert!(!instance.is_complete());
    }

    #[test]
    fn test_flow_context() {
        let mut instance = FileProcessingFlowInstance::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 = FileProcessingFlowInstance::new("test-3");
        assert!(!instance.is_running());

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

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