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

New Upstash Redis implementation #8350

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

New Upstash Redis implementation #8350

wants to merge 5 commits into from

Conversation

ardatan
Copy link
Owner

@ardatan ardatan commented Jan 31, 2025

Closes #8350

Summary by CodeRabbit

  • New Features

    • Added Upstash Redis caching implementation for GraphQL Mesh.
    • Introduced a new cache storage method for testing and configuration.
  • Dependencies

    • Added @graphql-mesh/cache-upstash-redis package.
  • Improvements

    • Enhanced caching capabilities with dynamic cache storage configuration.
    • Implemented key-value storage operations using Upstash Redis client.

Copy link

coderabbitai bot commented Jan 31, 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.

e2e/cache-control/cache-control.test.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

The pull request introduces a new implementation for Upstash Redis caching in the GraphQL Mesh framework. This includes the addition of the @graphql-mesh/cache-upstash-redis package, which provides a comprehensive implementation of a Redis-based cache mechanism. The changes involve creating a new package structure, implementing a cache class, updating test configurations, and adding necessary dependencies to support Upstash Redis as a caching option.

Changes

File Change Summary
.changeset/sixty-rivers-shave.md New changeset file for the Upstash Redis cache implementation
e2e/cache-control/cache-control.test.ts Added upstash-redis async function to cache storage options
e2e/cache-control/gateway.config.ts Dynamic cache configuration with Upstash Redis support
e2e/cache-control/package.json Added @graphql-mesh/cache-upstash-redis as a dev dependency
packages/cache/upstash-redis/package.json New package configuration for Upstash Redis cache
packages/cache/upstash-redis/src/index.ts Implemented UpstashRedisCache class with key-value cache methods

Sequence Diagram

sequenceDiagram
    participant Client
    participant UpstashRedisCache
    participant UpstashRedis

    Client->>UpstashRedisCache: Initialize with config
    Client->>UpstashRedisCache: set(key, value, options)
    UpstashRedisCache->>UpstashRedis: Store key-value
    Client->>UpstashRedisCache: get(key)
    UpstashRedisCache->>UpstashRedis: Retrieve value
    UpstashRedisCache-->>Client: Return value
    Client->>UpstashRedisCache: delete(key)
    UpstashRedisCache->>UpstashRedis: Remove key
Loading

Poem

🐰 In the realm of Redis so bright,
Upstash dances with caching delight.
Mesh weaves its magical thread,
Storing secrets where data is led.
A rabbit's cache, swift and clean! 🚀


📜 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 3c62e01 and 3768101.

📒 Files selected for processing (1)
  • e2e/cache-control/cache-control.test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • e2e/cache-control/cache-control.test.ts
⏰ Context from checks skipped due to timeout of 90000ms (13)
  • GitHub Check: unit / node 22
  • GitHub Check: integration / node 22
  • GitHub Check: unit / node 20
  • GitHub Check: e2e / node v22
  • GitHub Check: integration / node 20
  • GitHub Check: unit / node 18
  • GitHub Check: e2e / node v20
  • GitHub Check: release / snapshot
  • GitHub Check: integration / node 18
  • GitHub Check: e2e / node v18
  • GitHub Check: apollo-federation-compatibility
  • GitHub Check: check
  • GitHub Check: deployment

🪧 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 Jan 31, 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 Jan 31, 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-upstash-redis 0.0.1-alpha-20250131122034-37681017c13d2c8ddc07567295682c224a75a5a3 npm ↗︎ unpkg ↗︎

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

🧹 Nitpick comments (5)
packages/cache/upstash-redis/src/index.ts (1)

26-34: Optimize TTL conversion.

The TTL conversion to milliseconds could be more explicit and safer.

Consider this improvement:

   async set<T>(key: string, value: T, options?: { ttl?: number }) {
     if (options?.ttl) {
+      const ttlMs = Math.max(1, Math.floor(options.ttl * 1000));
       await this.redis.set(key, value, {
-        px: options.ttl * 1000,
+        px: ttlMs,
       });
     } else {
       await this.redis.set(key, value);
     }
   }
e2e/cache-control/gateway.config.ts (1)

7-14: Add type safety and error handling for cache configuration.

The current implementation could be more robust with proper type checking and error handling.

Consider this improvement:

