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

fix: Context method #126

Merged
merged 4 commits into from
Dec 15, 2024
Merged

fix: Context method #126

merged 4 commits into from
Dec 15, 2024

Conversation

hwbrzzl
Copy link
Contributor

@hwbrzzl hwbrzzl commented Dec 15, 2024

📑 Description

Previously, the context returned by the Context method can't get value normally, because we maintain a customized value.

Summary by CodeRabbit

  • New Features

    • Enhanced context management capabilities allowing for flexible storage and retrieval of multiple values.
  • Bug Fixes

    • Improved consistency in session management by replacing hard-coded strings with a variable for session keys.
  • Tests

    • Updated tests to validate the behavior of context value retrieval methods, including new assertions for key-value presence.

@hwbrzzl hwbrzzl requested a review from a team as a code owner December 15, 2024 04:52
Copy link

coderabbitai bot commented Dec 15, 2024

Warning

Rate limit exceeded

@hwbrzzl has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 19 minutes and 2 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 51b8945 and 0a730bd.

📒 Files selected for processing (2)
  • context.go (3 hunks)
  • context_test.go (1 hunks)

Walkthrough

The pull request introduces enhancements to context management in the Goravel framework. The changes focus on improving how context values are stored and retrieved by introducing a new map-based approach in context.go. New constants userContextKey, contextKey, and sessionKey are added to standardize key management, and the WithValue, Value, and Context methods are modified to support storing multiple values while preserving internal context key integrity. Additionally, updates in context_request.go and context_test.go reflect these changes.

Changes

File Change Summary
context.go - Added userContextKey, contextKey, and sessionKey constants
- Introduced internalContextKeys array
- Updated WithValue to store values in a map
- Modified Context method to retrieve values conditionally
- Updated Value method to check map first
- Added getGoravelContextValues() and getUserContext() private methods
context_request.go - Replaced hardcoded "session" string with sessionKey in HasSession(), Session(), and SetSession() methods
context_test.go - Renamed customKeyType to customType and customKey to customTypeKey
- Added userContext variable
- Updated assertions to reflect new key usage and validate context retrieval

Possibly related PRs


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (2)
context.go (2)

64-79: Optimize internal key lookup

The current implementation uses a nested loop to check for internal keys. This can be optimized using a map for O(1) lookup.

Consider this optimization:

