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

Debug logs for RedisCache behaviour #8355

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open

Conversation

enisdenjo
Copy link
Collaborator

@enisdenjo enisdenjo commented Feb 3, 2025

Summary by CodeRabbit

  • New Features
    • Introduced enhanced logging for caching operations, ensuring more comprehensive and consistent recording of cache activity.

Copy link
Contributor

coderabbitai bot commented Feb 3, 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.

packages/cache/redis/src/index.ts

Oops! Something went wrong! :(

ESLint: 9.19.0

ESLint couldn't find an eslint.config.(js|mjs|cjs) file.

From ESLint v9.0.0, the default configuration file is now eslint.config.js.
If you are using a .eslintrc.* file, please follow the migration guide
to update your configuration file to the new format:

https://eslint.org/docs/latest/use/configure/migration-guide

If you still have problems after following the migration guide, please stop by
https://eslint.org/chat/help to chat with the team.

📝 Walkthrough

Walkthrough

This pull request enhances debug logging in the caching package that interfaces with Redis. The changes introduce a dedicated logger within the Redis cache class, logging Redis connection attempts and caching operations (set, get, and delete). The improved logging adds visibility into cache operations, aiding in troubleshooting and performance monitoring, without altering any public interfaces.

Changes

File Change Summary
.changeset/...-nail.md Document summarizing the new debug logging for caching behavior in the package.
packages/cache/redis/src/index.ts Added a private logger member to the RedisCache class; updated the constructor to initialize the logger; enhanced logging across connection, set, get, and delete methods.

Sequence Diagram(s)

sequenceDiagram
    participant Client as Application
    participant RC as RedisCache
    participant Log as Logger
    participant Redis as Redis Server

    Client->>RC: Instantiate RedisCache(options)
    RC->>Log: Log Redis connection attempt
    RC->>Redis: Initiate connection
    Redis-->>RC: Connection response
Loading
sequenceDiagram
    participant Client as Application
    participant RC as RedisCache
    participant Log as Logger
    participant Redis as Redis Server

    Client->>RC: set(key, value, ttl)
    RC->>Log: Log set operation details (key, ttl)
    RC->>Redis: Execute SET command
    Redis-->>RC: Acknowledge storage
    RC->>Log: Log operation result
    RC-->>Client: Return set status
Loading

Poem

I'm a rabbit hopping through the code,
Logging each cache hit on my merry road.
With each set and get, I watch it all,
Redis whispers its secrets, big and small.
Jumping with joy as the logs unfold,
Debug trails gleaming like treasures of gold!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

🪧 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

github-actions bot commented Feb 3, 2025

Apollo Federation Subgraph Compatibility Results

Federation 1 Support Federation 2 Support
_service🟢
@key (single)🟢
@key (multi)🟢
@key (composite)🟢
repeatable @key🟢
@requires🟢
@provides🟢
federated tracing🟢
@link🟢
@shareable🟢
@tag🟢
@override🟢
@inaccessible🟢
@composeDirective🟢
@interfaceObject🟢

Learn more:

Copy link
Contributor

github-actions bot commented Feb 3, 2025

🚀 Snapshot Release (alpha)

The latest changes of this PR are available as alpha on npm (based on the declared changesets):

Package Version Info
@graphql-mesh/cache-redis 0.103.14-alpha-20250203141256-071b199bd8554cdbb86d476c97bf0f70219725f9 npm ↗︎ unpkg ↗︎

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

🧹 Nitpick comments (3)
packages/cache/redis/src/index.ts (3)

45-45: Consider masking sensitive information in connection logs.

While the connection logging is helpful for debugging, consider masking sensitive parts of the connection URL/details (like credentials) to prevent security risks if logs are exposed.

Apply this diff to mask sensitive information:

-      this.logger.debug(`Connecting to Redis at ${urlStr}`);
+      const maskedUrl = urlStr.replace(/\/\/([^:]+):([^@]+)@/, '//***:***@');
+      this.logger.debug(`Connecting to Redis at ${maskedUrl}`);
-        this.logger.debug(`Connecting to Redis at ${parsedHost}:${parsedPort}`);
+        this.logger.debug(`Connecting to Redis at ${parsedHost}:${parsedPort}${parsedUsername ? ' with credentials' : ''}`);

Also applies to: 58-58, 70-70


88-91: Consider truncating and sanitizing cached values in logs.

Including full values in debug logs could:

  1. Expose sensitive data
  2. Generate excessive log volume with large values

Apply this diff to truncate and sanitize values:

-      this.logger.debug(
-        `Caching using key "${key}" with ${options.ttl * 1000}s TTL`,
-        stringifiedValue,
-      );
+      const truncatedValue = stringifiedValue.length > 100 
+        ? `${stringifiedValue.substring(0, 100)}...` 
+        : stringifiedValue;
+      this.logger.debug(
+        `Caching using key "${key}" with ${options.ttl * 1000}s TTL`,
+        truncatedValue,
+      );
-      this.logger.debug(`Caching using key "${key}"`, stringifiedValue);
+      const truncatedValue = stringifiedValue.length > 100 
+        ? `${stringifiedValue.substring(0, 100)}...` 
+        : stringifiedValue;
+      this.logger.debug(`Caching using key "${key}"`, truncatedValue);

Also applies to: 94-94


118-118: Consider consolidating error handling logic.

The method has two separate error handling blocks with similar logging logic. Consider consolidating them for better maintainability.

Apply this diff to consolidate error handling:

   delete(key: string): PromiseLike<boolean> | boolean {
+    const handleError = (e: Error, context: string) => {
+      this.logger.error(`Error ${context} "${key}" from cache`, e);
+      return false;
+    };
+
     try {
       this.logger.debug(`Deleting "${key}" from cache`);
       return mapMaybePromise(
         this.client.del(key),
         value => value > 0,
-        e => {
-          this.logger.error(`Error deleting "${key}" from cache`, e);
-          return false;
-        },
+        e => handleError(e, 'deleting'),
       );
     } catch (e) {
-      this.logger.error(`Error trying to delete "${key}" from cache`, e);
-      return false;
+      return handleError(e, 'trying to delete');
     }
   }

Also applies to: 123-124, 128-128

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6d02448 and 071b199.

📒 Files selected for processing (2)
  • .changeset/many-boxes-nail.md (1 hunks)
  • packages/cache/redis/src/index.ts (6 hunks)
✅ Files skipped from review due to trivial changes (1)
  • .changeset/many-boxes-nail.md
⏰ Context from checks skipped due to timeout of 90000ms (12)
  • GitHub Check: integration / node 22
  • GitHub Check: unit / node 22
  • GitHub Check: integration / node 20
  • GitHub Check: e2e / node v22
  • GitHub Check: unit / node 20
  • GitHub Check: integration / node 18
  • GitHub Check: e2e / node v20
  • GitHub Check: unit / node 18
  • GitHub Check: release / snapshot
  • GitHub Check: e2e / node v18
  • GitHub Check: check
  • GitHub Check: deployment
🔇 Additional comments (1)
packages/cache/redis/src/index.ts (1)

21-24: LGTM! Well-structured logger initialization.

Good practice to store the logger as a private class member, ensuring consistent access throughout the class methods.

Comment on lines +100 to +108
this.logger.debug(`Getting "${key}" from cache`);
return mapMaybePromise(this.client.get(key), value => {
return value != null ? JSON.parse(value) : undefined;
const val = value != null ? JSON.parse(value) : undefined;
if (val) {
this.logger.debug(`Cache hit using "${key}"`, val);
} else {
this.logger.debug(`Cache miss using "${key}"`);
}
return val;
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

Optimize value logging and handle potential JSON.parse errors.

The current implementation has two areas for improvement:

  1. Similar to set operation, logging full values could expose sensitive data
  2. JSON.parse could throw for invalid JSON strings

Apply this diff to improve the implementation:

     this.logger.debug(`Getting "${key}" from cache`);
     return mapMaybePromise(this.client.get(key), value => {
-      const val = value != null ? JSON.parse(value) : undefined;
-      if (val) {
-        this.logger.debug(`Cache hit using "${key}"`, val);
-      } else {
-        this.logger.debug(`Cache miss using "${key}"`);
-      }
-      return val;
+      try {
+        const val = value != null ? JSON.parse(value) : undefined;
+        if (val) {
+          const truncatedValue = JSON.stringify(val).length > 100 
+            ? `${JSON.stringify(val).substring(0, 100)}...` 
+            : JSON.stringify(val);
+          this.logger.debug(`Cache hit using "${key}"`, truncatedValue);
+        } else {
+          this.logger.debug(`Cache miss using "${key}"`);
+        }
+        return val;
+      } catch (e) {
+        this.logger.error(`Error parsing cached value for "${key}"`, e);
+        return undefined;
+      }
📝 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
this.logger.debug(`Getting "${key}" from cache`);
return mapMaybePromise(this.client.get(key), value => {
return value != null ? JSON.parse(value) : undefined;
const val = value != null ? JSON.parse(value) : undefined;
if (val) {
this.logger.debug(`Cache hit using "${key}"`, val);
} else {
this.logger.debug(`Cache miss using "${key}"`);
}
return val;
this.logger.debug(`Getting "${key}" from cache`);
return mapMaybePromise(this.client.get(key), value => {
try {
const val = value != null ? JSON.parse(value) : undefined;
if (val) {
const truncatedValue = JSON.stringify(val).length > 100
? `${JSON.stringify(val).substring(0, 100)}...`
: JSON.stringify(val);
this.logger.debug(`Cache hit using "${key}"`, truncatedValue);
} else {
this.logger.debug(`Cache miss using "${key}"`);
}
return val;
} catch (e) {
this.logger.error(`Error parsing cached value for "${key}"`, e);
return undefined;
}
});

Copy link
Contributor

github-actions bot commented Feb 3, 2025

💻 Website Preview

The latest changes are available as preview in: https://f966323a.graphql-mesh.pages.dev

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