-
Notifications
You must be signed in to change notification settings - Fork 50
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
base: main
Are you sure you want to change the base?
feat(server): in-memory cache support for style #961
Conversation
✅ Deploy Preview for reearth-web canceled.
|
79d81b0
to
a40485c
Compare
WalkthroughThis 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
Possibly related PRs
Suggested Labels
Suggested Reviewers
Poem
✨ Finishing Touches
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
Documentation and Community
|
✅ Deploy Preview for reearth-web canceled.
|
There was a problem hiding this 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 thePing
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 fromuptrace.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 inServerConfig
is consistent with the usage.
This field ensures the adapter is accessible whereverServerConfig
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.
Usingt.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 insetToCache
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:
- Add TTL parameter to SetValue to prevent unbounded cache growth
- Consider adding type constraints or validation for the value parameter
- 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:
- Test cases for Redis connection failures
- Verification of Redis operations
- 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:
- Validate the StyleID
- Include a namespace prefix for better organization
- 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:
- Expected DSN format
- Configuration requirements
- 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 parameterWhile 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 operationsConsider 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
⛔ 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.
AddingRedisAdapter
toNewServer
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 intoServerConfig
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
: Addedredis gateway.RedisGateway
field toStyle
.
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 suggestionAdd Redis connection error handling.
The middleware should handle potential Redis connection failures gracefully. Consider:
- Adding error handling for Redis operations
- Implementing connection health checks
- 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 integrationThe 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 setupGood 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 strategyExcellent 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 validationThe function properly handles nil checks and type assertions for the Redis client.
server/Makefile (1)
19-21
: LGTM: Clean Makefile additionThe 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.
This reverts commit 14aead9.
16c9e38
to
4beff77
Compare
There was a problem hiding this 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 suggestionAdd TTL support and key validation.
The
SetValue
method needs the following improvements:
- TTL support for cache expiration
- 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 thatNewStyle
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 ifredisClient
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
andsetToCache
,deleteFromCache
ignores cases whereredisClient
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
⛔ 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 toNewContainer
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
leveragesminiredis
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 passingredis
intoNewStyle
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 goLength 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 goLength 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 goLength 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. TheStyle
struct inserver/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
Codecov ReportAttention: Patch coverage is
Additional details and impacted files@@ 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
Flags with carried forward coverage won't be shown. Click here to find out more.
|
There was a problem hiding this 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
📒 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 issueHandle 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 issueHandle 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
// 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) | ||
} | ||
}() |
There was a problem hiding this comment.
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.
// 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) | |
} | |
}() |
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
Infrastructure
Performance
Dependencies
The changes primarily focus on introducing Redis caching, improving observability, and enhancing the server's infrastructure capabilities.