Skip to content

KTOR-6963 Fix for Darwin engine ws frame limit #5013

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

bjhham
Copy link
Contributor

@bjhham bjhham commented Jul 15, 2025

Subsystem
Client, iOS, Websockets

Motivation
KTOR-6963 Darwin: The maxFrameSize option has no effect

Solution
We were assuming that we could set maxFrameSize on the session after the upgrade, but for Darwin, the property needs to be assigned before NSURLSessionWebSocketTask.resume() is called. So to provide access to the config value, I included the plugin details as an attribute for WS requests.

@bjhham bjhham requested a review from e5l July 15, 2025 11:29
Copy link
Contributor

coderabbitai bot commented Jul 15, 2025

Walkthrough

A new attribute key, WEBSOCKETS_KEY, was introduced to store the WebSockets plugin instance in the HTTP request context. The Darwin engine now uses this key to set the WebSocket maximum frame size per request. A corresponding test was added to verify frame size enforcement in WebSocket communications.

Changes

File(s) Change Summary
ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/websocket/WebSockets.kt Added public WEBSOCKETS_KEY attribute key for WebSockets; plugin instance stored in request context attributes.
ktor-client/ktor-client-darwin/darwin/src/io/ktor/client/engine/darwin/internal/DarwinSession.kt DarwinSession now retrieves maxFrameSize from request's WEBSOCKETS_KEY and sets WebSocket message size limit.
ktor-client/ktor-client-darwin/darwin/test/DarwinEngineTest.kt Added test testWebSocketMaxFrameSize to verify WebSocket frame size enforcement and exception handling.
✨ 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

@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 55e419f and 211a55c.

