Scoop API

scoop:scoop.http.server:0.1.0

src/sse/result.scoop

Selected production source · src/sse/result.scoop

1package scoop.http.server
3import scoop.asyncio.useAsync
4import scoop.http.asyncio.SseSink
5import scoop.time.Duration
7/** SSE endpoint behavior; application replay and subscription state remain external. */
8public 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 = false
13) {
14 init {
15 if (present(heartbeatInterval) && heartbeatInterval!! <= Duration.ZERO)
16 throw IllegalArgumentException(Some("SSE heartbeat interval must be positive"))
17 }
20/** Builds an SSE stream that flushes its headers before running the producer. */
21public fun sse(
22 options: SseOptions = SseOptions(),
23 produce: suspend (SseWriter) -> Unit
24): HttpResult =
25 httpResult {
26 this.status = 200U
27 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.allowCompression
35 }
37private suspend fun produceSse(
38 body: HttpBodyWriter,
39 options: SseOptions,
40 produce: suspend (SseWriter) -> Unit
41) {
42 SseSink(body).useAsync suspend {
43 sink ->
44 val writer = SseWriter(sink)
45 try {
46 writer.flush()
47 coroutineScope<Unit> {
48 val scope = this
50 val heartbeat: Job? =
51 when (options.heartbeatInterval) {
52 case None -> None
53 case Some(val interval) -> Some(
54 scope.launch suspend { runSseHeartbeat(writer, interval) }
55 )
56 }
57 var completed = false
58 try {
59 coroutineScope<Unit> { produce(writer) }
60 completed = true
61 } 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 }