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

Add migration script to detach documents from deactivated clients #1062

Merged
merged 7 commits into from
Nov 21, 2024

Conversation

raararaara
Copy link
Contributor

@raararaara raararaara commented Nov 11, 2024

What this PR does / why we need it?

This PR introduces a migration script to properly detach documents that are still attached to deactivated clients.

While PRs #907 and #1036 improved the housekeeping process to ensure documents can be detached correctly, there may still be documents attached to deactivated clients from before these changes were applied.

Given the complexity of handling presence clears and version vector deletions during the detachment process, this migration script does not directly detach the documents. Instead, it updates the relevant clients from deactivated to activated, allowing the housekeeping process to manage the actual detachment of documents as intended.

Any background context you want to provide?

Deactivated clients may still have attached documents, which can lead to complications in managing document states. By running this migration script, we ensure a cleaner and more reliable detachment process for documents linked to clients that are no longer active.

What are the relevant tickets?

Related #602

Special notes for your reviewer:

Does this PR introduce a user-facing change?:


Additional documentation:


Checklist:

  • Added relevant tests or not required
  • Didn't break anything

Summary by CodeRabbit

  • New Features

    • Introduced functionality to manage client document states, allowing for reactivation of clients with attached documents.
    • Added validation to ensure no deactivated clients retain attached documents post-migration.
  • Bug Fixes

    • Improved error handling during the migration process to capture and report issues effectively.
  • Documentation

    • Updated migration process to include logging for better tracking of client reactivation status.

Copy link

coderabbitai bot commented Nov 11, 2024

Walkthrough

This pull request introduces a new file, document-detach.go, in the v056 package, which implements functions for managing client document states in a MongoDB collection. Key functions include validateDetach, which checks for deactivated clients with attached documents, and processMigrationBatch, which updates the status of such clients to "activated." The main function, ReactivateClients, orchestrates the migration process, handling errors and logging progress. Additionally, the RunMigration function in main.go is updated to call ReactivateClients, integrating this new functionality into the migration workflow.

Changes

File Change Summary
migrations/v0.5.6/document-detach.go Added validateDetach, processMigrationBatch, and ReactivateClients functions for client document management.
migrations/v0.5.6/main.go Updated RunMigration to include a call to ReactivateClients and handle potential errors.

Possibly related PRs

Suggested reviewers

  • hackerwins

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d226473 and cca84e8.

📒 Files selected for processing (1)
  • migrations/v0.5.6/main.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • migrations/v0.5.6/main.go

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 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 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

codecov bot commented Nov 11, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 46.79%. Comparing base (6eef109) to head (cca84e8).
Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #1062   +/-   ##
=======================================
  Coverage   46.79%   46.79%           
=======================================
  Files          84       84           
  Lines       12219    12219           
=======================================
  Hits         5718     5718           
  Misses       5928     5928           
  Partials      573      573           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.


🚨 Try these New Features:

@raararaara raararaara marked this pull request as ready for review November 13, 2024 14:47
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: 7

🧹 Outside diff range and nitpick comments (2)
migrations/v0.5.6/main.go (1)

17-18: Enhance package documentation with migration purpose

The package documentation should provide more context about the specific purpose of this migration. Consider adding details about reactivating clients with attached documents to enable proper document detachment.

-// Package v056 provides migration for v0.5.6
+// Package v056 provides migration for v0.5.6 to handle document detachment from
+// deactivated clients. It temporarily reactivates clients that have attached
+// documents to allow the housekeeping process to properly detach these documents.
 package v056
cmd/yorkie/migration.go (1)

46-48: Consider migration safety and rollback strategy.

Given that this migration modifies client activation states which affects document attachments:

  1. Ensure the migration is idempotent and can be safely re-run
  2. Consider adding a dry-run mode to preview the changes
  3. Document the rollback procedure in case of partial migration failure

Would you like me to help draft the documentation for these safety considerations?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f8ebba2 and 8459181.

