stream.ts68 lines, 2.2 KB
| 1 | import { sleep } from './api' |
| 2 | |
| 3 | export type LiveEvent = { id: string; event: string; data: string } |
| 4 | export type Status = 'live' | 'away' |
| 5 | |
| 6 | // parser turns text/event-stream into events. A chunk can end in the |
| 7 | // middle of an event, so what's left waits for the next chunk. |
| 8 | export function parser(onEvent: (e: LiveEvent) => void) { |
| 9 | let rest = '' |
| 10 | return (chunk: string) => { |
| 11 | const blocks = (rest + chunk).split(/\r?\n\r?\n/) |
| 12 | rest = blocks.pop() ?? '' |
| 13 | for (const block of blocks) { |
| 14 | const e = { id: '', event: 'message', data: '' } |
| 15 | for (const line of block.split(/\r?\n/)) { |
| 16 | // ": still here" is a comment, and doesn't match |
| 17 | const [, field, value] = /^(\w+): ?(.*)$/.exec(line) ?? [] |
| 18 | if (field === 'data') e.data += (e.data && '\n') + value |
| 19 | if (field === 'id' || field === 'event') e[field] = value |
| 20 | } |
| 21 | if (e.data) onEvent(e) |
| 22 | } |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | // listen holds GET /live open until signal aborts. EventSource can't |
| 27 | // send a token, so this is fetch and a reader. After a break it waits |
| 28 | // 1, 2, 4… up to 30 seconds, or what Retry-After says, and asks for |
| 29 | // what it missed with Last-Event-ID. |
| 30 | export async function listen( |
| 31 | token: string, |
| 32 | onEvent: (e: LiveEvent) => void, |
| 33 | onStatus: (s: Status) => void, |
| 34 | signal: AbortSignal, |
| 35 | ) { |
| 36 | const headers: Record<string, string> = { |
| 37 | Authorization: `Bearer ${token}`, |
| 38 | } |
| 39 | const parse = parser((e) => { |
| 40 | if (e.id) headers['Last-Event-ID'] = e.id |
| 41 | onEvent(e) |
| 42 | }) |
| 43 | let wait = 1000 |
| 44 | while (!signal.aborted) { |
| 45 | try { |
| 46 | const res = await fetch('/api/live', { headers, signal }) |
| 47 | const after = Number(res.headers.get('Retry-After')) * 1000 |
| 48 | wait = Math.max(wait, after) |
| 49 | if (res.ok && res.body) { |
| 50 | onStatus('live') |
| 51 | wait = 1000 |
| 52 | const text = res.body.pipeThrough(new TextDecoderStream()) |
| 53 | const reader = text.getReader() |
| 54 | for (;;) { |
| 55 | const { done, value } = await reader.read() |
| 56 | if (done) break |
| 57 | parse(value) |
| 58 | } |
| 59 | } |
| 60 | } catch { |
| 61 | // the network is gone, or we stopped: the loop decides |
| 62 | } |
| 63 | if (signal.aborted) return |
| 64 | onStatus('away') |
| 65 | await sleep(wait + Math.random() * 500) |
| 66 | wait = Math.min(wait * 2, 30_000) |
| 67 | } |
| 68 | } |