Scoop API

scoop:scoop.http.asyncio:0.1.0

src/sse/sink.scoop

Selected production source · src/sse/sink.scoop

1package scoop.http.asyncio
3import scoop.asyncio.*
4import scoop.http.*
5import scoop.platform.io.WriteZeroException
6import scoop.platform.memory.NativeByteBuffer
8/** Serial SSE output over a borrowed sink; closing releases only local resources. */
9public class SseSink private constructor(private val writer: AsyncSseWriter) : AsyncCloseable {
10 /** Creates a bounded output adapter on the current event loop without writing bytes. */
11 public constructor(sink: AsyncByteSink, bufferSize: Long = 8192L) : this(createSseWriter(sink, bufferSize)) {}
13 /** Whether local cleanup has completed. */
14 public val isClosed: Boolean get() = writer.io.isClosed
15 /** The original terminal write or flush failure, when one occurred. */
16 public val failure: Throwable? get() = writer.io.failure
18 /** Sends a complete block with backpressure, without implicitly flushing. */
19 public suspend fun send(message: SseMessage) {
20 SseEncoder(message).use suspend { encoder -> writer.send(encoder) }
21 }
23 /** Sends a complete comment block, without implicitly flushing. */
24 public suspend fun comment(text: String) {
25 SseEncoder.comment(text).use suspend { encoder -> writer.send(encoder) }
26 }
28 /** Flushes the borrowed downstream sink without ending its HTTP body. */
29 public suspend fun flush() { writer.io.run({}) suspend { sink -> sink.flush() } }
31 /** Cancels and joins in-flight output before releasing the local buffer. */
32 public override suspend fun close() { writer.io.close() }
35internal class AsyncSseWriter(sink: AsyncByteSink, loop: EventLoop, private val buffer: NativeByteBuffer) {
36 val io: MessageIo<AsyncByteSink> = MessageIo<AsyncByteSink>(sink, None, loop) { buffer.close() }
38 suspend fun send(encoder: SseEncoder) {
39 io.run({}) suspend { sink ->
40 while (!encoder.isFinished) {
41 ensureActive()
42 buffer.clear()
43 encoder.writeInto(buffer)
44 while (buffer.readableBytes > 0L) {
45 ensureActive()
46 val requested = buffer.readableBytes
47 val beforeRead = buffer.readPosition
48 val beforeWrite = buffer.writePosition
49 val written = sink.writeFrom(buffer, requested)
50 httpProgress(written, requested)
51 if (buffer.readPosition - beforeRead != written || buffer.writePosition != beforeWrite)
52 throw IllegalStateException(Some("inconsistent SSE sink progress"))
53 if (written == 0L) throw WriteZeroException()
54 }
55 }
56 }
57 }
60private fun createSseWriter(sink: AsyncByteSink, bufferSize: Long): AsyncSseWriter {
61 val loop = currentEventLoop()
62 val job = httpJob(loop, true)
63 if (bufferSize <= 0L) throw IllegalArgumentException(Some("SSE buffer size must be positive"))
64 val buffer = NativeByteBuffer.allocate(bufferSize)
65 try { job.ensureActive(); return AsyncSseWriter(sink, loop, buffer) }
66 catch (error: Throwable) { buffer.close(); throw error }