tobogganSe connecter

louise

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

211 lignes · 5752 octetsBrut · Historique
1/// Server-Sent Events (ADR 0053, issue #179 §1b): one-way push to a
2/// browser or an app, over a streamed response (`std/http.stream`).
3///
4/// import std/http/sse
5///
6/// ("GET", "/events") -> sse.stream(fn(w) {
7/// let events = sse.subscribe(hub)
8/// events_loop(w, events)
9/// })
10///
11/// The loop selects on its subject with a timeout; a timeout sends a
12/// heartbeat, so proxies don't close an idle stream and a gone client is
13/// found by the next write:
14///
15/// fn events_loop(w, events) {
16/// match process.receive(events, 15000) {
17/// Some(msg) -> ... sse.send(w, sse.event(render(msg), id: ...)) and loop,
18/// None -> ... sse.send(w, sse.comment("hb")) and loop,
19/// }
20/// }
21///
22/// Either way, `Error` from `send` says the client is gone: the loop
23/// returns, unsubscribing first.
24
25import std/actor.{Continue}
26import std/bytes.{type Builder}
27import std/http
28import std/list
29import std/process.{type Subject, type proc}
30import std/random.{type random}
31import std/string
32import std/time.{type clock}
33
34/// A `text/event-stream` response with `Cache-Control: no-cache`: the
35/// head goes out at once, then `write` runs.
36pub fn stream ::
37 write: fn(http.Writer) -> () / <io, proc, clock, random, ffi>
38 -> http.Response
39{
40 http.with_header
41 (http.stream "text/event-stream" write)
42 "Cache-Control"
43 "no-cache"
44}
45
46/// An event: its `data`, and the optional `event:` name, `id:` and
47/// `retry:`. `sse.new_event(data)` then a record update:
48/// `Event(..sse.new_event("hi"), id: Some("42"))`.
49pub type Event
50{ Event(
51 data: String
52 , event: Option<String>
53 , id: Option<String>
54 , retry: Option<Int>
55 )
56}
57
58/// An event with just data.
59pub fn new_event :: data: String -> Event
60{
61 Event(data, None, None, None)
62}
63
64/// An event's frame: the `event:`, `id:` and `retry:` lines that are
65/// given, then one `data:` line per line of the data, then the blank
66/// line that ends the event.
67///
68/// sse.frame(Event(..sse.new_event("two\nlines"), id: Some("42")))
69/// -- "id: 42\ndata: two\ndata: lines\n\n"
70pub fn frame :: e: Event -> Bytes
71{
72 let Event(data, event, id, retry) = e
73 let b = bytes.builder ()
74 let b = match event
75 { Some(name) -> field_line b "event: " (one_line name), None -> b }
76 let b = match id { Some(i) -> field_line b "id: " (one_line i), None -> b }
77 let b = match retry { Some(r) -> field_line b "retry: " (show r), None -> b }
78 bytes.build (bytes.append_string (data_lines b (string.split data "\n")) "\n")
79}
80
81/// A comment frame (": text"), the heartbeat: clients ignore it, proxies
82/// keep the stream open for it. Newlines in `text` start new comment
83/// lines.
84pub fn comment :: text: String -> Bytes
85{
86 bytes.build
87 ( bytes.append_string
88 (comment_lines (bytes.builder ()) (string.split text "\n"))
89 "\n"
90 )
91}
92
93/// `"tag" <> value <> "\n"` appended without building the string.
94fn field_line :: b: Builder tag: String value: String -> Builder
95{
96 bytes.append_string
97 (bytes.append_string (bytes.append_string b tag) value)
98 "\n"
99}
100
101fn data_lines :: b: Builder lines: List<String> -> Builder
102{
103 match lines
104 { [] -> b, [line, ..rest] -> data_lines (field_line b "data: " line) rest }
105}
106
107fn comment_lines :: b: Builder lines: List<String> -> Builder
108{
109 match lines
110 { [] -> b, [line, ..rest] -> comment_lines (field_line b ": " line) rest }
111}
112
113/// The `Last-Event-ID` a request resumes from, if it gives one.
114pub fn last_event_id :: req: http.Request -> Option<String>
115{
116 http.header req "Last-Event-ID"
117}
118
119/// Send a frame. `Error` says the client is gone: the stream should end.
120pub fn send :: w: http.Writer frame: Bytes -> Result<(), String> / <io, proc>
121{
122 http.write_chunk w frame
123}
124
125/// `event:` and `id:` values hold one line each.
126fn one_line :: s: String -> String
127{
128 string.join (string.split s "\n") " "
129}
130
131// ---- a broadcast hub --------------------------------------------------------------
132
133/// A broadcast hub: streams `subscribe` and get a subject; `publish`
134/// reaches every subscriber. One hub per thing published (a user's
135/// changes, say).
136pub opaque type Hub<msg> { Hub(Subject<HubMsg<msg>>) }
137
138type HubMsg<msg>
139{ Subscribe(Subject<msg>), Unsubscribe(Subject<msg>), Published(msg) }
140
141/// A hub, its registry actor started.
142pub fn hub :: -> Hub<msg> / <proc> where Send<msg>
143{
144 Hub(actor.start [] fn subs msg { on_hub subs msg })
145}
146
147/// A fresh subject, subscribed: the stream's loop receives every
148/// published message on it.
149pub fn subscribe :: h: Hub<msg> -> Subject<msg> / <proc> where Send<msg>
150{
151 let Hub(inbox) = h
152 let subject = process.subject ()
153 process.send inbox Subscribe(subject)
154 subject
155}
156
157/// Stop receiving (a stream that ended).
158pub fn unsubscribe ::
159 h: Hub<msg>
160 subject: Subject<msg>
161 -> () / <proc>
162 where Send<msg>
163{
164 let Hub(inbox) = h
165 process.send inbox Unsubscribe(subject)
166}
167
168/// Reach every subscriber.
169pub fn publish :: h: Hub<msg> msg: msg -> () / <proc> where Send<msg>
170{
171 let Hub(inbox) = h
172 process.send inbox Published(msg)
173}
174
175fn on_hub ::
176 subs: List<Subject<msg>>
177 msg: HubMsg<msg>
178 -> actor.Next<List<Subject<msg>>> / <proc>
179 where Send<msg>
180{
181 match msg
182 { Subscribe(subject) -> Continue([subject, ..subs])
183 , Unsubscribe(subject) -> Continue(drop_subject subs subject)
184 , Published(m) ->
185 {
186 list.each subs fn s { process.send s m }
187 Continue(subs)
188 }
189 }
190}
191
192fn drop_subject ::
193 subs: List<Subject<msg>>
194 subject: Subject<msg>
195 -> List<Subject<msg>>
196{
197 match subs
198 { [] -> []
199 , [ s
200 , ..rest
201 ] -> if process.owner s == process.owner subject
202 && process.tag s == process.tag subject
203 {
204 rest
205 }
206 else
207 {
208 [s, ..drop_subject rest subject]
209 }
210 }
211}