Skip to content

feat(server): in-memory cache support for style #961

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

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

Conversation

akiyatomohiro
Copy link
Contributor

@akiyatomohiro akiyatomohiro commented Apr 16, 2024

This reverts commit 14aead9.

Overview

What I've done

What I haven't done

How I tested

Which point I want you to review particularly

Memo

Summary by CodeRabbit

Based on the comprehensive changes, here are the updated release notes:

  • New Features

    • Added Redis integration for improved caching and data storage.
    • Integrated Uptrace for enhanced application monitoring and observability.
    • Introduced a Redis service in the Docker Compose configuration.
  • Infrastructure

    • Enhanced server configuration to support Redis connectivity.
    • Added new environment configuration for Redis and Uptrace.
  • Performance

    • Implemented caching mechanisms using Redis for style-related operations.
    • Added OpenTelemetry tracing for improved performance tracking.
  • Dependencies

    • Updated and added multiple Go dependencies to support new features.
    • Upgraded various libraries to their latest versions.

The changes primarily focus on introducing Redis caching, improving observability, and enhancing the server's infrastructure capabilities.

Copy link

netlify bot commented Apr 16, 2024

Deploy Preview for reearth-web canceled.

Name Link
🔨 Latest commit 7a0923a
🔍 Latest deploy log https://app.netlify.com/sites/reearth-web/deploys/662100e45aa1d60008c78728

@akiyatomohiro akiyatomohiro marked this pull request as ready for review April 16, 2024 14:04
@akiyatomohiro akiyatomohiro self-assigned this Apr 18, 2024
@rot1024 rot1024 force-pushed the main branch 2 times, most recently from 79d81b0 to a40485c Compare September 10, 2024 23:22
Copy link
Contributor

coderabbitai bot commented Jan 29, 2025

Walkthrough

This pull request introduces comprehensive Redis integration into the ReEarth project. The changes span multiple files and include adding a Redis service to the Docker Compose configuration, updating environment configurations, implementing a Redis adapter, and integrating caching mechanisms across the server's components. The modifications enable Redis-based caching, enhance observability with Uptrace, and provide a flexible infrastructure for storing and retrieving data.

Changes

File Change Summary
.gitignore Added /redis to ignore Redis-related local files
docker-compose.yml Added reearth-redis service with Redis image and volume mapping
server/.env.example Added REDIS_URL and UPTRACE_DSN configuration variables
server/Makefile Added run-redis target for launching Redis service
server/go.mod Added multiple dependencies for Redis, Uptrace, and related libraries
server/internal/app/app.go Updated middleware to use Redis adapter
server/internal/app/config/config.go Added RedisURL and UptraceDSN to configuration struct
server/internal/app/main.go Initialized Redis client and adapter, configured Uptrace
server/internal/infrastructure/redis/redis_adapter.go Introduced RedisAdapter struct with methods for Redis operations
server/internal/usecase/gateway/redis.go Added RedisGateway interface for Redis interactions
server/internal/usecase/interactor/common.go Enhanced container with Redis adapter and added caching functions
server/internal/usecase/interactor/style.go Updated Style struct to use Redis for caching
server/pkg/scene/style.go Renamed fields in Style struct to public
server/pkg/scene/style_builder.go Updated StyleBuilder to reflect new public field names
server/internal/usecase/interactor/utils_test.go Added setupTestRedis utility for testing

Possibly related PRs

Suggested Labels

web

Suggested Reviewers

  • pyshx

Poem

🐰 Redis dances, data so light
Caching secrets with rabbit's might
Servers spin, performance gleams
In memory's magical streams
Code hops faster than before! 🚀

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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.

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

netlify bot commented Jan 29, 2025

Deploy Preview for reearth-web canceled.

Name Link
🔨 Latest commit df819b9
🔍 Latest deploy log https://app.netlify.com/sites/reearth-web/deploys/679b69d82668dd0008939753

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

🧹 Nitpick comments (16)
server/internal/app/main.go (3)

51-62: Consider a time-limited context for the Redis connection check.
While the Ping command is useful to verify the Redis connection, it may hang indefinitely in certain network conditions. Wrapping it with a context that has a timeout can help avoid blocking the entire server startup.

 ctx := context.Background()
