/// Server-Sent Events (ADR 0053, issue #179 ยง1b): one-way push to a /// browser or an app, over a streamed response (`std/http.stream`). /// /// import std/http/sse /// /// ("GET", "/events") -> sse.stream(fn(w) { /// let events = sse.subscribe(hub) /// events_loop(w, events) /// }) /// /// The loop selects on its subject with a timeout; a timeout sends a /// heartbeat, so proxies don't close an idle stream and a gone client is /// found by the next write: /// /// fn events_loop(w, events) { /// match process.receive(events, 15000) { /// Some(msg) -> ... sse.send(w, sse.event(render(msg), id: ...)) and loop, /// None -> ... sse.send(w, sse.comment("hb")) and loop, /// } /// } /// /// Either way, `Error` from `send` says the client is gone: the loop /// returns, unsubscribing first. import std/actor.{Continue} import std/bytes.{type Builder} import std/http import std/list import std/process.{type Subject, type proc} import std/random.{type random} import std/string import std/time.{type clock} /// A `text/event-stream` response with `Cache-Control: no-cache`: the /// head goes out at once, then `write` runs. pub fn stream :: write: fn(http.Writer) -> () / -> http.Response { http.with_header (http.stream "text/event-stream" write) "Cache-Control" "no-cache" } /// An event: its `data`, and the optional `event:` name, `id:` and /// `retry:`. `sse.new_event(data)` then a record update: /// `Event(..sse.new_event("hi"), id: Some("42"))`. pub type Event { Event( data: String , event: Option , id: Option , retry: Option ) } /// An event with just data. pub fn new_event :: data: String -> Event { Event(data, None, None, None) } /// An event's frame: the `event:`, `id:` and `retry:` lines that are /// given, then one `data:` line per line of the data, then the blank /// line that ends the event. /// /// sse.frame(Event(..sse.new_event("two\nlines"), id: Some("42"))) /// -- "id: 42\ndata: two\ndata: lines\n\n" pub fn frame :: e: Event -> Bytes { let Event(data, event, id, retry) = e let b = bytes.builder () let b = match event { Some(name) -> field_line b "event: " (one_line name), None -> b } let b = match id { Some(i) -> field_line b "id: " (one_line i), None -> b } let b = match retry { Some(r) -> field_line b "retry: " (show r), None -> b } bytes.build (bytes.append_string (data_lines b (string.split data "\n")) "\n") } /// A comment frame (": text"), the heartbeat: clients ignore it, proxies /// keep the stream open for it. Newlines in `text` start new comment /// lines. pub fn comment :: text: String -> Bytes { bytes.build ( bytes.append_string (comment_lines (bytes.builder ()) (string.split text "\n")) "\n" ) } /// `"tag" <> value <> "\n"` appended without building the string. fn field_line :: b: Builder tag: String value: String -> Builder { bytes.append_string (bytes.append_string (bytes.append_string b tag) value) "\n" } fn data_lines :: b: Builder lines: List -> Builder { match lines { [] -> b, [line, ..rest] -> data_lines (field_line b "data: " line) rest } } fn comment_lines :: b: Builder lines: List -> Builder { match lines { [] -> b, [line, ..rest] -> comment_lines (field_line b ": " line) rest } } /// The `Last-Event-ID` a request resumes from, if it gives one. pub fn last_event_id :: req: http.Request -> Option { http.header req "Last-Event-ID" } /// Send a frame. `Error` says the client is gone: the stream should end. pub fn send :: w: http.Writer frame: Bytes -> Result<(), String> / { http.write_chunk w frame } /// `event:` and `id:` values hold one line each. fn one_line :: s: String -> String { string.join (string.split s "\n") " " } // ---- a broadcast hub -------------------------------------------------------------- /// A broadcast hub: streams `subscribe` and get a subject; `publish` /// reaches every subscriber. One hub per thing published (a user's /// changes, say). pub opaque type Hub { Hub(Subject>) } type HubMsg { Subscribe(Subject), Unsubscribe(Subject), Published(msg) } /// A hub, its registry actor started. pub fn hub :: -> Hub / where Send { Hub(actor.start [] fn subs msg { on_hub subs msg }) } /// A fresh subject, subscribed: the stream's loop receives every /// published message on it. pub fn subscribe :: h: Hub -> Subject / where Send { let Hub(inbox) = h let subject = process.subject () process.send inbox Subscribe(subject) subject } /// Stop receiving (a stream that ended). pub fn unsubscribe :: h: Hub subject: Subject -> () / where Send { let Hub(inbox) = h process.send inbox Unsubscribe(subject) } /// Reach every subscriber. pub fn publish :: h: Hub msg: msg -> () / where Send { let Hub(inbox) = h process.send inbox Published(msg) } fn on_hub :: subs: List> msg: HubMsg -> actor.Next>> / where Send { match msg { Subscribe(subject) -> Continue([subject, ..subs]) , Unsubscribe(subject) -> Continue(drop_subject subs subject) , Published(m) -> { list.each subs fn s { process.send s m } Continue(subs) } } } fn drop_subject :: subs: List> subject: Subject -> List> { match subs { [] -> [] , [ s , ..rest ] -> if process.owner s == process.owner subject && process.tag s == process.tag subject { rest } else { [s, ..drop_subject rest subject] } } }