Skip to content

🐛 fix(ctx): delegate Deadline/Done/Err to the user context#4465

Open
yathboss wants to merge 3 commits into
gofiber:mainfrom
yathboss:fix/ctx-cancellation-delegation
Open

🐛 fix(ctx): delegate Deadline/Done/Err to the user context#4465
yathboss wants to merge 3 commits into
gofiber:mainfrom
yathboss:fix/ctx-cancellation-delegation

Conversation

@yathboss

Copy link
Copy Markdown

Description

DefaultCtx.Deadline(), Done() and Err() were hardcoded no-ops, so the context.Context contract was broken:

  • Done() returned nil → blocks forever in any select
  • Err() always returned nil → never reflected cancellation
  • Deadline() always reported no deadline

Because of this, a cancelable context set via SetContextincluding the context.WithTimeout installed by the timeout middleware — was invisible to any library that consumed fiber.Ctx as a context.Context (database drivers, HTTP/gRPC clients, etc.). They would never respect cancellation.

Fix

Delegate the three methods to c.Context():

func (c *DefaultCtx) Deadline() (time.Time, bool) { return c.Context().Deadline() }
func (c *DefaultCtx) Done() <-chan struct{}       { return c.Context().Done() }
func (c *DefaultCtx) Err() error                  { return c.Context().Err() }

When no context has been set, c.Context() returns context.Background(), whose Done() is nil, Err() is nil and Deadline() reports no deadline — so existing behavior is preserved and the change is backward compatible.

Tests

  • Added Test_Ctx_Deadline_Delegates, Test_Ctx_Done_Delegates, Test_Ctx_Err_Delegates covering deadline/cancellation propagation.
  • Existing Test_Ctx_Deadline, Test_Ctx_Done, Test_Ctx_Err (no-context case) still pass, confirming backward compatibility.
  • go vet clean; timeout-middleware and Context tests pass.

Updated the context.Context section in docs/api/ctx.md.

Fixes #4335

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>
@yathboss
yathboss requested a review from a team as a code owner June 26, 2026 20:23
@welcome

welcome Bot commented Jun 26, 2026

Copy link
Copy Markdown

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

@coderabbitai

coderabbitai Bot commented Jun 26, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 658efaac-a21b-49a7-916a-1c62851363a5

📥 Commits

Reviewing files that changed from the base of the PR and between 65bc896 and 3f22d72.

📒 Files selected for processing (1)
  • ctx_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • ctx_test.go

Walkthrough

DefaultCtx now delegates Deadline, Done, and Err to the context set via SetContext, falling back to context.Background() when unset. Tests and API documentation cover the updated behavior.

Changes

Context cancellation delegation

Layer / File(s) Summary
Context methods delegate
ctx.go
DefaultCtx.Deadline(), Done(), and Err() now delegate to Context() instead of returning fixed empty or nil values.
Context behavior validation
ctx_test.go, docs/api/ctx.md
Tests verify delegated deadlines and cancellation, while the API documentation describes SetContext and the context.Background() fallback.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related issues

Possibly related PRs

  • gofiber/fiber#3720: Introduces the Context() and SetContext() storage used by this delegation.
  • gofiber/fiber#4119: Strengthens timeout context propagation assertions that rely on delegated cancellation.
  • gofiber/fiber#4399: Updates the same context methods, tests, and API documentation.

Suggested reviewers: gaby, sixcolors, renewerner87, efectn

Poem

A bunny hopped through context bright,
And found Done() blinking back to light.
Err() and deadlines sprang alive,
Cancelable paths now safely thrive.
🐇✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: delegating Deadline/Done/Err to the user context.
Description check ✅ Passed The description covers the bug, fix, tests, docs update, and linked issue, so it is mostly complete.
Linked Issues check ✅ Passed The changes implement the requested delegation and tests for cancellation, deadlines, and no-context behavior in #4335.
Out of Scope Changes check ✅ Passed All code changes stay within the context delegation bug fix, its tests, and the documentation update.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@ReneWerner87 ReneWerner87 added this to v3 Jun 26, 2026
@ReneWerner87 ReneWerner87 added this to the v3 milestone Jun 26, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 win

Update the generated Ctx interface comments to match this contract.

ctx_interface_gen.go still says Deadline(), Done(), and Err() 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

📥 Commits

Reviewing files that changed from the base of the PR and between 464387b and 2912584.

📒 Files selected for processing (3)
  • ctx.go
  • ctx_test.go
  • docs/api/ctx.md

Comment thread docs/api/ctx.md
@gaby

gaby commented Jun 26, 2026

Copy link
Copy Markdown
Member

This is a duplicate of #4399

Copilot AI review requested due to automatic review settings July 16, 2026 13:07

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 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`:
- Around line 2652-2654: Resolve the inconsistency between the SendEarlyHints
caution and the HTTP-version behavior described in the surrounding
documentation. Update the affected HTTP-version statement so both sections
consistently specify the minimum protocol required for sending the interim 103
response, while preserving the documented Link-header behavior for unsupported
clients.
🪄 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: 778b3093-8162-4a6e-939a-02750fe1515e

📥 Commits

Reviewing files that changed from the base of the PR and between 2912584 and 65bc896.

📒 Files selected for processing (3)
  • ctx.go
  • ctx_test.go
  • docs/api/ctx.md
🚧 Files skipped from review as they are similar to previous changes (2)
  • ctx.go
  • ctx_test.go

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 1

🤖 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`:
- Around line 2652-2654: Resolve the inconsistency between the SendEarlyHints
caution and the HTTP-version behavior described in the surrounding
documentation. Update the affected HTTP-version statement so both sections
consistently specify the minimum protocol required for sending the interim 103
response, while preserving the documented Link-header behavior for unsupported
clients.
🪄 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: 778b3093-8162-4a6e-939a-02750fe1515e

📥 Commits

Reviewing files that changed from the base of the PR and between 2912584 and 65bc896.

📒 Files selected for processing (3)
  • ctx.go
  • ctx_test.go
  • docs/api/ctx.md
🚧 Files skipped from review as they are similar to previous changes (2)
  • ctx.go
  • ctx_test.go
🛑 Comments failed to post (1)
docs/api/ctx.md (1)

2652-2654: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Resolve the contradictory HTTP-version guidance.

The preceding SendEarlyHints caution says the feature requires HTTP/2 or newer, while this paragraph says HTTP/1.1 requests receive the interim response. Update one statement so the documented transport contract is consistent.

🤖 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` around lines 2652 - 2654, Resolve the inconsistency between
the SendEarlyHints caution and the HTTP-version behavior described in the
surrounding documentation. Update the affected HTTP-version statement so both
sections consistently specify the minimum protocol required for sending the
interim 103 response, while preserving the documented Link-header behavior for
unsupported clients.

@codecov

codecov Bot commented Jul 18, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.17%. Comparing base (981cf15) to head (3f22d72).

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #4465      +/-   ##
==========================================
- Coverage   93.23%   93.17%   -0.06%     
==========================================
  Files         140      140              
  Lines       14567    14567              
==========================================
- Hits        13581    13573       -8     
- Misses        614      621       +7     
- Partials      372      373       +1     
Flag Coverage Δ
unittests 93.17% <100.00%> (-0.06%) ⬇️

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

☔ View full report in Codecov by Harness.
📢 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.

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.

🐛 [Bug]: DefaultCtx.Done() returns nil — cancellation impossible through context.Context interface

4 participants