Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: option to keep deleted recordings in backup for certain period #645

Merged
merged 3 commits into from
Jan 27, 2025

Conversation

jibon57
Copy link
Member

@jibon57 jibon57 commented Jan 25, 2025

Summary by CodeRabbit

Release Notes

  • New Features

    • Added configuration options for managing recording file backups.
    • Implemented automatic backup and cleanup of deleted recording files.
  • Improvements

    • Enhanced recording file management with configurable backup settings.
    • Added hourly scheduler to check and remove old backup files.
    • Introduced option to prevent immediate deletion of recording files.
  • Configuration

    • New options to enable backup of deleted recordings.
    • Configurable backup path and retention duration.
    • Default backup retention set to 72 hours.

Copy link

coderabbitai bot commented Jan 25, 2025

📝 Walkthrough

Walkthrough

This pull request introduces an enhanced recording backup management system. The changes add new configuration options to control the deletion and backup of recording files. A new feature allows users to enable backup of deleted recordings, specifying a backup path and retention duration. The implementation includes modifications to the configuration handling, scheduler, and recording deletion processes to support this new functionality, providing more robust file management for recording files.

Changes

File Change Summary
config_sample.yaml Added new configuration options for recording backup: enable_del_recording_backup, del_recording_backup_path, del_recording_backup_duration
pkg/config/config.go Updated RecorderInfo struct with new fields for backup configuration and added initialization logic in New function
pkg/models/recording_delete.go Modified DeleteRecording method to support file renaming and backup when deletion is requested
pkg/models/scheduler.go Added hourly ticker to trigger backup path checking
pkg/models/scheduler_recording.go Implemented new checkDelRecordingBackupPath method for managing backup file deletion

Sequence Diagram

sequenceDiagram
    participant Config as Configuration
    participant Scheduler as Backup Scheduler
    participant FileSystem as File System
    
    Config->>Scheduler: Enable Backup
    Scheduler->>Scheduler: Start Hourly Check
    Scheduler->>FileSystem: Check Backup Directory
    FileSystem-->>Scheduler: Return File List
    Scheduler->>Scheduler: Calculate Cutoff Time
    Scheduler->>FileSystem: Remove Expired Backup Files
Loading

Possibly related PRs

Poem

🐰 A Rabbit's Backup Ballet 🎬
Files dance to a backup beat,
Seventy-two hours, a safety treat
Recordings saved from deletion's might,
Protected by a rabbit's digital light!
Hop, hop, through files we go! 🚀

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai or @coderabbitai title anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (3)
pkg/config/config.go (1)

90-94: Consider adding validation for backup configuration values.

The new fields look good, but consider adding validation to ensure:

  • DelRecordingBackupPath is in a safe location
  • DelRecordingBackupDuration is within reasonable bounds (e.g., minimum 1 hour, maximum 30 days)
pkg/models/recording_delete.go (1)

Line range hint 82-91: Consider preserving directory structure in backup.

The current implementation flattens the directory structure in backup. Consider preserving it to maintain organization and prevent filename collisions.

config_sample.yaml (1)

146-150: Consider making the backup path more configurable.

While the implementation works, the hardcoded "/app" prefix in the backup path might not be suitable for all deployment scenarios. Consider:

  1. Making it relative to recording_files_path
  2. Using environment variables for path configuration
  3. Adding validation to ensure both paths are on the same disk/volume

Example configuration using relative path:

- del_recording_backup_path: "/app/recording_files/del_backup"
+ del_recording_backup_path: "${recording_files_path}/del_backup"
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f4872e9 and 7d1ee5d.

