scoop:scoop.http:0.1.0
src/eventstream/decoder.scoop
Selected production source · src/eventstream/decoder.scoop
1
package scoop.http3
import scoop.platform.memory.NativeByteBuffer5
/** An incremental AWS EventStream decoder with one pending message and no network I/O. */6
public class AwsEventStreamDecoder public constructor() : Closeable {7
private val state = AwsEventStreamState()8
private val busy = AtomicBoolean(false)9
private var closed = false10
private var parseFailure: Throwable? = None12
public val isClosed: Boolean get() = closed13
public val isFinished: Boolean get() = state.ended && !state.hasPending14
public val failure: Throwable? get() = parseFailure16
/** 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 = 0L23
try {24
while (consumed < count && !state.hasPending) {25
val part = if (count - consumed < state.needed) count - consumed else state.needed26
state.read(buffer, part)27
consumed += part28
}29
} catch (error: Throwable) { fail(error); throw error }30
consumed31
}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.pending37
state.pending = None38
result39
}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 error49
}50
state.ended = true51
Unit52
}53
}55
public override fun close() {56
withUse {57
if (!closed) {58
closed = true59
state.discard()60
state.pending = None61
}62
Unit63
}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
}81
}