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 6 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 inform when such a mismatch occurs. 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.

Changes

File(s) Change Summary
ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/cache/HttpCache.kt Added logging when cached response's varyKeys size differs from the requested varyKeys size during cache lookup; control flow otherwise unchanged.
ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/cache/storage/UnlimitedCacheStorage.kt Relaxed cache lookup: now only requires all requested varyKeys to match, allowing cached entries with extra varyKeys; removed strict size equality check.
ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/plugins/CacheTest.kt Modified testDifferentVaryHeaders to remove exception expectation for different Vary headers; now asserts equality of responses instead.
✨ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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.

Comment on lines +849 to 858
val first = client.get("$TEST_SERVER/cache/different-vary") {
header("200", "true")
header("Set-Vary", "X-Requested-With,Accept-Encoding")
}
assertFailsWith<InvalidCacheStateException> {
client.get("$TEST_SERVER/cache/different-vary") {
header("Set-Vary", "X-Requested-With")
}
}
}.body<String>()
val second = client.get(url) {
header("Set-Vary", "X-Requested-With")
}.body<String>()

assertEquals(first, second)
}
Copy link

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Test updated to verify lenient Vary header behavior

The test has been correctly updated to verify the new lenient behavior. Instead of expecting an exception when Vary headers differ, it now confirms that the response is successfully returned from cache even with different Vary headers.

This change properly validates the changes made to the cache lookup mechanism.


🏁 Script executed:

#!/bin/bash
# Check if the 'url' variable referenced in line 853 is defined somewhere
# or if it should be a direct reference to the URL used in the first request
rg --type kotlin "val url " -A 2 ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/plugins/CacheTest.kt

Length of output: 2169


🏁 Script executed:

#!/bin/bash
# Locate the definition of `different-vary` to confirm that `val url` points to the same endpoint
rg --type kotlin "different-vary" -n -C 3 ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/plugins/CacheTest.kt

Length of output: 401


Define url before using it in the different-vary test
The second client.get(url) call references an undefined url variable, which will lead to a compilation error. Introduce a val url = "$TEST_SERVER/cache/different-vary" (or inline the same literal) before your requests so both calls use the same endpoint.

• File: CacheTest.kt, inside the different-vary test block (around lines 849–858)
• Suggested change:

 test { client ->
+   val url = "$TEST_SERVER/cache/different-vary"
    val first = client.get(url) {
        header("200", "true")
        header("Set-Vary", "X-Requested-With,Accept-Encoding")
    }.body<String>()
    val second = client.get(url) {
        header("Set-Vary", "X-Requested-With")
    }.body<String>()

    assertEquals(first, second)
}

Committable suggestion skipped: line range outside the PR's diff.

@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.

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.

2 participants