Scoop API

scoop:scoop.http.asyncio:0.1.0

src/websocket/message.scoop

Selected production source · src/websocket/message.scoop

1package scoop.http.asyncio
3import scoop.asyncio.*
4import scoop.bytes.ByteArrayBuilder
5import scoop.http.*
6import scoop.platform.memory.NativeByteBuffer
8/**
9 * A single incoming message exposed as a byte source. Its cursor advances once; aggregation
10 * methods collect only unread content.
11 */
12public class WebSocketMessage internal constructor(private val state: WsState, private val message: WsIncoming)
13 : AsyncByteSource, AsyncCloseable {
14 /**
15 * The Text or Binary message category.
16 */
17 public val type: WebSocketMessageType get() = message.type
18 /**
19 * Whether this particular message uses negotiated compression.
20 */
21 public val isCompressed: Boolean get() = message.isCompressed
22 /**
23 * Whether this body or message reached its successful boundary.
24 */
25 public val isComplete: Boolean get() = state.lock.withLock { message.life.complete }
26 /**
27 * Whether this body or message has been closed.
28 */
29 public val isClosed: Boolean get() = state.lock.withLock { message.life.closed }
31 /**
32 * Reads decoded message bytes under bounded backpressure; compression limits apply to decoded
33 * content.
34 */
35 public override suspend fun readInto(buffer: NativeByteBuffer, count: Long): Long =
36 wsOperation<Unit, Long>(state, true, {
37 checkWsMessage(state, message)
38 httpCount(count, buffer.writableBytes)
39 }, suspend { _ -> if (count == 0L) 0L else readWsMessage(state, message, buffer, count) })
41 /**
42 * Collects the remaining unread message bytes.
43 */
44 public suspend fun readBytes(): Array<Byte> = readAll(false)
45 /**
46 * Collects the remaining content of a Text message as UTF-8 text.
47 */
48 public suspend fun readText(): String = String.fromUtf8(readAll(true))
49 /**
50 * Closes the message. Abandoning an incomplete message aborts its session.
51 */
52 public override suspend fun close() { closeWsLife(state, message.life) }
54 private suspend fun readAll(text: Boolean): Array<Byte> =
55 wsOperation<Unit, Array<Byte>>(state, true, {
56 checkWsMessage(state, message)
57 if (text && message.type != WebSocketMessageType.Text)
58 throw IllegalStateException(Some("readText requires a Text message"))
59 }, suspend { _ ->
60 val bytes = ByteArrayBuilder()
61 NativeByteBuffer.allocate(state.options.incomingLimits.dataChunkBytes).use suspend { buffer ->
62 while (true) {
63 buffer.clear()
64 val count = readWsMessage(state, message, buffer, buffer.writableBytes)
65 if (count == 0L) break
66 bytes.append(buffer.readBytes(count))
67 }
68 }
69 bytes.toByteArray()
70 })
73private fun checkWsMessage(state: WsState, message: WsIncoming) {
74 if (message.life.closed) throw wsClosed(state)
75 if (!message.life.complete && !message.discarded &&
76 (!present(state.incoming) || state.incoming!! !== message))
77 throw IllegalStateException(Some("this is not the active WebSocket message"))
80internal suspend fun receiveWsMessage(state: WsState): WebSocketMessage? =
81 wsOperation<Unit, WebSocketMessage?>(state, true, {
82 if (!state.closing && !present(state.shutdown) && present(state.incoming)) {
83 val message = state.incoming!!
84 if (message.taken && !message.life.complete)
85 throw IllegalStateException(Some("previous WebSocket message is unfinished"))
86 }
87 Unit
88 }, suspend { _ ->
89 val message = suspendCoroutine<WsIncoming?> { continuation ->
90 val wait = WsWait<WsIncoming?>(continuation)
91 val actions = ArrayList<() -> Unit>()
92 state.lock.withLock {
93 if (state.closed) {
94 if (wsClean(state)) succeedWsWait(wait, None, actions)
95 else failWsWait(wait, state.failure ?: wsClosed(state), actions)
96 } else state.receiving = Some(wait)
97 }
98 for (action in actions) action()
99 driveWs(state)
100 }
101 when (message) {
102 case None -> None
103 case Some(val value) -> {
104 val job = httpJob(state.loop, true)
105 listenWsLife(state, value.life, job)
106 job.ensureActive()
107 Some(WebSocketMessage(state, value))
108 }
109 }
110 })
112internal suspend fun readWsMessage(state: WsState, message: WsIncoming, buffer: NativeByteBuffer, count: Long): Long =
113 suspendCoroutine<Long> { continuation ->
114 val wait = WsWait<Long>(continuation)
115 val actions = ArrayList<() -> Unit>()
116 state.lock.withLock {
117 if (message.life.complete) succeedWsWait(wait, 0L, actions)
118 else if (state.closed) failWsWait(wait, state.failure ?: wsInterrupted(state), actions)
119 else state.reader = Some(WsReadRequest(message, buffer, count, wait))
120 }
121 for (action in actions) action()
122 driveWs(state)
123 }