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

chore: Use Lettuce client to run clear keys across Redis nodes #36862

Merged
merged 4 commits into from
Oct 14, 2024

Conversation

nidhi-nair
Copy link
Contributor

@nidhi-nair nidhi-nair commented Oct 14, 2024

07/10 - Daily promotion## Description

Tip

Add a TL;DR when the description is longer than 500 words or extremely technical (helps the content, marketing, and DevRel team).

Please also include relevant motivation and context. List any dependencies that are required for this change. Add links to Notion, Figma or any other documents that might be relevant to the PR.

Fixes #Issue Number
or
Fixes Issue URL

Warning

If no issue exists, please create an issue first, and check with the maintainers if the issue is valid.

Automation

/ok-to-test tags=""

🔍 Cypress test results

Warning

Tests have not run on the HEAD 2e47baf yet


Mon, 14 Oct 2024 11:26:21 UTC

Communication

Should the DevRel and Marketing teams inform users about this change?

  • Yes
  • No

Summary by CodeRabbit

  • New Features

    • Introduced a new SMTP plugin with documentation support.
    • Updated Firestore plugin to enhance user interface components and schema usage.
    • Added new indexes for improved query performance across various collections.
  • Bug Fixes

    • Marked CRUD generation for the MSSQL plugin as unavailable to prevent confusion.
  • Improvements

    • Enhanced Redis operations for better key management and performance.
    • Updated plugin icons for improved asset management through a CDN.

Copy link
Contributor

coderabbitai bot commented Oct 14, 2024

Walkthrough

The changes made in this pull request focus on enhancing plugin and database management within a MongoDB context. Key modifications include changing method visibility, adding new migration steps via @ChangeSet annotations, and optimizing database indexing. Additionally, the Migration063CacheBustSpringBoot3_3 class has been updated to improve Redis operations by replacing ReactiveRedisTemplate with ReactiveRedisOperations and introducing a new method for scanning keys.

Changes

File Path Change Summary
app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/DatabaseChangelog1.java - Changed method visibility of doClearRedisKeys from protected to public.
- Added multiple new @ChangeSet annotations for various plugin updates and index management.
app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration063CacheBustSpringBoot3_3.java - Updated method signature to accept ReactiveRedisOperations instead of ReactiveRedisTemplate.
- Introduced a new method scanForKeysAcrossCluster for enhanced key scanning and deletion in Redis.

Possibly related PRs

Suggested labels

skip-changelog, ok-to-test, Needs Triaging, Production

Suggested reviewers

  • sharat87
  • abhvsn
  • mohanarpit

Poem

In the land of code, where changes flow,
New plugins and indexes begin to grow.
Redis now dances with keys that are bright,
As migrations take flight in the soft, gentle night.
So let’s celebrate this coding spree,
For each line brings us closer to glee! 🎉


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.

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.

@nidhi-nair
Copy link
Contributor Author

/build-deploy-preview skip-tests=true

Copy link

Deploying Your Preview: https://github.com/appsmithorg/appsmith/actions/runs/11326054119.
Workflow: On demand build Docker image and deploy preview.
skip-tests: true.
env: ``.
PR: 36862.
recreate: .

Copy link
Contributor

@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 (3)
app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/DatabaseChangelog1.java (3)

Line range hint 803-808: Add Null Check for firestorePlugin to Prevent Possible NullPointerException

It's important to handle cases where the Firestore plugin might not be found in the database. Before calling setUiComponent and save, please check if firestorePlugin is not null. This will help prevent a potential NullPointerException.

Here's how you can modify the code:

 Plugin firestorePlugin = mongoTemplate.findOne(query(where("packageName").is("firestore-plugin")), Plugin.class);
+ if (firestorePlugin != null) {
     firestorePlugin.setUiComponent("UQIDbEditorForm");

     // Update plugin data.
     mongoTemplate.save(firestorePlugin);
+ } else {
+     log.warn("Firestore plugin not found in the database.");
+ }

Line range hint 817-822: Ensure Null Safety and Clarify Method Naming

