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

🔥 feat: Add Session Access via Go Context #3339

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

Conversation

JIeJaitt
Copy link
Contributor

@JIeJaitt JIeJaitt commented Mar 6, 2025

In order to maintain the consistency of the fiber middleware, this pr is proposed to add the corresponding function mentioned in #3212 to the session middleware.

Copy link
Contributor

coderabbitai bot commented Mar 6, 2025

Walkthrough

The pull request integrates Go’s context support into session management. The middleware creates a Go context incorporating session data using context.WithValue and sets it on the Fiber context. A new function, FromGoContext, retrieves session information from the context, and the session store’s error handling is improved. Additional tests verify that sessions are accessible via both Fiber and Go contexts, as well as cover edge cases.

Changes

File(s) Change Summary
middleware/session/middleware.go, session.go Added Go context integration: middleware now creates a context with session data using context.WithValue (set via c.SetContext), and a new context key and FromGoContext function are introduced.
middleware/session/middleware_test.go Added two new tests, Test_Session_GoContext and Test_Session_GoContext_EdgeCases, to verify session accessibility in Fiber and Go contexts, with added imports for testing.
middleware/session/store.go Modified the Get method to capture session retrieval results and errors explicitly, returning errors immediately to improve error propagation.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant FiberApp
  participant Middleware
  participant Handler
  
  Client->>FiberApp: HTTP Request
  FiberApp->>Middleware: Process request with session middleware
  Middleware->>Middleware: Create Go Context with session (context.WithValue)
  Middleware->>FiberApp: Set context in Fiber (c.SetContext)
  FiberApp->>Handler: Forward request for processing
  Handler->>Middleware: Retrieve session using FromGoContext
  Middleware-->>Handler: Return session data
Loading

Poem

I'm a rabbit with a joyful leap,
Hopping through code where sessions sleep.
Fiber and Go now share the light,
Keeping session data snug and tight.
Test hops confirm the changes deep! 🐇


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e8f8e4d and aa756da.

📒 Files selected for processing (2)
  • middleware/session/middleware.go (3 hunks)
  • middleware/session/store.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • middleware/session/store.go
  • middleware/session/middleware.go

Note

🎁 Summarized by CodeRabbit Free

Your organization has reached its limit of developer seats under the Pro Plan. For new users, CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please add seats to your subscription by visiting https://app.coderabbit.ai/login.If you believe this is a mistake and have available seats, please assign one to the pull request author through the subscription management page using the link above.

🪧 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 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.

@JIeJaitt JIeJaitt marked this pull request as ready for review March 6, 2025 07:03
@JIeJaitt JIeJaitt requested a review from a team as a code owner March 6, 2025 07:03
@JIeJaitt JIeJaitt requested review from gaby, sixcolors, ReneWerner87 and efectn and removed request for a team March 6, 2025 07:03
Copy link

codecov bot commented Mar 6, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 83.61%. Comparing base (6953325) to head (aa756da).

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3339      +/-   ##
==========================================
- Coverage   83.65%   83.61%   -0.05%     
==========================================
  Files         118      118              
  Lines       11707    11724      +17     
==========================================
+ Hits         9794     9803       +9     
- Misses       1485     1491       +6     
- Partials      428      430       +2     
Flag Coverage Δ
unittests 83.61% <100.00%> (-0.05%) ⬇️

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

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@JIeJaitt JIeJaitt marked this pull request as draft March 6, 2025 07:05
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
middleware/session/middleware_test.go (1)

457-502: Well-structured test for Go context integration.

The test verifies that sessions can be accessed from both Fiber context and Go context, confirming that the implementation works correctly. It properly tests the "happy path" where a session exists and can be retrieved.

However, consider adding test cases for edge conditions:

Add tests for:

  1. When the provided context is nil
  2. When the context doesn't contain a session

This would improve test coverage for the FromGoContext function.

+func Test_Session_GoContext_EdgeCases(t *testing.T) {
+	t.Parallel()
+	
+	// Test with nil context
+	sess := FromGoContext(nil)
+	require.Nil(t, sess, "Session should be nil with nil context")
+	
+	// Test with context that doesn't have a session
+	ctx := context.Background()
+	sess = FromGoContext(ctx)
+	require.Nil(t, sess, "Session should be nil when not in context")
+}
middleware/session/store_test.go (1)

229-279: Well-structured test for the new Go context session functionality.

This test properly validates the new functionality for accessing session data via Go context. It covers the main flow by:

  1. Getting a session directly from the store
  2. Setting data in the session
  3. Retrieving and validating the same session from Go context
  4. Verifying data consistency between contexts
  5. Testing end-to-end with a real HTTP request

Consider adding test cases for edge scenarios, such as:

  • Behavior when a session hasn't been initialized before calling FromGoContext
  • Error handling when session operations fail

