Skip to content

KTOR-8352: Fix TRACE method handling in AndroidClientEngine #4899

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 1 commit into
base: main
Choose a base branch
from

Conversation

osipxd
Copy link
Member

@osipxd osipxd commented May 30, 2025

Subsystem
Client, Android

Motivation
KTOR-8352 Android: "ProtocolException: TRACE does not support writing" when sending TRACE request

Solution
Added test checking that all clients are able to send requests with any default HTTP header.
Fixed the Android client by using recently added !method.supportsRequestBody instead of checking METHODS_WITHOUT_BODY list.

@osipxd osipxd self-assigned this May 30, 2025
Copy link

coderabbitai bot commented May 30, 2025

"""

Walkthrough

This change updates HTTP method handling in the Ktor client and server. It replaces a hardcoded list of methods without request bodies with a property-based check, adds "TRACE" to the set of methods that do not allow bodies, introduces a new echo test endpoint, and adds corresponding client tests to verify support for all HTTP methods.

Changes

File(s) Change Summary
.../engine/android/AndroidClientEngine.kt Replaces list-based check for methods without request bodies with supportsRequestBody property.
.../HttpMethod.kt Adds "TRACE" to the set of HTTP methods that do not support request bodies.
.../tests/HttpMethodTest.kt Adds HttpMethodTest class and helper to test client support for all HTTP methods, including "TRACE".
.../tests/Echo.kt Introduces echoTest() function to add an echo endpoint returning the HTTP method in a response header.
.../ClientTestServer.kt Registers the new echoTest() endpoint in the test server's application setup.

Possibly related PRs

  • ktorio/ktor#4895: Refactors AndroidClientEngine to use supportsRequestBody for HTTP methods, closely related to the method handling changes in this PR.

Suggested reviewers

  • bjhham
    """

📜 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 0522790 and 17d86fd.

