Skip to content

Commit

Permalink
KTOR-6614 Fix SSE client breaking non-SSE requests (#3973)
Browse files Browse the repository at this point in the history
  • Loading branch information
bjhham committed Feb 8, 2024
1 parent 2ee301f commit cb14545
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ public val SSE: ClientPlugin<SSEConfig> = createClientPlugin(
val showRetryEvents = pluginConfig.showRetryEvents

transformRequestBody { request, _, _ ->
if (getAttributeValue(request, sseRequestAttr) != true) {
return@transformRequestBody null
}
LOGGER.trace("Sending SSE request ${request.url}")
request.setCapability(SSECapability, Unit)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import io.ktor.util.*
import kotlinx.coroutines.*
import kotlin.time.*

internal val sseRequestAttr = AttributeKey<Boolean>("SSERequestFlag")
internal val reconnectionTimeAttr = AttributeKey<Duration>("SSEReconnectionTime")
internal val showCommentEventsAttr = AttributeKey<Boolean>("SSEShowCommentEvents")
internal val showRetryEventsAttr = AttributeKey<Boolean>("SSEShowRetryEvents")
Expand Down Expand Up @@ -40,6 +41,7 @@ public suspend fun HttpClient.serverSentEventsSession(
val sessionDeferred = CompletableDeferred<ClientSSESession>()
val statement = prepareRequest {
block()
addAttribute(sseRequestAttr, true)
addAttribute(reconnectionTimeAttr, reconnectionTime)
addAttribute(showCommentEventsAttr, showCommentEvents)
addAttribute(showRetryEventsAttr, showRetryEvents)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import io.ktor.client.plugins.*
import io.ktor.client.plugins.auth.*
import io.ktor.client.plugins.auth.providers.*
import io.ktor.client.plugins.sse.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.client.tests.utils.*
import io.ktor.http.*
import io.ktor.sse.*
Expand All @@ -35,6 +37,20 @@ class ServerSentEventsTest : ClientLoader(timeoutSeconds = 120) {
}
}

@Test
fun normalRequestsWorkWithSSEInstalled() = clientTests {
config {
install(SSE)
}

test { client ->
val response = client.post("$TEST_SERVER/content/echo") {
setBody("Hello")
}
assertEquals("Hello", response.bodyAsText())
}
}

@Test
fun testSseSession() = clientTests {
config {
Expand Down

0 comments on commit cb14545

Please sign in to comment.