Debian Codegraph @

man/format_sse.Rd

raw
1 % Generated by roxygen2: do not edit by hand
2 % Please edit documentation in R/server.R
3 \name{format_sse}
4 \alias{format_sse}
5 \title{Format Server-Sent Event}
6 \usage{
7 format_sse(data, event = NULL, id = NULL, retry = NULL)
8 }
9 \arguments{
10 \item{data}{The data payload. Will be prefixed with "data: " on each line.}
11
12 \item{event}{[default NULL] Optional event type (e.g., "message", "error").}
13
14 \item{id}{[default NULL] Optional event ID for client reconnection.}
15
16 \item{retry}{[default NULL] Optional retry interval in milliseconds.}
17 }
18 \value{
19 A character string formatted as an SSE message, ready to pass to
20 \code{conn$send()}.
21 }
22 \description{
23 Helper function to format messages according to the Server-Sent Events (SSE)
24 specification. Use with \code{\link[=handler_stream]{handler_stream()}} to create SSE endpoints.
25 }
26 \details{
27 Server-Sent Events is a W3C standard for server-to-client streaming over
28 HTTP, supported natively by browsers via the \code{EventSource} API. SSE is
29 commonly used for real-time updates, notifications, and LLM token streaming.
30
31 SSE messages have this format:
32
33 \if{html}{\out{<div class="sourceCode">}}\preformatted{event: <event-type>
34 id: <event-id>
35 retry: <milliseconds>
36 data: <data-line-1>
37 data: <data-line-2>
38
39 }\if{html}{\out{</div>}}
40
41 Each message ends with two newlines. Multi-line data is split and each
42 line prefixed with "data: ".
43
44 When using SSE with \code{\link[=handler_stream]{handler_stream()}}, set the appropriate headers:
45 \itemize{
46 \item \code{Content-Type: text/event-stream}
47 \item \code{Cache-Control: no-cache}
48 \item \code{X-Accel-Buffering: no} (prevents proxy buffering)
49 }
50 }
51 \examples{
52 format_sse(data = "Hello")
53 #> "data: Hello\n\n"
54
55 format_sse(data = "Hello", event = "greeting")
56 #> "event: greeting\ndata: Hello\n\n"
57
58 format_sse(data = "Line 1\nLine 2")
59 #> "data: Line 1\ndata: Line 2\n\n"
60
61 # Typical SSE endpoint setup
62 h <- handler_stream("/events", function(conn, req) {
63 conn$set_header("Content-Type", "text/event-stream")
64 conn$set_header("Cache-Control", "no-cache")
65 conn$set_header("X-Accel-Buffering", "no")
66 conn$send(format_sse(data = "connected", id = "1"))
67 })
68
69 }
70 \seealso{
71 \code{\link[=handler_stream]{handler_stream()}} for creating streaming HTTP endpoints.
72 }