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(redis-kv): replace redis with (potentially) more stable ioredis #267

Merged
merged 1 commit into from
Jan 14, 2025

Conversation

hlolli
Copy link
Contributor

@hlolli hlolli commented Jan 13, 2025

I'd propose according to https://github.com/redis/ioredis#tls-options tls isn't a natively supported thing in redis but users can set their custom ca file in case of proxies. But in most cases it's not needed. But an option to pass custom ca file could give away for enableTls boolean.

@hlolli hlolli changed the title feat(redis-kv): replace redis with more stable ioredis feat(redis-kv): replace redis with (potentially) more stable ioredis Jan 13, 2025
@hlolli hlolli force-pushed the feature/PE-7414_ioredis branch from a14411f to b514290 Compare January 13, 2025 17:35
Copy link
Contributor

coderabbitai bot commented Jan 13, 2025

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 eslint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

error @permaweb/[email protected]: The engine "yarn" is incompatible with this module. Expected version "please-use-npm". Got "1.22.22"
error Found incompatible module.

📝 Walkthrough

Walkthrough

The pull request involves migrating the Redis client library from redis to ioredis in the application. This change impacts the package.json, src/store/redis-kv-store.ts, src/init/resolvers.ts, src/init/header-stores.ts, and src/system.ts files, updating the dependency and refactoring the Redis client implementation. The modifications focus on changing the client initialization, connection configuration, and method calls to align with the new library's API, including the removal of the useTls parameter in the instantiation logic.

Changes

File Change Summary
package.json - Removed "redis": "^4.6.10" dependency
- Added "ioredis": "^5.4.2" dependency
src/store/redis-kv-store.ts - Changed client property type from RedisClientType to Redis
- Removed useTls constructor parameter
- Updated client initialization using ioredis
- Modified get method to use getBuffer
- Updated set method parameter handling
src/init/resolvers.ts - Removed useTls from parameters passed to RedisKvStore in createArNSKvStore function
src/init/header-stores.ts - Removed useTls parameter from createKvBufferStore method signature
src/system.ts - Removed useTls property from KvArNSRegistryStore instantiation

Sequence Diagram

sequenceDiagram
    participant App
    participant RedisKvStore
    participant Redis

    App->>RedisKvStore: Create instance with redisUrl
    RedisKvStore->>Redis: Create new Redis client
    Redis-->>RedisKvStore: Client initialized
    
    App->>RedisKvStore: get(key)
    RedisKvStore->>Redis: getBuffer(key)
    Redis-->>RedisKvStore: Return value
    RedisKvStore-->>App: Return value

    App->>RedisKvStore: set(key, value, ttl)
    RedisKvStore->>Redis: set(key, value, ttl)
    Redis-->>RedisKvStore: Confirm set
    RedisKvStore-->>App: Confirm set
Loading

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 566a2b1 and 1824fc7.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (5)
  • package.json (1 hunks)
  • src/init/header-stores.ts (0 hunks)
  • src/init/resolvers.ts (0 hunks)
  • src/store/redis-kv-store.ts (3 hunks)
  • src/system.ts (0 hunks)
💤 Files with no reviewable changes (3)
  • src/init/resolvers.ts
  • src/system.ts
  • src/init/header-stores.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • package.json
  • src/store/redis-kv-store.ts

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

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 3

🛑 Comments failed to post (3)
src/store/redis-kv-store.ts (3)

19-19: ⚠️ Potential issue

Correct the import statement for ioredis

The ioredis library exports Redis as the default export. Therefore, the import statement should use the default import syntax.

Apply this diff to fix the import statement:

-import { Redis } from 'ioredis';
+import Redis from 'ioredis';
📝 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.

import Redis from 'ioredis';

42-45: 🛠️ Refactor suggestion

Simplify Redis client initialization and ensure TLS is correctly configured

You can simplify the Redis client initialization by passing the redisUrl directly to the Redis constructor. This approach allows ioredis to handle the parsing of the URL and automatically configure the connection options, including enabling TLS if the rediss:// protocol is used.

Apply this diff to simplify the client initialization:

-        const redisUrlObject = new URL(redisUrl);

-        this.client = new Redis({
-          host: redisUrlObject.hostname,
-          port: Number(redisUrlObject.port),
-          tls: {},
-        });
+        this.client = new Redis(redisUrl);
📝 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.

    this.client = new Redis(redisUrl);

66-66: ⚠️ Potential issue

Replace getBuffer with get and enable returnBuffers option in client configuration

The method getBuffer does not exist in ioredis. To retrieve buffer values, set returnBuffers: true in the client options and use this.client.get(key).

Apply these diffs to fix the issue:

In client initialization:

-        this.client = new Redis(redisUrl);
+        this.client = new Redis(redisUrl, { returnBuffers: true });

In the get method:

-        const value = await this.client.getBuffer(key);
+        const value = await this.client.get(key);

Committable suggestion skipped: line range outside the PR's diff.

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

🧹 Nitpick comments (2)
src/store/redis-kv-store.ts (2)

82-82: Add error handling for Redis operations.

While the set implementation is correct, consider adding error handling to properly handle Redis operation failures.

