Skip to main content

Module long_operation

Module long_operation 

Source
Expand description

This module provides a framework for managing long-running operations with the ability to track status, progress, and enable cancellation. It includes the infrastructure for defining, executing, and monitoring such operations. For undoable operations, it is recommended to use the Undo/Redo framework.

§Components:

  • OperationStatus: Enum representing the state of an operation.
  • OperationProgress: Struct holding details about the progress of an operation.
  • LongOperation: Trait that must be implemented by any long-running operation.
  • LongOperationManager: Manager that orchestrates the execution, tracking, and cleanup of multiple operations.

§Usage:

  1. Implement the LongOperation trait for your task.
  2. Use LongOperationManager to start, track, and manage your operations.
  3. Access methods like:
    • start_operation to start new operations.
    • get_operation_status, get_operation_progress to query operation details.
    • cancel_operation to cancel operations.
    • cleanup_finished_operations to remove completed or cancelled operations.

§Example:

// Define your long-running operation
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
use std::time::Duration;
use common::long_operation::{LongOperation, LongOperationManager, OperationProgress};

pub struct MyOperation {
    pub total_steps: usize,
}

impl LongOperation for MyOperation {
    fn execute(
        &self,
        progress_callback: Box<dyn Fn(OperationProgress) + Send>,
        cancel_flag: Arc<AtomicBool>,
    ) -> Result<(), String> {
        for i in 0..self.total_steps {
            if cancel_flag.load(Ordering::Relaxed) {
                return Err("Operation cancelled".to_string());
            }
            thread::sleep(Duration::from_millis(500));
            progress_callback(OperationProgress::new(
                (i as f32 / self.total_steps as f32) * 100.0,
                Some(format!("Step {}/{}", i + 1, self.total_steps)),
            ));
        }
        Ok(())
    }
}

let manager = LongOperationManager::new();
let my_operation = MyOperation { total_steps: 5 };
let operation_id = manager.start_operation(my_operation);

while let Some(status) = manager.get_operation_status(&operation_id) {
    println!("{:?}", status);
    thread::sleep(Duration::from_millis(100));
}

§Notes:

  • Thread-safety is ensured through the use of Arc<Mutex<T>> and AtomicBool.
  • Operations run in their own threads, ensuring non-blocking execution.
  • Proper cleanup of finished operations is encouraged using cleanup_finished_operations.

§Definitions:

§OperationStatus

Represents the state of an operation. Possible states are:

  • Running: Operation is ongoing.
  • Completed: Operation finished successfully.
  • Cancelled: Operation was cancelled by the user.
  • Failed(String): Operation failed with an error message.

§OperationProgress

Describes the progress of an operation, including:

  • percentage (0.0 to 100.0): Indicates completion progress.
  • message: Optional user-defined progress description.

§LongOperation Trait

Any custom long-running operation must implement this trait:

  • execute: Defines the operation logic, accepting a progress callback and cancellation flag.

§LongOperationManager

Provides APIs to manage operations, including:

  • start_operation: Starts a new operation and returns its unique ID.
  • get_operation_status: Queries the current status of an operation.
  • get_operation_progress: Retrieves the progress of an operation.
  • cancel_operation: Cancels an operation.
  • cleanup_finished_operations: Removes completed or cancelled operations to free resources.

§Example Operation: FileProcessingOperation

Represents a long-running operation to process files. Demonstrates typical usage of the framework.

  • Fields:
    • file_path: Path of the file to process.
    • total_files: Number of files to process.
  • Behavior: Simulates file processing with periodic progress updates. Supports cancellation.

Structs§

LongOperationManager
OperationProgress

Enums§

OperationStatus

Traits§

LongOperation