Diffinery

homeflare/celldpublic

celld/crates/celld/js/event_source.js
289 lines · 9.4 KBRaw History
1// EventSource over the streaming fetch path, following Workerd
2// (src/workerd/api/eventsource.c++): same reconnection ladder (2 s
3// default retry clamped to [1 s, 10 s], one no-body response retries and
4// a second fails), same header set, and the same parser — a message's
5// data lines join with "\n", an empty joined data dispatches nothing,
6// and `id:` persists as the Last-Event-ID for reconnects.
7(function () {
8 const kFrom = Symbol("celld.EventSource.from");
9
10 class EventSource extends EventTarget {
11 static CONNECTING = 0;
12 static OPEN = 1;
13 static CLOSED = 2;
14
15 constructor(url, init = undefined) {
16 super();
17 this._sourceState = 0; // CONNECTING
18 this._sourceUrl = "";
19 this._fetcher = null;
20 this._lastId = "";
21 this._retryMs = 2000;
22 this._dataLines = [];
23 this._eventType = "";
24 this._lineBuf = "";
25 this._fieldSeen = false;
26 this._sourceClosed = false;
27 this._retryTimer = null;
28 this._reader = null;
29 this._previousNoBody = false;
30 this._openHandler = null;
31 this._messageHandler = null;
32 this._errorHandler = null;
33 if (url === kFrom) return;
34 let parsed;
35 try {
36 parsed = new URL(String(url));
37 } catch {
38 throw new DOMException(
39 "Cannot open an EventSource to '" + String(url) +
40 "'. The URL is invalid.",
41 "SyntaxError");
42 }
43 if (init?.withCredentials) {
44 throw new DOMException(
45 "The init.withCredentials option is not supported. It must be " +
46 "false or undefined.",
47 "NotSupportedError");
48 }
49 this._sourceUrl = parsed.href;
50 this._fetcher = init?.fetcher ?? null;
51 this._connect();
52 }
53
54 // Workerd extension: parse an SSE stream directly, with no
55 // connection and therefore no reconnection.
56 static from(readable) {
57 if (!(readable instanceof ReadableStream)) {
58 throw new TypeError("argument is not a ReadableStream");
59 }
60 if (readable.locked) {
61 throw new TypeError("This ReadableStream is locked.");
62 }
63 const source = new EventSource(kFrom);
64 source._pump(readable, false);
65 return source;
66 }
67
68 get [Symbol.toStringTag]() { return "EventSource"; }
69 get readyState() { return this._sourceState; }
70 get url() { return this._sourceUrl; }
71 get withCredentials() { return false; }
72
73 get onopen() { return this._openHandler; }
74 set onopen(handler) {
75 this._openHandler = typeof handler === "function" ? handler : null;
76 }
77 get onmessage() { return this._messageHandler; }
78 set onmessage(handler) {
79 this._messageHandler = typeof handler === "function" ? handler : null;
80 }
81 get onerror() { return this._errorHandler; }
82 set onerror(handler) {
83 this._errorHandler = typeof handler === "function" ? handler : null;
84 }
85
86 close() {
87 if (this._sourceClosed) return;
88 this._sourceClosed = true;
89 this._sourceState = 2; // CLOSED
90 if (this._retryTimer !== null) {
91 clearTimeout(this._retryTimer);
92 this._retryTimer = null;
93 }
94 const reader = this._reader;
95 this._reader = null;
96 if (reader) reader.cancel().catch(() => {});
97 }
98
99 [Symbol.dispose]() { this.close(); }
100
101 _notifyError(message, reconnecting, error = undefined) {
102 if (this._sourceState === 2) return;
103 this._sourceState = reconnecting ? 0 : 2;
104 const event = new ErrorEvent("error", { message, error });
105 event._trust();
106 this.dispatchEvent(event);
107 }
108
109 _notifyOpen() {
110 if (this._sourceState === 2) return;
111 this._sourceState = 1; // OPEN
112 const event = new Event("open");
113 event._trust();
114 this.dispatchEvent(event);
115 }
116
117 _dispatchMessage() {
118 const data = this._dataLines.join("\n");
119 const type = this._eventType || "message";
120 this._dataLines = [];
121 this._eventType = "";
122 if (data === "") return;
123 let origin = "";
124 if (this._sourceUrl !== "") origin = new URL(this._sourceUrl).origin;
125 const event = new MessageEvent(type, {
126 data,
127 origin,
128 lastEventId: this._lastId,
129 });
130 event._trust();
131 this.dispatchEvent(event);
132 }
133
134 _feedLine(line) {
135 if (line === "") {
136 if (this._fieldSeen) {
137 this._fieldSeen = false;
138 this._dispatchMessage();
139 }
140 return;
141 }
142 if (line[0] === ":") return; // comment
143 const colon = line.indexOf(":");
144 let field, value;
145 if (colon === -1) {
146 field = line;
147 value = "";
148 } else {
149 field = line.slice(0, colon);
150 value = line.slice(colon + 1);
151 // Exactly one space after the colon is trimmed.
152 if (value[0] === " ") value = value.slice(1);
153 }
154 this._fieldSeen = true;
155 if (field === "data") this._dataLines.push(value);
156 else if (field === "event") this._eventType = value;
157 else if (field === "id") this._lastId = value;
158 else if (field === "retry" && /^\d+$/.test(value)) {
159 this._retryMs = Math.max(1000, Math.min(Number(value), 10000));
160 }
161 // Any other field is ignored.
162 }
163
164 _feedText(text, eof) {
165 this._lineBuf += text;
166 for (;;) {
167 const match = /[\r\n]/.exec(this._lineBuf);
168 if (!match) break;
169 const at = match.index;
170 // A "\r" at the buffer's end may be half of "\r\n"; wait for the
171 // next chunk unless the stream already ended.
172 if (this._lineBuf[at] === "\r" &&
173 at + 1 === this._lineBuf.length && !eof) {
174 break;
175 }
176 const line = this._lineBuf.slice(0, at);
177 const skip = this._lineBuf[at] === "\r" &&
178 this._lineBuf[at + 1] === "\n"
179 ? 2
180 : 1;
181 this._lineBuf = this._lineBuf.slice(at + skip);
182 this._feedLine(line);
183 }
184 // A partial line with no end-of-line is dropped at end of stream,
185 // as Workerd's sink does.
186 if (eof) this._lineBuf = "";
187 }
188
189 _scheduleReconnect() {
190 this._retryTimer = setTimeout(() => {
191 this._retryTimer = null;
192 if (this._sourceClosed) return;
193 this._connect();
194 }, this._retryMs);
195 }
196
197 async _pump(readable, withReconnection) {
198 this._notifyOpen();
199 try {
200 const reader = readable.getReader();
201 this._reader = reader;
202 const decoder = new TextDecoder(); // strips a leading BOM
203 for (;;) {
204 const { done, value } = await reader.read();
205 if (this._sourceClosed) return;
206 if (done) break;
207 this._feedText(decoder.decode(value, { stream: true }), false);
208 }
209 this._feedText(decoder.decode(), true);
210 this._reader = null;
211 this._notifyError("The server disconnected.", withReconnection);
212 if (withReconnection && !this._sourceClosed) {
213 this._scheduleReconnect();
214 }
215 } catch (error) {
216 if (this._sourceClosed) return;
217 this._reader = null;
218 this._notifyError(String(error?.message || error), false, error);
219 }
220 }
221
222 async _connect() {
223 if (this._sourceClosed) return;
224 const headers = {
225 "accept": "text/event-stream",
226 "cache-control": "no-cache",
227 };
228 if (this._lastId !== "") headers["last-event-id"] = this._lastId;
229 try {
230 const fetcher = this._fetcher;
231 const response = fetcher
232 ? await fetcher.fetch(this._sourceUrl, { headers })
233 : await fetch(this._sourceUrl, { headers });
234 if (this._sourceClosed) return;
235 if (!response.ok) {
236 this._notifyError(
237 "The response status code was " + response.status + ".", false);
238 return;
239 }
240 const contentType = response.headers.get("content-type");
241 if (!contentType) {
242 this._notifyError(
243 "No content type header was present in the response.", false);
244 return;
245 }
246 const essence = contentType.split(";")[0].trim().toLowerCase();
247 if (essence !== "text/event-stream") {
248 this._notifyError(
249 "The content type '" + contentType + "' is invalid.", false);
250 return;
251 }
252 if (response.redirected && response.url) {
253 try {
254 this._sourceUrl = new URL(response.url).href;
255 } catch { /* keep the configured URL */ }
256 }
257 // One empty response reads as a server hiccup and retries; a
258 // second reads as a broken server and fails the connection.
259 const body = response.status === 204 ? null : response.body;
260 if (!body) {
261 if (this._previousNoBody) {
262 this._notifyError("The server provided no content.", false);
263 } else {
264 this._previousNoBody = true;
265 this._notifyError(
266 "The server provided no content. Will try reconnecting.",
267 true);
268 this._scheduleReconnect();
269 }
270 return;
271 }
272 await this._pump(body, true);
273 } catch (error) {
274 if (this._sourceClosed) return;
275 this._notifyError(String(error?.message || error), false, error);
276 }
277 }
278 }
279
280 // The WebIDL constants live on the prototype as well as the interface.
281 for (const [name, value] of
282 [["CONNECTING", 0], ["OPEN", 1], ["CLOSED", 2]]) {
283 Object.defineProperty(EventSource.prototype, name, {
284 value, writable: false, enumerable: true, configurable: false,
285 });
286 }
287
288 globalThis.EventSource = EventSource;
289})();