Scoop API

scoop:scoop.http:0.1.0

src/eventstream/decoder.scoop

Selected production source · src/eventstream/decoder.scoop

1package scoop.http
3import scoop.platform.memory.NativeByteBuffer
5/** An incremental AWS EventStream decoder with one pending message and no network I/O. */
6public class AwsEventStreamDecoder public constructor() : Closeable {
7 private val state = AwsEventStreamState()
8 private val busy = AtomicBoolean(false)
9 private var closed = false
10 private var parseFailure: Throwable? = None
12 public val isClosed: Boolean get() = closed
13 public val isFinished: Boolean get() = state.ended && !state.hasPending
14 public val failure: Throwable? get() = parseFailure
16 /** Consumes a prefix, stopping immediately after one complete message. */
17 public fun receive(buffer: NativeByteBuffer, count: Long = buffer.readableBytes): Long = withUse {
18 requireOpen()
19 if (state.ended) throw IllegalStateException(Some("EventStream input has ended"))
20 if (count < 0L) throw IllegalArgumentException(Some("negative EventStream input count"))
21 if (count > buffer.readableBytes) throw IndexOutOfBoundsException()
22 var consumed = 0L
23 try {
24 while (consumed < count && !state.hasPending) {
25 val part = if (count - consumed < state.needed) count - consumed else state.needed
26 state.read(buffer, part)
27 consumed += part
28 }
29 } catch (error: Throwable) { fail(error); throw error }
30 consumed
31 }
33 /** Removes the single verified message, or returns None when more input is required. */
34 public fun nextMessage(): AwsEventStreamMessage? = withUse {
35 requireOpen()
36 val result = state.pending
37 state.pending = None
38 result
39 }
41 /** Ends input only at a complete frame boundary; partial frames are errors. */
42 public fun endInput() {
43 withUse {
44 requireOpen()
45 if (state.offset != 0L) {
46 val error = AwsEventStreamException(UnexpectedEof, state.offset, "truncated EventStream message")
47 fail(error)
48 throw error
49 }
50 state.ended = true
51 Unit
52 }
53 }
55 public override fun close() {
56 withUse {
57 if (!closed) {
58 closed = true
59 state.discard()
60 state.pending = None
61 }
62 Unit
63 }
64 }
66 private fun fail(error: Throwable) {
67 parseFailure = Some(error)
68 state.discard()
69 }
71 private fun requireOpen() {
72 if (closed) throw IllegalStateException(Some("EventStream decoder is closed"))
73 when (parseFailure) { case Some(_) -> throw IllegalStateException(Some("EventStream decoder has failed")); case None -> {} }
74 }
76 private fun <T> withUse(block: () -> T): T {
77 if (!busy.compareAndSet(false, true)) throw IllegalStateException(Some("EventStream decoder is already in use"))
78 try { return block() }
79 finally { busy.store(false) }
80 }