📒 Files selected for processing (3)
  • cmd/yorkie/migration.go (2 hunks)
  • migrations/v0.5.6/document-detach.go (1 hunks)
  • migrations/v0.5.6/main.go (1 hunks)
🔇 Additional comments (5)
migrations/v0.5.6/main.go (3)

20-24: LGTM!

The imports are clean and contain only the necessary packages.


1-34: Verify migration system integration

Let's ensure this migration is properly integrated into the migration system and follows the correct version sequence.

#!/bin/bash
# Check migration registration and version sequence
echo "Checking migration registration..."
rg -A 5 'migrationMap\[' cmd/yorkie/migration.go

echo "Checking for other v0.5.x migrations..."
fd -t d '^v0\.5\.' migrations/

26-34: 🛠️ Refactor suggestion

Improve function documentation and error handling

The function implementation needs several improvements:

  1. The function documentation should describe the purpose and parameters
  2. The error handling could be more specific about what went wrong
  3. The batchSize parameter's valid range should be validated
-// RunMigration runs migrations for v0.5.6
+// RunMigration executes the v0.5.6 migration to reactivate clients that have
+// attached documents, allowing the housekeeping process to properly detach them.
+// The batchSize parameter controls how many clients are processed in each batch.
+//
+// Parameters:
+//   - ctx: Context for the operation
+//   - db: MongoDB client
+//   - databaseName: Name of the database
+//   - batchSize: Number of clients to process in each batch (must be > 0)
 func RunMigration(ctx context.Context, db *mongo.Client, databaseName string, batchSize int) error {
+	if batchSize <= 0 {
+		return fmt.Errorf("invalid batch size: %d, must be greater than 0", batchSize)
+	}
+
 	err := ReactivateClients(ctx, db, databaseName, batchSize)
 	if err != nil {
-		return err
+		return fmt.Errorf("failed to reactivate clients: %w", err)
 	}
 
 	return nil
 }

Let's verify the ReactivateClients implementation:

cmd/yorkie/migration.go (2)

33-33: Verify the v0.5.6 migration package implementation.

The import looks correct. Let's verify the implementation of the migration package.

#!/bin/bash
# Description: Verify the v0.5.6 migration package implementation

# Check if the migration package exists and contains the required files
fd -t f "main.go|document-detach.go" -p "migrations/v0.5.6"

# Verify RunMigration function signature in the v0.5.6 package
ast-grep --pattern 'func RunMigration(ctx context.Context, db *mongo.Client, dbName string, batchSize int) error'

47-47: Verify version ordering in migrationMap.

The new version entry follows the correct pattern. However, let's ensure there are no missing versions between v0.5.3 and v0.5.6 that should be included.

migrations/v0.5.6/document-detach.go Show resolved Hide resolved
migrations/v0.5.6/document-detach.go Outdated Show resolved Hide resolved
migrations/v0.5.6/document-detach.go Outdated Show resolved Hide resolved
migrations/v0.5.6/document-detach.go Outdated Show resolved Hide resolved
migrations/v0.5.6/document-detach.go Outdated Show resolved Hide resolved
migrations/v0.5.6/document-detach.go Show resolved Hide resolved
migrations/v0.5.6/document-detach.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

🧹 Outside diff range and nitpick comments (1)
migrations/v0.5.6/main.go (1)

33-35: Consider adding logging and transaction wrapping

While the integration is correct, consider these improvements for better observability and reliability:

  1. Add logging before starting the reactivation step
  2. Consider wrapping the operation in a transaction for atomicity

Example enhancement:

+    fmt.Println("Starting client reactivation migration...")
+    
+    session, err := db.StartSession()
+    if err != nil {
+        return fmt.Errorf("failed to start session: %w", err)
+    }
+    defer session.EndSession(ctx)
+    
+    if err := session.StartTransaction(); err != nil {
+        return fmt.Errorf("failed to start transaction: %w", err)
+    }
+    
     if err := ReactivateClients(ctx, db, databaseName, batchSize); err != nil {
+        session.AbortTransaction(ctx)
         return err
     }
