tobogganSe connecter

packages

The Louise packages, each released on its own

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

259 lignes · 6303 octetsBrut · Historique
1/// Server-sent events, as a client reads them (the HTML standard's
2/// `text/event-stream`, section 9.2.6): fed with a body as it arrives
3/// (`fetch.request_streaming` and `fetch.next`), in pieces of any size.
4///
5/// let parser = sse.parser ()
6/// let (parser, events) = sse.feed parser piece // [Event(name: "delta", data: "Bon", id: "")]
7///
8/// The rules:
9/// - lines end with CRLF, LF or CR, even across pieces;
10/// - a blank line dispatches an event if any `data` came (an event with
11/// no `data` field is dropped);
12/// - `event` names it (`message` by default);
13/// - each `data` line adds a line to its data;
14/// - `id` sets the last event id, which every later event carries (an
15/// `id` holding a NUL is ignored);
16/// - `retry` (digits only) sets [`retry`];
17/// - lines starting with `:` are comments, and unknown fields are
18/// ignored;
19/// - after a field's colon, one space is dropped. A line without a colon
20/// is a field with an empty value.
21///
22/// The text is decoded as UTF-8, invalid bytes replaced (U+FFFD), and a
23/// byte order mark at the start is dropped. An event not ended by a blank
24/// line when the body ends is not dispatched.
25///
26/// Reconnecting (with `Last-Event-ID`) is the caller's choice: this module
27/// only parses.
28
29import std/bytes
30import std/list
31import std/string
32
33/// An event: its name, its data (lines joined with LF), and the last
34/// event id ("" when none was set).
35@derive Eq Show Debug
36pub type Event { Event(name: String, data: String, id: String) }
37
38/// A parser's state between pieces.
39pub opaque type Parser
40{ Parser(
41 pending: Bytes
42 , after_cr: Bool
43 , started: Bool
44 , name: String
45 , lines: List<String>
46 , id: String
47 , retry: Option<Int>
48 )
49}
50
51/// A parser at the start of a stream.
52pub fn parser :: -> Parser
53{
54 Parser(bytes.empty (), False, False, "", [], "", None)
55}
56
57/// The reconnection time the stream asked for, in milliseconds, if any.
58pub fn retry :: p: Parser -> Option<Int>
59{
60 p.retry
61}
62
63/// The parser after `piece`, and the events it completed, in order.
64pub fn feed :: p: Parser piece: Bytes -> (Parser, List<Event>)
65{
66 let n = bytes.length piece
67 if n == 0
68 {
69 (p, [])
70 }
71 else
72 {
73 // A CR that ended the last piece and an LF that starts this one are
74 // one line ending.
75 let piece = if p.after_cr && bytes.read_u8 piece 0 == 10
76 {
77 bytes.slice piece 1 n
78 }
79 else
80 {
81 piece
82 }
83 let data = bytes.concat p.pending piece
84 let p = Parser(..p, pending: bytes.empty (), after_cr: False)
85 if p.started
86 {
87 lines p data 0 0 []
88 }
89 else if bytes.length data < 3 && is_bom_prefix data
90 {
91 (Parser(..p, pending: data), [])
92 }
93 else
94 {
95 let data = if bytes.length data >= 3 && is_bom_prefix data
96 {
97 bytes.slice data 3 (bytes.length data)
98 }
99 else
100 {
101 data
102 }
103 lines (Parser(..p, started: True)) data 0 0 []
104 }
105 }
106}
107
108/// Whether `data` starts like UTF-8's byte order mark (EF BB BF).
109fn is_bom_prefix :: data: Bytes -> Bool
110{
111 let bom = [239, 187, 191]
112 let n = if bytes.length data < 3 { bytes.length data } else { 3 }
113 list.all
114 (list.zip (list.take bom n) (list.range 0 (n - 1)))
115 fn p { bytes.read_u8 data p.1 == p.0 }
116}
117
118/// Splits `data` into lines from `start`, `at` the next byte to look at;
119/// what follows the last line ending waits for the next piece.
120fn lines ::
121 p: Parser
122 data: Bytes
123 start: Int
124 at: Int
125 events: List<Event>
126 -> (Parser, List<Event>)
127{
128 let n = bytes.length data
129 if at >= n
130 {
131 (Parser(..p, pending: bytes.slice data start n), list.reverse events)
132 }
133 else
134 {
135 let b = bytes.read_u8 data at
136 if b == 10 || b == 13
137 {
138 let (p, events) = line p (bytes.slice data start at) events
139 if b == 10
140 {
141 lines p data (at + 1) (at + 1) events
142 }
143 else if at + 1 >= n
144 {
145 (Parser(..p, after_cr: True), list.reverse events)
146 }
147 else
148 {
149 let next = if bytes.read_u8 data (at + 1) == 10
150 {
151 at + 2
152 }
153 else
154 {
155 at + 1
156 }
157 lines p data next next events
158 }
159 }
160 else
161 {
162 lines p data start (at + 1) events
163 }
164 }
165}
166
167/// One line: a blank one dispatches, a comment is skipped, anything else
168/// is a field.
169fn line :: p: Parser text: Bytes events: List<Event> -> (Parser, List<Event>)
170{
171 let n = bytes.length text
172 if n == 0
173 {
174 dispatch p events
175 }
176 else if bytes.read_u8 text 0 == 58
177 {
178 (p, events)
179 }
180 else
181 {
182 let (field, value) = match colon text 0
183 { Some(i) -> (bytes.slice text 0 i, bytes.slice text (i + 1) n)
184 , None -> (text, bytes.empty ())
185 }
186 let value = if bytes.length value > 0 && bytes.read_u8 value 0 == 32
187 {
188 bytes.slice value 1 (bytes.length value)
189 }
190 else
191 {
192 value
193 }
194 (apply p (bytes.to_string_lossy field) value, events)
195 }
196}
197
198fn colon :: text: Bytes at: Int -> Option<Int>
199{
200 if at >= bytes.length text
201 {
202 None
203 }
204 else if bytes.read_u8 text at == 58
205 {
206 Some(at)
207 }
208 else
209 {
210 colon text (at + 1)
211 }
212}
213
214fn apply :: p: Parser field: String value: Bytes -> Parser
215{
216 let text = bytes.to_string_lossy value
217 match field
218 { "event" -> Parser(..p, name: text)
219 , "data" -> Parser(..p, lines: [text, ..p.lines])
220 , "id" -> if has_byte value 0 { p } else { Parser(..p, id: text) }
221 , "retry" -> if is_digits value
222 {
223 match string.to_int text
224 { Ok(ms) -> Parser(..p, retry: Some(ms)), Error(_) -> p }
225 }
226 else
227 {
228 p
229 }
230 , _ -> p
231 }
232}
233
234fn has_byte :: data: Bytes b: Int -> Bool
235{
236 list.any (bytes.to_list data) fn x { x == b }
237}
238
239fn is_digits :: data: Bytes -> Bool
240{
241 bytes.length data > 0
242 && list.all (bytes.to_list data) fn x { x >= 48 && x <= 57 }
243}
244
245/// The event the buffered fields make, if any `data` came; the name and
246/// the data start again, the id stays.
247fn dispatch :: p: Parser events: List<Event> -> (Parser, List<Event>)
248{
249 let reset = Parser(..p, name: "", lines: [])
250 match p.lines
251 { [] -> (reset, events)
252 , _ ->
253 {
254 let name = if p.name == "" { "message" } else { p.name }
255 let event = Event(name, string.join (list.reverse p.lines) "\n", p.id)
256 (reset, [event, ..events])
257 }
258 }
259}