📒 Files selected for processing (5)
  • ktor-client/ktor-client-android/jvm/src/io/ktor/client/engine/android/AndroidClientEngine.kt (1 hunks)
  • ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/HttpMethodTest.kt (1 hunks)
  • ktor-http/common/src/io/ktor/http/HttpMethod.kt (1 hunks)
  • ktor-test-server/src/main/kotlin/test/server/ClientTestServer.kt (1 hunks)
  • ktor-test-server/src/main/kotlin/test/server/tests/Echo.kt (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
  • ktor-http/common/src/io/ktor/http/HttpMethod.kt
  • ktor-test-server/src/main/kotlin/test/server/ClientTestServer.kt
  • ktor-client/ktor-client-android/jvm/src/io/ktor/client/engine/android/AndroidClientEngine.kt
  • ktor-test-server/src/main/kotlin/test/server/tests/Echo.kt
  • ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/HttpMethodTest.kt
✨ 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: 0

🧹 Nitpick comments (2)
ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/HttpMethodTest.kt (2)

20-28: Consider adding error handling for network failures.

The test doesn't handle potential network exceptions that could occur during HTTP requests. Consider wrapping the request in try-catch or using test framework utilities that handle failures gracefully.

Consider adding error handling:

 test { client ->
     for (method in httpMethods) {
         if (!client.supportsMethod(method)) continue
-
-        val response = client.request("$TEST_SERVER/echo/method") { this.method = method }
-        assertEquals(HttpStatusCode.OK, response.status)
-        assertEquals(method.value, response.headers["Http-Method"])
+
+        try {
+            val response = client.request("$TEST_SERVER/echo/method") { this.method = method }
+            assertEquals(HttpStatusCode.OK, response.status)
+            assertEquals(method.value, response.headers["Http-Method"])
+        } catch (e: Exception) {
+            throw AssertionError("Failed to send $method request: ${e.message}", e)
+        }
     }
 }

32-38: Good design with proper documentation.

The helper function properly handles engine-specific limitations with clear documentation. The JDK bug reference provides good context for the Android engine PATCH method exclusion.

However, consider these improvements:

  1. String-based engine identification could be fragile if class names change
  2. Verify the JDK bug is still relevant for current Android versions

Consider using type checking instead of string comparison:

-private fun HttpClient.supportsMethod(method: HttpMethod): Boolean {
-    return when(engine::class.simpleName) {
-        // https://bugs.openjdk.org/browse/JDK-7016595
-        "AndroidClientEngine" -> method != HttpMethod.Patch
-        else -> true
-    }
-}
+private fun HttpClient.supportsMethod(method: HttpMethod): Boolean {
+    return when {
+        // https://bugs.openjdk.org/browse/JDK-7016595
+        engine::class.qualifiedName?.contains("AndroidClientEngine") == true -> method != HttpMethod.Patch
+        else -> true
+    }
+}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between dcca250 and f5343df.

📒 Files selected for processing (5)
  • ktor-client/ktor-client-android/jvm/src/io/ktor/client/engine/android/AndroidClientEngine.kt (1 hunks)
  • ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/HttpMethodTest.kt (1 hunks)
  • ktor-http/common/src/io/ktor/http/HttpMethod.kt (1 hunks)
  • ktor-test-server/src/main/kotlin/test/server/ClientTestServer.kt (1 hunks)
  • ktor-test-server/src/main/kotlin/test/server/tests/Echo.kt (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
ktor-test-server/src/main/kotlin/test/server/ClientTestServer.kt (1)
ktor-test-server/src/main/kotlin/test/server/tests/Echo.kt (1)
  • echoTest (12-25)
🔇 Additional comments (7)
ktor-test-server/src/main/kotlin/test/server/ClientTestServer.kt (1)

34-34: LGTM: Clean integration of echo test endpoint.

The addition of echoTest() properly integrates the new echo endpoint for HTTP method testing. The positioning between existing test servers is appropriate and follows the established pattern.

ktor-http/common/src/io/ktor/http/HttpMethod.kt (1)

62-62: LGTM: Correct addition of TRACE method to methods without body.

Adding HttpMethod("TRACE") to REQUESTS_WITHOUT_BODY is correct according to HTTP specification (RFC 7231). The TRACE method is used for diagnostic purposes and should not have a request body, which aligns with the PR objective to fix TRACE method handling.

ktor-test-server/src/main/kotlin/test/server/tests/Echo.kt (1)

12-25: LGTM: Well-designed echo endpoint for HTTP method testing.

The implementation is clean and appropriate for its purpose:

  • Uses response header instead of body to accommodate methods that don't support bodies
  • Clear route structure at /echo/method
  • Proper extraction of HTTP method using call.request.local.method.value
  • Returns 200 OK status which is appropriate for all HTTP methods

This endpoint will effectively support testing of all HTTP methods, including the newly supported TRACE method.

ktor-client/ktor-client-android/jvm/src/io/ktor/client/engine/android/AndroidClientEngine.kt (1)

65-65: LGTM: Core fix for TRACE method handling in Android client engine.

This change from checking a hardcoded list to using !data.method.supportsRequestBody is the main fix for KTOR-8352. Benefits include:

  • Consistency: Now uses the same property-based approach as the rest of the codebase
  • Maintainability: No need to maintain separate lists in different places
  • Correctness: Automatically handles TRACE and any future methods added to REQUESTS_WITHOUT_BODY

The existing error handling logic is preserved, making this a safe and focused fix.

ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/HttpMethodTest.kt (3)

1-13: LGTM!

The package declaration and imports are well-organized and include all necessary dependencies for HTTP client testing.


24-26:

✅ Verification successful

Verify test server endpoint and header name consistency.

The test relies on the /echo/method endpoint returning the HTTP method in an "Http-Method" header. Ensure this endpoint exists and the header name matches the server implementation.


🏁 Script executed:

#!/bin/bash
# Description: Verify the echo endpoint implementation and header name consistency
# Expected: Find the echo endpoint implementation with correct header name

# Search for echo endpoint implementation
rg -A 10 -B 5 "echo.*method" --type kotlin

# Search for Http-Method header usage
rg "Http-Method" --type kotlin

Length of output: 3126


Echo endpoint and header name are consistent

The /echo/method route in ktor-test-server/src/main/kotlin/test/server/tests/Echo.kt indeed calls

call.response.header("Http-Method", method)

which matches the test’s expectation (response.headers["Http-Method"]). No changes required.


18-18:

✅ Verification successful

Verify TRACE method handling consistency.

The TRACE method is manually added to the default methods list. While this aligns with the PR objective to fix TRACE handling, consider whether TRACE should be included in HttpMethod.DefaultMethods for consistency.


🏁 Script executed:

#!/bin/bash
# Description: Check if TRACE method is properly defined in HttpMethod and whether it should be part of DefaultMethods
# Expected: Find TRACE method definition and verify its inclusion in DefaultMethods

# Search for TRACE method definition
rg -A 3 -B 3 "TRACE.*=" --type kotlin

# Search for DefaultMethods definition
rg -A 10 "DefaultMethods.*=" --type kotlin

Length of output: 2619


No change needed: TRACE is intentionally excluded from DefaultMethods

The HttpMethod.DefaultMethods list in ktor-http/common/src/io/ktor/http/HttpMethod.kt is defined as:

public val DefaultMethods: List<HttpMethod> = listOf(Get, Post, Put, Patch, Delete, Head, Options)

TRACE is handled separately (e.g. in REQUESTS_WITHOUT_BODY), so manually appending HttpMethod("TRACE") in the test ensures it’s covered without altering the core defaults.

If the goal is to make TRACE a true “default” method everywhere, update the DefaultMethods definition above. Otherwise, the test’s approach is correct.

@osipxd osipxd force-pushed the osipxd/android-trace-method branch 2 times, most recently from 303880f to 0522790 Compare June 2, 2025 11:12
@osipxd osipxd force-pushed the osipxd/android-trace-method branch from 0522790 to 17d86fd Compare June 2, 2025 11:18
@osipxd osipxd requested a review from bjhham June 2, 2025 11:19
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.

1 participant