For example:

t.Run("no session in context", func(t *testing.T) {
    app := fiber.New()
    c := app.AcquireCtx(&fasthttp.RequestCtx{})
    defer app.ReleaseCtx(c)
    
    // No session has been created yet
    goCtxSess := FromGoContext(c.Context())
    require.Nil(t, goCtxSess)
})
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a5c7b77 and 740d04f.

📒 Files selected for processing (5)
  • middleware/session/middleware.go (2 hunks)
  • middleware/session/middleware_test.go (2 hunks)
  • middleware/session/session.go (3 hunks)
  • middleware/session/store.go (2 hunks)
  • middleware/session/store_test.go (2 hunks)
🧰 Additional context used
🪛 GitHub Check: codecov/patch
middleware/session/session.go

[warning] 529-530: middleware/session/session.go#L529-L530
Added lines #L529 - L530 were not covered by tests


[warning] 534-534: middleware/session/session.go#L534
Added line #L534 was not covered by tests

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: unit (1.24.x, windows-latest)
  • GitHub Check: Compare
  • GitHub Check: repeated
🔇 Additional comments (8)
middleware/session/middleware.go (2)

6-6: Context package import added correctly.

This import is needed for integrating Go's standard context capabilities with Fiber's session management.


94-97: Well-implemented session integration with Go context.

The implementation properly adds the session to Go's context using the standard context.WithValue pattern and then updates the Fiber context. This enables retrieving the session via Go's context package, which aligns with modern Go practices.

middleware/session/session.go (2)

5-5: Context package import added correctly.

This import is needed for the new FromGoContext function.


34-41: Well-designed context key implementation.

Using an unexported type for context keys is a best practice in Go as it prevents key collisions with other packages. The implementation follows the recommendations from the Go context package documentation.

middleware/session/store.go (2)

4-4: Context package import added correctly.

This import is needed for the enhanced Get method implementation.


104-113: Robust error handling and context integration.

The enhanced Get method now properly:

  1. Explicitly handles errors from getSession
  2. Sets the session in the Go context
  3. Updates the Fiber context with the Go context

This provides a consistent way to access sessions from both Fiber and Go contexts.

middleware/session/middleware_test.go (1)

4-5: Appropriate imports for testing.

The added imports for io and net/http/httptest are needed for reading response bodies and creating test HTTP requests.

middleware/session/store_test.go (1)

5-6: LGTM: New imports support the new test functionality.

The added imports (io and net/http/httptest) are appropriate for the new test function that requires reading response bodies and simulating HTTP requests.

@JIeJaitt
Copy link
Contributor Author

JIeJaitt commented Mar 6, 2025

This unit test I ran locally reported no errors and I didn't change it. Anything else to note here? @ReneWerner87 @gaby
image

image

@JIeJaitt JIeJaitt marked this pull request as ready for review March 6, 2025 07:20
}

// Add session to Go context
ctx := context.WithValue(c.Context(), sessionContextKey, sess)
Copy link
Member

Choose a reason for hiding this comment

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

we should not add or change anything in a get function, this does not meet the expectations of the user

Copy link
Contributor Author

@JIeJaitt JIeJaitt Mar 6, 2025

Choose a reason for hiding this comment

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

@ReneWerner87 I think we have to have this, look at this code below,

app.Post("/process-data", func(c fiber.Ctx) error {
    sess, err := store.Get(c)
    if err != nil {
        return err
    }
    
    go processDataInBackground(c.Context(), c.Body())
    
    return c.SendStatus(fiber.StatusAccepted)
})

func processDataInBackground(ctx context.Context, data []byte) {
    // Getting sessions from Go context
    sess := session.FromGoContext(ctx)
    if sess == nil {
        log.Error("Session not found in context")
        return
    }
    
    userID := sess.Get("userID").(string)
}

Copy link
Member

Choose a reason for hiding this comment

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

please do not write anything in a read context method
the value in the context should work the same as the value in the locals, i.e. at every place where we write to the locals, we should also write to the context

Copy link
Contributor Author

Choose a reason for hiding this comment

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

you are right, the value in the context should work the same as the value in the locals

Copy link
Member

Choose a reason for hiding this comment

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

Then it would make the most sense to create a new method and set the value in context and locals in this method

This method can then be used in all places where the locals are currently set

@ReneWerner87
Copy link
Member

@sixcolors can you check this

@JIeJaitt
Copy link
Contributor Author

JIeJaitt commented Mar 6, 2025

@ReneWerner87 How can I avoid lint error , I used the following comment but it doesn't seem to have any effect, he still reports lint error:
image

@gaby gaby changed the title 🔥 Feature: Add Session Access via Go Context 🔥 feat: Add Session Access via Go Context Mar 6, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Status: No status
Development

Successfully merging this pull request may close these issues.

2 participants