forked from oakserver/oak
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server_sent_event.ts
427 lines (385 loc) · 12.4 KB
/
server_sent_event.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
// Copyright 2018-2021 the oak authors. All rights reserved. MIT license.
import type { Application } from "./application.ts";
import type { Context } from "./context.ts";
import { assert, BufWriter } from "./deps.ts";
import { NativeRequest } from "./http_server_native.ts";
import type { ServerRequest } from "./http_server_std.ts";
const encoder = new TextEncoder();
export interface ServerSentEventInit extends EventInit {
/** An optional `id` which will be sent with the event and exposed in the
* client `EventSource`. */
id?: number;
/** The replacer is passed to `JSON.stringify` when converting the `data`
* property to a JSON string. */
replacer?:
| (string | number)[]
// deno-lint-ignore no-explicit-any
| ((this: any, key: string, value: any) => any);
/** Space is passed to `JSON.stringify` when converting the `data` property
* to a JSON string. */
space?: string | number;
}
export interface ServerSentEventTargetOptions {
/** Additional headers to send to the client during startup. These headers
* will overwrite any of the default headers if the key is duplicated. */
headers?: Headers;
}
class CloseEvent extends Event {
constructor(eventInit: EventInit) {
super("close", eventInit);
}
}
/** An event which contains information which will be sent to the remote
* connection and be made available in an `EventSource` as an event. */
export class ServerSentEvent extends Event {
#data: string;
#id?: number;
#type: string;
constructor(
type: string,
// deno-lint-ignore no-explicit-any
data: any,
{ replacer, space, ...eventInit }: ServerSentEventInit = {},
) {
super(type, eventInit);
this.#type = type;
try {
this.#data = typeof data === "string"
? data
: JSON.stringify(data, replacer as (string | number)[], space);
} catch (e) {
assert(e instanceof Error);
throw new TypeError(
`data could not be coerced into a serialized string.\n ${e.message}`,
);
}
const { id } = eventInit;
this.#id = id;
}
/** The data associated with the event, which will be sent to the client and
* be made available in the `EventSource`. */
get data(): string {
return this.#data;
}
/** The optional ID associated with the event that will be sent to the client
* and be made available in the `EventSource`. */
get id(): number | undefined {
return this.#id;
}
toString(): string {
const data = `data: ${this.#data.split("\n").join("\ndata: ")}\n`;
return `${this.#type === "__message" ? "" : `event: ${this.#type}\n`}${
this.#id ? `id: ${String(this.#id)}\n` : ""
}${data}\n`;
}
}
const response = `HTTP/1.1 200 OK\n`;
const responseHeaders = new Headers(
[
["Connection", "Keep-Alive"],
["Content-Type", "text/event-stream"],
["Cache-Control", "no-cache"],
["Keep-Alive", `timeout=${Number.MAX_SAFE_INTEGER}`],
],
);
export interface ServerSentEventTarget extends EventTarget {
/** Is set to `true` if events cannot be sent to the remote connection.
* Otherwise it is set to `false`.
*
* *Note*: This flag is lazily set, and might not reflect a closed state until
* another event, comment or message is attempted to be processed. */
readonly closed: boolean;
/** Close the target, refusing to accept any more events. */
close(): Promise<void>;
/** Send a comment to the remote connection. Comments are not exposed to the
* client `EventSource` but are used for diagnostics and helping ensure a
* connection is kept alive.
*
* ```ts
* import { Application } from "https://deno.land/x/oak/mod.ts";
*
* const app = new Application();
*
* app.use((ctx) => {
* const sse = ctx.getSSETarget();
* sse.dispatchComment("this is a comment");
* });
*
* await app.listen();
* ```
*/
dispatchComment(comment: string): boolean;
/** Dispatch a message to the client. This message will contain `data: ` only
* and be available on the client `EventSource` on the `onmessage` or an event
* listener of type `"message"`. */
// deno-lint-ignore no-explicit-any
dispatchMessage(data: any): boolean;
/** Dispatch a server sent event to the client. The event `type` will be
* sent as `event: ` to the client which will be raised as a `MessageEvent`
* on the `EventSource` in the client.
*
* Any local event handlers will be dispatched to first, and if the event
* is cancelled, it will not be sent to the client.
*
* ```ts
* import { Application, ServerSentEvent } from "https://deno.land/x/oak/mod.ts";
*
* const app = new Application();
*
* app.use((ctx) => {
* const sse = ctx.getSSETarget();
* const evt = new ServerSentEvent("ping", "hello");
* sse.dispatchEvent(evt);
* });
*
* await app.listen();
* ```
*/
dispatchEvent(event: ServerSentEvent): boolean;
/** Dispatch a server sent event to the client. The event `type` will be
* sent as `event: ` to the client which will be raised as a `MessageEvent`
* on the `EventSource` in the client.
*
* Any local event handlers will be dispatched to first, and if the event
* is cancelled, it will not be sent to the client.
*
* ```ts
* import { Application, ServerSentEvent } from "https://deno.land/x/oak/mod.ts";
*
* const app = new Application();
*
* app.use((ctx) => {
* const sse = ctx.getSSETarget();
* const evt = new ServerSentEvent("ping", "hello");
* sse.dispatchEvent(evt);
* });
*
* await app.listen();
* ```
*/
dispatchEvent(event: CloseEvent | ErrorEvent): boolean;
}
export class SSEStreamTarget extends EventTarget
implements ServerSentEventTarget {
#closed = false;
#context: Context;
#controller?: ReadableStreamDefaultController<Uint8Array>;
// deno-lint-ignore no-explicit-any
#error(error: any) {
this.dispatchEvent(new CloseEvent({ cancelable: false }));
const errorEvent = new ErrorEvent("error", { error });
this.dispatchEvent(errorEvent);
this.#context.app.dispatchEvent(errorEvent);
}
#push(payload: string) {
if (!this.#controller) {
this.#error(new Error("The controller has not been set."));
return;
}
if (this.#closed) {
return;
}
this.#controller.enqueue(encoder.encode(payload));
}
get closed(): boolean {
return this.#closed;
}
constructor(
context: Context,
{ headers }: ServerSentEventTargetOptions = {},
) {
super();
this.#context = context;
context.response.body = new ReadableStream<Uint8Array>({
start: (controller) => {
this.#controller = controller;
},
cancel: (error) => {
this.#error(error);
},
});
if (headers) {
for (const [key, value] of headers) {
context.response.headers.set(key, value);
}
}
for (const [key, value] of responseHeaders) {
context.response.headers.set(key, value);
}
this.addEventListener("close", () => {
this.#closed = true;
if (this.#controller) {
this.#controller.close();
}
});
}
close(): Promise<void> {
this.dispatchEvent(new CloseEvent({ cancelable: false }));
return Promise.resolve();
}
dispatchComment(comment: string): boolean {
this.#push(`: ${comment.split("\n").join("\n: ")}\n\n`);
return true;
}
// deno-lint-ignore no-explicit-any
dispatchMessage(data: any): boolean {
const event = new ServerSentEvent("__message", data);
return this.dispatchEvent(event);
}
dispatchEvent(event: ServerSentEvent): boolean;
dispatchEvent(event: CloseEvent | ErrorEvent): boolean;
dispatchEvent(event: ServerSentEvent | CloseEvent | ErrorEvent): boolean {
const dispatched = super.dispatchEvent(event);
if (dispatched && event instanceof ServerSentEvent) {
this.#push(String(event));
}
return dispatched;
}
}
export class SSEStdLibTarget extends EventTarget
implements ServerSentEventTarget {
#app: Application;
#closed = false;
#prev = Promise.resolve();
#ready: Promise<void> | true;
#serverRequest: ServerRequest;
#writer: BufWriter;
async #send(payload: string, prev: Promise<void>): Promise<void> {
if (this.#closed) {
return;
}
if (this.#ready !== true) {
await this.#ready;
this.#ready = true;
}
try {
await prev;
await this.#writer.write(encoder.encode(payload));
await this.#writer.flush();
} catch (error) {
this.dispatchEvent(new CloseEvent({ cancelable: false }));
const errorEvent = new ErrorEvent("error", { error });
this.dispatchEvent(errorEvent);
this.#app.dispatchEvent(errorEvent);
}
}
async #setup(overrideHeaders?: Headers): Promise<void> {
const headers = new Headers(responseHeaders);
if (overrideHeaders) {
for (const [key, value] of overrideHeaders) {
headers.set(key, value);
}
}
let payload = response;
for (const [key, value] of headers) {
payload += `${key}: ${value}\n`;
}
payload += `\n`;
try {
await this.#writer.write(encoder.encode(payload));
await this.#writer.flush();
} catch (error) {
this.dispatchEvent(new CloseEvent({ cancelable: false }));
const errorEvent = new ErrorEvent("error", { error });
this.dispatchEvent(errorEvent);
this.#app.dispatchEvent(errorEvent);
throw error;
}
}
get closed(): boolean {
return this.#closed;
}
constructor(
context: Context,
{ headers }: ServerSentEventTargetOptions = {},
) {
super();
this.#app = context.app;
assert(!(context.request.originalRequest instanceof NativeRequest));
this.#serverRequest = context.request.originalRequest;
this.#writer = this.#serverRequest.w;
this.addEventListener("close", () => {
this.#closed = true;
try {
this.#serverRequest.conn.close();
} catch (error) {
if (!(error instanceof Deno.errors.BadResource)) {
const errorEvent = new ErrorEvent("error", { error });
this.dispatchEvent(errorEvent);
this.#app.dispatchEvent(errorEvent);
}
}
});
this.#ready = this.#setup(headers);
}
/** Stop sending events to the remote connection and close the connection. */
async close(): Promise<void> {
if (this.#ready !== true) {
await this.#ready;
}
await this.#prev;
this.dispatchEvent(new CloseEvent({ cancelable: false }));
}
/** Send a comment to the remote connection. Comments are not exposed to the
* client `EventSource` but are used for diagnostics and helping ensure a
* connection is kept alive.
*
* ```ts
* import { Application } from "https://deno.land/x/oak/mod.ts";
*
* const app = new Application();
*
* app.use((ctx) => {
* const sse = ctx.getSSETarget();
* sse.dispatchComment("this is a comment");
* });
*
* await app.listen();
* ```
*/
dispatchComment(comment: string): boolean {
this.#prev = this.#send(
`: ${comment.split("\n").join("\n: ")}\n\n`,
this.#prev,
);
return true;
}
/** Dispatch a message to the client. This message will contain `data: ` only
* and be available on the client `EventSource` on the `onmessage` or an event
* listener of type `"message"`. */
// deno-lint-ignore no-explicit-any
dispatchMessage(data: any): boolean {
const event = new ServerSentEvent("__message", data);
return this.dispatchEvent(event);
}
/** Dispatch a server sent event to the client. The event `type` will be
* sent as `event: ` to the client which will be raised as a `MessageEvent`
* on the `EventSource` in the client.
*
* Any local event handlers will be dispatched to first, and if the event
* is cancelled, it will not be sent to the client.
*
* ```ts
* import { Application, ServerSentEvent } from "https://deno.land/x/oak/mod.ts";
*
* const app = new Application();
*
* app.use((ctx) => {
* const sse = ctx.getSSETarget();
* const evt = new ServerSentEvent("ping", "hello");
* sse.dispatchEvent(evt);
* });
*
* await app.listen();
* ```
*/
dispatchEvent(event: ServerSentEvent): boolean;
dispatchEvent(event: CloseEvent | ErrorEvent): boolean;
dispatchEvent(event: ServerSentEvent | CloseEvent | ErrorEvent): boolean {
const dispatched = super.dispatchEvent(event);
if (dispatched && event instanceof ServerSentEvent) {
this.#prev = this.#send(String(event), this.#prev);
}
return dispatched;
}
}