@@ -2,26 +2,51 @@ package com.sakethh.linkora
22
33import com.sakethh.linkora.WebSocketManager.closeWriteChannel
44import com.sakethh.linkora.WebSocketManager.initializeWriteChannel
5+ import com.sakethh.linkora.domain.dto.Correlation
56import io.ktor.server.application.*
67import io.ktor.server.auth.*
78import io.ktor.server.routing.*
89import io.ktor.server.websocket.*
9- import java.util.*
10+ import io.ktor.websocket.*
11+ import kotlinx.serialization.json.Json
1012
1113fun Application.eventsWebSocket () {
1214 routing {
1315 authenticate(Security .BEARER .name) {
14- webSocket(" /events" ) {
15- val sessionId = UUID .randomUUID().toString()
16- initializeWriteChannel(sessionId)
16+ webSocket(path = " /events" ) {
17+ val correlationParam = call.parameters[" correlation" ]
18+ if (correlationParam == null ) {
19+ this .close(
20+ CloseReason (
21+ message = " Expected `correlation` as an encoded JSON string via parameter, but it was not provided." ,
22+ code = CloseReason .Codes .CANNOT_ACCEPT
23+ )
24+ )
25+ return @webSocket
26+ }
27+ val correlation = try {
28+ Json .decodeFromString<Correlation >(correlationParam)
29+ } catch (e: Exception ) {
30+ e.printStackTrace()
31+ this .close(
32+ CloseReason (
33+ message = " The schema of the provided JSON does not match the expected format." ,
34+ code = CloseReason .Codes .CANNOT_ACCEPT
35+ )
36+ )
37+ return @webSocket
38+ }
39+ val correlationId = correlation.id
40+ initializeWriteChannel(correlationId)
41+ println (" Established the `events` socket connection with \" ${correlation.clientName} \" ." )
1742 try {
1843 for (frame in incoming) {
1944 }
2045 } catch (e: Exception ) {
21- println (" WebSocket error: ${e.message} " )
46+ println (" WebSocket error for \" ${correlation.clientName} \" : ${e.message} " )
2247 } finally {
23- closeWriteChannel(sessionId )
24- println (" WebSocket closed." )
48+ closeWriteChannel(correlationId )
49+ println (" WebSocket closed for \" ${correlation.clientName} \" ." )
2550 }
2651 }
2752 }
0 commit comments