Scoop API

scoop:scoop.http:0.1.0

src/websocket/frames/decoder.scoop

Selected production source · src/websocket/frames/decoder.scoop

1package scoop.http
3import scoop.platform.memory.NativeByteBuffer
5/**
6 * A serial incremental frame parser that validates masking, fragmentation, control frames, and
7 * limits. Compression flag acceptance does not itself inflate message data.
8 */
9public class WebSocketFrameDecoder public constructor(
10 /**
11 * The endpoint role determining incoming/outgoing masking requirements.
12 */
13 public val role: HttpRole, compressionEnabled: Boolean = false,
14 limits: WebSocketFrameLimits = WebSocketFrameLimits()) : Closeable {
15 private val state: WebSocketReadState = WebSocketReadState(role, compressionEnabled, limits)
16 private val busy: AtomicBoolean = AtomicBoolean(false)
17 private var closed: Boolean = false
18 private var error: Throwable? = None
19 /**
20 * Whether local frame state has been closed.
21 */
22 public val isClosed: Boolean get() = closed
23 /**
24 * Whether the terminal End event has been removed.
25 */
26 public val isFinished: Boolean get() = state.finished
27 /**
28 * Whether a close frame has been processed.
29 */
30 public val hasCloseFrame: Boolean get() = state.hasCloseFrame
31 /**
32 * The parsed close payload, once a close frame has arrived.
33 */
34 public val closeFrame: WebSocketClose? get() = state.closeFrame
35 /**
36 * The retained framing or message failure.
37 */
38 public val failure: Throwable? get() = error
40 /**
41 * Consumes a prefix of the readable buffer and advances by the returned count. A pending event
42 * can stop progress; drain events before supplying more bytes.
43 */
44 public fun receive(buffer: NativeByteBuffer, count: Long = buffer.readableBytes): Long = withUse {
45 requireOpen()
46 if (state.inputEnded) throw IllegalStateException(Some("WebSocket input has ended"))
47 if (count < 0L) throw IllegalArgumentException(Some("negative WebSocket input count"))
48 if (count > buffer.readableBytes) throw IndexOutOfBoundsException()
49 if (count == 0L) return@withUse 0L
50 try { state.pump() } catch (failure: Throwable) { fail(failure) }
51 if (state.hasPending) return@withUse 0L
52 @Unsafe {
53 val borrow = buffer.borrowReadable(count)
54 var consumed = 0L
55 try {
56 val pointer = borrow.pointer()!!
57 while (consumed < count && !state.hasPending) {
58 val byte = pointer.load(consumed)
59 consumed += 1L
60 state.accept(byte)
61 }
62 state.flushData()
63 return@withUse consumed
64 } catch (failure: Throwable) { fail(failure) }
65 finally { borrow.complete(consumed) }
66 }
67 }
69 /**
70 * Removes the next parsed event, or returns None when no event is ready.
71 */
72 public fun nextEvent(): WebSocketFrameEvent? = withUse {
73 requireOpen()
74 try {
75 state.pump()
76 val result = state.pending
77 state.pending = None
78 when (result) { case Some(WebSocketFrameEvent.End) -> state.finished = true; else -> {} }
79 result
80 } catch (failure: Throwable) { fail(failure) }
81 }
83 /**
84 * Reports transport EOF and advances final validation; incomplete framing or unclosed protocol
85 * state is reported as a failure.
86 */
87 public fun endInput() {
88 withUse {
89 requireOpen()
90 state.inputEnded = true
91 try { state.pump() } catch (failure: Throwable) { fail(failure) }
92 Unit
93 }
94 }
96 /**
97 * Releases local state; it does not send a Close frame or close a transport.
98 */
99 public override fun close() { withUse { if (!closed) { closed = true; state.close() }; Unit } }
101 private fun requireOpen() {
102 if (closed) throw IllegalStateException(Some("WebSocket frame decoder is closed"))
103 when (error) { case Some(_) -> throw IllegalStateException(Some("WebSocket frame decoder failed")); case None -> {} }
104 }
106 private fun fail(failure: Throwable): Nothing {
107 var result: Throwable = failure
108 if (failure is WebSocketFrameException && failure.byteOffset == None)
109 result = WebSocketFrameException(failure.closeCode, failure.detail, Some(state.position), failure.cause)
110 try { state.close() } catch (cleanup: Throwable) { result = ResourceUseException(result, cleanup) }
111 error = Some(result)
112 throw result
113 }
115 private fun <T> withUse(block: () -> T): T {
116 if (!busy.compareAndSet(false, true)) throw IllegalStateException(Some("WebSocket frame decoder is already in use"))
117 try { return block() } finally { busy.store(false) }
118 }