📒 Files selected for processing (3)
  • ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/websocket/WebSockets.kt (2 hunks)
  • ktor-client/ktor-client-darwin/darwin/src/io/ktor/client/engine/darwin/internal/DarwinSession.kt (2 hunks)
  • ktor-client/ktor-client-darwin/darwin/test/DarwinEngineTest.kt (1 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{kt,kts}

Instructions used from:

Sources:
📄 CodeRabbit Inference Engine

  • CLAUDE.md
**/*.{kt,kts,json,yaml,yml}

Instructions used from:

Sources:
📄 CodeRabbit Inference Engine

  • CLAUDE.md
**/test/**/*.kt

Instructions used from:

Sources:
📄 CodeRabbit Inference Engine

  • CLAUDE.md
🧠 Learnings (4)
📓 Common learnings
Learnt from: CR
PR: ktorio/ktor#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-30T08:41:41.935Z
Learning: Prefix commit messages with KTOR-{NUM} (YouTrack issue)
Learnt from: osipxd
PR: ktorio/ktor#4970
File: build-logic/src/main/kotlin/ktorbuild.kmp.gradle.kts:67-72
Timestamp: 2025-07-01T10:54:53.751Z
Learning: In build-logic/src/main/kotlin/ktorbuild.kmp.gradle.kts, the KT-70915 and KT-77609 workarounds that limit parallelism for KotlinNativeLink and CInteropCommonizerTask should remain unconditional (not gated behind CI flag) as these limits are beneficial for both local and CI builds.
Learnt from: osipxd
PR: ktorio/ktor#4856
File: teamcity.default.properties:5-5
Timestamp: 2025-05-14T15:56:33.598Z
Learning: The Ktor project runs binary-compatibility-validator tasks on CI which require substantial metaspace, so adding metaspace size limits (-XX:MaxMetaspaceSize) to Gradle options would cause these tasks to fail.
Learnt from: CR
PR: ktorio/ktor#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-23T12:49:56.883Z
Learning: Prefix commit messages with KTOR-{NUM} (YouTrack issue), and write them in present tense, imperative mood.
Learnt from: bjhham
PR: ktorio/ktor#4916
File: ktor-server/ktor-server-core/api/ktor-server-core.api:151-151
Timestamp: 2025-06-09T07:08:35.085Z
Learning: Breaking changes are acceptable in Ktor codebase when the code hasn't been released yet, as confirmed by bjhham from the development team.
ktor-client/ktor-client-darwin/darwin/src/io/ktor/client/engine/darwin/internal/DarwinSession.kt (7)
Learnt from: osipxd
PR: ktorio/ktor#4856
File: teamcity.default.properties:5-5
Timestamp: 2025-05-14T15:56:33.598Z
Learning: The Ktor project runs binary-compatibility-validator tasks on CI which require substantial metaspace, so adding metaspace size limits (-XX:MaxMetaspaceSize) to Gradle options would cause these tasks to fail.
Learnt from: rururux
PR: ktorio/ktor#4896
File: ktor-client/ktor-client-core/jvm/test/FileStorageTest.kt:1-12
Timestamp: 2025-05-30T06:45:52.309Z
Learning: The headersOf() function from io.ktor.http package is available through wildcard imports like `import io.ktor.http.*`, so no explicit import statement is needed when using wildcard imports from that package.
Learnt from: rururux
PR: ktorio/ktor#4896
File: ktor-client/ktor-client-core/jvm/test/FileStorageTest.kt:1-12
Timestamp: 2025-05-30T06:45:52.309Z
Learning: The headersOf() function from io.ktor.http package is available through wildcard imports like `import io.ktor.http.*`, so no explicit import statement is needed when using wildcard imports from that package.
Learnt from: tre3p
PR: ktorio/ktor#4936
File: ktor-utils/jvm/src/io/ktor/util/ZstdEncoding.kt:28-35
Timestamp: 2025-06-16T17:03:45.729Z
Learning: In the Ktor codebase, encoder implementations consistently use GlobalScope.writer and GlobalScope.reader patterns for compression/decompression operations. This is the established architectural pattern used throughout the codebase for byte channel transformations.
Learnt from: CR
PR: ktorio/ktor#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-30T08:41:41.935Z
Learning: Applies to **/*.{kt,kts} : Error handling follows Kotlin conventions with specific Ktor exceptions
Learnt from: CR
PR: ktorio/ktor#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-23T12:49:56.883Z
Learning: Error handling should follow Kotlin conventions and use specific Ktor exceptions.
Learnt from: CR
PR: ktorio/ktor#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-30T08:41:41.935Z
Learning: Applies to **/*.{kt,kts} : Use star imports for io.ktor.* packages (configured in .editorconfig)
ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/websocket/WebSockets.kt (1)
Learnt from: bjhham
PR: ktorio/ktor#4855
File: ktor-server/ktor-server-plugins/ktor-server-di/api/ktor-server-di.klib.api:334-336
Timestamp: 2025-05-14T18:05:02.321Z
Learning: Breaking changes in constructor parameter order are acceptable for the ktor-server-di module when the code hasn't been released yet, as confirmed by the development team.
ktor-client/ktor-client-darwin/darwin/test/DarwinEngineTest.kt (1)
Learnt from: CR
PR: ktorio/ktor#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-23T12:49:56.883Z
Learning: Error handling should follow Kotlin conventions and use specific Ktor exceptions.
🧬 Code Graph Analysis (1)
ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/websocket/WebSockets.kt (1)
ktor-utils/common/src/io/ktor/util/Attributes.kt (1)
  • AttributeKey (19-21)
🔇 Additional comments (3)
ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/websocket/WebSockets.kt (2)

22-23: LGTM: Well-implemented internal attribute key

The new WEBSOCKETS_KEY follows the established pattern of REQUEST_EXTENSIONS_KEY and is correctly annotated with @InternalAPI since it's intended for internal engine usage. The attribute name clearly indicates its purpose.


190-190: LGTM: Proper placement of plugin instance storage

The plugin instance is correctly stored in the request attributes after extension installation and before proceeding with WebSocket content. This enables Darwin engine to access the plugin configuration during WebSocket setup.

ktor-client/ktor-client-darwin/darwin/src/io/ktor/client/engine/darwin/internal/DarwinSession.kt (1)

36-38: Document magic ratio for Darwin WebSocket frame size

It looks like WEBSOCKETS_KEY is always set by the WebSockets plugin for upgrade requests, so a null-check around request.attributes[WEBSOCKETS_KEY] isn’t needed. However, dividing maxFrameSize by 10 is a “magic number” that needs clarifying.

• File: ktor-client/ktor-client-darwin/darwin/src/io/ktor/client/engine/darwin/internal/DarwinSession.kt
Lines: 36–38

Please add a comment or extract a named constant to explain why we divide by 10 (e.g. Darwin platform/WebSocketTask limitation) and consider exposing it via config or at least centralizing the factor:

@@ internal suspend fun execute(request: HttpRequestData, callContext: CoroutineContext): HttpResponseData {
-            val maxFrameSize = request.attributes[WEBSOCKETS_KEY].maxFrameSize
-            task.setMaximumMessageSize(maxFrameSize / 10)
+            val maxFrameSize = request.attributes[WEBSOCKETS_KEY].maxFrameSize
+            // Darwin NSURLSessionWebSocketTask treats message size differently;
+            // divide by 10 to work around platform buffer limits
+            val darwinScaleFactor = 10
+            task.setMaximumMessageSize(maxFrameSize / darwinScaleFactor)

Comment on lines +263 to +284
@Test
fun testWebSocketMaxFrameSize() = testClient {
config {
install(WebSockets) {
maxFrameSize = 100
}
}

val shortMessage = "abc".repeat(5)
val longMessage = "def".repeat(500)
test { client ->
assertFailsWith<DarwinHttpRequestException> {
client.webSocket("$TEST_WEBSOCKET_SERVER/websockets/echo") {
send(shortMessage)
assertEquals(shortMessage, (incoming.receive() as Frame.Text).readText())
send(longMessage)
val frame = incoming.receive() as Frame.Text
assertEquals(longMessage, frame.readText())
}
}
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify test logic for frame size calculation

The test configures maxFrameSize = 100, but the Darwin engine divides this by 10, resulting in a 10-byte limit. However, the short message "abc".repeat(5) is 15 characters/bytes, which should exceed the limit but is expected to succeed.

Please verify the frame size calculation logic:

The test might need adjustment based on the actual frame size enforcement logic. Consider whether the units are bytes vs characters, or if the division by 10 is correctly applied.


🏁 Script executed:

#!/bin/bash
# Check if there are other tests or documentation about frame size units
rg -A 10 -B 5 "maxFrameSize.*=.*[0-9]" --type kt

Length of output: 77


🏁 Script executed:

#!/bin/bash
# Locate all usages of `maxFrameSize` in Kotlin sources to inspect how it's applied
rg -n 'maxFrameSize' -g '*.kt' -C 5

Length of output: 75532


🏁 Script executed:

#!/bin/bash
# Search for the `convert()` extension in the Darwin engine sources
rg -n 'convert(' -g 'ktor-client-darwin/darwin/src/**'

Length of output: 123


🏁 Script executed:

#!/bin/bash
# Search for the `convert` extension implementation in Darwin engine sources
rg -F -n 'convert(' -g 'ktor-client-darwin/darwin/src/**/*.kt'

Length of output: 213


Adjust DarwinEngineTest to account for 10× reduction in Darwin engine’s frame limit

The Darwin engine does:

task.setMaximumMessageSize(maxFrameSize / 10)

so configuring maxFrameSize = 100 actually enforces a 10-byte limit. Your test’s shortMessage is 15 bytes and will fail under that rule. You need to either:

  • Raise the configured maxFrameSize so that (configuredValue/10) ≥ 15 (for example, use maxFrameSize = 150 → 150/10=15), or
  • Shrink shortMessage to at most 10 bytes to match the current behavior.

Locations to update:

  • ktor-client/ktor-client-darwin/darwin/test/DarwinEngineTest.kt at line 267 (maxFrameSize = …)
🤖 Prompt for AI Agents
In ktor-client/ktor-client-darwin/darwin/test/DarwinEngineTest.kt around lines
263 to 284, the test sets maxFrameSize to 100, but the Darwin engine enforces a
limit of maxFrameSize divided by 10, effectively 10 bytes. Since the
shortMessage is 15 bytes, the test will fail. Fix this by either increasing
maxFrameSize to at least 150 so that the effective limit is 15 bytes or reducing
shortMessage to 10 bytes or less to comply with the current limit.

@@ -32,6 +33,9 @@ internal class DarwinSession(
val (task, response) = if (request.isUpgradeRequest()) {
val task = session.webSocketTaskWithRequest(nativeRequest)
val response = delegate.read(task, callContext)
val maxFrameSize = request.attributes[WEBSOCKETS_KEY].maxFrameSize
task.setMaximumMessageSize(maxFrameSize / 10)
Copy link
Member

Choose a reason for hiding this comment

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

could you write a comment behind the magic number?

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