+type CacheType = 'upstash-redis' | 'redis' | 'inmemory-lru';
+
+function isValidCacheType(type: string): type is CacheType {
+  return ['upstash-redis', 'redis', 'inmemory-lru'].includes(type);
+}
+
+const cacheType = process.env.CACHE_STORAGE;
+if (!cacheType || !isValidCacheType(cacheType)) {
+  throw new Error(`Invalid cache type: ${cacheType}`);
+}
+
-if (process.env.CACHE_STORAGE === 'upstash-redis') {
+if (cacheType === 'upstash-redis') {
   config.cache = new UpstashRedisCache();
 } else {
   config.cache = {
     // @ts-expect-error - We know it
-    type: process.env.CACHE_STORAGE,
+    type: cacheType,
   };
 }
e2e/cache-control/cache-control.test.ts (2)

102-102: Enhance container health check.

The current health check only verifies HTTP availability but not Redis functionality through the HTTP interface.

Consider this improvement:

-          healthcheck: ['CMD', 'curl', '-f', 'http://localhost'],
+          healthcheck: ['CMD', 'curl', '-f', 'http://localhost/health' '-H', 'Authorization: Bearer example_token'],

110-113: Add error handling for container disposal.

The disposal of containers should handle potential errors gracefully.

Consider this improvement:

   async [DisposableSymbols.asyncDispose]() {
-    await redis[DisposableSymbols.asyncDispose]();
-    await srh[DisposableSymbols.asyncDispose]();
+    try {
+      await Promise.all([
+        redis[DisposableSymbols.asyncDispose](),
+        srh[DisposableSymbols.asyncDispose](),
+      ]);
+    } catch (error) {
+      console.error('Error disposing containers:', error);
+      throw error;
+    }
   }
packages/cache/upstash-redis/package.json (1)

34-36: Consider constraining the graphql peer dependency version range.

Using "*" for the graphql peer dependency might lead to compatibility issues. Consider specifying a minimum version or version range that has been tested with this package.

-    "graphql": "*"
+    "graphql": "^16.0.0"
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 93b17fe and a30bb9a.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (6)
  • .changeset/sixty-rivers-shave.md (1 hunks)
  • e2e/cache-control/cache-control.test.ts (1 hunks)
  • e2e/cache-control/gateway.config.ts (1 hunks)
  • e2e/cache-control/package.json (1 hunks)
  • packages/cache/upstash-redis/package.json (1 hunks)
  • packages/cache/upstash-redis/src/index.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • .changeset/sixty-rivers-shave.md
⏰ Context from checks skipped due to timeout of 90000ms (13)
  • GitHub Check: e2e / node v22
  • GitHub Check: unit / node 22
  • GitHub Check: e2e / node v20
  • GitHub Check: integration / node 22
  • GitHub Check: unit / node 20
  • GitHub Check: integration / node 20
  • GitHub Check: release / snapshot
  • GitHub Check: unit / node 18
  • GitHub Check: integration / node 18
  • GitHub Check: e2e / node v18
  • GitHub Check: check
  • GitHub Check: deployment
  • GitHub Check: apollo-federation-compatibility
🔇 Additional comments (5)
e2e/cache-control/package.json (1)

8-8: Update version specification.

The version ^0.0.0 is not a proper semantic version and might cause issues with dependency resolution.

Please verify and update to a proper version number following semantic versioning.

packages/cache/upstash-redis/package.json (4)

14-32: LGTM! Excellent dual CJS/ESM support configuration.

The exports field is well-structured with proper type definitions for both CommonJS and ES modules.


44-48: LGTM! Publishing configuration is well-structured.

The publishing configuration correctly specifies public access and the dist directory, with sideEffects properly set to false for better tree-shaking.


49-51: LGTM! TypeScript configuration is consistent.

The TypeScript definition path matches the exports configuration.


37-43: Verify @upstash/redis version compatibility and security.

Let's check if version 1.34.3 of @upstash/redis is the latest stable version and if it has any known security vulnerabilities.

✅ Verification successful

@upstash/redis version 1.34.3 is verified as secure and up-to-date

The package is using the latest stable version, is actively maintained by the Upstash team, and has no known security vulnerabilities. While version 1.35.0-canary exists, it's a pre-release version not recommended for production use.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check @upstash/redis version and security advisories

# Check NPM for latest version
echo "Latest version from NPM:"
npm view @upstash/redis version

# Check for security advisories
echo -e "\nSecurity advisories:"
npm audit @upstash/[email protected]

Length of output: 539


Script:

#!/bin/bash
# Get detailed package information
echo "Package details:"
npm view @upstash/redis

# Check GitHub security advisories
echo -e "\nGitHub security advisories:"
gh api \
  -H "Accept: application/vnd.github+json" \
  -H "X-GitHub-Api-Version: 2022-11-28" \
  /repos/upstash/upstash-redis/security-advisories

Length of output: 1184

packages/cache/upstash-redis/src/index.ts Outdated Show resolved Hide resolved
packages/cache/upstash-redis/src/index.ts Show resolved Hide resolved
packages/cache/upstash-redis/package.json Show resolved Hide resolved
Copy link
Contributor

github-actions bot commented Jan 31, 2025

💻 Website Preview

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

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

♻️ Duplicate comments (1)
packages/cache/upstash-redis/src/index.ts (1)

10-20: ⚠️ Potential issue

Add environment variable validation.

The constructor should validate the required environment variables to prevent runtime errors.

Add validation as follows:

   constructor(config?: Partial<RedisConfigNodejs>) {
     this.abortCtrl = new AbortController();
+    const url = process.env.UPSTASH_REDIS_REST_URL;
+    const token = process.env.UPSTASH_REDIS_REST_TOKEN;
+    if (!url || !token) {
+      throw new Error('UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN must be set');
+    }
     this.redis = new Redis({
-      url: process.env.UPSTASH_REDIS_REST_URL,
-      token: process.env.UPSTASH_REDIS_REST_TOKEN,
+      url,
+      token,
       enableAutoPipelining: true,
       signal: this.abortCtrl.signal,
       latencyLogging: !!process.env.DEBUG,
       ...config,
     });
   }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a30bb9a and d0790de.

📒 Files selected for processing (1)
  • packages/cache/upstash-redis/src/index.ts (1 hunks)
🧰 Additional context used
🪛 GitHub Check: e2e / node v22
packages/cache/upstash-redis/src/index.ts

[failure] 49-49:
Type 'string' is not assignable to type 'number'.

🪛 GitHub Check: e2e / node v20
packages/cache/upstash-redis/src/index.ts

[failure] 49-49:
Type 'string' is not assignable to type 'number'.

🪛 GitHub Check: e2e / node v18
packages/cache/upstash-redis/src/index.ts

[failure] 49-49:
Type 'string' is not assignable to type 'number'.

🪛 GitHub Check: apollo-federation-compatibility
packages/cache/upstash-redis/src/index.ts

[failure] 49-49:
Type 'string' is not assignable to type 'number'.

🪛 GitHub Check: integration / node 22
packages/cache/upstash-redis/src/index.ts

[failure] 49-49:
Type 'string' is not assignable to type 'number'.

🪛 GitHub Check: integration / node 20
packages/cache/upstash-redis/src/index.ts

[failure] 49-49:
Type 'string' is not assignable to type 'number'.

🪛 GitHub Check: integration / node 18
packages/cache/upstash-redis/src/index.ts

[failure] 49-49:
Type 'string' is not assignable to type 'number'.

🪛 GitHub Check: release / snapshot
packages/cache/upstash-redis/src/index.ts

[failure] 49-49:
Type 'string' is not assignable to type 'number'.

🪛 GitHub Check: deployment
packages/cache/upstash-redis/src/index.ts

[failure] 49-49:
Type 'string' is not assignable to type 'number'.

🪛 GitHub Actions: website
packages/cache/upstash-redis/src/index.ts

[error] 49-49: Type 'string' is not assignable to type 'number'

🪛 GitHub Actions: pr
packages/cache/upstash-redis/src/index.ts

[error] 49-49: Type 'string' is not assignable to type 'number'

⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: unit / node 22
  • GitHub Check: unit / node 20
  • GitHub Check: unit / node 18
  • GitHub Check: check
🔇 Additional comments (4)
packages/cache/upstash-redis/src/index.ts (4)

1-9: LGTM!

The imports and class declaration are well-structured and follow best practices.


22-24: LGTM!

The get method is correctly implemented with proper type safety.


36-39: LGTM!

The delete method is correctly implemented, properly handling the Redis response.


55-57: LGTM!

The dispose method correctly implements the disposal pattern.

packages/cache/upstash-redis/src/index.ts Show resolved Hide resolved
packages/cache/upstash-redis/src/index.ts Outdated Show resolved Hide resolved
ardatan and others added 3 commits January 31, 2025 12:46
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d0790de and 0194643.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (6)
  • .changeset/sixty-rivers-shave.md (1 hunks)
  • e2e/cache-control/cache-control.test.ts (1 hunks)
  • e2e/cache-control/gateway.config.ts (1 hunks)
  • e2e/cache-control/package.json (1 hunks)
  • packages/cache/upstash-redis/package.json (1 hunks)
  • packages/cache/upstash-redis/src/index.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
  • e2e/cache-control/package.json
  • .changeset/sixty-rivers-shave.md
  • e2e/cache-control/cache-control.test.ts
  • packages/cache/upstash-redis/package.json
  • packages/cache/upstash-redis/src/index.ts
⏰ Context from checks skipped due to timeout of 90000ms (13)
  • GitHub Check: unit / node 22
  • GitHub Check: unit / node 20
  • GitHub Check: e2e / node v22
  • GitHub Check: unit / node 18
  • GitHub Check: e2e / node v20
  • GitHub Check: e2e / node v18
  • GitHub Check: apollo-federation-compatibility
  • GitHub Check: check
  • GitHub Check: integration / node 22
  • GitHub Check: integration / node 20
  • GitHub Check: integration / node 18
  • GitHub Check: deployment
  • GitHub Check: release / snapshot
🔇 Additional comments (3)
e2e/cache-control/gateway.config.ts (3)

2-2: LGTM! Clean import and configuration initialization.

The import of UpstashRedisCache and empty configuration initialization look good.

Also applies to: 5-5


Line range hint 16-29: LGTM! Clear plugin configuration with proper error handling.

The logging and plugin configuration logic is well-structured with appropriate error handling for unknown plugin types.


8-8: 🛠️ Refactor suggestion

Add configuration options and error handling for Redis connection.

The UpstashRedisCache is initialized without configuration options or error handling.

Please verify if UpstashRedisCache requires configuration options:

Consider adding configuration and error handling:

-config.cache = new UpstashRedisCache();
+try {
+  config.cache = new UpstashRedisCache({
+    // Add necessary configuration options based on environment variables
+    url: process.env.UPSTASH_REDIS_URL,
+    token: process.env.UPSTASH_REDIS_TOKEN,
+  });
+} catch (error) {
+  console.error('Failed to initialize Upstash Redis cache:', error);
+  throw error;
+}

Comment on lines +7 to +14
if (process.env.CACHE_STORAGE === 'upstash-redis') {
config.cache = new UpstashRedisCache();
} else {
config.cache = {
// @ts-expect-error - We know it
type: process.env.CACHE_STORAGE,
};
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add type safety and environment variable validation.

The current implementation has several areas for improvement:

  1. Using @ts-expect-error is a code smell that indicates potential type safety issues
  2. Missing validation for CACHE_STORAGE environment variable

Consider this safer implementation:

-if (process.env.CACHE_STORAGE === 'upstash-redis') {
+const VALID_CACHE_TYPES = ['upstash-redis', 'memory', 'redis'] as const;
+type CacheType = typeof VALID_CACHE_TYPES[number];
+
+const cacheStorage = process.env.CACHE_STORAGE as string;
+
+if (!VALID_CACHE_TYPES.includes(cacheStorage as CacheType)) {
+  throw new Error(`Invalid cache storage type: ${cacheStorage}. Valid types are: ${VALID_CACHE_TYPES.join(', ')}`);
+}
+
+if (cacheStorage === 'upstash-redis') {
   config.cache = new UpstashRedisCache();
 } else {
   config.cache = {
-    // @ts-expect-error - We know it
-    type: process.env.CACHE_STORAGE,
+    type: cacheStorage as CacheType,
   };
 }
📝 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
if (process.env.CACHE_STORAGE === 'upstash-redis') {
config.cache = new UpstashRedisCache();
} else {
config.cache = {
// @ts-expect-error - We know it
type: process.env.CACHE_STORAGE,
};
}
const VALID_CACHE_TYPES = ['upstash-redis', 'memory', 'redis'] as const;
type CacheType = typeof VALID_CACHE_TYPES[number];
const cacheStorage = process.env.CACHE_STORAGE as string;
if (!VALID_CACHE_TYPES.includes(cacheStorage as CacheType)) {
throw new Error(`Invalid cache storage type: ${cacheStorage}. Valid types are: ${VALID_CACHE_TYPES.join(', ')}`);
}
if (cacheStorage === 'upstash-redis') {
config.cache = new UpstashRedisCache();
} else {
config.cache = {
type: cacheStorage as CacheType,
};
}

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