-
Notifications
You must be signed in to change notification settings - Fork 7
/
events.js
321 lines (294 loc) · 8.59 KB
/
events.js
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
import { writable } from 'svelte/store'
import { ok } from './ok'
import { error } from './error'
function uuid({ short } = { short: false }) {
let dt = new Date().getTime()
const BLUEPRINT = short ? 'xyxxyxyx' : 'xxxxxxxx-xxxx-yxxx-yxxx-xxxxxxxxxxxx'
const RESULT = BLUEPRINT.replace(/[xy]/g, function check(c) {
const r = (dt + Math.random() * 16) % 16 | 0
dt = Math.floor(dt / 16)
return (c == 'x' ? r : (r & 0x3) | 0x8).toString(16)
})
return RESULT
}
/**
* @typedef CreateEmitterPayload
* @property {ReadableStreamDefaultController} controller
* @property {{connected:boolean}} context
*/
/**
*
* @param {CreateEmitterPayload} payload
* @returns {(eventName:string,data:string)=>import('./types').Unsafe<void>}}
*/
function createEmitter({ controller, context }) {
let id = 1
const encoder = new TextEncoder()
return function emit(eventName, data) {
if (!context.connected) {
return error('Client disconnected from the stream.')
}
const typeOfEventName = typeof eventName
const typeOfData = typeof data
if (typeOfEventName !== 'string') {
return error(
`Event name must of type \`string\`, received \`${typeOfEventName}\`.`,
)
}
if (typeOfData !== 'string') {
return error(
`Event data must of type \`string\`, received \`${typeOfData}\`.`,
)
}
if (eventName.includes('\n')) {
return error(
`Event name must not contain new line characters, received "${eventName}".`,
)
}
try {
controller.enqueue(encoder.encode(`id: ${id}\nevent: ${eventName}\n`))
const chunks = data.split('\n')
for (const chunk of chunks) {
controller.enqueue(
encoder.encode(`data: ${encodeURIComponent(chunk)}\n`),
)
}
controller.enqueue(encoder.encode('\n'))
id++
return ok()
} catch (e) {
return error(e)
}
}
}
/**
* @type {Map<string,NodeJS.Timeout>}
*/
const timeouts = new Map()
/**
* @type {Map<string,import('svelte/store').Writable<boolean>>}
*/
const locks = new Map()
/**
* @typedef StreamContext
* @property {boolean} connected
*/
/**
* @typedef CreateTimeoutAndLockPayload
* @property {StreamContext} context
* @property {number} timeout
*/
/**
* @typedef CreateTimeoutPayload
* @property {StreamContext} context
* @property {import('svelte/store').Writable<boolean>} lock
* @property {number} timeout
*/
/**
*
* @param {CreateTimeoutPayload} payload
* @returns
*/
function createTimeout({ context, lock, timeout }) {
return setTimeout(async function run() {
if (!context.connected) {
return
}
lock.set(false)
}, timeout)
}
/**
* @typedef CreateStreamPayload
* @property {Start} start
* @property {string} id
* @property {import('svelte/store').Writable<boolean>} lock
* @property {StreamContext} context
* @property {number} timeout
* @property {Cancel} [cancel]
*/
/**
*
* @param {CreateStreamPayload} payload
* @returns
*/
function createStream({ start, id, lock, context, cancel, timeout }) {
return new ReadableStream({
async start(controller) {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const self = this
const emit = createEmitter({ controller, context })
const started = start({ source: self, emit, lock })
/**
*
* @param {{$lock:boolean}} payload
* @returns {Promise<boolean>}
*/
async function stop({ $lock }) {
if ($lock || !context.connected) {
return false
}
try {
controller.close()
} catch {
// Do nothing.
// This means the client has already disconnected without notice.
}
context.connected = false
const cancelInline = await started
if (cancelInline) {
await cancelInline(self)
}
if (cancel) {
await cancel(self)
}
return true
}
const unsubscribe = lock.subscribe(async function run($lock) {
if (await stop({ $lock })) {
unsubscribe()
}
})
if (timeout > 0) {
timeouts.set(id, createTimeout({ context, timeout, lock }))
}
},
cancel() {
lock.set(false)
},
})
}
/**
* @callback OnCancel
* @param {UnderlyingDefaultSource<string>} stream
* @returns {void|PromiseLike<void>}
*/
/**
* @typedef Connection
* @property {(eventName:string,data:string)=>import('./types').Unsafe<void>} emit Emit events to the client.\
* The `Unsafe<void>` wrapper may contain an error
* ## Example
* ```js
* const {error} = emit('message', 'hello world')
* if(error){
* console.error(error)
* lock.set(false)
* return
* }
* ```
* @property {import("svelte/store").Writable<boolean>} lock This store is initialized with `true`,
* it prevents the underlying `Response` from resolving automatically.\
* Set it to `false` in order to unlock the `Response` and end the stream immediately.
*
* > **Note**\
* > You shouldn't `emit` any more events after setting the lock to `false`.\
* > Attempting to emit more data afterwards will result into an error.
* > ```js
* > lock.set(false)
* > const {error} = emit('message', 'hello world')
* > if(error){
* > console.error(error) // "Client disconnected from the stream."
* > return
* > }
* > ```
* @property {UnderlyingDefaultSource<string>} source
*/
/**
* @callback Start
* @param {Connection} payload
* @returns {void|Cancel|PromiseLike<Cancel>}
*/
/**
* @callback Cancel
* @param {UnderlyingDefaultSource<string>} stream
* @returns {void|PromiseLike<void>}
*/
/**
* test
* @typedef EventsPayload
* @property {Request} request
* @property {Start} start The stream has started, run all your logic inside this function.
* > **Warning**\
* > You should delegate all code that you would normally write directly under your `export function POST` function to this method instead.\
* > That is because the whole endpoint is actually going to be used to collect beacon signals from the client in order to correctly detect inactivity or disconnected clients.\
* > Beacon signals will be collected repeatedly (by default every `5 seconds`), thus, unless you want to collect that beacon data, you should put all your code inside this `start` function, which will get triggered only once per client connection: the first time they connect.
* > ## Example
* > ```js
* > export function POST({ request }) {
* > return events({
* > request,
* > timeout: 3000,
* > start({emit}) {
* > const notifications = [
* > { title: 'title-1', body: 'lorem...' },
* > { title: 'title-2', body: 'lorem...' },
* > { title: 'title-3', body: 'lorem...' },
* > ]
* > notifications.forEach(function pass(notification){
* > emit('notification', JSON.stringify(notification))
* > })
* > }
* > })
}
* > ```
* @property {Record<string, string>} [headers]
* @property {Cancel} [cancel] Do something when the stream is canceled.\
* The following qualify as "canceling"
* - Calling `.cancel` on the underlying `ReadableStream`
* - Calling `lock.set(false)`
* - Timeout due to missing beacon signals
* @property {number} [timeout] A countdown in `milliseconds`.\
* If it expires the stream ends immediately.\
* Each client can send a beacon to the server to reset this timeout and keep the stream online.
*
* > **Note**\
* > You can set the `timeout` to `0` or a negative value to disable this behavior and let
* > the stream live indefinitely or until you manually close it through `lock.set(false)`.
*/
/**
* Create one stream and emit multiple server sent events.
* @param {EventsPayload} payload
*/
export function events({ start, cancel, request, headers, timeout = 7000 }) {
/**
* @type {StreamContext}
*/
const context = { connected: true }
const parts = request.url.split('?')
let id = 2 === parts.length ? parts[1] ?? '' : ''
if (id) {
const timeoutOld = timeouts.get(id)
if (timeoutOld) {
clearTimeout(timeoutOld)
const lock = locks.get(id)
if (timeout <= 0 || !lock) {
return new Response()
}
timeouts.set(id, createTimeout({ timeout, context, lock }))
locks.set(id, lock)
}
return new Response()
}
do {
id = uuid({ short: false })
} while (timeouts.has(id))
const lock = writable(true)
locks.set(id, lock)
const stream = createStream({
start,
timeout,
id,
lock,
cancel,
context,
})
return new Response(stream, {
//@ts-ignore
headers: {
'Cache-Control': 'no-store',
'Content-Type': 'text/event-stream',
'Connection': 'keep-alive',
...headers,
'x-sse-id': id,
},
})
}