+var internalContextKeysMap = make(map[any]bool)
+
+func init() {
+    for _, key := range internalContextKeys {
+        internalContextKeysMap[key] = true
+    }
+}

 func (c *Context) Context() context.Context {
     ctx := c.instance.UserContext()
     values := c.getGoravelContextValues()
     for key, value := range values {
-        skip := false
-        for _, internalContextKey := range internalContextKeys {
-            if key == internalContextKey {
-                skip = true
-            }
-        }
-
-        if !skip {
+        if !internalContextKeysMap[key] {
             ctx = context.WithValue(ctx, key, value)
         }
     }

     return ctx
 }

107-114: Add documentation for getGoravelContextValues

The helper method would benefit from documentation explaining its purpose and behavior.

Add this documentation:

+// getGoravelContextValues retrieves the map of context values stored under contextKey.
+// Returns an empty map if no values are found or if type assertion fails.
 func (c *Context) getGoravelContextValues() map[any]any {
     value := c.instance.UserContext().Value(contextKey)
     if goravelCtxVal, ok := value.(map[any]any); ok {
         return goravelCtxVal
     }

     return make(map[any]any)
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 52ad9b9 and 2f6c3e2.

📒 Files selected for processing (3)
  • context.go (4 hunks)
  • context_request.go (2 hunks)
  • context_test.go (0 hunks)
💤 Files with no reviewable changes (1)
  • context_test.go
🧰 Additional context used
🪛 golangci-lint (1.62.2)
context.go

55-55: SA1029: should not use built-in type string as key for value; define your own type to avoid collisions

(staticcheck)

🔇 Additional comments (2)
context.go (1)

95-99: LGTM: Value method implementation is correct

The method properly checks the values map first before falling back to the context's Value method.

context_request.go (1)

142-142: LGTM: Session handling changes are consistent

The changes correctly use the new sessionKey constant across all session-related methods, maintaining consistency with the changes in context.go.

Also applies to: 395-399, 403-404

context.go Outdated Show resolved Hide resolved
context.go Outdated Show resolved Hide resolved
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: 0

♻️ Duplicate comments (2)
context.go (2)

12-23: ⚠️ Potential issue

Use typed keys for context values

Using string constants as context keys is prone to collisions. Consider using custom types for context keys following Go's best practices.

+type userContextKeyType struct{}
+type contextKeyType struct{}
+type sessionKeyType struct{}

 const (
-    userContextKey = "goravel_userContextKey"
-    contextKey     = "goravel_contextKey"
-    sessionKey     = "goravel_session"
+    userContextKey = userContextKeyType{}
+    contextKey     = contextKeyType{}
+    sessionKey     = sessionKeyType{}
 )

54-57: ⚠️ Potential issue

Add nil check for values map

The current implementation assumes the map exists. Add a nil check to ensure the map is initialized.

 func (c *Context) WithValue(key any, value any) {
     values := c.getGoravelContextValues()
+    if values == nil {
+        values = make(map[any]any)
+    }
     values[key] = value
     ctx := context.WithValue(c.instance.UserContext(), contextKey, values)
     c.instance.SetUserContext(ctx)
 }
🧰 Tools
🪛 golangci-lint (1.62.2)

57-57: SA1029: should not use built-in type string as key for value; define your own type to avoid collisions

(staticcheck)

🧹 Nitpick comments (1)
context.go (1)

69-84: Optimize internal keys lookup

The current implementation uses nested loops to check for internal keys. Consider using a map for O(1) lookup performance.

 var (
+    internalContextKeysMap = map[any]struct{}{
+        contextKey: {},
+        sessionKey: {},
+    }
     internalContextKeys = []any{
         contextKey,
         sessionKey,
     }
 )

 func (c *Context) Context() context.Context {
     ctx := c.getUserContext()
     values := c.getGoravelContextValues()
     for key, value := range values {
-        skip := false
-        for _, internalContextKey := range internalContextKeys {
-            if key == internalContextKey {
-                skip = true
-            }
-        }
-
-        if !skip {
+        if _, isInternal := internalContextKeysMap[key]; !isInternal {
             ctx = context.WithValue(ctx, key, value)
         }
     }

     return ctx
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2f6c3e2 and fa6c419.

📒 Files selected for processing (2)
  • context.go (3 hunks)
  • context_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • context_test.go
🧰 Additional context used
🪛 golangci-lint (1.62.2)
context.go

57-57: SA1029: should not use built-in type string as key for value; define your own type to avoid collisions

(staticcheck)


63-63: SA1029: should not use built-in type string as key for value; define your own type to avoid collisions

(staticcheck)


64-64: SA1029: should not use built-in type string as key for value; define your own type to avoid collisions

(staticcheck)

🔇 Additional comments (3)
context.go (3)

62-64: LGTM! Good approach for preserving context.

The implementation correctly maintains both the original context and the values map.

🧰 Tools
🪛 golangci-lint (1.62.2)

63-63: SA1029: should not use built-in type string as key for value; define your own type to avoid collisions

(staticcheck)


64-64: SA1029: should not use built-in type string as key for value; define your own type to avoid collisions

(staticcheck)


100-104: LGTM! Clear and correct implementation.

The method correctly prioritizes the values map before falling back to the original context.


112-128: LGTM! Robust helper methods.

Both helper methods handle type assertions correctly and provide appropriate fallbacks.

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

♻️ Duplicate comments (1)
context.go (1)

12-23: ⚠️ Potential issue

Use typed keys for context values instead of strings

Using string constants as context keys is prone to collisions. Following Go's best practices, consider using custom types for context keys.

Apply this change:

+type userContextKeyType struct{}
+type contextKeyType struct{}
+type sessionKeyType struct{}

 const (
-    userContextKey = "goravel_userContextKey"
-    contextKey     = "goravel_contextKey"
-    sessionKey     = "goravel_session"
+    userContextKey = userContextKeyType{}
+    contextKey     = contextKeyType{}
+    sessionKey     = sessionKeyType{}
 )
🧹 Nitpick comments (2)
context.go (1)

71-87: Consider optimizing the internal keys check

The current implementation iterates through internalContextKeys for each value. Consider using a map for O(1) lookup of internal keys.

 var (
+    internalContextKeysMap = map[any]struct{}{
+        contextKey: {},
+        sessionKey: {},
+    }
     internalContextKeys = []any{
         contextKey,
         sessionKey,
     }
 )

 func (c *Context) Context() context.Context {
     ctx := c.getUserContext()
     values := c.getGoravelContextValues()
     for key, value := range values {
-        skip := false
-        for _, internalContextKey := range internalContextKeys {
-            if key == internalContextKey {
-                skip = true
-            }
-        }
-
-        if !skip {
+        if _, isInternal := internalContextKeysMap[key]; !isInternal {
             ctx = context.WithValue(ctx, key, value)
         }
     }

     return ctx
 }
context_test.go (1)

11-44: Consider adding edge case tests

While the current tests cover the main functionality well, consider adding tests for:

  • Handling of nil values
  • Type assertion failures in getGoravelContextValues and getUserContext
  • Concurrent access to context values

Example test cases:

func TestContextEdgeCases(t *testing.T) {
    httpCtx := Background()
    
    // Test nil value
    httpCtx.WithValue("key", nil)
    assert.Nil(t, httpCtx.Value("key"))
    
    // Test type assertion failure
    ctx := context.WithValue(context.Background(), contextKey, "invalid")
    httpCtx.WithContext(ctx)
    assert.NotNil(t, httpCtx.getGoravelContextValues())
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fa6c419 and 51b8945.

📒 Files selected for processing (2)
  • context.go (3 hunks)
  • context_test.go (1 hunks)
🧰 Additional context used
🪛 golangci-lint (1.62.2)
context.go

60-60: SA1029: should not use built-in type string as key for value; define your own type to avoid collisions

(staticcheck)


66-66: SA1029: should not use built-in type string as key for value; define your own type to avoid collisions

(staticcheck)


67-67: SA1029: should not use built-in type string as key for value; define your own type to avoid collisions

(staticcheck)

🔇 Additional comments (3)
context.go (3)

54-62: LGTM: Good implementation of value storage

The implementation correctly handles value storage using a map, includes proper nil checking, and maintains context integrity. The comment clearly explains the rationale.

🧰 Tools
🪛 golangci-lint (1.62.2)

60-60: SA1029: should not use built-in type string as key for value; define your own type to avoid collisions

(staticcheck)


64-69: LGTM: Good context preservation strategy

The implementation correctly preserves both the original context and values map, ensuring proper context inheritance.

🧰 Tools
🪛 golangci-lint (1.62.2)

66-66: SA1029: should not use built-in type string as key for value; define your own type to avoid collisions

(staticcheck)


67-67: SA1029: should not use built-in type string as key for value; define your own type to avoid collisions

(staticcheck)


115-131: LGTM: Well-implemented helper methods

The helper methods properly handle type assertions and provide appropriate default values.

@hwbrzzl hwbrzzl merged commit b078236 into master Dec 15, 2024
7 checks passed
@hwbrzzl hwbrzzl deleted the bowen/#282 branch December 15, 2024 08:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant