Skip to content

🐛 bug: Fix Cache middleware handling of Age #3547

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

Merged
merged 8 commits into from
Jun 30, 2025
Merged

Conversation

gaby
Copy link
Member

@gaby gaby commented Jun 26, 2025

Summary

  • RFC 9111 Compliance for Age Header: The cache middleware now correctly calculates and sets the Age header for cached responses. It achieves this by storing the Age value received from the upstream server and adding the time the response has been resident in the cache, adhering to the specifications of RFC 9111.
  • Stop Caching 418 I'm a teapot Responses: The middleware has been updated to no longer cache responses with the 418 I'm a teapot status code. This change removes a non-standard caching behavior and aligns the middleware with typical HTTP caching practices.

Related #3383

Copy link
Contributor

coderabbitai bot commented Jun 26, 2025

"""

Walkthrough

This update refines the Ctx interface with improved comments, clarifies method behaviors, and reorders methods for clarity. Cache middleware logic is updated to handle the Age header according to RFC 9111, removes HTTP 418 from cacheable statuses, and extends serialization to support new fields. Benchmark tests are modernized to use idiomatic Go loops.

Changes

File(s) Change Summary
ctx_interface_gen.go Improved comments and reordered methods in Ctx interface; clarified behaviors of Deadline, Done, Err, Path, and Subdomains.
docs/middleware/cache.md Updated documentation to remove HTTP 418 (I'm a teapot) from list of cacheable statuses.
middleware/cache/cache.go Updated cache logic to remove HTTP 418 as cacheable; revised Age header handling for RFC 9111 compliance.
middleware/cache/cache_test.go Added test for upstream Age header handling; updated tests to verify HTTP 418 is not cacheable.
middleware/cache/manager.go Added age field to cache item struct; reset age and ttl fields on release.
middleware/cache/manager_msgp.go Extended serialization/deserialization to support new age and ttl fields in cache items.
middleware/cache/manager_msgp_test.go
middleware/csrf/storage_manager_msgp_test.go
middleware/idempotency/response_msgp_test.go
middleware/session/data_msgp_test.go
Updated all benchmarks to use standard Go for-loop pattern with b.ResetTimer(); replaced deprecated b.Loop().

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant CacheMiddleware
    participant UpstreamHandler

    Client->>CacheMiddleware: HTTP Request
    alt Cache Hit
        CacheMiddleware->>Client: Response with updated Age header
    else Cache Miss
        CacheMiddleware->>UpstreamHandler: Forward Request
        UpstreamHandler->>CacheMiddleware: Response (may include Age header)
        CacheMiddleware->>CacheMiddleware: Store response, parse/set Age
        CacheMiddleware->>Client: Response with Age header
    end
Loading

Possibly related PRs

  • gofiber/fiber#3488: Related cache middleware changes handling the Age header and cacheable status codes, including removal of HTTP 418.
  • gofiber/fiber#3382: Introduced the Deadline(), Done(), and Err() methods to fiber.Ctx for context.Context compatibility; this PR directly refines those methods' documentation and behavior.

Suggested reviewers

  • sixcolors
  • efectn
  • ReneWerner87

Poem

A bunny hops through code anew,
Tidying comments, benchmarks too!
No more teapots in the cache,
Age headers now with proper math.
Serialization learned some tricks,
As Go loops do their benchmark kicks.
Hippity-hop, the code’s refreshed—
Bugs and cobwebs laid to rest! 🐇
"""


📜 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 a0012c3 and ee8340e.

