🐛 fix(ctx): delegate Deadline/Done/Err to the user context#4465
🐛 fix(ctx): delegate Deadline/Done/Err to the user context#4465yathboss wants to merge 1 commit into
Conversation
DefaultCtx.Deadline(), Done() and Err() were hardcoded no-ops, so the context.Context contract was broken: Done() returned nil (blocking forever in select), Err() always returned nil, and Deadline() never reported a deadline. Cancellation set via SetContext — including the context.WithTimeout installed by the timeout middleware — was therefore invisible to any library that consumed fiber.Ctx as a context.Context. Delegate the three methods to c.Context(). When no context has been set, c.Context() returns context.Background(), preserving the previous behavior (nil Done, nil Err, no deadline) so the change is backward compatible. Adds tests covering cancellation/deadline propagation and updates the context.Context docs. Fixes gofiber#4335 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
|
Thanks for opening this pull request! 🎉 Please check out our contributing guidelines. If you need help or want to chat with us, join us on Discord https://gofiber.io/discord |
WalkthroughDefaultCtx now delegates Deadline, Done, and Err to the context set via SetContext, falling back to context.Background() when unset. Tests cover deadline and cancellation behavior, and the API docs describe the updated compatibility contract. ChangesContext cancellation delegation
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes Possibly related issues
Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Warning There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure. 🔧 golangci-lint (2.12.2)level=error msg="[linters_context] typechecking error: pattern ./...: directory prefix . does not contain main module or its selected dependencies" 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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
ctx.go (1)
158-184: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winUpdate the generated
Ctxinterface comments to match this contract.
ctx_interface_gen.gostill saysDeadline(),Done(), andErr()are fasthttp no-ops, so the GoDoc now contradicts both this implementation and the updated Markdown docs. Please regenerate or update that interface documentation in the same change.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@ctx.go` around lines 158 - 184, The generated Ctx interface comments are outdated and still describe Deadline(), Done(), and Err() as fasthttp no-ops, which contradicts the DefaultCtx methods in ctx.go and the current docs. Update the interface documentation in ctx_interface_gen.go so it matches the contract implemented by DefaultCtx.Context(), Deadline(), Done(), and Err(), or regenerate that file if it is derived from templates, ensuring the GoDoc reflects delegation to the configured context rather than no-op behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@docs/api/ctx.md`:
- Line 83: The timeout middleware reference in the Ctx documentation is pointing
to the wrong relative path. Update the markdown link in docs/api/ctx.md so the
mention of the timeout middleware resolves from the API docs folder to the
middleware docs using the correct relative target, and keep the rest of the
Ctx/SetContext/Context wording unchanged.
---
Outside diff comments:
In `@ctx.go`:
- Around line 158-184: The generated Ctx interface comments are outdated and
still describe Deadline(), Done(), and Err() as fasthttp no-ops, which
contradicts the DefaultCtx methods in ctx.go and the current docs. Update the
interface documentation in ctx_interface_gen.go so it matches the contract
implemented by DefaultCtx.Context(), Deadline(), Done(), and Err(), or
regenerate that file if it is derived from templates, ensuring the GoDoc
reflects delegation to the configured context rather than no-op behavior.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 6e3b63d4-bf8a-49f9-820d-fbb6316bd57c
📒 Files selected for processing (3)
ctx.goctx_test.godocs/api/ctx.md
| ### context.Context | ||
|
|
||
| `Ctx` implements `context.Context`. However due to [current limitations in how fasthttp](https://github.com/valyala/fasthttp/issues/965#issuecomment-777268945) works, `Deadline()`, `Done()` and `Err()` are no-ops. The `fiber.Ctx` instance is reused after the handler returns and must not be used for asynchronous operations once the handler has completed. Call [`Context`](#context) within the handler to obtain a `context.Context` that can be used outside the handler. | ||
| `Ctx` implements `context.Context`. `Deadline()`, `Done()` and `Err()` delegate to the context set via [`SetContext`](#setcontext) (the same context returned by [`Context`](#context)). When no context has been set they fall back to `context.Background()`, so `Done()` returns `nil`, `Err()` returns `nil` and `Deadline()` reports no deadline. This means a cancelable context — such as the one installed by the [timeout middleware](./middleware/timeout.md) — propagates cancellation through `c.Done()`/`c.Err()`. The `fiber.Ctx` instance is reused after the handler returns and must not be used for asynchronous operations once the handler has completed. Call [`Context`](#context) within the handler to obtain a `context.Context` that can be used outside the handler. |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
python - <<'PY'
from pathlib import Path
src = Path("docs/api/ctx.md")
for rel in ("./middleware/timeout.md", "../middleware/timeout.md"):
target = (src.parent / rel).resolve()
print(f"{rel} -> {target} exists={target.exists()}")
PYRepository: gofiber/fiber
Length of output: 327
Fix the timeout middleware link docs/api/ctx.md should use ../middleware/timeout.md; ./middleware/timeout.md points under docs/api/ and does not exist.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@docs/api/ctx.md` at line 83, The timeout middleware reference in the Ctx
documentation is pointing to the wrong relative path. Update the markdown link
in docs/api/ctx.md so the mention of the timeout middleware resolves from the
API docs folder to the middleware docs using the correct relative target, and
keep the rest of the Ctx/SetContext/Context wording unchanged.
|
This is a duplicate of #4399 |
Description
DefaultCtx.Deadline(),Done()andErr()were hardcoded no-ops, so thecontext.Contextcontract was broken:Done()returnednil→ blocks forever in anyselectErr()always returnednil→ never reflected cancellationDeadline()always reported no deadlineBecause of this, a cancelable context set via
SetContext— including thecontext.WithTimeoutinstalled by the timeout middleware — was invisible to any library that consumedfiber.Ctxas acontext.Context(database drivers, HTTP/gRPC clients, etc.). They would never respect cancellation.Fix
Delegate the three methods to
c.Context():When no context has been set,
c.Context()returnscontext.Background(), whoseDone()isnil,Err()isnilandDeadline()reports no deadline — so existing behavior is preserved and the change is backward compatible.Tests
Test_Ctx_Deadline_Delegates,Test_Ctx_Done_Delegates,Test_Ctx_Err_Delegatescovering deadline/cancellation propagation.Test_Ctx_Deadline,Test_Ctx_Done,Test_Ctx_Err(no-context case) still pass, confirming backward compatibility.go vetclean; timeout-middleware and Context tests pass.Updated the
context.Contextsection indocs/api/ctx.md.Fixes #4335