-    await this.client.set(key, buffer, 'EX', this.ttlSeconds);
+    try {
+      await this.client.set(key, buffer, 'EX', this.ttlSeconds);
+    } catch (error) {
+      this.log.error('Failed to set key in Redis', {
+        key,
+        error: error.message,
+      });
+      metrics.redisErrorCounter.inc();
+      throw error;
+    }

42-46: Add connection timeout configuration.

To improve stability (PR objective), consider adding connection timeout settings.

   this.client = new Redis({
     host: redisUrlObject.hostname,
     port: Number(redisUrlObject.port),
     tls: {},
+    connectTimeout: 10000, // 10 seconds
+    maxRetriesPerRequest: 3,
+    retryStrategy: (times: number) => {
+      const delay = Math.min(times * 200, 2000);
+      return delay;
+    },
   });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a14411f and b514290.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (3)
  • package.json (1 hunks)
  • src/init/resolvers.ts (0 hunks)
  • src/store/redis-kv-store.ts (3 hunks)
💤 Files with no reviewable changes (1)
  • src/init/resolvers.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • package.json
🔇 Additional comments (2)
src/store/redis-kv-store.ts (2)

18-19: LGTM! Clean import replacement.

The migration from redis to ioredis types and imports is clean and correctly implemented.

Also applies to: 25-25


66-67: LGTM! Proper buffer handling.

The change to getBuffer with null coalescing is a clean implementation that correctly handles binary data and undefined cases.

Comment on lines 40 to 41
const redisUrlObject = new URL(redisUrl);

Copy link
Contributor

@coderabbitai coderabbitai bot Jan 13, 2025

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for URL parsing.

The URL parsing could fail with invalid URLs. Consider adding try-catch block to handle potential URL parsing errors.

-    const redisUrlObject = new URL(redisUrl);
+    let redisUrlObject: URL;
+    try {
+      redisUrlObject = new URL(redisUrl);
+    } catch (error) {
+      throw new Error(`Invalid Redis URL: ${error.message}`);
+    }
📝 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
const redisUrlObject = new URL(redisUrl);
let redisUrlObject: URL;
try {
redisUrlObject = new URL(redisUrl);
} catch (error) {
throw new Error(`Invalid Redis URL: ${error.message}`);
}

Copy link
Contributor Author

Choose a reason for hiding this comment

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

that's a good idea, appending this

Copy link
Contributor

Choose a reason for hiding this comment

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

@hlolli Great! This will make the Redis URL parsing more robust.

(`^´)
\
\
__
(/_
)\
( )-,-´


If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!

src/store/redis-kv-store.ts Outdated Show resolved Hide resolved
@hlolli hlolli force-pushed the feature/PE-7414_ioredis branch 3 times, most recently from 6f4d413 to 292a612 Compare January 13, 2025 17:42
Copy link

codecov bot commented Jan 13, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 71.75%. Comparing base (9ffdee0) to head (1824fc7).
Report is 1 commits behind head on develop.

Additional details and impacted files
@@           Coverage Diff            @@
##           develop     #267   +/-   ##
========================================
  Coverage    71.75%   71.75%           
========================================
  Files           37       37           
  Lines         9280     9280           
  Branches       537      537           
========================================
  Hits          6659     6659           
  Misses        2617     2617           
  Partials         4        4           

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

@hlolli hlolli force-pushed the feature/PE-7414_ioredis branch from 292a612 to 04a1bfd Compare January 13, 2025 18:16
@dtfiedler
Copy link
Collaborator

dtfiedler commented Jan 13, 2025

does ioredis support the rediss protocol - I just learned of it and believed can be used to establish secure connections

@dtfiedler
Copy link
Collaborator

dtfiedler commented Jan 13, 2025

does ioredis support the rediss protocol - I just learned of it and learned it can be used to establish secure connections

sure enough - it does! https://github.com/redis/ioredis?tab=readme-ov-file#connect-to-redis

You can also specify connection options as a redis:// URL or rediss:// URL when using TLS encryption:

@hlolli
Copy link
Contributor Author

hlolli commented Jan 14, 2025

@dtfiedler ok given this nice finding, I may want to revisit if the hostname property actually contains the protocol, but this also means for us that the url alone could replace the tls on/off switch, almost like postgresql, 1 url for user/pw/options and all.

@hlolli
Copy link
Contributor Author

hlolli commented Jan 14, 2025

@dtfiedler the power of the url is such designed, that I think we'll be making ours and the users life simpler by passing a single url string into the constructor and not parse the url. I'm adjusting the PR

Different issue: I do feel we should be less forgiving if the connection fails for any reason, at least initially, to crash the application if it fails, it's not easy to discover this from the logs alone imo.

@hlolli hlolli force-pushed the feature/PE-7414_ioredis branch from 04a1bfd to 566a2b1 Compare January 14, 2025 10:12
@hlolli hlolli force-pushed the feature/PE-7414_ioredis branch from 566a2b1 to 1824fc7 Compare January 14, 2025 17:32
@djwhitt djwhitt merged commit 2155614 into develop Jan 14, 2025
6 checks passed
@djwhitt djwhitt deleted the feature/PE-7414_ioredis branch January 14, 2025 17:50
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.

3 participants