Once again, please add a null check for firestorePlugin to prevent a possible NullPointerException. Additionally, consider renaming the method migrateFirestorePluginToUqi3 to something more descriptive to enhance code readability and maintainability.

Apply the following changes:

 Plugin firestorePlugin = mongoTemplate.findOne(query(where("packageName").is("firestore-plugin")), Plugin.class);
+ if (firestorePlugin != null) {
     firestorePlugin.setUiComponent("UQIDbEditorForm");

     // Update plugin data.
     mongoTemplate.save(firestorePlugin);
+ } else {
+     log.warn("Firestore plugin not found in the database.");
+ }

Consider renaming the method for clarity, for example:

-public void migrateFirestorePluginToUqi3(MongoTemplate mongoTemplate) {
+public void migrateFirestorePluginToUqiVersion3(MongoTemplate mongoTemplate) {

Line range hint 843-848: Replace assert with Explicit Null Check for Robustness

Using assert to check if plugin is not null can be insufficient because assertions might be disabled at runtime. It's better to use an explicit null check to ensure that the code behaves correctly regardless of runtime settings. This approach enhances the robustness of your code.

Here's the improved code:

 Plugin plugin = mongoTemplate.findOne(query(where("packageName").is("mssql-plugin")), Plugin.class);
- assert plugin != null;
+ if (plugin != null) {
     plugin.setGenerateCRUDPageComponent(null);
     mongoTemplate.save(plugin);
+ } else {
+     log.warn("MSSQL plugin not found in the database.");
+ }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 97f2560 and 485ef8d.

📒 Files selected for processing (2)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/DatabaseChangelog1.java (1 hunks)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration063CacheBustSpringBoot3_3.java (2 hunks)
🧰 Additional context used
🔇 Additional comments (4)
app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration063CacheBustSpringBoot3_3.java (2)

24-26: Updating Method Signature to Use ReactiveRedisOperations

Well done on updating the method signature to use ReactiveRedisOperations<String, Object>. This change aligns the code with the latest best practices in Spring Data Redis, ensuring better compatibility and maintainability.


25-25: ⚠️ Potential issue

Consider Avoiding Blocking Calls in Reactive Streams

In reactive programming, we aim to keep the data flow non-blocking to fully leverage the benefits of asynchronous processing. The use of .block() can introduce blocking behavior, which might lead to performance issues.

As an alternative, you could modify the execute method to return a Mono<Void> and handle the reactive stream without blocking:

-    public void execute(
+    public Mono<Void> execute(
             @Qualifier("reactiveRedisOperations") ReactiveRedisOperations<String, Object> reactiveRedisOperations) {
-        scanForKeysAcrossCluster(reactiveRedisOperations, "*").block();
+        return scanForKeysAcrossCluster(reactiveRedisOperations, "*");
     }

However, please verify whether the migration framework supports reactive return types. If it doesn't, and blocking is necessary in this context, consider documenting the reason to inform future developers.

Please check the migration framework's capabilities regarding reactive return types and adjust accordingly.

app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/DatabaseChangelog1.java (2)

Line range hint 791-797: Consider the Visibility Change of doClearRedisKeys Method

Dear student, I notice that you've changed the doClearRedisKeys method from protected to public. Exposing this method publicly means it can now be accessed from outside its class and package. Please ensure that this change is necessary and aligns with the design principles of encapsulation and security. Public methods should be carefully managed to prevent unintended usage or security vulnerabilities.


Line range hint 850-862: Verify Index Names Against Length Limitations

When creating indexes with names like "unpublishedActionPageId_deleted_compound_index", it's essential to ensure that they comply with MongoDB's index name length limitations. Long index names can cause errors or be truncated unexpectedly, leading to potential issues during database operations. Please verify that all index names meet the necessary constraints.

Comment on lines +28 to +43
private Mono<Void> scanForKeysAcrossCluster(
ReactiveRedisOperations<String, Object> reactiveRedisOperations, String pattern) {
return reactiveRedisOperations
.execute(connection -> {
Flux<ByteBuffer> scanFlux = connection
.keyCommands()
.scan(ScanOptions.scanOptions()
.match(pattern)
.count(1000)
.build());
return scanFlux.flatMap(scannedKey -> {
return connection.keyCommands().del(scannedKey);
})
.then();
})
.then();
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Optimizing Key Scanning and Deletion in Redis

You've effectively encapsulated the Redis key scanning and deletion logic within the scanForKeysAcrossCluster method. Here are some suggestions to enhance its performance and reliability:

  1. Refine the Scan Pattern: Scanning with a wildcard "*" can be resource-intensive, especially in a production environment with a large number of keys. If possible, narrow down the pattern to target only the relevant keys that need deletion.

  2. Batch Deletion for Efficiency: Deleting keys individually may lead to increased overhead. Batching the keys and performing a bulk delete can improve performance significantly.

  3. Handle Potential Exceptions: It's important to anticipate and handle any exceptions that might occur during the scanning and deletion process to prevent unexpected failures.

Here's how you could modify the method to incorporate these suggestions:

 private Mono<Void> scanForKeysAcrossCluster(
         ReactiveRedisOperations<String, Object> reactiveRedisOperations, String pattern) {
     return reactiveRedisOperations
             .execute(connection -> {
                 Flux<ByteBuffer> scanFlux = connection
                         .keyCommands()
                         .scan(ScanOptions.scanOptions()
                                 .match(pattern)
                                 .count(1000)
                                 .build());
-                return scanFlux.flatMap(scannedKey -> {
-                            return connection.keyCommands().del(scannedKey);
-                        })
+                return scanFlux.buffer(1000)
+                        .flatMap(keys -> connection.keyCommands().del(keys.toArray(new ByteBuffer[0])))
+                        .onErrorContinue((throwable, obj) -> {
+                            log.error("Error deleting keys: {}", throwable.getMessage());
+                        });
             })
             .then();
 }
  • Batching with buffer(1000): This groups the keys into batches of 1000 before deletion.
  • Bulk Deletion: Deleting the keys in bulk reduces the number of network calls and improves efficiency.
  • Error Handling with onErrorContinue: This ensures that if an error occurs during deletion, it logs the error but continues processing the remaining keys.

If you'd like further assistance in implementing these changes or have questions about Redis key management, please let me know!

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
private Mono<Void> scanForKeysAcrossCluster(
ReactiveRedisOperations<String, Object> reactiveRedisOperations, String pattern) {
return reactiveRedisOperations
.execute(connection -> {
Flux<ByteBuffer> scanFlux = connection
.keyCommands()
.scan(ScanOptions.scanOptions()
.match(pattern)
.count(1000)
.build());
return scanFlux.flatMap(scannedKey -> {
return connection.keyCommands().del(scannedKey);
})
.then();
})
.then();
private Mono<Void> scanForKeysAcrossCluster(
ReactiveRedisOperations<String, Object> reactiveRedisOperations, String pattern) {
return reactiveRedisOperations
.execute(connection -> {
Flux<ByteBuffer> scanFlux = connection
.keyCommands()
.scan(ScanOptions.scanOptions()
.match(pattern)
.count(1000)
.build());
return scanFlux.buffer(1000)
.flatMap(keys -> connection.keyCommands().del(keys.toArray(new ByteBuffer[0])))
.onErrorContinue((throwable, obj) -> {
log.error("Error deleting keys: {}", throwable.getMessage());
});
})
.then();
}

Copy link

Deploy-Preview-URL: https://ce-36862.dp.appsmith.com

@nidhi-nair nidhi-nair changed the title Merge pull request #36723 from appsmithorg/release chore: Use Lettuce client to run clear keys across Redis nodes Oct 14, 2024
@github-actions github-actions bot added the skip-changelog Adding this label to a PR prevents it from being listed in the changelog label Oct 14, 2024
@nidhi-nair nidhi-nair merged commit add9808 into release Oct 14, 2024
16 checks passed
@nidhi-nair nidhi-nair deleted the tagged/v1.44 branch October 14, 2024 11:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
skip-changelog Adding this label to a PR prevents it from being listed in the changelog
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants