-
Notifications
You must be signed in to change notification settings - Fork 1k
/
DefaultWebSocketSession.kt
318 lines (270 loc) · 10.7 KB
/
DefaultWebSocketSession.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
/*
* Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.websocket
import io.ktor.util.*
import io.ktor.util.cio.*
import io.ktor.utils.io.core.*
import kotlinx.atomicfu.*
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import io.ktor.utils.io.errors.*
import kotlin.coroutines.*
/**
* Default websocket session with ping-pong and timeout processing and built-in [closeReason] population
*/
public interface DefaultWebSocketSession : WebSocketSession {
/**
* Ping interval or `-1L` to disable pinger. Please note that pongs will be handled despite this setting.
*/
public var pingIntervalMillis: Long
/**
* A timeout to wait for pong reply to ping otherwise the session will be terminated immediately.
* It doesn't have any effect if [pingIntervalMillis] is `-1` (pinger is disabled).
*/
public var timeoutMillis: Long
/**
* A close reason for this session. It could be `null` if a session is terminated with no close reason
* (for example due to connection failure).
*/
public val closeReason: Deferred<CloseReason?>
/**
* Start WebSocket conversation.
*
* @param negotiatedExtensions specify negotiated extensions list to use in current session.
*/
@InternalAPI
public fun start(negotiatedExtensions: List<WebSocketExtension<*>> = emptyList())
}
/**
* Create [DefaultWebSocketSession] from session.
*/
public fun DefaultWebSocketSession(
session: WebSocketSession,
pingInterval: Long = -1L,
timeoutMillis: Long = 15000L
): DefaultWebSocketSession {
require(session !is DefaultWebSocketSession) { "Cannot wrap other DefaultWebSocketSession" }
return DefaultWebSocketSessionImpl(session, pingInterval, timeoutMillis)
}
private val IncomingProcessorCoroutineName = CoroutineName("ws-incoming-processor")
private val OutgoingProcessorCoroutineName = CoroutineName("ws-outgoing-processor")
private val NORMAL_CLOSE = CloseReason(CloseReason.Codes.NORMAL, "OK")
/**
* Default web socket session implementation that handles ping-pongs, close sequence and frame fragmentation
*/
internal class DefaultWebSocketSessionImpl(
private val raw: WebSocketSession,
pingInterval: Long,
timeoutMillis: Long,
) : DefaultWebSocketSession, WebSocketSession {
private val pinger = atomic<SendChannel<Frame.Pong>?>(null)
private val closeReasonRef = CompletableDeferred<CloseReason>()
private val filtered = Channel<Frame>(8)
private val outgoingToBeProcessed = Channel<Frame>(8)
private val closed: AtomicBoolean = atomic(false)
private val context = Job(raw.coroutineContext[Job])
private val _extensions: MutableList<WebSocketExtension<*>> = mutableListOf()
private val started = atomic(false)
override val incoming: ReceiveChannel<Frame> get() = filtered
override val outgoing: SendChannel<Frame> get() = outgoingToBeProcessed
override val extensions: List<WebSocketExtension<*>>
get() = _extensions
override val coroutineContext: CoroutineContext = raw.coroutineContext + context + CoroutineName("ws-default")
override var masking: Boolean
get() = raw.masking
set(value) {
raw.masking = value
}
override var maxFrameSize: Long
get() = raw.maxFrameSize
set(value) {
raw.maxFrameSize = value
}
override var pingIntervalMillis: Long = pingInterval
set(newValue) {
field = newValue
runOrCancelPinger()
}
override var timeoutMillis: Long = timeoutMillis
set(newValue) {
field = newValue
runOrCancelPinger()
}
override val closeReason: Deferred<CloseReason?> = closeReasonRef
@OptIn(InternalAPI::class)
override fun start(negotiatedExtensions: List<WebSocketExtension<*>>) {
if (!started.compareAndSet(false, true)) {
error("WebSocket session is already started.")
}
_extensions.addAll(negotiatedExtensions)
runOrCancelPinger()
runIncomingProcessor(ponger(outgoing))
runOutgoingProcessor()
}
/**
* Close session with GOING_AWAY reason
*/
public suspend fun goingAway(message: String = "Server is going down") {
sendCloseSequence(CloseReason(CloseReason.Codes.GOING_AWAY, message))
}
override suspend fun flush() {
raw.flush()
}
@Deprecated(
"Use cancel() instead.",
ReplaceWith("cancel()", "kotlinx.coroutines.cancel"),
level = DeprecationLevel.ERROR
)
override fun terminate() {
context.cancel()
raw.cancel()
}
@OptIn(InternalAPI::class)
private fun runIncomingProcessor(ponger: SendChannel<Frame.Ping>): Job = launch(
IncomingProcessorCoroutineName + Dispatchers.Unconfined
) {
var last: BytePacketBuilder? = null
var closeFramePresented = false
try {
@OptIn(ExperimentalCoroutinesApi::class)
raw.incoming.consumeEach { frame ->
when (frame) {
is Frame.Close -> {
if (!outgoing.isClosedForSend) {
outgoing.send(Frame.Close(frame.readReason() ?: NORMAL_CLOSE))
}
closeFramePresented = true
return@launch
}
is Frame.Pong -> pinger.value?.send(frame)
is Frame.Ping -> ponger.send(frame)
else -> {
checkMaxFrameSize(last, frame)
if (!frame.fin) {
if (last == null) {
last = BytePacketBuilder()
}
last!!.writeFully(frame.data)
return@consumeEach
}
val frameToSend = last?.let { builder ->
builder.writeFully(frame.data)
Frame.byType(
fin = true,
frame.frameType,
builder.build().readBytes(),
frame.rsv1,
frame.rsv2,
frame.rsv3
)
} ?: frame
last = null
filtered.send(processIncomingExtensions(frameToSend))
}
}
}
} catch (ignore: ClosedSendChannelException) {
} catch (cause: Throwable) {
ponger.close()
filtered.close(cause)
} finally {
ponger.close()
last?.release()
filtered.close()
if (!closeFramePresented) {
@Suppress("DEPRECATION")
close(CloseReason(CloseReason.Codes.CLOSED_ABNORMALLY, "Connection was closed without close frame"))
}
}
}
private fun runOutgoingProcessor(): Job = launch(
OutgoingProcessorCoroutineName + Dispatchers.Unconfined,
start = CoroutineStart.UNDISPATCHED
) {
try {
outgoingProcessorLoop()
} catch (ignore: ClosedSendChannelException) {
} catch (ignore: ClosedReceiveChannelException) {
} catch (ignore: CancellationException) {
} catch (ignore: ChannelIOException) {
} catch (cause: Throwable) {
outgoingToBeProcessed.cancel(CancellationException("Failed to send frame", cause))
raw.closeExceptionally(cause)
} finally {
outgoingToBeProcessed.cancel()
raw.close()
}
}
private suspend fun outgoingProcessorLoop() {
for (frame in outgoingToBeProcessed) {
val processedFrame: Frame = when (frame) {
is Frame.Close -> {
sendCloseSequence(frame.readReason())
break
}
is Frame.Text,
is Frame.Binary -> processOutgoingExtensions(frame)
else -> frame
}
raw.outgoing.send(processedFrame)
}
}
@OptIn(InternalAPI::class)
private suspend fun sendCloseSequence(reason: CloseReason?, exception: Throwable? = null) {
if (!tryClose()) return
context.complete()
val reasonToSend = reason ?: CloseReason(CloseReason.Codes.NORMAL, "")
try {
runOrCancelPinger()
@Suppress("DEPRECATION")
if (reasonToSend.code != CloseReason.Codes.CLOSED_ABNORMALLY.code) {
raw.outgoing.send(Frame.Close(reasonToSend))
}
} finally {
closeReasonRef.complete(reasonToSend)
if (exception != null) {
outgoingToBeProcessed.close(exception)
filtered.close(exception)
}
}
}
private fun tryClose(): Boolean = closed.compareAndSet(false, true)
private fun runOrCancelPinger() {
val interval = pingIntervalMillis
val newPinger: SendChannel<Frame.Pong>? = when {
closed.value -> null
interval > 0L -> pinger(raw.outgoing, interval, timeoutMillis) {
sendCloseSequence(it, IOException("Ping timeout"))
}
else -> null
}
// pinger is always lazy so we publish it first and then start it by sending EmptyPong
// otherwise it may send ping before it get published so corresponding pong will not be dispatched to pinger
// that will cause it to terminate connection on timeout
pinger.getAndSet(newPinger)?.close()
// it is safe here to send dummy pong because pinger will ignore it
newPinger?.trySend(EmptyPong)?.isSuccess
if (closed.value && newPinger != null) {
runOrCancelPinger()
}
}
private suspend fun checkMaxFrameSize(
packet: BytePacketBuilder?,
frame: Frame
) {
val size = frame.data.size + (packet?.size ?: 0)
if (size > maxFrameSize) {
packet?.release()
close(CloseReason(CloseReason.Codes.TOO_BIG, "Frame is too big: $size. Max size is $maxFrameSize"))
throw FrameTooBigException(size.toLong())
}
}
private fun processIncomingExtensions(frame: Frame): Frame =
extensions.fold(frame) { current, extension -> extension.processIncomingFrame(current) }
private fun processOutgoingExtensions(frame: Frame): Frame =
extensions.fold(frame) { current, extension -> extension.processOutgoingFrame(current) }
companion object {
private val EmptyPong = Frame.Pong(ByteArray(0), NonDisposableHandle)
}
}