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

Open
wants to merge 5 commits into
base: main
Choose a base branch
from

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 migration version v0.5.6, enhancing the migration system's capability.
    • Added functionality to manage client document states and reactivation of clients with attached documents.
  • Bug Fixes
    • Improved error handling during database operations, ensuring better reliability.
  • Documentation
    • Updated documentation to reflect the new migration version and its functionalities.

Copy link

coderabbitai bot commented Nov 11, 2024

Walkthrough

The changes introduce a new migration version (v0.5.6) to the migration functionality in the Yorkie application. This includes updates to the migrationMap to link the new version to its corresponding RunMigration function in the v056 package. Additionally, new functions are added to manage client document states in a MongoDB collection, including validation and reactivation of clients with attached documents. The overall structure and error handling of the migration system remain consistent with previous versions.

Changes

File Path Change Summary
cmd/yorkie/migration.go Added migration version v0.5.6 to migrationMap, linking it to RunMigration from the v056 package.
migrations/v0.5.6/document-detach.go Introduced functions for managing client document states: validateDetach, processMigrationBatch, and ReactivateClients.
migrations/v0.5.6/main.go Added RunMigration function to initiate the migration process, calling ReactivateClients.

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 8459181 and d91a5f7.

📒 Files selected for processing (1)
  • migrations/v0.5.6/document-detach.go (1 hunks)
🧰 Additional context used
📓 Learnings (1)
migrations/v0.5.6/document-detach.go (1)
Learnt from: raararaara
PR: yorkie-team/yorkie#1062
File: migrations/v0.5.6/document-detach.go:166-167
Timestamp: 2024-11-14T05:10:21.630Z
Learning: In the `ReactivateClients` function in `migrations/v0.5.6/document-detach.go`, when `totalCount` is zero, the cursor will be empty, and the loop where `percentage` is calculated won't execute, so division by zero is not a concern.
🔇 Additional comments (2)
migrations/v0.5.6/document-detach.go (2)

183-183: LGTM!

The migration script is well-structured and aligns with the PR objectives. Error handling and logging are appropriately implemented.


169-170: 🛠️ Refactor suggestion

Correct the progress percentage calculation to reflect actual progress

Currently, the progress percentage is calculated using batchSize * batchCount, which may not accurately represent the actual number of clients processed, especially in the last batch where the number of clients may be less than the batch size.

Apply this diff to use done (the actual number of clients processed) in the calculation:

- percentage := int(float64(batchSize*batchCount) / float64(totalCount) * 100)
+ percentage := int(float64(done) / float64(totalCount) * 100)
⛔ Skipped due to learnings
Learnt from: raararaara
PR: yorkie-team/yorkie#1062
File: migrations/v0.5.6/document-detach.go:166-167
Timestamp: 2024-11-14T05:10:21.630Z
Learning: In the `ReactivateClients` function in `migrations/v0.5.6/document-detach.go`, when `totalCount` is zero, the cursor will be empty, and the loop where `percentage` is calculated won't execute, so division by zero is not a concern.

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.82%. Comparing base (f8ebba2) to head (d91a5f7).

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #1062   +/-   ##
=======================================
  Coverage   46.82%   46.82%           
=======================================
  Files          84       84           
  Lines       12180    12180           
=======================================
  Hits         5703     5703           
  Misses       5909     5909           
  Partials      568      568           

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

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