📒 Files selected for processing (1)
  • middleware/cache/cache.go (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • middleware/cache/cache.go
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: unit (1.24.x, macos-13)
  • GitHub Check: unit (1.24.x, ubuntu-latest)
  • GitHub Check: unit (1.24.x, macos-latest)
  • GitHub Check: lint
  • GitHub Check: Analyse
  • GitHub Check: unit (1.24.x, windows-latest)
  • 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.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Summary of Changes

Hello @gaby, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request refines the cache middleware's behavior by improving its compliance with RFC 9111 for the Age header and by discontinuing the caching of 418 I'm a teapot responses. These changes involve modifications to the cache entry structure, its serialization, and corresponding updates to documentation and tests.

Highlights

  • RFC 9111 Compliance for Age Header: The cache middleware now correctly calculates and sets the Age header for cached responses. It achieves this by storing the Age value received from the upstream server and adding the time the response has been resident in the cache, adhering to the specifications of RFC 9111.
  • Stop Caching 418 I'm a teapot Responses: The middleware has been updated to no longer cache responses with the 418 I'm a teapot status code. This change removes a non-standard caching behavior and aligns the middleware with typical HTTP caching practices.
  • Cache Entry Structure and Serialization Updates: The internal item struct, which represents a cached entry, now includes a dedicated age field to store the upstream Age header value. The msgp serialization code for this struct has been regenerated to properly handle the new age field, as well as ensuring explicit serialization/deserialization for the existing ttl field.
  • Documentation and Test Updates: The project documentation has been updated to reflect that 418 I'm a teapot responses are no longer cached. Corresponding tests have also been adjusted to verify that 418 responses are now correctly identified as uncacheable.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist is currently in preview and may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments to provide feedback.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@gaby gaby changed the title Fix cache Age handling 🐛 bug: Fix Cache middleware handling of Age Jun 26, 2025
Copy link

codecov bot commented Jun 26, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 91.00%. Comparing base (55818fb) to head (b71be30).
Report is 5 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3547      +/-   ##
==========================================
- Coverage   91.02%   91.00%   -0.02%     
==========================================
  Files         110      110              
  Lines       10955    10967      +12     
==========================================
+ Hits         9972     9981       +9     
- Misses        731      733       +2     
- Partials      252      253       +1     
Flag Coverage Δ
unittests 91.00% <100.00%> (-0.02%) ⬇️

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.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request implements RFC 9111 for Age header handling, stops caching 418 Teapot responses, and updates documentation and tests. A fix for serializing the ttl field for cached items when using external storage is also included. One suggestion has been made to improve the robustness of object pooling by resetting the heapidx field.

@gaby gaby added this to v3 Jun 26, 2025
@gaby gaby added this to the v3 milestone Jun 26, 2025
@gaby gaby moved this to In Progress in v3 Jun 26, 2025
Copy link
Contributor

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

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

⚠️ Performance Alert ⚠️

Possible performance regression was detected for benchmark.
Benchmark result of this commit is worse than the previous benchmark result exceeding threshold 1.50.

Benchmark suite Current: b71be30 Previous: 55818fb Ratio
Benchmark_Cache 14180 ns/op 41319 B/op 7 allocs/op 423 ns/op 16 B/op 2 allocs/op 33.52
Benchmark_Cache - ns/op 14180 ns/op 423 ns/op 33.52
Benchmark_Cache - B/op 41319 B/op 16 B/op 2582.44
Benchmark_Cache - allocs/op 7 allocs/op 2 allocs/op 3.50
Benchmark_Cache_Storage 14296 ns/op 41319 B/op 7 allocs/op 796.5 ns/op 134 B/op 5 allocs/op 17.95
Benchmark_Cache_Storage - ns/op 14296 ns/op 796.5 ns/op 17.95
Benchmark_Cache_Storage - B/op 41319 B/op 134 B/op 308.35
Benchmark_Cache_AdditionalHeaders 107052 ns/op 324 B/op 4 allocs/op 554.2 ns/op 16 B/op 2 allocs/op 193.16
Benchmark_Cache_AdditionalHeaders - ns/op 107052 ns/op 554.2 ns/op 193.16
Benchmark_Cache_AdditionalHeaders - B/op 324 B/op 16 B/op 20.25
Benchmark_Cache_AdditionalHeaders - allocs/op 4 allocs/op 2 allocs/op 2
BenchmarkAppendMsgitem-4_middleware_csrf - MB/s 3215.63 MB/s 356.77 MB/s 9.01
BenchmarkAppendMsgstorageManager - MB/s 1606.91 MB/s 244.34 MB/s 6.58
BenchmarkAppendMsgdata - MB/s 1604.91 MB/s 267.69 MB/s 6.00
BenchmarkEncodedata - MB/s 242.11 MB/s 152.83 MB/s 1.58

This comment was automatically generated by workflow using github-action-benchmark.

@gaby gaby marked this pull request as ready for review June 26, 2025 03:56
@gaby gaby requested a review from a team as a code owner June 26, 2025 03:56
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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 93ff8fb and cc665ff.

📒 Files selected for processing (1)
  • middleware/cache/cache.go (3 hunks)
🧰 Additional context used
🪛 GitHub Check: unit (1.24.x, ubuntu-latest)
middleware/cache/cache.go

[failure] 246-246:
cannot use v (variable of type int) as uint64 value in assignment

🪛 GitHub Check: govulncheck-check
middleware/cache/cache.go

[failure] 246-246:
cannot use v (variable of type int) as uint64 value in assignment

🪛 GitHub Check: unit (1.24.x, windows-latest)
middleware/cache/cache.go

[failure] 246-246:
cannot use v (variable of type int) as uint64 value in assignment

🪛 GitHub Actions: Run govulncheck
middleware/cache/cache.go

[error] 246-246: Cannot use variable 'v' of type int as uint64 value in assignment.

⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: unit (1.24.x, macos-13)
  • GitHub Check: unit (1.24.x, macos-latest)
  • GitHub Check: lint
  • GitHub Check: repeated
  • GitHub Check: Compare
  • GitHub Check: Analyse
🔇 Additional comments (2)
middleware/cache/cache.go (2)

15-15: Import addition looks correct.

The fasthttp import is appropriately added to support the ParseUint function used in the Age header parsing logic.


171-174: Excellent RFC 9111 compliant Age header implementation.

The Age header calculation correctly implements RFC 9111 by:

  • Computing resident time as e.ttl - (e.exp - ts)
  • Adding the stored upstream age (e.age) to the resident time
  • Providing the total age to clients

This ensures proper cache age tracking across the cache hierarchy.

@ReneWerner87 ReneWerner87 merged commit bdd9e22 into main Jun 30, 2025
13 of 14 checks passed
@github-project-automation github-project-automation bot moved this from In Progress to Done in v3 Jun 30, 2025
@gaby gaby deleted the 2025-06-26-02-37-44 branch June 30, 2025 11:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

2 participants