scoop:scoop.http.server:0.1.0
src/sse/result.scoop
Selected production source · src/sse/result.scoop
1
package scoop.http.server3
import scoop.asyncio.useAsync4
import scoop.http.asyncio.SseSink5
import scoop.time.Duration7
/** SSE endpoint behavior; application replay and subscription state remain external. */8
public class SseOptions public constructor(9
/** Idle interval for flushed comment heartbeats; None disables them. */10
public val heartbeatInterval: Duration? = None,11
/** Whether the installed response compression policy may encode this event stream. */12
public val allowCompression: Boolean = false13
) {14
init {15
if (present(heartbeatInterval) && heartbeatInterval!! <= Duration.ZERO)16
throw IllegalArgumentException(Some("SSE heartbeat interval must be positive"))17
}18
}20
/** Builds an SSE stream that flushes its headers before running the producer. */21
public fun sse(22
options: SseOptions = SseOptions(),23
produce: suspend (SseWriter) -> Unit24
): HttpResult =25
httpResult {26
this.status = 200U27
this.fields =28
[29
field("Content-Type", "text/event-stream; charset=utf-8"),30
field("Cache-Control", "no-cache")31
]32
this.body =33
HttpBody.Stream(HttpStreamBody(suspend { body -> produceSse(body, options, produce) }))34
this.allowCompression = options.allowCompression35
}37
private suspend fun produceSse(38
body: HttpBodyWriter,39
options: SseOptions,40
produce: suspend (SseWriter) -> Unit41
) {42
SseSink(body).useAsync suspend {43
sink ->44
val writer = SseWriter(sink)45
try {46
writer.flush()47
coroutineScope<Unit> {48
val scope = this50
val heartbeat: Job? =51
when (options.heartbeatInterval) {52
case None -> None53
case Some(val interval) -> Some(54
scope.launch suspend { runSseHeartbeat(writer, interval) }55
)56
}57
var completed = false58
try {59
coroutineScope<Unit> { produce(writer) }60
completed = true61
} finally {62
writer.invalidate()63
if (present(heartbeat)) {64
if (!completed)65
heartbeat!!.cancel()66
nonCancellableScope<Unit> { heartbeat!!.join() }67
}68
}69
}70
} finally {71
writer.invalidate()72
}73
}74
}