🧹 chore: Improve Cache middleware compliance#3973
Conversation
|
Note Other AI code review bot(s) detectedCodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review. WalkthroughOverhaul of cache middleware: comprehensive Cache-Control parsing, per-entry vary manifests, expanded expiration/revalidation model, header storage refactor with msgp serialization updates, extensive new tests (including mutating storage), and updated IP benchmark contexts using TrustProxy loopback settings. Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant Cache as Cache Middleware
participant Manifest as Vary Manifest Store
participant Storage as External Storage
participant Upstream as Upstream
Client->>Cache: Request (headers: Cache-Control, Vary, Authorization)
activate Cache
rect rgb(245,250,255)
Note over Cache: Parse request directives and determine variant key
Cache->>Cache: parseRequestCacheControl() / parseVary()
end
Cache->>Manifest: loadVaryManifest(manifestKey)
activate Manifest
Manifest-->>Cache: manifest (or nil)
deactivate Manifest
alt variant found (cache hit)
Cache->>Storage: Get metadata (+body if stored)
activate Storage
Storage-->>Cache: entry + body
deactivate Storage
Cache->>Cache: computeAge() / check freshness & directives
alt needs revalidation
Cache->>Upstream: Conditional request (If-None-Match / If-Modified-Since)
activate Upstream
Upstream-->>Cache: 304 or updated response
deactivate Upstream
Cache->>Storage: update stored entry
Cache-->>Client: updated or cached response
else serve cached
Cache-->>Client: cached response (+Age, maybe Warning)
end
else miss
Cache->>Upstream: Forward request
activate Upstream
Upstream-->>Cache: response (Cache-Control, Expires, ETag, Date)
deactivate Upstream
rect rgb(255,250,240)
Note over Cache: computeExpiration() from sources (Config, max-age, s-maxage, Expires, generator)
Cache->>Manifest: storeVaryManifest(manifestKey)
Cache->>Storage: store metadata (+body per storage policy)
end
Cache-->>Client: fresh response
end
deactivate Cache
Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes Possibly related PRs
Suggested reviewers
Poem
Pre-merge checks and finishing touches❌ Failed checks (2 warnings)
✅ Passed checks (1 passed)
✨ Finishing touches
📜 Recent review detailsConfiguration used: Repository UI Review profile: CHILL Plan: Pro 📒 Files selected for processing (2)
🧰 Additional context used📓 Path-based instructions (2)**/*.go📄 CodeRabbit inference engine (AGENTS.md)
Files:
**/*_test.go📄 CodeRabbit inference engine (AGENTS.md)
Files:
🧠 Learnings (14)📚 Learning: 2025-09-28T17:39:26.644ZApplied to files:
📚 Learning: 2024-10-08T19:06:06.583ZApplied to files:
📚 Learning: 2024-10-08T19:06:06.583ZApplied to files:
📚 Learning: 2025-10-16T07:15:26.529ZApplied to files:
📚 Learning: 2024-12-13T08:14:22.851ZApplied to files:
📚 Learning: 2024-07-26T21:00:12.902ZApplied to files:
📚 Learning: 2025-10-16T07:19:52.418ZApplied to files:
📚 Learning: 2024-10-08T19:06:06.583ZApplied to files:
📚 Learning: 2025-12-07T15:07:23.885ZApplied to files:
📚 Learning: 2024-09-25T17:05:06.991ZApplied to files:
📚 Learning: 2024-11-29T12:37:27.581ZApplied to files:
📚 Learning: 2024-10-08T19:06:06.583ZApplied to files:
📚 Learning: 2024-06-30T00:38:06.580ZApplied to files:
📚 Learning: 2024-10-08T19:06:06.583ZApplied to files:
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
🔇 Additional comments (14)
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 |
Summary of ChangesHello @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 introduces significant optimizations and RFC compliance improvements to the caching middleware. It refines how Highlights
🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console. Using Gemini Code AssistThe 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 by creating a comment using either
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 Limitations & Feedback Gemini Code Assist 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. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here. 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
|
There was a problem hiding this comment.
Code Review
This pull request significantly improves the cache middleware's compliance with HTTP caching standards. The changes are extensive, introducing more sophisticated logic for cache key generation, expiration calculation, and handling of various Cache-Control directives. The addition of comprehensive tests is a great step towards ensuring the correctness of this complex logic. I've found one critical issue related to resource management with sync.Pool that could lead to race conditions, and a minor issue regarding an unused function parameter that affects code clarity. Overall, this is a high-quality contribution that makes the caching middleware much more robust and spec-compliant.
|
/gemini review |
There was a problem hiding this comment.
⚠️ 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: 6ef236e | Previous: 789c56f | Ratio |
|---|---|---|---|
Benchmark_Cache_MaxSize/Disabled - B/op |
183 B/op |
39 B/op |
4.69 |
Benchmark_Cache_MaxSize/Disabled - allocs/op |
6 allocs/op |
3 allocs/op |
2 |
Benchmark_Cache_MaxSize/Unlim - B/op |
183 B/op |
39 B/op |
4.69 |
Benchmark_Cache_MaxSize/Unlim - allocs/op |
6 allocs/op |
3 allocs/op |
2 |
Benchmark_Cache_MaxSize/LowBounded - B/op |
183 B/op |
39 B/op |
4.69 |
Benchmark_Cache_MaxSize/LowBounded - allocs/op |
6 allocs/op |
3 allocs/op |
2 |
BenchmarkMarshalMsgitem-4_middleware_cache - B/op |
240 B/op |
144 B/op |
1.67 |
BenchmarkAppendMsgitem-4_middleware_cache |
61.73 ns/op 2559.62 MB/s 0 B/op 0 allocs/op |
40.3 ns/op 1985.30 MB/s 0 B/op 0 allocs/op |
1.53 |
BenchmarkAppendMsgitem-4_middleware_cache - ns/op |
61.73 ns/op |
40.3 ns/op |
1.53 |
BenchmarkUnmarshalitem-4_middleware_cache |
174.1 ns/op 907.30 MB/s 0 B/op 0 allocs/op |
100.4 ns/op 796.69 MB/s 0 B/op 0 allocs/op |
1.73 |
BenchmarkUnmarshalitem-4_middleware_cache - ns/op |
174.1 ns/op |
100.4 ns/op |
1.73 |
BenchmarkEncodeitem-4_middleware_cache |
182.2 ns/op 867.04 MB/s 0 B/op 0 allocs/op |
109.6 ns/op 729.94 MB/s 0 B/op 0 allocs/op |
1.66 |
BenchmarkEncodeitem-4_middleware_cache - ns/op |
182.2 ns/op |
109.6 ns/op |
1.66 |
BenchmarkDecodeitem-4_middleware_cache |
362.1 ns/op 436.31 MB/s 0 B/op 0 allocs/op |
202.8 ns/op 394.47 MB/s 0 B/op 0 allocs/op |
1.79 |
BenchmarkDecodeitem-4_middleware_cache - ns/op |
362.1 ns/op |
202.8 ns/op |
1.79 |
This comment was automatically generated by workflow using github-action-benchmark.
There was a problem hiding this comment.
Code Review
This pull request significantly improves the cache middleware's compliance with HTTP caching standards (RFC 9111). The changes are extensive and well-thought-out, introducing support for Vary, s-maxage, private, must-revalidate, max-stale, min-fresh, and more accurate Age header calculation. The handling of authenticated requests is also much more robust by separating cache entries based on the Authorization header. The test suite has been massively expanded to cover these new complex scenarios, which is excellent. Overall, this is a fantastic contribution. I have a few suggestions to improve code maintainability and remove some minor redundancies.
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #3973 +/- ##
==========================================
- Coverage 91.60% 90.96% -0.65%
==========================================
Files 119 119
Lines 10262 10782 +520
==========================================
+ Hits 9401 9808 +407
- Misses 544 617 +73
- Partials 317 357 +40
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Pull request overview
This pull request significantly improves the cache middleware's compliance with HTTP caching standards (RFC 9111). The changes introduce sophisticated logic for handling Cache-Control directives, request-based cache control, Vary header support, and proper age calculation.
Key changes:
- Enhanced HTTP cache compliance with proper handling of Cache-Control directives (max-age, s-maxage, must-revalidate, proxy-revalidate, no-cache, private, etc.)
- Added support for Vary header to separate cache variants based on request headers
- Implemented proper Age header calculation and Date header clamping to prevent invalid dates
- Authorization header handling with SHA-256 hashing for secure cache key separation
- Request-level cache control directives (max-stale, min-fresh, only-if-cached, Pragma: no-cache)
- Warning headers (110, 113) for stale and heuristic freshness responses
- Made StatusPermanentRedirect (308) cacheable with proper Cache-Control directives
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated 4 comments.
| File | Description |
|---|---|
| middleware/cache/manager.go | Added new fields to item struct (cacheControl, expires, etag, date, forceRevalidate, revalidate, private) and updated release() to reset them |
| middleware/cache/manager_msgp.go | Generated MessagePack serialization code for new item struct fields (17 fields total) |
| middleware/cache/cache.go | Core logic changes: request directive parsing, Vary support, authorization hashing, age calculation, expiration from multiple sources (max-age/s-maxage/Expires), warning headers, and proper shared cache semantics |
| middleware/cache/cache_test.go | Comprehensive test coverage for new features including 1300+ new test lines covering edge cases for all new directives and behaviors |
Remove heap entries before revalidating to prevent duplicate heap records and byte counting issues. This fixes: - maxAge forced revalidation - minFresh forced revalidation - forceRevalidate directive handling - expired entry revalidation Addresses feedback from code review on lines 284-288. Co-authored-by: gaby <835733+gaby@users.noreply.github.com>
Avoid mutating shared cache entry in memory mode by computing clamped date locally instead of modifying e.date. When using in-memory storage, the same *item pointer is shared across concurrent requests, so mutating e.date causes data races. Addresses feedback: #3973 (comment) Co-authored-by: gaby <835733+gaby@users.noreply.github.com>
Only remove old heap entry when replacement is actually stored. Previously, heap entry was removed immediately when revalidation was triggered, which caused accounting issues if the new response wasn't cacheable. Now we: - Track the old heap index when marking for revalidation - Keep the old entry in heap accounting until replacement - Remove old heap entry only when storing the new entry This ensures MaxBytes accounting remains accurate even when revalidation fails or response is not cacheable. Co-authored-by: gaby <835733+gaby@users.noreply.github.com>
Remove old heap entry AFTER successful storage instead of before. This ensures that if storage fails, the old entry remains tracked in the heap. Previously: - Old heap entry was removed before storage - If storage failed, cleanup would remove the new entry - Result: no heap entry at all, but old cached data still in storage Now: - Add new heap entry before storage (as before) - If storage fails, cleanup removes new entry, old stays tracked - If storage succeeds, remove old heap entry after - Result: accurate accounting in all scenarios Co-authored-by: gaby <835733+gaby@users.noreply.github.com>
Added 4 test cases covering: - max-age=0 revalidation removes old entry on success - min-fresh revalidation with MaxBytes - Revalidation respects MaxBytes eviction - Non-cacheable response preserves old entry These tests verify heap accounting remains accurate during revalidation scenarios when MaxBytes is enabled. Co-authored-by: gaby <835733+gaby@users.noreply.github.com>
Applied code formatting with gofumpt to ensure consistency with project standards. Co-authored-by: gaby <835733+gaby@users.noreply.github.com>
Check error return values from io.ReadAll in test cases to satisfy errcheck linter. Co-authored-by: gaby <835733+gaby@users.noreply.github.com>
🐛 fix: Heap accounting and data race in cache middleware
|
/gemini review |
There was a problem hiding this comment.
Code Review
This is an impressive and extensive pull request that significantly enhances the cache middleware's compliance with HTTP caching standards. The introduction of more sophisticated logic for cache key generation, expiration calculation, and handling of various Cache-Control directives is a great step forward. The code shows a deep understanding of HTTP caching intricacies. I've found a critical issue related to a race condition and potential state inconsistency in the cache eviction logic that needs to be addressed. I've also noted a minor compliance issue in the Cache-Control parser. Overall, fantastic work on this complex feature.
| if cfg.MaxBytes > 0 { | ||
| for storedBytes+bodySize > cfg.MaxBytes { | ||
| for { | ||
| mux.Lock() | ||
| if storedBytes+bodySize <= cfg.MaxBytes { | ||
| mux.Unlock() | ||
| break | ||
| } | ||
| keyToRemove, size := heap.removeFirst() | ||
| storedBytes -= size | ||
| mux.Unlock() | ||
|
|
||
| if err := deleteKey(reqCtx, keyToRemove); err != nil { | ||
| return fmt.Errorf("cache: failed to delete key %q while evicting: %w", maskKey(keyToRemove), err) | ||
| } | ||
| storedBytes -= size | ||
| } | ||
| } |
There was a problem hiding this comment.
This eviction loop has a race condition and a potential for creating an inconsistent state.
-
Race Condition: The process of checking for available space (lines 588-591) and adding a new item to the cache (lines 736-742) is not atomic. Another concurrent request could add an item to the cache in between these two operations, which could lead to the
MaxByteslimit being exceeded. -
Inconsistent State:
storedBytesis decremented under lock (line 593) beforedeleteKeyis called outside the lock (line 596). IfdeleteKeyfails, the function returns an error, butstoredBytesis not restored to its previous value. This leaves the cache size tracking in an inconsistent state. The entry is removed from the heap but not from the storage, creating a zombie entry.
A safer approach would be to ensure atomicity for checking space, evicting, and inserting. This is complex, especially when avoiding I/O under lock. One possible strategy could be to collect keys to be deleted under a lock, release the lock to perform deletions, and then re-acquire the lock to insert the new item, potentially re-validating the space check.
There was a problem hiding this comment.
@copilot Implement a fix for the two issue raised here. These are critical.
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
middleware/cache/cache.go (1)
267-278: Consider documenting the lock/unlock pattern.The explicit
unlock()andrelock()helpers with state tracking are functionally correct, but the pattern adds complexity. Consider adding a comment explaining why this approach is used (non-blocking storage I/O) and ensuring all code paths properly manage lock state.
📜 Review details
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
middleware/cache/cache.gomiddleware/cache/cache_test.go
🧰 Additional context used
📓 Path-based instructions (2)
**/*.go
📄 CodeRabbit inference engine (AGENTS.md)
Prefer
github.com/gofiber/utils/v2helpers (for example,utils.Trim) when performing common operations such as string manipulation, whenever it is practical and appropriate for the surrounding code
Files:
middleware/cache/cache.gomiddleware/cache/cache_test.go
**/*_test.go
📄 CodeRabbit inference engine (AGENTS.md)
When adding Go tests, always invoke
t.Parallel()at the start of each test and subtest to maximize concurrency
Files:
middleware/cache/cache_test.go
🧠 Learnings (13)
📚 Learning: 2025-09-28T17:39:26.644Z
Learnt from: arturmelanchyk
Repo: gofiber/fiber PR: 3768
File: client/request.go:162-166
Timestamp: 2025-09-28T17:39:26.644Z
Learning: In fasthttp-based code like gofiber, using utils.UnsafeString(key) instead of string(key) is acceptable when values are used immediately within the same call stack and not stored for later use, as it avoids allocations and aligns with fasthttp's zero-allocation design philosophy.
Applied to files:
middleware/cache/cache.go
📚 Learning: 2024-10-08T19:06:06.583Z
Learnt from: sixcolors
Repo: gofiber/fiber PR: 3016
File: middleware/session/session.go:272-293
Timestamp: 2024-10-08T19:06:06.583Z
Learning: In the `middleware/session/session.go` file, the `saveSession()` method returns either `nil` or an error, so additional error wrapping in the `Save()` method is unnecessary.
Applied to files:
middleware/cache/cache.go
📚 Learning: 2025-10-16T07:15:26.529Z
Learnt from: grivera64
Repo: gofiber/fiber PR: 3807
File: adapter_test.go:118-144
Timestamp: 2025-10-16T07:15:26.529Z
Learning: In Fiber v3, net/http handlers (http.Handler, http.HandlerFunc, or raw func(http.ResponseWriter, *http.Request)) can be passed directly to routing methods like app.Get(), app.Post(), etc. The framework automatically detects and wraps them internally via toFiberHandler/collectHandlers. The github.com/gofiber/fiber/v3/middleware/adaptor package is legacy and should not be suggested for tests or code using native net/http handler support.
Applied to files:
middleware/cache/cache.go
📚 Learning: 2024-10-08T19:06:06.583Z
Learnt from: sixcolors
Repo: gofiber/fiber PR: 3016
File: middleware/csrf/csrf_test.go:188-193
Timestamp: 2024-10-08T19:06:06.583Z
Learning: In the Fiber framework tests, using `ctx.Response.Header.Cookie` may not be suitable for parsing cookies from the response header, as it requires a `*Cookie` and fills it rather than returning a string value; thus, manual parsing of the `Set-Cookie` header may be necessary.
Applied to files:
middleware/cache/cache.gomiddleware/cache/cache_test.go
📚 Learning: 2024-12-13T08:14:22.851Z
Learnt from: efectn
Repo: gofiber/fiber PR: 3162
File: hooks_test.go:228-228
Timestamp: 2024-12-13T08:14:22.851Z
Learning: In Go test files, prefer using the `require` methods from the `testify` package for assertions instead of manual comparisons and calls to `t.Fatal` or `t.Fatalf`.
Applied to files:
middleware/cache/cache_test.go
📚 Learning: 2024-07-26T21:00:12.902Z
Learnt from: sixcolors
Repo: gofiber/fiber PR: 2922
File: middleware/cors/utils.go:63-71
Timestamp: 2024-07-26T21:00:12.902Z
Learning: The project uses the testify/assert package for assertions in unit tests.
Applied to files:
middleware/cache/cache_test.go
📚 Learning: 2025-10-16T07:19:52.418Z
Learnt from: grivera64
Repo: gofiber/fiber PR: 3807
File: adapter_test.go:118-144
Timestamp: 2025-10-16T07:19:52.418Z
Learning: In the Fiber codebase, the linter does not allow `require` assertions from within HTTP handlers (including net/http-style handlers). Use `t.Fatalf`, `t.Errorf`, or similar `testing.T` methods for error handling inside handler functions instead.
Applied to files:
middleware/cache/cache_test.go
📚 Learning: 2024-10-08T19:06:06.583Z
Learnt from: sixcolors
Repo: gofiber/fiber PR: 3016
File: middleware/session/store.go:164-167
Timestamp: 2024-10-08T19:06:06.583Z
Learning: Unit tests in this project use testify require.
Applied to files:
middleware/cache/cache_test.go
📚 Learning: 2025-12-07T15:07:23.885Z
Learnt from: CR
Repo: gofiber/fiber PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-07T15:07:23.885Z
Learning: Applies to **/*_test.go : When adding Go tests, always invoke `t.Parallel()` at the start of each test and subtest to maximize concurrency
Applied to files:
middleware/cache/cache_test.go
📚 Learning: 2024-09-25T17:05:06.991Z
Learnt from: sixcolors
Repo: gofiber/fiber PR: 3016
File: middleware/session/middleware_test.go:190-191
Timestamp: 2024-09-25T17:05:06.991Z
Learning: When testing session `IdleTimeout` expiration, it's acceptable to use `time.Sleep` to simulate the passage of time in tests.
Applied to files:
middleware/cache/cache_test.go
📚 Learning: 2024-11-29T12:37:27.581Z
Learnt from: efectn
Repo: gofiber/fiber PR: 3162
File: app_test.go:893-895
Timestamp: 2024-11-29T12:37:27.581Z
Learning: In the `Test_App_ShutdownWithContext` function in `app_test.go`, the `clientDone` channel is used to synchronize the client's request completion before proceeding, eliminating the need for additional `time.Sleep` calls.
Applied to files:
middleware/cache/cache_test.go
📚 Learning: 2024-10-08T19:06:06.583Z
Learnt from: sixcolors
Repo: gofiber/fiber PR: 3016
File: middleware/session/config.go:122-122
Timestamp: 2024-10-08T19:06:06.583Z
Learning: In `DefaultErrorHandler(c *fiber.Ctx, err error)`, since `c` is a pointer to an interface, we need to dereference `*c` when calling interface methods like `SendStatus`.
Applied to files:
middleware/cache/cache_test.go
📚 Learning: 2024-06-30T00:38:06.580Z
Learnt from: sixcolors
Repo: gofiber/fiber PR: 3051
File: middleware/session/session.go:215-216
Timestamp: 2024-06-30T00:38:06.580Z
Learning: Parallel tests for `Session.Save` already exist in the `middleware/session/session_test.go` file, specifically in the `Test_Session_Save` and `Test_Session_Save_Expiration` functions.
Applied to files:
middleware/cache/cache_test.go
🧬 Code graph analysis (1)
middleware/cache/cache_test.go (2)
constants.go (3)
HeaderAge(167-167)HeaderCacheControl(168-168)HeaderExpires(170-170)internal/memory/memory.go (1)
Storage(27-30)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (7)
- GitHub Check: Agent
- GitHub Check: CodeQL analysis (go)
- GitHub Check: Compare
- GitHub Check: unit (1.25.x, macos-latest)
- GitHub Check: unit (1.25.x, windows-latest)
- GitHub Check: lint
- GitHub Check: repeated
🔇 Additional comments (11)
middleware/cache/cache_test.go (2)
1073-1084: LGTM: Improved test stability with deadline-based polling.The refactored expiration waiting logic is more robust than a fixed
time.Sleep. Using a deadline with polling prevents test flakiness from timestamp tick delays while still catching failures if expiration doesn't occur.
1583-1584: Correct behavior change for upstream Age handling.The expectation change from
cacheHittocacheUnreachablereflects proper RFC 9111 compliance. When upstream Age exhausts the remaining freshness lifetime (Age=5s with Expiration=3s), the response should not be cached.middleware/cache/cache.go (9)
140-147: LGTM: Efficient buffer pooling for hash operations.The hex buffer pool and hash function factories effectively reduce allocations for Authorization and Vary key hashing. The defensive capacity checks ensure correctness even if the pool is misused.
443-445: Past issue resolved: Date clamping no longer mutates shared entry.The code correctly computes the clamped date in a local variable instead of mutating
e.date, preventing data races when using in-memory storage.
791-795: Past issue resolved: Revalidation now removes stale heap entry.The code correctly tracks
oldHeapIdxduring revalidation and removes the prior heap entry after successfully storing the refreshed response, preventing duplicate bookkeeping for the same cache key.
1130-1134: LGTM: Appropriate error handling for hash operations.The
//nolint:errcheckdirectives with explanatory comments are correct. TheWritemethod onhash.Hashimplementations from the standard library never returns errors.
1172-1186: LGTM: Vary manifest loading is safe.The
loadVaryManifestfunction safely returns the parsed names slice. SinceparseVaryallocates a new slice withmake()rather than using a pool, there's no use-after-free risk.
172-193: LGTM: Robust heap entry removal with defensive checks.The
removeHeapEntryfunction includes thorough bounds checking and validates entry consistency before removal, preventing potential panics from invalid heap indices.
198-206: LGTM: Comprehensive request directive parsing with HTTP/1.0 compatibility.The code correctly parses Cache-Control directives and falls back to Pragma: no-cache for HTTP/1.0 clients, following RFC 9111 § 5.4.
506-544: LGTM: Proper handling of response cache-control directives.The code correctly processes response directives and appropriately deletes cached entries and vary manifests when no-store, no-cache, private, or Vary: * are present.
697-720: LGTM: RFC-compliant age and freshness calculations.The apparent age calculation correctly implements RFC 9111 § 4.2.3 by considering both upstream Age and response Date. The remaining freshness calculation properly accounts for time already spent in upstream caches.
…directives Co-authored-by: gaby <835733+gaby@users.noreply.github.com>
Implement RFC 9111 compliant quoted-string parsing for Cache-Control directives
Summary