📒 Files selected for processing (5)
  • config_sample.yaml (1 hunks)
  • pkg/config/config.go (3 hunks)
  • pkg/models/recording_delete.go (3 hunks)
  • pkg/models/scheduler.go (2 hunks)
  • pkg/models/scheduler_recording.go (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test
🔇 Additional comments (3)
pkg/models/scheduler.go (1)

54-55: LGTM! Clean implementation of the hourly backup cleanup.

The hourly ticker is properly initialized and cleaned up, following the same pattern as other tickers in the scheduler.

Also applies to: 67-68

config_sample.yaml (2)

142-145: LGTM! Clear documentation of the backup feature.

The configuration and its documentation clearly explain the purpose and behavior of the deleted recording backup feature.


151-152: LGTM! Clear duration configuration.

The backup duration is well-documented and uses Go's standard duration format.

pkg/config/config.go Show resolved Hide resolved
pkg/models/scheduler_recording.go Show resolved Hide resolved
pkg/models/recording_delete.go Outdated Show resolved Hide resolved
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (3)
pkg/models/recording_delete.go (3)

72-74: Improve error handling in cleanup operations.

The current implementation silently ignores errors when removing compressed and JSON files. Consider logging these errors for better debugging capabilities.

Apply this diff:

-_ = os.Remove(filePath + ".fiber.gz")
-_ = os.Remove(filePath + ".json")
+if err := os.Remove(filePath + ".fiber.gz"); err != nil && !os.IsNotExist(err) {
+    log.Debugf("Failed to remove compressed file: %v", err)
+}
+if err := os.Remove(filePath + ".json"); err != nil && !os.IsNotExist(err) {
+    log.Debugf("Failed to remove JSON file: %v", err)
+}

Line range hint 79-87: Enhance directory cleanup robustness.

The directory cleanup logic could be improved in several ways:

  1. Use filepath.Clean for path comparison
  2. Add debug logging for directory removal attempts
  3. Consider using filepath.Dir instead of string replacement

Apply this diff:

-dir := strings.Replace(filePath, f.Name(), "", 1)
+dir := filepath.Dir(filePath)
+cleanRecordingPath := filepath.Clean(config.GetConfig().RecorderInfo.RecordingFilesPath)
-if dir != config.GetConfig().RecorderInfo.RecordingFilesPath {
+if filepath.Clean(dir) != cleanRecordingPath {
     empty, err := m.isDirEmpty(dir)
     if err == nil && empty {
+        log.Debugf("Attempting to remove empty directory: %s", dir)
         err = os.Remove(dir)
         if err != nil {
-            log.Error(err)
+            log.Errorf("Failed to remove directory %s: %v", dir, err)
         }
     }
 }

16-16: Add documentation for the backup functionality.

Consider adding documentation to explain:

  1. The purpose of the backup feature
  2. The behavior when backup is enabled/disabled
  3. How the retention period works
  4. Any limitations or requirements for the backup path

Add this documentation above the DeleteRecording method:

// DeleteRecording removes a recording identified by RecordId. If backup is enabled
// via RecorderInfo.EnableDelRecordingBackup, the recording will be moved to the
// backup location specified by DelRecordingBackupPath instead of being deleted.
// The backup will be retained according to DelRecordingBackupDuration setting.
// Returns an error if the operation fails.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7d1ee5d and 556ed53.

📒 Files selected for processing (2)
  • config_sample.yaml (1 hunks)
  • pkg/models/recording_delete.go (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • config_sample.yaml
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test
🔇 Additional comments (1)
pkg/models/recording_delete.go (1)

39-61: Improve reliability of backup operations.

The current backup implementation has several reliability concerns:

  1. No space check before backup operation
  2. No handling of cross-device moves (could fail on different filesystems)
  3. Setting modification time to current time might affect retention calculations
  4. JSON file backup error handling could be improved

Consider implementing the improvements suggested in the previous review comment, which addresses these concerns comprehensively.

pkg/models/recording_delete.go Outdated Show resolved Hide resolved
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (1)
pkg/models/recording_delete.go (1)

41-69: ⚠️ Potential issue

Improve reliability of backup operations.

The backup implementation needs several reliability improvements:

  1. No handling of cross-device moves (os.Rename may fail)
  2. No size checks for backup directory
  3. No validation of backup directory existence and permissions

Please refer to the previous review comment for the detailed implementation suggestions, including:

  • Adding space checks before backup
  • Handling cross-device moves with fallback to copy
  • Using Go's standard library for file modification time updates
🧹 Nitpick comments (2)
pkg/models/recording_delete.go (2)

26-36: Enhance error handling robustness.

While the switch to errors.As is good, the error handling could be improved:

  1. The error message splitting using strings.SplitN is fragile and may not work consistently across different error messages.
  2. The error handling could be more informative for debugging purposes.

Consider this improvement:

     f, err := os.Stat(filePath)
     if err != nil {
         var pathError *fs.PathError
         if errors.As(err, &pathError) {
-            log.Errorln(filePath + " does not exist, so deleting from DB without stopping")
+            log.WithFields(log.Fields{
+                "path": filePath,
+                "error": err,
+            }).Info("File not found, proceeding with DB deletion")
             fileExist = false
         } else {
-            ms := strings.SplitN(err.Error(), "/", -1)
-            return errors.New(ms[len(ms)-1])
+            return fmt.Errorf("failed to check file status: %w", err)
         }
     }

Line range hint 74-89: Improve cleanup operations reliability.

The cleanup operations have potential issues:

  1. Errors from cleanup operations are silently ignored
  2. There's a potential race condition in the directory emptiness check

Consider these improvements:

-    _ = os.Remove(filePath + ".fiber.gz")
-    _ = os.Remove(filePath + ".json")
+    if err := os.Remove(filePath + ".fiber.gz"); err != nil && !errors.Is(err, fs.ErrNotExist) {
+        log.WithError(err).Warn("Failed to remove compressed file")
+    }
+    if err := os.Remove(filePath + ".json"); err != nil && !errors.Is(err, fs.ErrNotExist) {
+        log.WithError(err).Warn("Failed to remove JSON file")
+    }

     // we will check if the directory is empty or not
     // if empty then better to delete that directory
     if fileExist {
         dir := strings.Replace(filePath, f.Name(), "", 1)
         if dir != config.GetConfig().RecorderInfo.RecordingFilesPath {
-            empty, err := m.isDirEmpty(dir)
-            if err == nil && empty {
-                err = os.Remove(dir)
-                if err != nil {
-                    log.Error(err)
-                }
+            // Use RemoveAll only if directory is empty to handle race conditions
+            entries, err := os.ReadDir(dir)
+            if err == nil && len(entries) == 0 {
+                if err := os.RemoveAll(dir); err != nil {
+                    log.WithError(err).Error("Failed to remove empty directory")
+                }
             }
         }
     }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 556ed53 and cfc33b7.

📒 Files selected for processing (1)
  • pkg/models/recording_delete.go (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test
🔇 Additional comments (2)
pkg/models/recording_delete.go (2)

10-14: LGTM! Appropriate imports added for new functionality.

The new imports support the enhanced file operations and time-based features.


Line range hint 1-89: Verify implementation completeness across the codebase.

Let's verify the implementation for potential issues:

  1. Check for consistent error handling patterns
  2. Look for potential backup path issues
  3. Verify scheduler integration for backup cleanup
✅ Verification successful

Implementation is complete and well-integrated

The codebase shows:

  • Consistent error handling patterns
  • Proper backup path validation and creation
  • Complete scheduler integration for backup cleanup
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify implementation completeness and consistency

# Check for consistent error handling patterns
echo "Checking error handling patterns..."
rg -A 2 "os\.(Rename|Remove)" --type go

# Look for backup path validation
echo "Checking backup path validation..."
rg "DelRecordingBackupPath" --type go

# Verify scheduler integration
echo "Checking scheduler integration..."
rg "checkDelRecordingBackupPath" --type go

Length of output: 4433

@jibon57 jibon57 merged commit cf64f3c into main Jan 27, 2025
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant