scoop:scoop.http.server:0.1.0
src/sse/writer.scoop
Selected production source · src/sse/writer.scoop
1
package scoop.http.server3
import scoop.http.SseMessage4
import scoop.http.asyncio.SseSink5
import scoop.platform.time.MonotonicTimeSource6
import scoop.time.*8
/** A borrowed, serial event writer, valid only during its SSE producer. */9
public 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 = false35
try {36
ensureActive()37
requireActive()38
while (!outputBusy.compareAndSet(false, true)) available.await()39
acquired = true40
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 interval62
return lock.withLock { remainingServerTime(Some(interval), lastOutput)!! }63
}65
internal suspend fun heartbeat(interval: Duration) {66
if (stopped || applicationBusy.load() || !outputBusy.compareAndSet(false, true)) return67
try {68
val due = lock.withLock { remainingServerTime(Some(interval), lastOutput)!! == Duration.ZERO }69
if (stopped || !due) return70
sink.comment("")71
sink.flush()72
recordOutput()73
} finally { releaseOutput() }74
}76
internal fun invalidate() { active.store(false); changes.signal() }77
}