+    
+    if err := session.CommitTransaction(ctx); err != nil {
+        return fmt.Errorf("failed to commit transaction: %w", err)
+    }
+    
+    fmt.Println("Client reactivation migration completed successfully")
🧰 Tools
🪛 GitHub Check: build

[failure] 33-33:
undefined: err


[failure] 34-34:
undefined: err (typecheck)


[failure] 33-33:
undefined: err


[failure] 34-34:
undefined: err) (typecheck)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d91a5f7 and d226473.

📒 Files selected for processing (1)
  • migrations/v0.5.6/main.go (1 hunks)
🧰 Additional context used
🪛 GitHub Check: build
migrations/v0.5.6/main.go

[failure] 33-33:
undefined: err


[failure] 34-34:
undefined: err (typecheck)


[failure] 33-33:
undefined: err


[failure] 34-34:
undefined: err) (typecheck)

🔇 Additional comments (1)
migrations/v0.5.6/main.go (1)

33-35: Verify migration safety and rollback mechanism

Since this migration modifies client states which triggers document detachment via housekeeping:

  1. Ensure there's a rollback strategy if the migration fails midway
  2. Verify the housekeeping process can handle the potential surge in activated clients

Let's check for related housekeeping code:

✅ Verification successful

Let me gather more information about the migration and rollback mechanisms.


Let me check the complete implementation of the migration and its error handling.


Migration is safe with proper error handling and batch processing

The implementation shows a well-designed migration with:

  1. Batch processing with progress tracking to handle large datasets
  2. Proper error handling and logging for each client update
  3. Post-migration validation to ensure consistency
  4. Idempotent operations using FindOneAndUpdate
  5. No risk of document detachment surge as it only activates clients that already have attached documents

The housekeeping process won't be impacted as this migration is corrective in nature - fixing an inconsistency where deactivated clients had attached documents.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for housekeeping-related code that handles document detachment
rg -A 5 "func.*[Hh]ousekeeping|func.*[Dd]etach[Dd]ocument"

# Look for any rate limiting or batch processing in housekeeping
ast-grep --pattern 'func $FUNC($_) {
  $$$
  batch$_ := $_
  $$$
}'

Length of output: 15195


Script:

#!/bin/bash
# Check the migration file for rollback mechanism and batch processing
rg -A 10 "func ReactivateClients|func Rollback" migrations/

# Look for any error handling and transaction management in the migration
ast-grep --pattern 'func $FUNC($_) {
  $$$
  tx := $_.Begin()
  $$$
}'

# Check for any batch size configuration or rate limiting
rg -A 5 "batchSize.*:=|const.*[Bb]atch[Ss]ize"

Length of output: 836


Script:

#!/bin/bash
# Get the complete implementation of the migration file
cat migrations/v0.5.6/document-detach.go

# Check for any transaction or error handling patterns in migrations
rg -A 10 "func.*Up.*|func.*Down.*" migrations/v0.5.6/

# Look for any MongoDB bulk operation patterns
rg -A 5 "UpdateMany|BulkWrite" migrations/v0.5.6/

Length of output: 5148

🧰 Tools
🪛 GitHub Check: build

[failure] 33-33:
undefined: err


[failure] 34-34:
undefined: err (typecheck)


[failure] 33-33:
undefined: err


[failure] 34-34:
undefined: err) (typecheck)

migrations/v0.5.6/main.go Outdated Show resolved Hide resolved
@hackerwins hackerwins self-requested a review November 20, 2024 07:50
Copy link
Member

@hackerwins hackerwins left a comment

Choose a reason for hiding this comment

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

Thanks for your contribution.

@hackerwins hackerwins merged commit 082224c into main Nov 21, 2024
5 checks passed
@hackerwins hackerwins deleted the detach-doc-migration branch November 21, 2024 00:45
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.

2 participants