Scoop API

scoop:scoop.http.server:0.1.0

src/sse/writer.scoop

Selected production source · src/sse/writer.scoop

1package scoop.http.server
3import scoop.http.SseMessage
4import scoop.http.asyncio.SseSink
5import scoop.platform.time.MonotonicTimeSource
6import scoop.time.*
8/** A borrowed, serial event writer, valid only during its SSE producer. */
9public class SseWriter internal constructor(private val sink: SseSink) {
10 private val applicationBusy: AtomicBoolean = AtomicBoolean(false)
11 private val outputBusy: AtomicBoolean = AtomicBoolean(false)
12 private val active: AtomicBoolean = AtomicBoolean(true)
13 private val available: ServerSignal = ServerSignal()
14 private val lock: ServerLock = ServerLock()
15 private var lastOutput: TimeMark = MonotonicTimeSource.markNow()
16 internal val changes: ServerSignal = ServerSignal()
17 internal val stopped: Boolean get() = !active.load()
19 /** Sends one complete event and, by default, flushes it before returning. */
20 public suspend fun send(message: SseMessage, flush: Boolean = true) {
21 write(suspend { sink.send(message); if (flush) sink.flush() })
22 }
24 /** Sends one complete comment and, by default, flushes it before returning. */
25 public suspend fun comment(text: String, flush: Boolean = true) {
26 write(suspend { sink.comment(text); if (flush) sink.flush() })
27 }
29 /** Flushes previously batched events without ending the response. */
30 public suspend fun flush() { write(suspend { sink.flush() }) }
32 private suspend fun write(block: suspend () -> Unit) {
33 if (!applicationBusy.compareAndSet(false, true)) throw IllegalStateException(Some("concurrent SSE sends"))
34 var acquired = false
35 try {
36 ensureActive()
37 requireActive()
38 while (!outputBusy.compareAndSet(false, true)) available.await()
39 acquired = true
40 requireActive()
41 block()
42 recordOutput()
43 } finally {
44 if (acquired) releaseOutput()
45 applicationBusy.store(false)
46 }
47 }
49 private fun requireActive() {
50 if (!active.load()) throw IllegalStateException(Some("SSE producer has ended"))
51 }
53 private fun recordOutput() {
54 lock.withLock { lastOutput = MonotonicTimeSource.markNow() }
55 changes.signal()
56 }
58 private fun releaseOutput() { outputBusy.store(false); available.signal() }
60 internal fun remainingIdle(interval: Duration): Duration {
61 if (applicationBusy.load() || outputBusy.load()) return interval
62 return lock.withLock { remainingServerTime(Some(interval), lastOutput)!! }
63 }
65 internal suspend fun heartbeat(interval: Duration) {
66 if (stopped || applicationBusy.load() || !outputBusy.compareAndSet(false, true)) return
67 try {
68 val due = lock.withLock { remainingServerTime(Some(interval), lastOutput)!! == Duration.ZERO }
69 if (stopped || !due) return
70 sink.comment("")
71 sink.flush()
72 recordOutput()
73 } finally { releaseOutput() }
74 }
76 internal fun invalidate() { active.store(false); changes.signal() }