fiber icon indicating copy to clipboard operation
fiber copied to clipboard

feat: fiber.Context implement context.Context

Open pjebs opened this issue 9 months ago • 4 comments

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.

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

Checklist

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

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

pjebs avatar Mar 30 '25 11:03 pjebs

Walkthrough

The changes remove the previous mechanism for storing and retrieving a context.Context from the Fiber context, replacing it with direct implementation of the context.Context interface on fiber.Ctx. Four new methods (Deadline, Done, Err, Value) are added, with documentation and tests updated to reflect these changes and the limitations of the underlying fasthttp library.

Changes

File(s) Change Summary
ctx.go, ctx_interface_gen.go Remove Context()/SetContext(context.Context); add Deadline, Done, Err, Value methods to fiber.Ctx.
ctx_test.go Remove tests for old context methods; add tests for new context interface methods and value retrieval.
middleware/timeout/timeout.go,
middleware/timeout/timeout_test.go
Update timeout middleware and its tests to use the new context interface directly on fiber.Ctx.
docs/api/ctx.md Update documentation to show fiber.Ctx implements context.Context, remove Context() docs, add examples.
docs/whats_new.md Add note that fiber.Ctx now implements context.Context with new methods and usage examples.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant FiberCtx
    participant Handler

    User->>FiberCtx: Set Locals(key, value)
    Handler->>FiberCtx: Value(key)
    FiberCtx-->>Handler: value (from Locals)
    Handler->>FiberCtx: Deadline()
    FiberCtx-->>Handler: (zero, false)
    Handler->>FiberCtx: Done()
    FiberCtx-->>Handler: nil
    Handler->>FiberCtx: Err()
    FiberCtx-->>Handler: nil

Assessment against linked issues

Objective Addressed Explanation
Make fiber.Ctx implement context.Context interface, removing Context()/SetContext() ([#3344])
Ensure new methods (Deadline, Done, Err, Value) are present and documented ([#3344])
Remove reliance on standard context.Context storage in fiber.Ctx ([#3344])
Update tests and documentation to match new context interface ([#3344])

Possibly related PRs

  • gofiber/fiber#3364: Also removes storing a separate context.Context in fiber.Ctx and adds direct implementation of the context interface.
  • gofiber/fiber#3365: Reverts middleware changes that copied values into a standard context, simplifying context usage in middleware.
  • gofiber/fiber#3200: Adds support for retrieving request ID from either fiber.Ctx or standard context.Context, related to context interface usage.

Suggested reviewers

  • sixcolors
  • gaby
  • ReneWerner87
  • efectn

Poem

In Fiber’s code, a change takes root,
Contexts now are resolute!
No more juggling, no more fuss,
The interface is part of us.
Deadline, Done, and Value too—
Simpler flows for me and you.
🐰✨


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6949586132ff60503b89ec34a4fa595689c3ea44 and 2ef037b54836c6e3b12dc428d8d3601962e83cbc.

📒 Files selected for processing (1)
  • ctx.go (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • ctx.go
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: unit (1.24.x, macos-13)
  • GitHub Check: unit (1.23.x, macos-13)
  • GitHub Check: repeated
  • GitHub Check: Compare
✨ Finishing Touches
  • [ ] 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

coderabbitai[bot] avatar Mar 30 '25 11:03 coderabbitai[bot]

Codecov Report

All modified and coverable lines are covered by tests :white_check_mark:

Project coverage is 84.39%. Comparing base (a5f76a7) to head (2ef037b). Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3382      +/-   ##
==========================================
- Coverage   84.41%   84.39%   -0.02%     
==========================================
  Files         120      120              
  Lines       12194    12190       -4     
==========================================
- Hits        10293    10288       -5     
  Misses       1473     1473              
- Partials      428      429       +1     
Flag Coverage Δ
unittests 84.39% <100.00%> (-0.02%) :arrow_down:

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

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.

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

codecov[bot] avatar Mar 30 '25 11:03 codecov[bot]

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

gaby avatar Mar 31 '25 14:03 gaby

Please update the pull request title and description template.

The documentation for context also needs to be updated

gaby avatar Apr 06 '25 02:04 gaby

@coderabbitai full review

gaby avatar May 24 '25 22:05 gaby

✅ Actions performed

Full review triggered.

coderabbitai[bot] avatar May 24 '25 22:05 coderabbitai[bot]

@pjebs Are the concerns about timeout middleware valid? I believe they are.

gaby avatar May 24 '25 23:05 gaby

The concerns about timeout are not valid.

timeoutContext, cancel := context.WithTimeout(ctx, timeout) // ctx is fiber.Ctx
defer cancel()

timeoutContext will be a (unexported) context.timerCtx: https://cs.opensource.google/go/go/+/refs/tags/go1.24.3:src/context/context.go;l=631 It will timeout only based on timeout value since ctx is a nop. This is by design.

Also relevant: https://github.com/gofiber/fiber/issues/3394

pjebs avatar May 25 '25 01:05 pjebs

tests are flaky

pjebs avatar May 26 '25 00:05 pjebs