Skip to content

Improve WebRTC data channel iteration, exceptions#5684

Merged
Pantus Oleh (zibet27) merged 1 commit into
mainfrom
webrtc-io-exceptions
Jun 16, 2026
Merged

Improve WebRTC data channel iteration, exceptions#5684
Pantus Oleh (zibet27) merged 1 commit into
mainfrom
webrtc-io-exceptions

Conversation

@zibet27

Copy link
Copy Markdown
Collaborator

Subsystem
WebRTC Client

Motivation
KTOR-9610 WebRtcPeerConnection::close causes ClosedReceiveChannelException for other peer

Solution

  • When the channel is closed, ReceiveChannel.receive() throws a general closed channel exception with a stacktrace pointing at close(), which is confusing for users; throw WebRtc.ClosedException instead
  • add an iterator over the data channel, so users don't need to catch such exceptions and iterate safely
  • throw common WebRtc.IOException in WebRtc.Datachannel.send() so users can catch it in common code

@coderabbitai

coderabbitai Bot commented Jun 5, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

An error occurred during the review process. Please try again later.

📝 Walkthrough

Walkthrough

This PR introduces a unified exception hierarchy for WebRTC data channels (WebRtc.IOException and WebRtc.DataChannelClosedException), adds an iterator method for message consumption, implements a withIOException helper for exception wrapping, adds requireOpen() validation guards across all platform implementations (Android, iOS, Rust, Web), and includes comprehensive tests for iterator behavior and closed-channel error handling.

Changes

WebRTC Data Channel Error Handling and Iterator Support

Layer / File(s) Summary
Exception types and API contracts
ktor-client/ktor-client-webrtc/common/src/io/ktor/client/webrtc/WebRtc.kt, ktor-client/ktor-client-webrtc/api/jvm/ktor-client-webrtc.api, ktor-client/ktor-client-webrtc/api/ktor-client-webrtc.klib.api
New public exception hierarchy: WebRtc.IOException extending kotlinx.io.IOException and WebRtc.DataChannelClosedException as a subtype. DataChannel KDoc updated to declare @throws for send and receive operations. JVM and KLIB API artifacts reflect the new types, iterator method, and withIOException helper.
Iterator and exception handling in core DataChannel
ktor-client/ktor-client-webrtc/common/src/io/ktor/client/webrtc/WebRtcDataChannel.kt
Added iterator() returning ChannelIterator for message consumption that drains buffered messages after channel closure. Updated receive() to use receiveCatching() and throw DataChannelClosedException with label context when the channel is closed and drained. Introduced @InternalAPI withIOException helper that preserves CancellationException and WebRtc.IOException while wrapping other exceptions.
Platform send validation and error handling
ktor-client/ktor-client-webrtc/android/src/io/ktor/client/webrtc/DataChannel.kt, ktor-client/ktor-client-webrtc/ktor-client-webrtc-rs/common/src/io/ktor/client/webrtc/rs/DataChannel.kt, ktor-client/ktor-client-webrtc/web/src/io/ktor/client/webrtc/DataChannel.kt, ktor-client/ktor-client-webrtc/ios/src/io/ktor/client/webrtc/DataChannel.kt
Added requireOpen() guards across all platforms that check state.canSend() and throw WebRtc.DataChannelClosedException when the channel cannot send. Updated send() implementations to validate native send boolean results and throw WebRtc.IOException with payload-specific messages on failure. Rust and Web implementations wrap native sends with withIOException and mark with @OptIn(InternalAPI::class).
Iterator and close-handling tests
ktor-client/ktor-client-webrtc/common/test/io/ktor/client/webrtc/WebRtcDataChannelIteratorTest.kt, ktor-client/ktor-client-webrtc/common/test/io/ktor/client/webrtc/WebRtcDataChannelTest.kt
New tests validate iterator behavior: draining buffered messages after receiving-side closure, returning empty when closed without buffered messages, and preserving message order and content type. Close-handling tests updated to assert WebRtc.DataChannelClosedException for send and receive operations on closed channels.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • ktorio/ktor#5670: Overlaps at WebRTC DataChannel close/transport shutdown behavior (e.g., closeTransport(), stopReceivingMessages(), and closed-state idempotency).

Suggested reviewers

  • bjhham
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 12.12% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Improve WebRTC data channel iteration, exceptions' directly summarizes the main changes: adding iterator functionality and improving exception handling for WebRTC data channels.
Description check ✅ Passed The PR description includes all required template sections: Subsystem, Motivation (with issue reference KTOR-9610), and Solution with specific technical details about the changes.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch webrtc-io-exceptions

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
ktor-client/ktor-client-webrtc/common/src/io/ktor/client/webrtc/WebRtcDataChannel.kt (1)

247-256: ⚡ Quick win

Make wrapped I/O errors include operation context.

withIOException always throws "Error in WebRtcDataChannel operation", which drops useful context (e.g., text vs binary send, channel label) at call sites. Consider accepting a context message parameter and propagating it into the wrapped exception.

Suggested diff
-@InternalAPI
-public suspend inline fun <R> withIOException(crossinline block: suspend () -> R): R {
+@InternalAPI
+public suspend inline fun <R> withIOException(
+    operation: String,
+    crossinline block: suspend () -> R
+): R {
     return try {
         block()
     } catch (cause: kotlinx.coroutines.CancellationException) {
         throw cause
     } catch (cause: WebRtc.IOException) {
         throw cause
     } catch (cause: Exception) {
-        throw WebRtc.IOException("Error in WebRtcDataChannel operation", cause)
+        throw WebRtc.IOException("Error in $operation", cause)
     }
 }

As per coding guidelines, error messages should be actionable and include problematic context.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@ktor-client/ktor-client-webrtc/common/src/io/ktor/client/webrtc/WebRtcDataChannel.kt`
around lines 247 - 256, withIOException currently replaces all inner error
context with the generic string "Error in WebRtcDataChannel operation"; change
its signature to accept a context message parameter (e.g., context: String =
"WebRtcDataChannel operation") and use that context when wrapping
non-Cancellation/IOException exceptions into WebRtc.IOException so the thrown
WebRtc.IOException includes the operation-specific message; then update all
callers inside WebRtcDataChannel (e.g., send/sendText/sendBinary/any methods
that call withIOException) to pass a descriptive context like "send text
(label=...)" or "send binary (label=...)" so logs and stacktraces preserve
actionable context.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In
`@ktor-client/ktor-client-webrtc/common/src/io/ktor/client/webrtc/WebRtcDataChannel.kt`:
- Around line 247-256: withIOException currently replaces all inner error
context with the generic string "Error in WebRtcDataChannel operation"; change
its signature to accept a context message parameter (e.g., context: String =
"WebRtcDataChannel operation") and use that context when wrapping
non-Cancellation/IOException exceptions into WebRtc.IOException so the thrown
WebRtc.IOException includes the operation-specific message; then update all
callers inside WebRtcDataChannel (e.g., send/sendText/sendBinary/any methods
that call withIOException) to pass a descriptive context like "send text
(label=...)" or "send binary (label=...)" so logs and stacktraces preserve
actionable context.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: b136aef9-d915-4e6b-8b6a-39e60f3a4876

📥 Commits

Reviewing files that changed from the base of the PR and between 9d12537 and d46e999.

📒 Files selected for processing (10)
  • ktor-client/ktor-client-webrtc/android/src/io/ktor/client/webrtc/DataChannel.kt
  • ktor-client/ktor-client-webrtc/api/jvm/ktor-client-webrtc.api
  • ktor-client/ktor-client-webrtc/api/ktor-client-webrtc.klib.api
  • ktor-client/ktor-client-webrtc/common/src/io/ktor/client/webrtc/WebRtc.kt
  • ktor-client/ktor-client-webrtc/common/src/io/ktor/client/webrtc/WebRtcDataChannel.kt
  • ktor-client/ktor-client-webrtc/common/test/io/ktor/client/webrtc/WebRtcDataChannelIteratorTest.kt
  • ktor-client/ktor-client-webrtc/common/test/io/ktor/client/webrtc/WebRtcDataChannelTest.kt
  • ktor-client/ktor-client-webrtc/ios/src/io/ktor/client/webrtc/DataChannel.kt
  • ktor-client/ktor-client-webrtc/ktor-client-webrtc-rs/common/src/io/ktor/client/webrtc/rs/DataChannel.kt
  • ktor-client/ktor-client-webrtc/web/src/io/ktor/client/webrtc/DataChannel.kt

@bjhham Bruce Hamilton (bjhham) left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

lgtm 👍

…l iterator

# Conflicts:
#	ktor-client/ktor-client-webrtc/android/src/io/ktor/client/webrtc/DataChannel.kt
#	ktor-client/ktor-client-webrtc/common/test/io/ktor/client/webrtc/WebRtcDataChannelTest.kt
@zibet27 Pantus Oleh (zibet27) merged commit a16ffd4 into main Jun 16, 2026
16 checks passed
@zibet27 Pantus Oleh (zibet27) deleted the webrtc-io-exceptions branch June 16, 2026 13:46
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