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

Merged
merged 4 commits into from
Apr 24, 2025

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

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

🧹 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

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

♻️ Duplicate comments (1)
topics/server-server-sent-events.topic (1)

151-169: Good documentation of serialization functionality.

The serialization section clearly explains how to enable and use serialization with SSE, which addresses another PR objective.

However, as noted in a previous review comment, it would be helpful to mention the serialize parameter in the main "Handle SSE sessions" section (around line 65), where you describe the ways to set up an SSE route. This would make readers aware of this capability earlier.

🧹 Nitpick comments (1)
topics/server-server-sent-events.topic (1)

130-150: Great addition of heartbeat documentation.

This new section clearly explains the purpose and implementation of the heartbeat functionality, which was one of the PR objectives.

One suggestion: The example uses a 10-millisecond interval, which is extremely short. Consider adding a note that real-world applications would typically use longer intervals (seconds or minutes) to avoid unnecessary network traffic.

📜 Review details

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

📥 Commits

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

📒 Files selected for processing (2)
  • topics/client-server-sent-events.topic (3 hunks)
  • topics/server-server-sent-events.topic (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • topics/client-server-sent-events.topic
🔇 Additional comments (3)
topics/server-server-sent-events.topic (3)

94-96: Good improvement to formatting.

Adding the <code> tag around ServerSSESession improves readability and properly indicates this is a code entity.


126-129: Clear reference to the full example.

Adding a link to the complete example is valuable for readers who want to see the implementation in context.


163-164: Clear explanation of the serialization function.

This line effectively addresses the previous review comment by clarifying that the example converts objects specifically to JSON.

@vnikolova vnikolova merged commit 744fc59 into main Apr 24, 2025
1 check passed
@vnikolova vnikolova deleted the vnikolova/sse-improvements branch April 24, 2025 10:43
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