+ctxTimeout, cancel := context.WithTimeout(ctx, 3*time.Second)
+defer cancel()

 // ...
 _, err = redisClient.Ping(ctxTimeout).Result()
 if err != nil {

63-74: Gracefully handle Uptrace initialization failures.
Currently, the code does not check for errors from uptrace.ConfigureOpentelemetry itself. While a fatal error is logged if the shutdown fails, consider logging or handling errors from the configuration as well, should it fail to initialize properly.


99-99: New field in ServerConfig is consistent with the usage.
This field ensures the adapter is accessible wherever ServerConfig is passed around. Consider documenting how it integrates with existing features for clarity.

server/e2e/common.go (1)

85-98: Guard your tests against missing Redis.
Using t.Fatalf is reasonable for test failures, but if Redis is optional, consider skipping tests when Redis is unavailable (e.g., running in short mode or partially offline). This helps avoid failing unrelated tests in environments without Redis.

server/internal/usecase/interactor/style.go (4)

26-32: Constructor now receives a Redis gateway.
If the Redis gateway is not essential in some scenarios, consider documenting or handling a nil gateway scenario to avoid potential NPEs.


75-80: Failure in writing to cache after DB commit halts the operation entirely.
Currently, an error in setToCache stops the entire operation from succeeding. Consider whether failing to cache should block the operation or if you prefer a best-effort approach that allows the flow to complete, then logs the caching failure.


141-149: Similar comment on best-effort caching logic.
After a successful DB commit, consider whether caching failures should block the entire request.


Line range hint 215-244: Duplicated style caching.
Storing the duplicated style in the cache helps performance. Nothing critical here, but consider a unique or more descriptive cache key if duplication happens often, to avoid collisions or confusion if reading from cache logs.

server/internal/usecase/gateway/redis.go (1)

5-9: Consider adding TTL parameter and value validation.

The interface design looks good, but consider these improvements:

  1. Add TTL parameter to SetValue to prevent unbounded cache growth
  2. Consider adding type constraints or validation for the value parameter
  3. Add batch operations for better performance when handling multiple keys

Example enhancement:

 type RedisGateway interface {
 	GetValue(ctx context.Context, key string) (string, error)
-	SetValue(ctx context.Context, key string, value interface{}) error
+	SetValue(ctx context.Context, key string, value interface{}, ttl time.Duration) error
 	RemoveValue(ctx context.Context, key string) error
+	// Batch operations
+	MGetValue(ctx context.Context, keys ...string) ([]string, error)
+	MSetValue(ctx context.Context, pairs map[string]interface{}, ttl time.Duration) error
 }
server/e2e/ping_test.go (2)

13-20: Enhance Redis test coverage.

While the miniredis setup is good, consider adding:

  1. Test cases for Redis connection failures
  2. Verification of Redis operations
  3. Test cleanup verification

Example test enhancement:

 	mr, err := miniredis.Run()
 	if err != nil {
 		t.Fatal(err)
 	}
 	defer mr.Close()
+
+	// Test Redis operations
+	mr.Set("test_key", "test_value")
+	if got, err := mr.Get("test_key"); err != nil || got != "test_value" {
+		t.Errorf("Redis operation failed: got %v, err %v", got, err)
+	}
+
+	// Test Redis connection failure
+	mr.Close()
+	e := StartServer(t, &config.Config{
+		RedisURL: redisURL,
+	}, false, nil)
+	// Verify server handles Redis failure gracefully

19-19: Use environment variable for Redis URL.

Consider using an environment variable for the Redis URL to match production configuration.

-	redisURL := fmt.Sprintf("redis://:@%s/0", mr.Addr())
+	redisURL := os.Getenv("TEST_REDIS_URL")
+	if redisURL == "" {
+		redisURL = fmt.Sprintf("redis://:@%s/0", mr.Addr())
+	}
server/pkg/scene/style.go (1)

59-61: Enhance cache key generation with validation and namespace.

The cache key generation should:

  1. Validate the StyleID
  2. Include a namespace prefix for better organization
  3. Consider potential key collisions
 func StyleCacheKey(id StyleID) string {
-    return fmt.Sprintf("style:%s", id)
+    if id.IsNil() {
+        return ""
+    }
+    return fmt.Sprintf("reearth:style:%s", id)
 }
server/internal/adapter/gql/resolver_mutation_style.go (1)

33-36: Enhance OpenTelemetry tracing with error handling and attributes.

The tracing implementation should include error recording and relevant attributes for better observability.

 tracer := otel.Tracer("gql")
 ctx, span := tracer.Start(ctx, "mutationResolver.UpdateStyle")
-defer span.End()
+defer func() {
+    if err != nil {
+        span.RecordError(err)
+        span.SetStatus(codes.Error, err.Error())
+    }
+    span.End()
+}()
+span.SetAttributes(
+    attribute.String("style.id", input.StyleID),
+    attribute.Bool("has_name", input.Name != nil),
+    attribute.Bool("has_value", input.Value != nil),
+)
server/internal/app/config/config.go (1)

77-77: Add documentation for UptraceDSN configuration.

The UptraceDSN field lacks documentation about its format and usage. Consider adding comments to explain:

  1. Expected DSN format
  2. Configuration requirements
  3. Impact on tracing functionality
+    // UptraceDSN is the DSN for Uptrace observability platform.
+    // Format: https://uptrace.dev/get/connect.html#connection-url
     UptraceDSN string `envconfig:"UPTRACE_DSN" pp:",omitempty"`
server/internal/usecase/interactor/common.go (2)

256-279: Consider adding cache TTL parameter

While the implementation is solid, consider adding a TTL parameter to prevent cache entries from living indefinitely.

-func getFromCache[T any](ctx context.Context, redisClient any, cacheKey string) (T, error) {
+func getFromCache[T any](ctx context.Context, redisClient any, cacheKey string, ttl time.Duration) (T, error) {

281-293: Add context timeout for Redis operations

Consider adding a timeout to the context for Redis operations to prevent hanging in case of Redis connectivity issues.

 func setToCache[T any](ctx context.Context, redisClient any, cacheKey string, data T) error {
+    ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
+    defer cancel()
     redisAdapter, ok := checkRedisClient(redisClient)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a40485c and 16c9e38.

⛔ Files ignored due to path filters (2)
  • go.work.sum is excluded by !**/*.sum
  • server/go.sum is excluded by !**/*.sum
📒 Files selected for processing (19)
  • .gitignore (1 hunks)
  • docker-compose.yml (2 hunks)
  • server/.env.example (1 hunks)
  • server/Makefile (1 hunks)
  • server/e2e/common.go (2 hunks)
  • server/e2e/gql_style_test.go (3 hunks)
  • server/e2e/ping_test.go (1 hunks)
  • server/go.mod (8 hunks)
  • server/internal/adapter/gql/resolver_mutation_style.go (2 hunks)
  • server/internal/app/app.go (1 hunks)
  • server/internal/app/config/config.go (1 hunks)
  • server/internal/app/main.go (4 hunks)
  • server/internal/app/usecase.go (2 hunks)
  • server/internal/infrastructure/redis/redis_adapter.go (1 hunks)
  • server/internal/usecase/gateway/redis.go (1 hunks)
  • server/internal/usecase/interactor/common.go (5 hunks)
  • server/internal/usecase/interactor/style.go (8 hunks)
  • server/pkg/scene/style.go (1 hunks)
  • server/pkg/scene/style_builder.go (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • .gitignore
🔇 Additional comments (18)
server/internal/app/main.go (2)

10-13: Imports look organized and purposeful.
You are bringing in Redis and Uptrace dependencies, which appear necessary for the new caching and observability features.

Also applies to: 19-19


83-83: Excellent addition of the Redis adapter to the server.
Adding RedisAdapter to NewServer helps ensure that your Redis caching capability is available within the server lifecycle.

server/e2e/common.go (2)

10-16: New imports for Redis in E2E tests are appropriate.
Ensuring the E2E tests can initialize Redis is vital for testing cache-related logic.


106-106: Redis adapter injected into ServerConfig for E2E testing.
This seamlessly allows end-to-end tests to exercise real caching paths with Redis.

server/internal/usecase/interactor/style.go (5)

7-14: New imports for gateway and OpenTelemetry tracing.
Integrating a caching gateway and tracing is a beneficial addition for observability and performance.


23-23: Added redis gateway.RedisGateway field to Style.
This new field cleanly extends the struct to incorporate caching mechanisms alongside the existing repository logic.


85-99: Tracing approach is well-structured but consider aggregator usage.
In the event multiple steps fail, be mindful of how the aggregator logs these spans for better user understanding. Overall, you’re capturing the necessary context in each trace.


113-126: Cache miss gracefully handled by fallback to DB.
This approach is a standard pattern for heavy read scenarios. The code looks consistent and follows the same pattern in other methods.


Line range hint 166-198: Delete from cache after successful repository removal.
This ordering ensures that the repository and cache remain in sync. Make sure to handle any errors from Redis gracefully to avoid partial deletes blocking the entire operation.

server/pkg/scene/style.go (1)

6-9: Consider the implications of exposing internal fields.

Making the fields public with msgpack tags suggests these are being exposed for serialization. While this enables Redis caching, it also increases the risk of external manipulation. Consider using an interface or implementing custom serialization methods to maintain encapsulation.

server/internal/app/usecase.go (1)

16-17: 🛠️ Refactor suggestion

Add Redis connection error handling.

The middleware should handle potential Redis connection failures gracefully. Consider:

  1. Adding error handling for Redis operations
  2. Implementing connection health checks
  3. Adding fallback behavior when Redis is unavailable
 func UsecaseMiddleware(r *repo.Container, g *gateway.Container, ar *accountrepo.Container, ag *accountgateway.Container, redisAdapter *infraRedis.RedisAdapter, config interactor.ContainerConfig) echo.MiddlewareFunc {
+    if redisAdapter != nil {
+        if err := redisAdapter.Ping(); err != nil {
+            log.Warn("Redis connection failed, falling back to repository: %v", err)
+            redisAdapter = nil
+        }
+    }
     return ContextMiddleware(func(ctx context.Context) context.Context {

Also applies to: 40-42

server/internal/app/app.go (1)

Line range hint 98-102: LGTM: Clean Redis adapter integration

The Redis adapter is properly injected into the UsecaseMiddleware, following good dependency injection practices.

server/e2e/gql_style_test.go (2)

179-189: LGTM: Well-structured Redis test setup

Good use of miniredis for testing Redis functionality. The setup is clean and handles cleanup properly with defer mr.Close().


266-272: LGTM: Good test coverage strategy

Excellent approach to test both with and without Redis using parameterized tests, ensuring the functionality works in both scenarios.

server/internal/usecase/interactor/common.go (1)

244-254: LGTM: Robust Redis client validation

The function properly handles nil checks and type assertions for the Redis client.

server/Makefile (1)

19-21: LGTM: Clean Makefile addition

The run-redis target follows the same pattern as run-db and is properly marked as .PHONY.

Also applies to: 25-25

server/go.mod (2)

39-39: Verify Uptrace and OpenTelemetry compatibility.

Ensure that the Uptrace version (v1.24.0) is compatible with the OpenTelemetry SDK version (v1.24.0).

Also applies to: 47-48

✅ Verification successful

✓ Uptrace v1.24.0 is compatible with OpenTelemetry v1.24.0

The versions are perfectly aligned - Uptrace v1.24.0 is built against and compatible with OpenTelemetry v1.24.0 across all components (core, SDK, metrics, and tracing).

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check compatibility matrix
curl -s "https://raw.githubusercontent.com/uptrace/uptrace-go/master/go.mod" | grep "go.opentelemetry.io/otel"

Length of output: 737


Script:

#!/bin/bash
# Check compatibility matrix for specific version
curl -s "https://raw.githubusercontent.com/uptrace/uptrace-go/v1.24.0/go.mod" | grep "go.opentelemetry.io/otel"

Length of output: 589


15-15: Verify Redis client version compatibility.

The Redis client version (v8.11.5) is not the latest stable version. Consider upgrading to v9.x.x for better performance and security improvements.

@akiyatomohiro akiyatomohiro force-pushed the feat/in-memory-cache-system-and-uptrace-for-style branch from 16c9e38 to 4beff77 Compare January 30, 2025 11:27
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: 5

🔭 Outside diff range comments (1)
server/go.mod (1)

Line range hint 191-191: Fix invalid Go version.

The specified Go version 1.23.5 is invalid. The latest stable version of Go is 1.22.

-go 1.23.5
+go 1.22
♻️ Duplicate comments (1)
server/internal/infrastructure/redis/redis_adapter.go (1)

21-23: 🛠️ Refactor suggestion

Add TTL support and key validation.

The SetValue method needs the following improvements:

  1. TTL support for cache expiration
  2. Key validation to prevent empty keys

Apply this diff to enhance the method:

-func (r *RedisAdapter) SetValue(ctx context.Context, key string, value interface{}) error {
+func (r *RedisAdapter) SetValue(ctx context.Context, key string, value interface{}, ttl time.Duration) error {
+	if key == "" {
+		return errors.New("key cannot be empty")
+	}
-	return r.client.Set(ctx, key, value, 0).Err()
+	return r.client.Set(ctx, key, value, ttl).Err()
}
🧹 Nitpick comments (8)
server/internal/usecase/interactor/common.go (4)

8-9: Replace direct redis import with an alias or single standard reference.

Both lines introduce Redis into the codebase. While functional, consider standardizing the import references (either alias all imports or avoid renaming unless needed) to reduce cognitive load.


47-47: Check Style interactor for fallback logic.

NewStyle(r, redisAdapter) passes the Redis adapter. Verify that NewStyle gracefully handles scenarios where the adapter may be unavailable, preventing caching-related exceptions.


256-279: Consider logging when cache is unavailable.

Currently, getFromCache silently returns a zero value if redisClient is invalid or if a cache miss occurs. Consider logging or at least documenting this fallback behavior to help with debugging.


295-302: Align deleteFromCache with error handling strategy.

Like getFromCache and setToCache, deleteFromCache ignores cases where redisClient is invalid. Consider adding optional logging or returning an informative error if the cache is disabled or unavailable.

server/internal/infrastructure/redis/redis_adapter.go (2)

17-19: Add key validation and error wrapping.

The GetValue method should validate the key and wrap Redis errors for better error handling.

Apply this diff to enhance the method:

func (r *RedisAdapter) GetValue(ctx context.Context, key string) (string, error) {
+	if key == "" {
+		return "", errors.New("key cannot be empty")
+	}
-	return r.client.Get(ctx, key).Result()
+	result, err := r.client.Get(ctx, key).Result()
+	if err != nil {
+		return "", fmt.Errorf("redis get failed: %w", err)
+	}
+	return result, nil
}

25-27: Add key validation and error wrapping.

The RemoveValue method should validate the key and wrap Redis errors for better error handling.

Apply this diff to enhance the method:

func (r *RedisAdapter) RemoveValue(ctx context.Context, key string) error {
+	if key == "" {
+		return errors.New("key cannot be empty")
+	}
-	return r.client.Del(ctx, key).Err()
+	if err := r.client.Del(ctx, key).Err(); err != nil {
+		return fmt.Errorf("redis delete failed: %w", err)
+	}
+	return nil
}
server/internal/app/main.go (1)

63-73: Validate Uptrace DSN before configuration.

The Uptrace configuration should validate the DSN to prevent initialization with an empty or invalid DSN.

Add validation before configuring Uptrace:

 	// Init uptrace
+	if conf.UptraceDSN == "" {
+		log.Warn("Uptrace DSN is empty, skipping Uptrace initialization")
+		return
+	}
 	uptrace.ConfigureOpentelemetry(
server/e2e/gql_style_test.go (1)

179-188: Ensure Redis cleanup in test failure scenarios.

The Redis cleanup is handled by defer mr.Close(), but it's important to ensure cleanup happens even if the test fails before reaching the defer statement.

Move the Redis initialization to a separate function:

+func initRedis(t *testing.T) (string, func()) {
+	mr, err := miniredis.Run()
+	if err != nil {
+		t.Fatal(err)
+	}
+	return fmt.Sprintf("redis://:@%s/0", mr.Addr()), func() {
+		mr.Close()
+	}
+}

 func styleCRUD(t *testing.T, isUseRedis bool) {
 	redisURL := ""
+	var cleanup func()
 	if isUseRedis {
-		mr, err := miniredis.Run()
-		if err != nil {
-			t.Fatal(err)
-		}
-		defer mr.Close()
-		redisURL = fmt.Sprintf("redis://:@%s/0", mr.Addr())
+		redisURL, cleanup = initRedis(t)
+		t.Cleanup(cleanup)
 	}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 16c9e38 and 4beff77.

⛔ Files ignored due to path filters (2)
  • go.work.sum is excluded by !**/*.sum
  • server/go.sum is excluded by !**/*.sum
📒 Files selected for processing (21)
  • .gitignore (1 hunks)
  • docker-compose.yml (1 hunks)
  • server/.env.example (1 hunks)
  • server/Makefile (2 hunks)
  • server/e2e/common.go (2 hunks)
  • server/e2e/gql_style_test.go (3 hunks)
  • server/e2e/ping_test.go (1 hunks)
  • server/go.mod (8 hunks)
  • server/internal/adapter/gql/resolver_mutation_style.go (2 hunks)
  • server/internal/app/app.go (1 hunks)
  • server/internal/app/config/config.go (1 hunks)
  • server/internal/app/main.go (4 hunks)
  • server/internal/app/usecase.go (2 hunks)
  • server/internal/infrastructure/redis/redis_adapter.go (1 hunks)
  • server/internal/usecase/gateway/redis.go (1 hunks)
  • server/internal/usecase/interactor/common.go (5 hunks)
  • server/internal/usecase/interactor/style.go (9 hunks)
  • server/internal/usecase/interactor/style_test.go (1 hunks)
  • server/internal/usecase/interactor/utils_test.go (1 hunks)
  • server/pkg/scene/style.go (1 hunks)
  • server/pkg/scene/style_builder.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (12)
  • .gitignore
  • server/Makefile
  • server/e2e/ping_test.go
  • server/.env.example
  • server/internal/app/usecase.go
  • server/internal/app/config/config.go
  • server/internal/app/app.go
  • docker-compose.yml
  • server/pkg/scene/style_builder.go
  • server/internal/usecase/gateway/redis.go
  • server/pkg/scene/style.go
  • server/internal/adapter/gql/resolver_mutation_style.go
🧰 Additional context used
📓 Learnings (2)
server/internal/usecase/interactor/common.go (3)
Learnt from: akiyatomohiro
PR: reearth/reearth-visualizer#961
File: server/internal/infrastructure/redis/redis_adapter.go:13-15
Timestamp: 2025-01-29T10:36:26.420Z
Learning: The checkRedisClient function in reearth-visualizer handles Redis client validation comprehensively by:
1. Checking if the client is nil
2. Performing type assertion to *infraRedis.RedisAdapter
3. Verifying the resulting adapter is not nil
This makes additional nil checks in the RedisAdapter constructor redundant and provides better error handling through boolean return values instead of panics.
Learnt from: akiyatomohiro
PR: reearth/reearth-visualizer#961
File: server/internal/infrastructure/redis/redis_adapter.go:9-11
Timestamp: 2025-01-29T10:32:33.083Z
Learning: Nil check for Redis client is not needed in RedisAdapter struct as checkRedisClient function in server/internal/usecase/interactor/common.go already performs this validation.
Learnt from: akiyatomohiro
PR: reearth/reearth-visualizer#961
File: server/internal/infrastructure/redis/redis_adapter.go:13-15
Timestamp: 2025-01-29T10:36:26.420Z
Learning: Nil checks for Redis client in reearth-visualizer are handled by the checkRedisClient function at a higher level, making additional nil checks in the RedisAdapter constructor redundant.
server/internal/infrastructure/redis/redis_adapter.go (4)
Learnt from: akiyatomohiro
PR: reearth/reearth-visualizer#961
File: server/internal/infrastructure/redis/redis_adapter.go:13-15
Timestamp: 2025-01-29T10:36:26.420Z
Learning: The checkRedisClient function in reearth-visualizer handles Redis client validation comprehensively by:
1. Checking if the client is nil
2. Performing type assertion to *infraRedis.RedisAdapter
3. Verifying the resulting adapter is not nil
This makes additional nil checks in the RedisAdapter constructor redundant and provides better error handling through boolean return values instead of panics.
Learnt from: akiyatomohiro
PR: reearth/reearth-visualizer#961
File: server/internal/infrastructure/redis/redis_adapter.go:13-15
Timestamp: 2025-01-29T10:36:26.420Z
Learning: Nil checks for Redis client in reearth-visualizer are handled by the checkRedisClient function at a higher level, making additional nil checks in the RedisAdapter constructor redundant.
Learnt from: akiyatomohiro
PR: reearth/reearth-visualizer#961
File: server/internal/infrastructure/redis/redis_adapter.go:21-23
Timestamp: 2025-01-29T10:34:59.789Z
Learning: The Redis adapter's SetValue method in server/internal/infrastructure/redis/redis_adapter.go needs to be refactored to include TTL support and proper error handling, which will be addressed in a future PR.
Learnt from: akiyatomohiro
PR: reearth/reearth-visualizer#961
File: server/internal/infrastructure/redis/redis_adapter.go:9-11
Timestamp: 2025-01-29T10:32:33.083Z
Learning: Nil check for Redis client is not needed in RedisAdapter struct as checkRedisClient function in server/internal/usecase/interactor/common.go already performs this validation.
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: ci-server / ci-server-test
  • GitHub Check: Redirect rules - reearth-web
  • GitHub Check: Header rules - reearth-web
  • GitHub Check: Pages changed - reearth-web
🔇 Additional comments (9)
server/internal/usecase/interactor/common.go (3)

22-22: Ensure msgpack import usage is justified.

The msgpack library is useful for efficient serialization. Confirm that the usage and library dependencies (like version pinning) are properly documented to maintain long-term code stability.


34-34: Validate new redisAdapter parameter usage.

The added redisAdapter parameter ensures Redis integration; confirm that external calls to NewContainer are updated accordingly, preventing runtime errors.


243-254: Appreciate the consolidated nil-check for Redis client.

checkRedisClient gracefully validates and returns the typed adapter. This approach is consistent with the retrieved learnings, avoiding additional nil checks elsewhere. Great job!

server/internal/usecase/interactor/utils_test.go (1)

12-29: Well-structured test setup for Redis.

setupTestRedis leverages miniredis effectively, providing a convenient fixture and clean teardown. This approach ensures realistic testing without external dependencies. Good job!

server/internal/usecase/interactor/style_test.go (1)

27-30: Excellent Redis integration in style tests.

The addition of setupTestRedis and passing redis into NewStyle ensures coverage of newly introduced cache logic. Keep an eye on test performance with external services and continue expanding coverage for robust caching behavior.

server/internal/usecase/interactor/style.go (1)

114-137: Extract cache retrieval logic to reduce duplication.

The cache retrieval pattern is repeated in multiple methods. Extract it to a reusable function.

Create a helper function:

+func (i *Style) getStyleFromCache(ctx context.Context, styleID id.StyleID) (*scene.Style, error) {
+	tr := otel.Tracer("interactor")
+	_, span := tr.Start(ctx, "Style.getStyleFromCache")
+	defer span.End()
+
+	style, err := getFromCache[*scene.Style](ctx, i.redis, scene.StyleCacheKey(styleID))
+	if err != nil {
+		span.RecordError(err)
+		return nil, err
+	}
+
+	if style == nil {
+		_, dbSpan := tr.Start(ctx, "Style.getStyleFromCache.DBFindById")
+		defer dbSpan.End()
+		
+		style, err = i.styleRepo.FindByID(ctx, styleID)
+		if err != nil {
+			dbSpan.RecordError(err)
+			return nil, err
+		}
+	}
+
+	return style, nil
+}
server/go.mod (3)

15-15: Verify Redis integration completeness.

The addition of github.com/go-redis/redis/v8 suggests Redis integration. Ensure that all necessary Redis-related configurations and error handling are implemented in the codebase.

✅ Verification successful

Redis integration is properly implemented

The codebase shows a complete Redis implementation with:

  • Proper configuration and connection management
  • Comprehensive error handling
  • Type-safe caching patterns
  • Integration tests using miniredis
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for Redis configuration and error handling implementation

# Check for Redis configuration
echo "Checking for Redis configuration..."
rg -l 'redis' --type go

# Check for Redis error handling
echo "Checking for Redis error handling..."
ast-grep --pattern 'if err := $redis.$_; err != nil {
  $$$
}'

Length of output: 663


Script:

#!/bin/bash
# Check Redis adapter implementation and initialization
echo "=== Redis Adapter Implementation ==="
cat server/internal/infrastructure/redis/redis_adapter.go

echo -e "\n=== Redis Configuration ==="
cat server/internal/app/config/config.go

echo -e "\n=== Redis Initialization ==="
rg -A 5 "NewRedis" --type go

echo -e "\n=== Alternative Error Handling Patterns ==="
rg "redis.*err|err.*redis" --type go

Length of output: 10957


48-49: Verify OpenTelemetry version compatibility.

The update to OpenTelemetry v1.24.0 and related packages is significant. Ensure that all OpenTelemetry instrumentation is compatible and properly configured.

Also applies to: 162-169

✅ Verification successful

OpenTelemetry v1.24.0 update is properly configured and compatible

The implementation follows OpenTelemetry best practices with proper SDK initialization, sampling configuration, and support for both GCP and Jaeger backends. The update is safe to proceed.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for OpenTelemetry configuration and usage

# Check for OpenTelemetry initialization
echo "Checking for OpenTelemetry setup..."
rg -A 5 'otel\.GetTracerProvider|otel\.GetMeterProvider'

# Check for potential version compatibility issues in instrumentation
echo "Checking for OpenTelemetry instrumentation..."
rg -l 'otel' --type go

Length of output: 478


Script:

#!/bin/bash
# Check OpenTelemetry initialization and configuration patterns
echo "=== Checking tracer.go configuration ==="
cat server/internal/app/tracer.go

echo -e "\n=== Checking for SDK initialization patterns ==="
rg -A 5 'sdktrace\.NewTracerProvider|sdkmetric\.NewMeterProvider'

echo -e "\n=== Checking OpenTelemetry instrumentation imports ==="
rg '^import \($|^[[:space:]]*"go\.opentelemetry\.io/otel.*"$' -A 10 --type go

Length of output: 66051


43-43: Verify msgpack serialization implementation.

The addition of github.com/vmihailenco/msgpack/v5 suggests binary serialization. Ensure proper error handling and performance considerations in the implementation.

✅ Verification successful

✅ MsgPack implementation verified and follows best practices

The implementation in server/internal/usecase/interactor/common.go shows proper error handling for both serialization and deserialization operations. The Style struct in server/pkg/scene/style.go uses appropriate msgpack tags and efficient memory layout with pointer fields where needed.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for msgpack implementation and error handling

# Check for msgpack usage
echo "Checking for msgpack implementation..."
ast-grep --pattern 'msgpack.Marshal($_)'

# Check for error handling in msgpack operations
echo "Checking for msgpack error handling..."
ast-grep --pattern 'if err := msgpack.$_($$_); err != nil {
  $$$
}'

Length of output: 287


Script:

#!/bin/bash
# Search for msgpack imports and usage with broader patterns

# Find Go files importing msgpack
echo "Files importing msgpack:"
rg --type go "import.*\"github.com/vmihailenco/msgpack/v5\""

# Look for any msgpack-related code
echo -e "\nMsgpack-related code:"
rg --type go -i "msgpack" -A 3 -B 1

# Look for struct tags
echo -e "\nStruct fields with msgpack tags:"
rg --type go "\`.*msgpack:\".*\`"

Length of output: 2036

Copy link

codecov bot commented Jan 30, 2025

Codecov Report

Attention: Patch coverage is 14.68927% with 151 lines in your changes missing coverage. Please review.

Project coverage is 22.83%. Comparing base (a52c0a4) to head (789b7c6).

Files with missing lines Patch % Lines
server/internal/usecase/interactor/style.go 3.03% 64 Missing ⚠️
server/internal/usecase/interactor/common.go 0.00% 45 Missing ⚠️
server/internal/app/main.go 0.00% 23 Missing ⚠️
server/e2e/common.go 53.84% 4 Missing and 2 partials ⚠️
...er/internal/adapter/gql/resolver_mutation_style.go 0.00% 4 Missing ⚠️
server/pkg/scene/style.go 55.55% 4 Missing ⚠️
server/internal/app/usecase.go 0.00% 2 Missing ⚠️
server/pkg/scene/style_builder.go 66.66% 1 Missing and 1 partial ⚠️
server/internal/app/app.go 0.00% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main     #961      +/-   ##
==========================================
- Coverage   22.84%   22.83%   -0.02%     
==========================================
  Files        1054     1055       +1     
  Lines      109647   109797     +150     
  Branches      669      669              
==========================================
+ Hits        25054    25070      +16     
- Misses      83293    83425     +132     
- Partials     1300     1302       +2     
Flag Coverage Δ
server 31.52% <14.68%> (-0.08%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
server/internal/app/config/config.go 35.61% <ø> (ø)
...ver/internal/infrastructure/redis/redis_adapter.go 100.00% <100.00%> (ø)
server/internal/app/app.go 0.00% <0.00%> (ø)
server/internal/app/usecase.go 21.87% <0.00%> (ø)
server/pkg/scene/style_builder.go 70.37% <66.66%> (ø)
...er/internal/adapter/gql/resolver_mutation_style.go 0.00% <0.00%> (ø)
server/pkg/scene/style.go 29.41% <55.55%> (-1.84%) ⬇️
server/e2e/common.go 71.09% <53.84%> (-1.14%) ⬇️
server/internal/app/main.go 0.00% <0.00%> (ø)
server/internal/usecase/interactor/common.go 6.74% <0.00%> (-2.15%) ⬇️
... and 1 more

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 comments (2)
server/internal/usecase/interactor/style.go (2)

Line range hint 182-218: Handle cache operations gracefully in RemoveStyle.

Cache operations should not be treated as critical failures.

 	style, err = getFromCache[*scene.Style](ctx, i.redis, scene.StyleCacheKey(styleID))
 	if err != nil {
-		return styleID, err
+		log.Errorf("Cache retrieval failed: %v", err)
 	}

 	err = deleteFromCache(ctx, i.redis, scene.StyleCacheKey(styleID))
 	if err != nil {
-		return styleID, err
+		log.Errorf("Cache deletion failed: %v", err)
 	}

Line range hint 236-269: Handle cache operations gracefully in DuplicateStyle.

Cache operations should not be treated as critical failures.

 	style, err = getFromCache[*scene.Style](ctx, i.redis, scene.StyleCacheKey(styleID))
 	if err != nil {
-		return nil, err
+		log.Errorf("Cache retrieval failed: %v", err)
 	}

 	err = setToCache(ctx, i.redis, scene.StyleCacheKey(duplicatedStyle.ID()), duplicatedStyle)
 	if err != nil {
-		return nil, err
+		log.Errorf("Cache set failed: %v", err)
 	}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 789b7c6 and df819b9.

📒 Files selected for processing (3)
  • server/e2e/common.go (2 hunks)
  • server/internal/app/main.go (4 hunks)
  • server/internal/usecase/interactor/style.go (9 hunks)
🔇 Additional comments (6)
server/internal/app/main.go (2)

51-66: LGTM! Robust Redis initialization.

The Redis client initialization is well-implemented with proper error handling, connection testing, and cleanup.


88-88: LGTM! Clean struct field addition.

The RedisAdapter field is properly integrated into the ServerConfig struct.

Also applies to: 104-104

server/internal/usecase/interactor/style.go (3)

27-27: LGTM! Clean Redis gateway integration.

The Redis gateway is properly integrated into the Style struct and constructor.

Also applies to: 30-39


158-164: ⚠️ Potential issue

Handle cache set failure gracefully.

Cache set failures should not prevent returning a successful database update.

 	err = setToCache[*scene.Style](ctx, i.redis, scene.StyleCacheKey(style.ID()), style)
 	if err != nil {
 		dbSpan.RecordError(err)
 		dbSpan.End()
-		return nil, err
+		log.Errorf("Cache set failed: %v", err)
 	}

Likely invalid or redundant comment.


116-121: ⚠️ Potential issue

Handle cache miss gracefully.

Cache retrieval errors should not be treated as critical failures. Consider logging the error and proceeding with the database lookup.

 	style, err = getFromCache[*scene.Style](ctx, i.redis, scene.StyleCacheKey(param.StyleID))
 	if err != nil {
 		redisSpan.RecordError(err)
 		redisSpan.End()
-		return nil, err
+		log.Errorf("Cache retrieval failed: %v", err)
 	}

Likely invalid or redundant comment.

server/e2e/common.go (1)

93-111: LGTM! Well-implemented test Redis setup.

The Redis initialization in the test server is properly implemented with:

  • Conditional initialization based on config
  • Proper error handling
  • Clean test cleanup using t.Cleanup

Comment on lines +68 to +78
// Init uptrace
uptrace.ConfigureOpentelemetry(
uptrace.WithDSN(conf.UptraceDSN),
uptrace.WithServiceName("reearth"),
uptrace.WithServiceVersion("1.0.0"),
)
defer func() {
if err := uptrace.Shutdown(ctx); err != nil {
log.Fatalf("failed to shutdown uptrace: %v", err)
}
}()
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

Use the provided version parameter instead of hardcoding.

The service version is hardcoded as "1.0.0". Since the version is already available as a parameter to the Start function, use it instead.

 	uptrace.ConfigureOpentelemetry(
 		uptrace.WithDSN(conf.UptraceDSN),
 		uptrace.WithServiceName("reearth"),
-		uptrace.WithServiceVersion("1.0.0"),
+		uptrace.WithServiceVersion(version),
 	)
📝 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
// Init uptrace
uptrace.ConfigureOpentelemetry(
uptrace.WithDSN(conf.UptraceDSN),
uptrace.WithServiceName("reearth"),
uptrace.WithServiceVersion("1.0.0"),
)
defer func() {
if err := uptrace.Shutdown(ctx); err != nil {
log.Fatalf("failed to shutdown uptrace: %v", err)
}
}()
// Init uptrace
uptrace.ConfigureOpentelemetry(
uptrace.WithDSN(conf.UptraceDSN),
uptrace.WithServiceName("reearth"),
uptrace.WithServiceVersion(version),
)
defer func() {
if err := uptrace.Shutdown(ctx); err != nil {
log.Fatalf("failed to shutdown uptrace: %v", err)
}
}()

@akiyatomohiro akiyatomohiro requested a review from pyshx January 30, 2025 12:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants