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: fiber.Context implement context.Context #3382

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

Conversation

pjebs
Copy link
Contributor

@pjebs pjebs commented Mar 30, 2025

Description

Makes fiber.Context implement context.Context

Fixes #3344

Changes introduced

fiber.Context now incorporates :

  1. Done() <-chan struct{}
  2. Err() error
  3. Value(key any) any
  4. Deadline() (deadline time.Time, ok bool)

Type of change

Please delete options that are not relevant.

  • Enhancement (improvement to existing features and functionality)
  • Documentation update (changes to documentation)

Checklist

Before you submit your pull request, please make sure you meet these requirements:

  • Followed the inspiration of the Express.js framework for new functionalities, making them similar in usage.
  • Conducted a self-review of the code and provided comments for complex or critical parts.
  • Updated the documentation in the /docs/ directory for Fiber's documentation.
  • Added or updated unit tests to validate the effectiveness of the changes or new features.
  • Ensured that new and existing unit tests pass locally with the changes.
  • Verified that any new dependencies are essential and have been agreed upon by the maintainers/community.
  • Aimed for optimal performance with minimal allocations in the new code.
  • Provided benchmarks for the new code to analyze and improve upon.

Copy link
Contributor

coderabbitai bot commented Mar 30, 2025

Warning

Rate limit exceeded

@pjebs has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 8 minutes and 16 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 4aafa9e and 103be81.

📒 Files selected for processing (8)
  • ctx.go (4 hunks)
  • ctx_interface_gen.go (3 hunks)
  • ctx_test.go (1 hunks)
  • docs/api/ctx.md (1 hunks)
  • middleware/requestid/requestid.go (0 hunks)
  • middleware/requestid/requestid_test.go (0 hunks)
  • middleware/timeout/timeout.go (1 hunks)
  • middleware/timeout/timeout_test.go (3 hunks)

Walkthrough

This pull request refactors the context management in the Fiber framework. The older methods for handling a custom context—Context() and SetContext()—are removed and replaced by new methods (Deadline(), Done(), Err(), and Value()) that mirror the standard context.Context interface with no-operation behaviors. Updates are applied across core context files, middleware components, and associated tests to align functionality with these interface changes.

Changes

File(s) Summary of Changes
ctx.go, ctx_interface_gen.go, ctx_test.go Removed Context() and SetContext(ctx context.Context); added Deadline(), Done(), Err(), and Value(key any) methods with no-op implementations; updated tests accordingly.
middleware/requestid/requestid.go, middleware/requestid/requestid_test.go Removed request ID propagation via context; deleted test case for retrieving from context; adjusted remaining tests.
middleware/timeout/timeout.go, middleware/timeout/timeout_test.go Modified timeout context creation to use fiber.Ctx directly; updated test cases to reflect new context handling.
docs/api/ctx.md Updated documentation to reflect changes in context methods; removed Context() method signature; added new method signatures for Deadline(), Done(), Err(), and Value(key any).

Sequence Diagram(s)

sequenceDiagram
    participant C as Client/Handler
    participant F as fiber.Ctx
    C->>F: Call Deadline()
    F-->>C: Returns (zero time, false)
    C->>F: Call Done()
    F-->>C: Returns nil channel
    C->>F: Call Err()
    F-->>C: Returns nil
    C->>F: Call Value(key)
    F-->>C: Returns value (or nil)
Loading

Poem

Oh, I’m a rabbit, leaping through code,
Hopping past old ways on this new road,
No more Context() to hold me tight,
New methods gleam in the soft moonlight,
With every test and middleware cheer,
I nibble bytes and hop with cheer 🐇!


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 plan to trigger planning for file edits and PR creation.
  • @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

codecov bot commented Mar 30, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 83.84%. Comparing base (5515703) to head (103be81).

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3382      +/-   ##
==========================================
- Coverage   83.93%   83.84%   -0.10%     
==========================================
  Files         119      119              
  Lines       11904    11896       -8     
==========================================
- Hits         9992     9974      -18     
- Misses       1484     1492       +8     
- Partials      428      430       +2     
Flag Coverage Δ
unittests 83.84% <100.00%> (-0.10%) ⬇️

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.

@gaby
Copy link
Member

gaby commented Mar 31, 2025

@pjebs Can you take a look at the merge conflicts and failing tests

@gaby gaby added this to the v3 milestone Mar 31, 2025
@gaby gaby changed the title Context feat: Context Mar 31, 2025
@pjebs pjebs marked this pull request as ready for review April 6, 2025 02:18
@pjebs pjebs requested a review from a team as a code owner April 6, 2025 02:18
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)
ctx.go (2)

43-43: Consider removing or clarifying the unused type.

Currently, contextKey is declared but not referenced. If it's intended for future use, consider adding explanatory comments or referencing it to avoid confusion and lint warnings.


1820-1829: Clarify distinction from standard context.

Value(key any) delegates to c.fasthttp.UserValue, which differs from typical context.Context scoping rules. If the goal is standard context.Context compatibility, document any differences or add disclaimers to prevent confusion.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5515703 and 76e3784.

📒 Files selected for processing (7)
  • ctx.go (4 hunks)
  • ctx_interface_gen.go (3 hunks)
  • ctx_test.go (1 hunks)
  • middleware/requestid/requestid.go (0 hunks)
  • middleware/requestid/requestid_test.go (0 hunks)
  • middleware/timeout/timeout.go (1 hunks)
  • middleware/timeout/timeout_test.go (3 hunks)
💤 Files with no reviewable changes (2)
  • middleware/requestid/requestid_test.go
  • middleware/requestid/requestid.go
🔇 Additional comments (10)
ctx.go (3)

426-434: Confirm no-op behavior.

Deadline() intentionally returns no deadline (time.Time{}, false). Ensure this aligns with your design, as callers expecting real context.Context behavior might be surprised by the missing deadline support.


436-446: Confirm no-op behavior.

Done() intentionally returns nil, which omits the usual cancellation signals in a standard context.Context. Verify this is acceptable so that dependent callers won't assume actual cancellation mechanics.


472-482: Confirm no-op behavior.

Err() unconditionally returns nil, indicating no cancellation or deadline exceeded errors are signaled. Double-check that this matches your requirements for a partial context-like interface.

ctx_test.go (1)

2190-2255: Well-implemented tests for the new context interface methods.

The tests for the new context methods (Deadline(), Done(), Err(), and Value()) look good. They follow a consistent pattern and thoroughly verify that these methods implement the standard Go context.Context interface with the appropriate no-operation behaviors. The test cases are clear, concise, and maintain the same structure as other tests in the file.

ctx_interface_gen.go (5)

10-10: Import of "time" looks good
This import is presumably required to support the newly introduced context-deadline methods.


60-63: Validate Deadline() implementation
The documentation mirrors standard context.Context behavior. Please ensure that the implemented Deadline() method truly reflects the described functionality, including concurrency safety and proper deadline reporting.

Would you like a script to confirm the method’s actual implementation usage?


64-69: Check Done() channel consistency
The doc states it may return nil if the context can’t be canceled. Verify that this channel is properly closed and tested wherever timeouts or cancellations occur.


75-80: Clarify Err() behavior
Ensure that this reliably distinguishes between Canceled and DeadlineExceeded. If it’s effectively a no-op, clarify how and why.


331-337: Consider concurrency implications in Value(key any) any
Reading/writing local values across goroutines can cause data races. Confirm whether this method needs synchronization or is guaranteed to be single-threaded.

middleware/timeout/timeout_test.go (1)

44-44: Ensure sleepWithContext receives a valid context.Context
Replacing c.Context() with c implies that fiber.Ctx must implement the standard context.Context. Confirm that all tests pass and that no unexpected type assertions fail.

Also applies to: 63-63, 84-84

@@ -19,12 +19,9 @@ func New(h fiber.Handler, timeout time.Duration, tErrs ...error) fiber.Handler {

// Create a context with the specified timeout; any operation exceeding
// this deadline will be canceled automatically.
timeoutContext, cancel := context.WithTimeout(ctx.Context(), timeout)
timeoutContext, cancel := context.WithTimeout(ctx, timeout)
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

❓ Verification inconclusive

Confirm fiber.Ctx implements context.Context
context.WithTimeout(ctx, timeout) expects a valid context.Context. If fiber.Ctx is intended to fully satisfy this interface, confirm at compile-time and runtime.


🏁 Script executed:

#!/bin/bash
# Attempt building the codebase to ensure no type mismatch errors.
go build ./...

Length of output: 209


Below is a new verification script to ascertain at compile time that the provided ctx (of type fiber.Ctx) indeed implements the context.Context interface:


Review Update: Verify fiber.Ctx Compliance with context.Context

Please ensure that the ctx you pass to context.WithTimeout(ctx, timeout) (located in middleware/timeout/timeout.go at line 22) is a valid context.Context. The above script creates a compile-time check for *fiber.Ctx to assert that it implements context.Context. If the script fails to build, you’ll need to either modify the code or explicitly convert/extract a proper context.Context from fiber.Ctx.


🏁 Script executed:

#!/bin/bash
set -e

# Create a temporary directory for the compile-time check
mkdir -p temp_assert && cd temp_assert

# Write a small Go program that asserts fiber.Ctx implements context.Context.
cat > tmp_assert.go << 'EOF'
package main

import (
	"context"
	"fmt"
	"github.com/gofiber/fiber/v2"
)

func main() {
	// Compile-time assertion: if *fiber.Ctx doesn't implement context.Context,
	// this line will cause a compilation error.
	var _ context.Context = (*fiber.Ctx)(nil)
	fmt.Println("fiber.Ctx implements context.Context")
}
EOF

# Initialize a temporary go module and fetch the fiber dependency.
go mod init temp_assert_module
go get github.com/gofiber/fiber/v2

# Attempt to build and run the temporary program.
go build tmp_assert.go && ./tmp_assert

Length of output: 1681


Update Required: Invalid Context for Timeout

Our verification shows that *fiber.Ctx does not implement context.Context (it's missing the Deadline method). That means the call to context.WithTimeout(ctx, timeout) in middleware/timeout/timeout.go (line 22) is passing an invalid argument.

  • In middleware/timeout/timeout.go, update the code so that a valid context.Context is provided. If available, consider using a method like ctx.Context() (if it returns a standard Go context) or use a fallback such as context.Background().
  • Example revision (if ctx.Context() yields a standard context):
    timeoutContext, cancel := context.WithTimeout(ctx.Context(), timeout)

Please ensure the revised context usage accurately reflects the intended behavior in your application.

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

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

43-43: Unused type declaration needs explanation.

The contextKey type is marked as unused with a nolint directive, with a comment that it's needed for future use. Since this was previously used for the Context() functionality that has been removed, consider adding more context about its future purpose or remove it entirely if it's no longer needed.


426-434: Implementation of context.Context interface: Deadline method

This method implements the Deadline() method from the standard context.Context interface but returns no deadline. The comment explains that this is a no-op due to fasthttp limitations, which is useful information for users.

Consider adding a link to discussions or issues explaining the design decision to implement the context.Context interface with no-op methods, which would help users understand why this approach was chosen over other alternatives.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 76e3784 and c348cd1.

📒 Files selected for processing (2)
  • ctx.go (4 hunks)
  • ctx_interface_gen.go (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: unit (1.24.x, windows-latest)
  • GitHub Check: unit (1.23.x, windows-latest)
  • GitHub Check: Compare
  • GitHub Check: repeated
🔇 Additional comments (6)
ctx.go (3)

436-446: Implementation of context.Context interface: Done method

This method implements the Done() method from the standard context.Context interface but returns nil, meaning this context can never be canceled. The comment correctly explains the limitations.

Good job providing clear documentation explaining the fasthttp limitations. This helps users understand why cancellation signals aren't supported.


472-482: Implementation of context.Context interface: Err method

This method implements the Err() method from the standard context.Context interface but always returns nil. The implementation aligns with the comment that this is a no-op due to fasthttp limitations.

The documentation is clear and matches the implementation.


1820-1824: Implementation of context.Context interface: Value method

This method implements the Value() method from the standard context.Context interface by retrieving values from the fasthttp UserValue store. This approach provides a working implementation for storing request-scoped values.

Unlike the other context methods, this one actually provides useful functionality rather than being a no-op. The implementation is simple and efficient.

ctx_interface_gen.go (3)

10-10: Added time package for context.Context interface

The time package was added to support the Deadline() method from the context.Context interface. This change is necessary and correctly implemented.


60-80: Interface declaration for context.Context methods

The Deadline(), Done(), and Err() methods have been added to the Ctx interface to match the standard context.Context interface. The documentation for these methods is comprehensive and follows the standard context package documentation.

These changes enable the Fiber Ctx interface to satisfy the standard context.Context interface, which improves compatibility with libraries expecting context.Context.


331-333: Interface declaration for Value method

The Value() method has been added to complete the context.Context interface implementation. The documentation is clear and explains that this method retrieves values scoped to the request.

This method provides a way to access request-scoped values, which is a key part of the context.Context interface. The implementation works with the Locals() method but provides context.Context compatibility.

Copy link

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

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

Copilot reviewed 7 out of 7 changed files in this pull request and generated no comments.

Comments suppressed due to low confidence (2)

middleware/timeout/timeout.go:21

  • The removal of updating the Fiber context with the timeout-bound context may lead to unexpected behavior if downstream handlers depend on the updated context. Please confirm that this change is intentional and that all affected handlers are adjusted accordingly.
ctx.SetContext(timeoutContext)

middleware/requestid/requestid_test.go:73

  • The removal of the 'From context.Context' test case reduces coverage of context-based request ID extraction. Please ensure that either this functionality is no longer supported or that alternative tests are provided to cover the desired behavior.
{ name: "From context.Context", args: { inputFunc: func(c fiber.Ctx) any { return c.Context() } } },

@gaby
Copy link
Member

gaby commented Apr 6, 2025

Please update the pull request title and description template.

The documentation for context also needs to be updated

@pjebs pjebs changed the title feat: Context feat: fiber.Context implement context.Context Apr 6, 2025
@pjebs pjebs force-pushed the context branch 3 times, most recently from 1c2ac6a to 4aafa9e Compare April 6, 2025 03:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Status: In Progress
Development

Successfully merging this pull request may close these issues.

📝 [Proposal]: Make fiber.Ctx implement context.Context
2 participants