Skip to content

Ktor 8345: Make VaryHeader check lenient #4816

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

Open
wants to merge 8 commits into
base: main
Choose a base branch
from

Conversation

StefMa
Copy link

@StefMa StefMa commented Apr 29, 2025

Subsystem
Client, Caching

Motivation & Solution
This PR fixes https://youtrack.jetbrains.com/issue/KTOR-8345/HttpCache-InvalidCacheStateException-thrown-when-Vary-header-has-different-entries-is-overly-severe

Let me explain:
All starts with this.
Someone requested to update cache in case the Vary header differs.
Actually this violates the Vary header spec.
See https://developer.mozilla.org/de/docs/Web/HTTP/Reference/Headers/Vary

The same Vary header value should be used on all responses for a given URL, including 304 Not Modified responses and the "default" response.

To make Ktor more compliant with the specs, this PR was opened.

The change leads to throwing of an InvalidCacheStateException in case the Vary header differs from the original response (200) to the second response (304).
E.g.
GET 200 -> Vary: Accept-Encoding, Language
GET 304 -> Vary: Accept-Encoding --> InvalidCacheStateException

The problem with that approach?
We (as client developers) can't fix this on ourselves.
We just end up with yelling at our backend team (or even worse, third-party servers) to fix their Vary header.
That is all we can do, sadly.

This PR makes this check more lenient (again).
How it was before❗
But instead of running blindly into issues like KTOR-7104, we now log the problem with a clear description that we return "the best matching cache" (which doesn't mean it is the correct one!).
(I'm not sure if this Logging is also propergated to users of the lib, or if its just internal. Let me know if this is wrong and if I have to adjust it.)


Honestly, I'm not sure if this is the best-fitting solution.
But I also think that we can't serve both problems - relying on the spec & make client developers happy.
Since the later is IMHO more important, I thought we can relax the ktor client here a bit.

What do you think?

Copy link

coderabbitai bot commented Apr 29, 2025

Walkthrough

This change updates the HTTP cache handling logic in the Ktor client library. The cache lookup mechanism is modified to relax the requirement that the number of varyKeys in a cached response must exactly match the number of requested varyKeys. Now, as long as all requested varyKeys match those in the cache, extra keys in the cached entry are allowed. Additional logging is introduced to warn when a 304 response's varyKeys size differs from the cached entry. Correspondingly, a test case is adjusted to reflect the new behavior, no longer expecting an exception for differing Vary headers and instead checking for response equality. Minor changes were also made to server test responses and whitespace in headers.

Changes

File(s) Change Summary
ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/cache/HttpCache.kt Added warning log when cached response's varyKeys size differs from 304 response's varyKeys; simplified findAndRefresh to use cached varyKeys directly.
ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/cache/storage/UnlimitedCacheStorage.kt Relaxed cache lookup: removed strict size equality check on varyKeys; now cached entries with extra varyKeys beyond those queried are matched.
ktor-client/ktor-client-core/jvm/src/io/ktor/client/plugins/cache/storage/FileCacheStorage.kt Removed size equality check on varyKeys in cache lookup; matching requires only that all queried keys exist with matching values in cached entry.
ktor-client/ktor-client-core/jvm/src/io/ktor/client/plugins/cache/storage/CachingCacheStorage.kt Same relaxation of varyKeys matching logic as FileCacheStorage: size equality check removed in find method.
ktor-client/ktor-client-core/jvm/test/CachingCacheStorageTest.kt Adjusted find method in InMemoryCacheStorage to remove varyKeys size equality check, relaxing matching criteria.
ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/plugins/CacheTest.kt Modified testDifferentVaryHeaders to remove exception expectation; now asserts responses are equal and only one cache entry exists despite differing Vary headers.
ktor-test-server/src/main/kotlin/test/server/tests/Cache.kt Updated /different-vary route: added space after comma in "Vary" header; changed "200" header response from empty OK to text "Ok".

📜 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 9b49d6b and 5eda066.

📒 Files selected for processing (5)
  • ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/cache/HttpCache.kt (2 hunks)
  • ktor-client/ktor-client-core/jvm/src/io/ktor/client/plugins/cache/storage/FileCacheStorage.kt (2 hunks)
  • ktor-client/ktor-client-core/jvm/test/CachingCacheStorageTest.kt (1 hunks)
  • ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/plugins/CacheTest.kt (1 hunks)
  • ktor-test-server/src/main/kotlin/test/server/tests/Cache.kt (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/plugins/CacheTest.kt
  • ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/cache/HttpCache.kt
🔇 Additional comments (4)
ktor-test-server/src/main/kotlin/test/server/tests/Cache.kt (1)

123-124: LGTM! Test server updates support the lenient cache behavior.

The changes improve the test server's realism by:

  1. Adding proper spacing in the Vary header format
  2. Providing actual response content instead of empty body

These modifications align well with testing the updated lenient cache matching behavior.

ktor-client/ktor-client-core/jvm/test/CachingCacheStorageTest.kt (1)

102-102: Excellent logic improvement for lenient cache matching.

The removal of the size equality check it.varyKeys.size == varyKeys.size allows cached entries with additional vary keys to match, which aligns perfectly with the PR objective of being more lenient with server-side Vary header inconsistencies.

The updated logic ensures all requested vary keys match while tolerating extra keys in the cache, maintaining correctness while improving usability.

ktor-client/ktor-client-core/jvm/src/io/ktor/client/plugins/cache/storage/FileCacheStorage.kt (2)

50-50: Consistent implementation of lenient cache matching in CachingCacheStorage.

The logic change removes the size equality requirement while maintaining key-value matching, consistent with other storage implementations in this PR.


86-86: Consistent implementation of lenient cache matching in FileCacheStorage.

The same lenient matching logic is properly applied here, ensuring consistent behavior across all cache storage implementations (in-memory, file-based, and caching wrapper).

✨ 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

@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 5621540 and 9b49d6b.

📒 Files selected for processing (3)
  • ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/cache/HttpCache.kt (1 hunks)
  • ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/cache/storage/UnlimitedCacheStorage.kt (2 hunks)
  • ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/plugins/CacheTest.kt (1 hunks)
🔇 Additional comments (3)
ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/cache/storage/UnlimitedCacheStorage.kt (2)

26-26: Makes HTTP cache lookup mechanism more lenient

This change relaxes the Vary header validation by removing the requirement that the number of varyKeys must exactly match. Now a cached entry will be considered a match as long as all the requested keys match, even if the cached entry contains additional keys.

This aligns with the PR objectives to improve developer experience when dealing with servers that don't strictly follow the HTTP specification for Vary headers.


48-48: Consistent implementation of the lenient cache matching logic

This change correctly applies the same lenient matching logic to the second implementation of the cache lookup mechanism, ensuring consistent behavior.

ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/cache/HttpCache.kt (1)

346-352:

✅ Verification successful

Add helpful logging for Vary header size mismatch

This change adds informative logging when a Vary header size mismatch is detected, enhancing the developer experience by clearly explaining:

  1. That the mismatch is a violation of the specification
  2. That the library will return the best matching cache despite the mismatch
  3. That the issue should be reported to the server team

This implements the "improved logging" part of the PR objectives while maintaining backward compatibility.


🏁 Script executed:

#!/bin/bash
# Check if the default logging level would show this message
rg --type kotlin "val LOGGER" ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/cache/HttpCache.kt -A 1

# Check if there are similar messages elsewhere that use a different log level
rg "LOGGER\.info.*Vary header" --type kotlin

Length of output: 510


Confirm INFO-level logging for Vary header mismatch

The new LOGGER.info call in HttpCache.kt will be visible by default, since KtorSimpleLogger defaults to INFO. This change clearly:

  • Notes the Vary‐header spec violation
  • Explains that the best matching cache is still returned
  • Advises reporting the server’s incorrect behavior

LGTM.

@JohannesTrussellRasch
Copy link

I haven't looked into the code at all, so I don't know if this is possible. But, one solution might be to log and catch the exception, then retry the request without any conditional headers like If-Match, If-None-Match, or If-Modified-Since. It would align with the HTTP standard and keep client developers happy. This would force the server to respond with status: 200 since it can no longer verify that it's the same content.

@StefMa
Copy link
Author

StefMa commented May 11, 2025

@JohannesTrussellRasch yep, that might be a solution. But also a bit overkill I think 🤔.
Another solution would also be to disable either caching at all, or at least for the affected endpoint...

But still I think ktor should be more lenient here.

@marychatte
Copy link
Member

@StefMa Thanks for the PR. You are right that client users shouldn't get an exception in this case. It's better to log it than to throw it, so let's add logging because as you mentioned, it isn't a correct behaviour, according to RFC 7232:

The server generating a 304 response MUST generate any of the
following header fields that would have been sent in a 200 (OK)
response to the same request: Cache-Control, Content-Location, Date,
ETag, Expires, and Vary.

But RFC 9111 also says the next:

When a cache receives a request that can be satisfied by a stored response and that stored response contains a Vary header field, the cache MUST NOT use that stored response without revalidation unless all the presented request header fields nominated by that Vary field value match those fields in the original request (i.e., the request that caused the cached response to be stored).

But I think we can simplify it and retrieve the cache if cache.varyKeys() includes response.varyKeys()

I added a commit with removing check varyKeys.size == it.varyKeys.size in other CacheStorages too. And also fix that we had two saved cache responses after these two requests.

@osipxd can you please take a look at the changes?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants