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

Propagate fiberCtx.UserContext() to huma.Context - Context() #659

Merged
merged 1 commit into from
Dec 2, 2024

Conversation

excavador
Copy link
Contributor

@excavador excavador commented Nov 22, 2024

The problem: fiber uses UserContext() to hold user data, Huma invokes Context(). As the result, I could not propagate data inside context from Fiber. I have JWT/some other fiber middleware (this is right for us, we use fiber without Huma also), but Huma.Context.Context does not see these values

fix: adapters/humafiber - fixed Context() method - use 'fiberCtx.Context()' for everything, except 'Value', 'Value' first tries to find value inside 'fiberCtx.UserContext()' and only if value is missed call original'fiberCtx.Context().Value()'

Summary by CodeRabbit

  • New Features
    • Introduced a new context adapter that enhances value retrieval by prioritizing user context in the Fiber framework.
    • Updated context handling in the application to utilize the new adapter for improved compatibility with Go's context management.

Copy link

coderabbitai bot commented Nov 22, 2024

Walkthrough

The changes introduce a new type called contextAdapter in the humafiber.go file, which embeds *fiber.Ctx and includes a done channel and a user function for value retrieval. This adapter implements the context.Context interface with methods for Deadline, Done, Err, and Value, where Value prioritizes the user function before falling back to the embedded context. The Context method in the fiberCtx struct has been updated to return an instance of contextAdapter, initialized with the original Fiber context and the user context. No other significant changes to existing methods are present.

Changes

File Change Summary
adapters/humafiber/humafiber.go - Added new type contextAdapter.
- Implemented methods: Deadline, Done, Err, Value.
- Updated Context method in fiberCtx to return contextAdapter initialized with user context.

Poem

In the land where fibers weave,
A new adapter we believe.
With user context in the fray,
Our values shine in bright array.
Hopping through the code with glee,
A brighter path for you and me! 🐇✨


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

🧹 Outside diff range and nitpick comments (1)
adapters/humafiber/humafiber.go (1)

62-64: LGTM: Clean adapter instantiation

The Context() method correctly instantiates the new contextAdapter, properly wrapping the original Fiber context. This implementation maintains a clean separation of concerns while providing the enhanced context handling capabilities.

This adapter pattern implementation is a good example of how to extend functionality without modifying the underlying Fiber context, making it easier to maintain and update in the future.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between bb5d167 and 2654729.

📒 Files selected for processing (1)
  • adapters/humafiber/humafiber.go (2 hunks)
🔇 Additional comments (3)
adapters/humafiber/humafiber.go (3)

18-22: LGTM: Clean struct definition with interface compliance check

The contextAdapter struct is well-designed with proper interface assertion using the var _ pattern to ensure compile-time verification of context.Context interface implementation.


24-34: LGTM: Clean implementation of standard context methods

The Deadline, Done, and Err methods correctly delegate to the underlying Fiber context, maintaining the expected context.Context behavior.


36-42: LGTM: Value method correctly implements priority lookup

The implementation aligns with the PR objective by:

  1. First checking UserContext().Value()
  2. Falling back to Context().Value() if no value is found

Let's verify the usage of UserContext in the codebase:

✅ Verification successful

Value method implementation is unique and correctly prioritizes context lookup

The implementation in adapters/humafiber/humafiber.go is the only Value method in the codebase that handles context values. The prioritized lookup (UserContext first, then falling back to Context) is unique to this adapter and doesn't conflict with any other implementations.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for other UserContext usages to ensure consistency
# and verify there are no potential conflicts with this new implementation

rg -A 2 "UserContext\(\)" --type go

Length of output: 213


Script:

#!/bin/bash
# Let's check for any other implementations of Value method in the codebase
# to ensure consistency with context handling

ast-grep --pattern 'func $_Value(key any) any {
  $$$
}'

Length of output: 58


Script:

#!/bin/bash
# Let's check for any Value method implementations and context handling patterns
# using a broader search to catch potential variations

rg -A 5 "func.*Value.*any.*any" --type go

Length of output: 401

…ext()' for everything, except 'Value', 'Value' first tries to find value inside 'fiberCtx.UserContext()' and only if value is missed call original'fiberCtx.Context().Value()'
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

🧹 Outside diff range and nitpick comments (1)
adapters/humafiber/humafiber.go (1)

65-69: Consider handling nil Done channel.

While the implementation correctly initializes the contextAdapter, consider handling the case where Context().Done() returns nil. This is a valid case in the context.Context interface.

Consider this safer initialization:

 return &contextAdapter{
   Ctx:  c.orig,
-  done: c.orig.Context().Done(),
+  done: func() <-chan struct{} {
+    if done := c.orig.Context().Done(); done != nil {
+      return done
+    }
+    return nil
+  }(),
   user: c.orig.UserContext().Value,
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d1f522e and f355429.

📒 Files selected for processing (1)
  • adapters/humafiber/humafiber.go (2 hunks)
🔇 Additional comments (3)
adapters/humafiber/humafiber.go (3)

18-23: LGTM! Good approach to prevent race conditions.

The contextAdapter type effectively prevents race conditions in fasthttp by caching both the Done() channel and the UserContext().Value function. The embedded *fiber.Ctx maintains access to other context functionality.


39-45: LGTM! Correct implementation of value priority.

The Value method correctly implements the PR objective by:

  1. First checking the user context via the cached function
  2. Falling back to the original context's Value method if no user value is found

Line range hint 18-69: Verify context propagation with Fiber middleware.

The changes look good, but let's verify the interaction with Fiber middleware and potential memory implications.

Copy link

codecov bot commented Dec 2, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 93.04%. Comparing base (bb5d167) to head (f355429).
Report is 6 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main     #659   +/-   ##
=======================================
  Coverage   93.04%   93.04%           
=======================================
  Files          22       22           
  Lines        4901     4901           
=======================================
  Hits         4560     4560           
  Misses        298      298           
  Partials       43       43           

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

Copy link
Owner

@danielgtaylor danielgtaylor left a comment

Choose a reason for hiding this comment

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

Thanks, I wasn't aware of UserContext in Fiber!

@danielgtaylor danielgtaylor merged commit 1c8e5c9 into danielgtaylor:main Dec 2, 2024
5 checks passed
@danielgtaylor danielgtaylor mentioned this pull request Dec 22, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants