scoop:scoop.http:0.1.0
src/sse/decoder.scoop
Selected production source · src/sse/decoder.scoop
1
package scoop.http3
import scoop.platform.memory.NativeByteBuffer4
import scoop.text.indexOf6
/**7
* An incremental UTF-8 event-stream parser with bounded line and event data. It tracks event IDs8
* and retry hints but performs no reconnection or network I/O.9
*/10
public class SseDecoder public constructor(limits: SseLimits = SseLimits(), initialLastEventId: String = "") : Closeable {11
private val state: SseState = SseState(limits, initialLastEventId)12
private val busy: AtomicBoolean = AtomicBoolean(false)13
private var closed: Boolean = false14
private var parseFailure: Throwable? = None16
init {17
if (initialLastEventId.indexOf('\u0000') >= 0L || initialLastEventId.indexOf('\r') >= 0L || initialLastEventId.indexOf('\n') >= 0L)18
throw IllegalArgumentException(Some("invalid initial SSE event ID"))19
}21
/**22
* Whether local parser state has been closed.23
*/24
public val isClosed: Boolean get() = closed25
/**26
* Whether EOF has been reported and all pending complete events have been removed.27
*/28
public val isFinished: Boolean get() = state.ended && !state.hasPending29
/**30
* The current persistent event ID, including updates from ID-only events.31
*/32
public val lastEventId: String get() = state.lastEventId33
/**34
* The latest valid nonnegative retry hint, in milliseconds.35
*/36
public val retryMilliseconds: Long? get() = state.retryMilliseconds37
/**38
* The retained parse failure, if the decoder has failed.39
*/40
public val failure: Throwable? get() = parseFailure42
/**43
* Consumes a prefix of the readable buffer and advances by the returned count. A pending event44
* can stop progress; drain events before supplying more bytes.45
*/46
public fun receive(buffer: NativeByteBuffer, count: Long = buffer.readableBytes): Long = withUse {47
requireOpen()48
if (state.ended) throw IllegalStateException(Some("SSE input has ended"))49
if (count < 0L) throw IllegalArgumentException(Some("negative SSE input count"))50
if (count > buffer.readableBytes) throw IndexOutOfBoundsException()51
if (count == 0L || state.hasPending) return@withUse 0L52
@Unsafe {53
val borrow = buffer.borrowReadable(count)54
var consumed = 0L55
try {56
val pointer = borrow.pointer()!!57
while (consumed < count && !state.hasPending) {58
val byte = pointer.load(consumed)59
consumed += 1L60
state.accept(byte)61
}62
return@withUse consumed63
} catch (error: Throwable) {64
parseFailure = Some(error)65
state.discardIncomplete()66
throw error67
} finally { borrow.complete(consumed) }68
}69
}71
/**72
* Removes the next parsed event, or returns None when no event is ready.73
*/74
public fun nextEvent(): SseEvent? = withUse {75
requireOpen()76
val result = state.pending77
state.pending = None78
result79
}81
/**82
* Reports EOF and discards an unterminated event; a blank line is required for dispatch.83
*/84
public fun endInput() {85
withUse {86
requireOpen()87
if (!state.ended) { state.ended = true; state.discardIncomplete() }88
Unit89
}90
}92
/**93
* Closes the parser and discards incomplete and queued data without network I/O.94
*/95
public override fun close() {96
withUse {97
if (!closed) {98
closed = true99
state.discardIncomplete()100
state.pending = None101
}102
Unit103
}104
}106
private fun requireOpen() {107
if (closed) throw IllegalStateException(Some("SSE decoder is closed"))108
when (parseFailure) { case Some(_) -> throw IllegalStateException(Some("SSE decoder has failed")); case None -> {} }109
}111
private fun <T> withUse(block: () -> T): T {112
if (!busy.compareAndSet(false, true)) throw IllegalStateException(Some("SSE decoder is already in use"))113
try { return block() }114
finally { busy.store(false) }115
}116
}