Skip to content

docs: Add documentation for SSE serialization, reconnection, and heartbeat #612

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

Conversation

vnikolova
Copy link
Collaborator

@vnikolova vnikolova commented Apr 20, 2025

KTOR-7776 Documentation for Add serialization for SSE
KTOR-8181 Documentation for Add reconnection in ClientSSESession
KTOR-7954 Documentation for Add heartbeat to SSE

Preview on staging:
Client SSE
Server SSE

@vnikolova vnikolova self-assigned this Apr 20, 2025
Copy link

coderabbitai bot commented Apr 20, 2025

Walkthrough

This update introduces Kotlin serialization support to both the client and server SSE (Server-Sent Events) code examples by adding the Kotlin serialization plugin and Ktor JSON serialization dependencies to their respective build scripts. New serializable data classes (Customer and Product) are added to both client and server codebases. The server now exposes additional SSE endpoints that emit JSON-serialized events and heartbeat messages, while the client demonstrates deserializing incoming SSE events into typed Kotlin objects. Corresponding documentation is expanded to describe these new serialization and heartbeat features, and new tests are added to verify the server's JSON and heartbeat SSE endpoints.

Changes

Files/Paths Change Summary
codeSnippets/snippets/client-sse/build.gradle.kts, codeSnippets/snippets/server-sse/build.gradle.kts Added Kotlin serialization plugin (version 2.1.20) and Ktor JSON serialization dependency to enable JSON serialization support in both client and server projects.
codeSnippets/snippets/client-sse/src/main/kotlin/com.example/Application.kt Introduced serializable data classes (Customer, Product). Added logic to deserialize SSE events into these data classes using Kotlin serialization, based on event type. The original SSE client usage remains.
codeSnippets/snippets/server-sse/src/main/kotlin/com/example/Application.kt Added serializable data classes (Customer, Product). Introduced /json SSE endpoint emitting JSON-serialized events and /heartbeat endpoint sending periodic heartbeat and "Hello" events, both using Kotlin serialization.
codeSnippets/snippets/server-sse/src/test/kotlin/com/example/ApplicationTest.kt Added two test functions: one for verifying JSON SSE events from the /json endpoint, and another for validating heartbeat and "Hello" events from the /heartbeat endpoint, using coroutine-based event collection and assertions.
topics/client-server-sent-events.topic Reorganized and expanded documentation: added chapters on automatic reconnection, event filtering, and deserialization of SSE events into Kotlin objects. Updated interface and function references, improved formatting, and included new code examples and links to the full example repository.
topics/server-server-sent-events.topic Updated documentation: formatted class references, added example snippet references, and introduced new chapters on SSE heartbeat and serialization, with explanatory text, code examples, and links to the full example repository. Moved the final reference to the example repository to the end of the serialization chapter.

Suggested reviewers

  • Stexxe

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.
✨ 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 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

🧹 Nitpick comments (2)
codeSnippets/snippets/server-sse/src/test/kotlin/com/example/ApplicationTest.kt (1)

53-80: Consider adding assertions for heartbeat event counts

The heartbeat test captures both regular events and heartbeat events and cancels after receiving at least 3 of each. Consider adding assertions at the end of the test to verify that you received the expected number of events before cancellation.

             withTimeout(5_000) {
                 client.sse("/heartbeat") {
                     incoming.collect { event ->
                         when (event.data) {
                             "Hello" -> hellos++
                             "heartbeat" -> heartbeats++
                         }
                         if (hellos > 3 && heartbeats > 3) {
                             cancel()
                         }
                     }
                 }
             }
+            // Verify we received the expected number of events
+            assert(hellos > 3) { "Expected more than 3 Hello events, got $hellos" }
+            assert(heartbeats > 3) { "Expected more than 3 heartbeat events, got $heartbeats" }
         }
codeSnippets/snippets/client-sse/src/main/kotlin/com.example/Application.kt (1)

43-51: Consider using the deserialized objects

The current implementation deserializes the events but doesn't use the resulting objects. For documentation purposes, consider adding code that demonstrates how to use the deserialized objects.

            incoming.collect { event: TypedServerSentEvent<String> ->
                when (event.event) {
                    "customer" -> {
                        val customer: Customer? = deserialize<Customer>(event.data)
+                       customer?.let { 
+                           println("Received customer: ${it.firstName} ${it.lastName}")
+                       }
                    }
                    "product" -> {
                        val product: Product? = deserialize<Product>(event.data)
+                       product?.let {
+                           println("Received product with ID: ${it.id}, prices: ${it.prices}")
+                       }
                    }
                }
            }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e3604cc and 2f1b36c.

📒 Files selected for processing (7)
  • codeSnippets/snippets/client-sse/build.gradle.kts (2 hunks)
  • codeSnippets/snippets/client-sse/src/main/kotlin/com.example/Application.kt (2 hunks)
  • codeSnippets/snippets/server-sse/build.gradle.kts (2 hunks)
  • codeSnippets/snippets/server-sse/src/main/kotlin/com/example/Application.kt (2 hunks)
  • codeSnippets/snippets/server-sse/src/test/kotlin/com/example/ApplicationTest.kt (2 hunks)
  • topics/client-server-sent-events.topic (2 hunks)
  • topics/server-server-sent-events.topic (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
codeSnippets/snippets/server-sse/src/test/kotlin/com/example/ApplicationTest.kt (1)
codeSnippets/snippets/server-sse/src/main/kotlin/com/example/Application.kt (1)
  • module (21-54)
🔇 Additional comments (17)
codeSnippets/snippets/server-sse/build.gradle.kts (2)

8-8: Appropriate Kotlin serialization plugin addition.

Adding the Kotlin serialization plugin is necessary for enabling JSON serialization in the SSE examples. This aligns with the PR objective to add documentation for SSE serialization.


25-25: Correct Ktor JSON serialization dependency.

The addition of ktor-serialization-kotlinx-json dependency ensures that the server can properly serialize objects to JSON. This matches the existing Ktor version used in the project.

codeSnippets/snippets/client-sse/build.gradle.kts (2)

9-9: Appropriate Kotlin serialization plugin addition.

Adding the serialization plugin enables the client-side deserialization capabilities required for the SSE example. This matches the server-side configuration approach.


29-29: Correct Ktor JSON serialization dependency.

The addition of ktor-serialization-kotlinx-json dependency is necessary for the client to deserialize JSON data from SSE events. This supports the PR objective of documenting SSE serialization.

codeSnippets/snippets/server-sse/src/main/kotlin/com/example/Application.kt (4)

8-11: Appropriate serialization imports.

The added imports are necessary for supporting JSON serialization in the SSE examples. These imports enable the use of @Serializable annotation and JSON encoding.


13-17: Well-structured serializable data classes.

The Customer and Product data classes are properly marked with @Serializable annotation, making them suitable for JSON serialization. They provide good example models for demonstrating SSE serialization.


32-39: Good implementation of SSE with serialization.

The /json endpoint demonstrates how to use custom serialization with SSE. The implementation correctly:

  1. Obtains the appropriate serializer dynamically using reflection
  2. Encodes objects to JSON strings
  3. Sends different types of serialized objects as events

This implementation addresses the PR objective of documenting SSE serialization (KTOR-7776).


41-52: Well-implemented heartbeat functionality.

The /heartbeat endpoint effectively demonstrates:

  1. Setting up periodic heartbeat events with a 10ms interval
  2. Configuring a custom heartbeat event message
  3. Sending additional events alongside heartbeats

This implementation addresses the PR objective of adding heartbeat functionality to SSE (KTOR-7954).

topics/server-server-sent-events.topic (4)

94-96: Improved code formatting in documentation.

The ServerSSESession class name is now properly wrapped in a <code> tag within its hyperlink, improving the consistency and readability of the documentation.


127-129: Useful link to complete example.

Adding a link to the full example repository helps users understand the implementation in context and provides a reference for implementing SSE in their own applications.


131-150: Comprehensive documentation for SSE heartbeat.

The new section on SSE heartbeat:

  1. Clearly explains the purpose of heartbeats in maintaining SSE connections
  2. Provides a well-documented code example showing how to configure heartbeats
  3. Links to the relevant API documentation

This documentation addresses the PR objective related to heartbeat functionality (KTOR-7954).


151-165: Clear and informative serialization documentation.

The serialization section:

  1. Explains how to enable serialization in SSE routes
  2. Shows a practical example of implementing serialization
  3. References the appropriate API class
  4. Clarifies how serialized data is handled in SSE events

This documentation addresses the PR objective related to SSE serialization (KTOR-7776).

codeSnippets/snippets/server-sse/src/test/kotlin/com/example/ApplicationTest.kt (1)

31-51: Implementation of JSON serialization tests looks good

The test correctly verifies that the server emits properly serialized JSON events by validating the structure of two different event types (Customer and Product). This test appropriately complements the server-side serialization implementation.

codeSnippets/snippets/client-sse/src/main/kotlin/com.example/Application.kt (1)

12-16: Data class implementation is well structured

The Customer and Product data classes are correctly annotated with @serializable and have appropriate fields for serialization/deserialization purposes.

topics/client-server-sent-events.topic (3)

52-72: Clear documentation on reconnection functionality

The reconnection section effectively explains the configuration options available for automatic reconnection, including the maximum number of attempts and reconnection delay time. The note about OkHttp not supporting this feature is also valuable information for users.


73-80: Well-documented event filtering examples

The event filtering section clearly explains how to include comment-only and retry-only events in the incoming flow, with appropriate code references.


167-188: Comprehensive documentation on deserialization

The deserialization section effectively explains how to deserialize SSE events into type-safe Kotlin objects, including the necessary configuration and usage of the ClientSSESessionWithDeserialization class. The included code example from the snippets provides a clear illustration of real-world usage.

Comment on lines +35 to +54
// example with deserialization
client.sse({
url("http://localhost:8080/serverSentEvents")
}, deserialize = {
typeInfo, jsonString ->
val serializer = Json.serializersModule.serializer(typeInfo.kotlinType!!)
Json.decodeFromString(serializer, jsonString)!!
}) { // `this` is `ClientSSESessionWithDeserialization`
incoming.collect { event: TypedServerSentEvent<String> ->
when (event.event) {
"customer" -> {
val customer: Customer? = deserialize<Customer>(event.data)
}
"product" -> {
val product: Product? = deserialize<Product>(event.data)
}
}
}
}
client.close()
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Remove nullable operator (!!) in deserialization function

The use of !! in the deserialization function could cause a NullPointerException if deserialization fails. It's best to handle this case more gracefully.

        client.sse({
            url("http://localhost:8080/serverSentEvents")
        }, deserialize = {
                typeInfo, jsonString ->
            val serializer = Json.serializersModule.serializer(typeInfo.kotlinType!!)
-            Json.decodeFromString(serializer, jsonString)!!
+            Json.decodeFromString(serializer, jsonString)
        }) { // `this` is `ClientSSESessionWithDeserialization`

Also consider adding error handling for the deserialization process:

        client.sse({
            url("http://localhost:8080/serverSentEvents")
        }, deserialize = {
                typeInfo, jsonString ->
            val serializer = Json.serializersModule.serializer(typeInfo.kotlinType!!)
-            Json.decodeFromString(serializer, jsonString)!!
+            try {
+                Json.decodeFromString(serializer, jsonString)
+            } catch (e: Exception) {
+                println("Failed to deserialize: $jsonString")
+                null
+            }
        }) { // `this` is `ClientSSESessionWithDeserialization`

@vnikolova vnikolova requested a review from marychatte April 20, 2025 07:07
Copy link
Member

@marychatte marychatte left a comment

Choose a reason for hiding this comment

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

Good and clear documentation :)
I just left a few small notes

include-lines="8-13"/>
<chapter title="SSE reconnect" id="sse-reconnect">
<tldr>
<p>️️Not supported on: <code>OkHttp</code></p>
Copy link
Member

Choose a reason for hiding this comment

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

nit: should this be "in OkHttp" instead of "on OkHttp"? since we're referring to something inside the client implementation

<p>
If the connection to the server is lost, the client will wait for the specified
<code>reconnectionTime</code> before attempting to reconnect. It will make up to
the specified number of <code>maxReconnectionAttempts</code> attempts to reestablish the connection.
Copy link
Member

Choose a reason for hiding this comment

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

nit: maybe we can say just "It will make up to maxReconnectionAttempts ..." without "the specified number of"

</p>
<p>
To enable deserialization, provide a custom deserialization function using the <code>deserialize</code>
parameter on an SSE access function and use the
Copy link
Member

Choose a reason for hiding this comment

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

nit: should we mention parameter deserialize in the block "Optionally, the following parameters are available to configure the connection:" above?

</chapter>
<chapter title="Serialization" id="serialization">
<p>
To enable serialization, provide a custom serialization function using the <code>serialize</code>
Copy link
Member

Choose a reason for hiding this comment

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

nit: should we mention parameter serialize in the "Handle SSE sessions" block, where we are writing about ways to configure route?

<code-block lang="kotlin" src="snippets/server-sse/src/main/kotlin/com/example/Application.kt"
include-lines="12-17,20-24,32-39,53-54"/>
<p>
The <code>serialize</code> function is responsible for converting data objects into JSON, which is then
Copy link
Member

Choose a reason for hiding this comment

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

nit: maybe mention here that it is example: "The serialize function in the example is responsible for converting data objects into JSON"

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