@prunellejs/live 0.0.0-stage → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/llms.txt +56 -0
- package/package.json +25 -4
- package/src/client.ts +148 -0
- package/src/index.ts +385 -0
- package/README.md +0 -3
package/llms.txt
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
# @prunellejs/live Reference
|
|
2
|
+
|
|
3
|
+
> Zero-dependency typed Server-Sent Events (SSE) rooms, microtask-coalesced broadcasts, connection caps, backpressure handling, and a reactive `useLive()` browser hook.
|
|
4
|
+
|
|
5
|
+
## Imports
|
|
6
|
+
|
|
7
|
+
- `@prunellejs/live`: `createRooms`; types `Rooms`, `RoomsOptions`, `RoomsEndpointOptions`, `StreamOptions`, `Subscriber`, `ConnectionLimits`, `LiveAuthorizeHook`.
|
|
8
|
+
- `@prunellejs/live/client`: `useLive`; types `LiveConnection`, `LiveStatus`, `UseLiveOptions`.
|
|
9
|
+
|
|
10
|
+
## Server Setup (`createRooms<TMessage, TMember>(options?)`)
|
|
11
|
+
|
|
12
|
+
`createRooms()` returns a single object that is both the `PrunellePlugin` (register in `prunelle.config.ts` so streams close on `api.onShutdown()`) and the handle routes/actions publish with:
|
|
13
|
+
|
|
14
|
+
- Mounted endpoint mode (`path` set): mounts `GET <path>` as `text/event-stream`.
|
|
15
|
+
- `path`: route path (e.g. `'/api/events'`).
|
|
16
|
+
- `room`: room name or `(ctx: RequestContext) => string` (default `'default'`).
|
|
17
|
+
- `member`: `(ctx: RequestContext) => TMember | Promise<TMember>` (required when `path` is set).
|
|
18
|
+
- `authorize`: `(ctx, room) => boolean | Response | Promise<boolean | Response>` (`false` → `403`).
|
|
19
|
+
- `pingMs`: keepalive interval in ms (default `20000`, `0` disables).
|
|
20
|
+
- `onJoin(room, member)`, `onLeave(room, member)`.
|
|
21
|
+
- Manual route mode (omit `path`): no route mounted; return `rooms.stream(ctx, { room, member, pingMs?, onJoin?, onLeave?, ...limits })` from a `GET` route handler.
|
|
22
|
+
- `ConnectionLimits`: `maxConnectionsPerRoom` (`1000`), `maxConnectionsPerClient` (`10`, returns `429`), `maxTotalConnections` (`10000`, returns `503`), `clientKey(ctx)` (defaults to `ctx.ip`), `highWaterMark` (`64`).
|
|
23
|
+
|
|
24
|
+
## Handle Methods & Client Hook
|
|
25
|
+
|
|
26
|
+
- `rooms.publish(room, message, event?, id?)`: broadcasts JSON-serialized SSE frames to all room subscribers.
|
|
27
|
+
- `rooms.coalesce(build, event?)`: returns `(room) => void` that batches burst updates into one microtask broadcast per room.
|
|
28
|
+
- `rooms.members(room)`, `rooms.size(room)`, `rooms.stream(ctx, opts)`, `rooms.join(room, sub)`, `rooms.leave(room, sub)`.
|
|
29
|
+
- `useLive<TMessage>(url, onMessage?, options?)` (`@prunellejs/live/client`): returns `{ status: Signal<'connecting' | 'open' | 'closed'>, last: Signal<TMessage | undefined>, close() }` with exponential-backoff reconnect (`baseDelayMs`, `maxDelayMs`, `jitterMs`, `events`, `withCredentials`) and automatic `onMount` cleanup.
|
|
30
|
+
|
|
31
|
+
## Snippets
|
|
32
|
+
|
|
33
|
+
```ts
|
|
34
|
+
// src/rooms.ts (and register `plugins: [chat]` in prunelle.config.ts)
|
|
35
|
+
import { createRooms } from '@prunellejs/live'
|
|
36
|
+
|
|
37
|
+
export type ChatMsg = { from: string, text: string }
|
|
38
|
+
export const chat = createRooms<ChatMsg, { name: string }>({
|
|
39
|
+
path: '/api/chat',
|
|
40
|
+
room: ctx => ctx.url.searchParams.get('room') ?? 'general',
|
|
41
|
+
member: ctx => ({ name: ctx.locals.user?.name ?? 'guest' }),
|
|
42
|
+
})
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
```tsx
|
|
46
|
+
// src/components/ChatFeed.tsx (auto-island)
|
|
47
|
+
import { signal } from 'prunelle'
|
|
48
|
+
import { useLive } from '@prunellejs/live/client'
|
|
49
|
+
import type { ChatMsg } from '../rooms'
|
|
50
|
+
|
|
51
|
+
export function ChatFeed({ room }: { room: string }) {
|
|
52
|
+
const messages = signal<ChatMsg[]>([])
|
|
53
|
+
const live = useLive<ChatMsg>(`/api/chat?room=${room}`, m => { messages.value = [...messages.value, m] })
|
|
54
|
+
return <section data-status={live.status.value}>{messages.value.map((m, i) => <p key={i}>{m.from}: {m.text}</p>)}</section>
|
|
55
|
+
}
|
|
56
|
+
```
|
package/package.json
CHANGED
|
@@ -1,6 +1,27 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prunellejs/live",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.6.0",
|
|
4
|
+
"description": "Zero-dependency typed SSE rooms and coalesced presence plugin for Prunelle",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"files": [
|
|
9
|
+
"src",
|
|
10
|
+
"llms.txt"
|
|
11
|
+
],
|
|
12
|
+
"exports": {
|
|
13
|
+
".": "./src/index.ts",
|
|
14
|
+
"./client": "./src/client.ts"
|
|
15
|
+
},
|
|
16
|
+
"engines": {
|
|
17
|
+
"bun": ">=1.4.0"
|
|
18
|
+
},
|
|
19
|
+
"repository": {
|
|
20
|
+
"type": "git",
|
|
21
|
+
"url": "https://github.com/Kayno0o/prunelle",
|
|
22
|
+
"directory": "packages/plugin-live"
|
|
23
|
+
},
|
|
24
|
+
"peerDependencies": {
|
|
25
|
+
"prunelle": "^0.6.0"
|
|
26
|
+
}
|
|
27
|
+
}
|
package/src/client.ts
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
// Browser client helper for @prunellejs/live SSE rooms (~65 LOC, zero dependencies).
|
|
2
|
+
|
|
3
|
+
import type { Signal } from 'prunelle'
|
|
4
|
+
import { onMount, signal } from 'prunelle'
|
|
5
|
+
|
|
6
|
+
export type LiveStatus = 'connecting' | 'open' | 'closed'
|
|
7
|
+
|
|
8
|
+
export interface LiveConnection<TMessage> {
|
|
9
|
+
readonly status: Signal<LiveStatus>
|
|
10
|
+
readonly last: Signal<TMessage | undefined>
|
|
11
|
+
close(): void
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface UseLiveOptions {
|
|
15
|
+
/** Base reconnect delay in milliseconds after EventSource enters CLOSED state (default: 1000). */
|
|
16
|
+
baseDelayMs?: number | undefined
|
|
17
|
+
/** Maximum exponential backoff delay in milliseconds before jitter (default: 30000). */
|
|
18
|
+
maxDelayMs?: number | undefined
|
|
19
|
+
/** Maximum random jitter added in milliseconds (default: 30% of current delay). */
|
|
20
|
+
jitterMs?: number | undefined
|
|
21
|
+
/** Maximum consecutive failed reconnect attempts before staying closed (default: 5; resets on open). */
|
|
22
|
+
maxRetries?: number | undefined
|
|
23
|
+
/** Named SSE `event:` types to listen for in addition to default unnamed `message` events. */
|
|
24
|
+
events?: readonly string[] | undefined
|
|
25
|
+
/** Send cookies / credentials on cross-origin EventSource connections. */
|
|
26
|
+
withCredentials?: boolean | undefined
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const DEFAULT_BASE_DELAY_MS = 1_000
|
|
30
|
+
const DEFAULT_MAX_DELAY_MS = 30_000
|
|
31
|
+
const DEFAULT_MAX_RETRIES = 5
|
|
32
|
+
const DEFAULT_INITIAL_MAX_RETRIES = 2
|
|
33
|
+
|
|
34
|
+
function isPermanentHttpStatus(status: unknown): boolean {
|
|
35
|
+
return typeof status === 'number' && status >= 400 && status < 500 && status !== 408 && status !== 429
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function useLive<TMessage>(
|
|
39
|
+
url: string,
|
|
40
|
+
onMessage?: (message: TMessage) => void,
|
|
41
|
+
options?: UseLiveOptions,
|
|
42
|
+
): LiveConnection<TMessage> {
|
|
43
|
+
const status = signal<LiveStatus>('connecting')
|
|
44
|
+
const last = signal<TMessage | undefined>(undefined)
|
|
45
|
+
let source: EventSource | undefined
|
|
46
|
+
let reconnectTimer: ReturnType<typeof setTimeout> | undefined
|
|
47
|
+
let attempt = 0
|
|
48
|
+
let hasOpened = false
|
|
49
|
+
let manuallyClosed = false
|
|
50
|
+
|
|
51
|
+
const clearReconnectTimer = () => {
|
|
52
|
+
if (reconnectTimer !== undefined) {
|
|
53
|
+
clearTimeout(reconnectTimer)
|
|
54
|
+
reconnectTimer = undefined
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const close = () => {
|
|
59
|
+
manuallyClosed = true
|
|
60
|
+
clearReconnectTimer()
|
|
61
|
+
source?.close()
|
|
62
|
+
source = undefined
|
|
63
|
+
status.value = 'closed'
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const connect = () => {
|
|
67
|
+
if (manuallyClosed)
|
|
68
|
+
return
|
|
69
|
+
clearReconnectTimer()
|
|
70
|
+
status.value = 'connecting'
|
|
71
|
+
const es = options?.withCredentials !== undefined
|
|
72
|
+
? new EventSource(url, { withCredentials: options.withCredentials })
|
|
73
|
+
: new EventSource(url)
|
|
74
|
+
source = es
|
|
75
|
+
|
|
76
|
+
es.onopen = () => {
|
|
77
|
+
if (source !== es || manuallyClosed)
|
|
78
|
+
return
|
|
79
|
+
hasOpened = true
|
|
80
|
+
attempt = 0
|
|
81
|
+
status.value = 'open'
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
es.onerror = (ev?: Event) => {
|
|
85
|
+
if (source !== es || manuallyClosed)
|
|
86
|
+
return
|
|
87
|
+
const errStatus = (ev as { status?: unknown } | undefined)?.status
|
|
88
|
+
if (isPermanentHttpStatus(errStatus)) {
|
|
89
|
+
es.close()
|
|
90
|
+
source = undefined
|
|
91
|
+
status.value = 'closed'
|
|
92
|
+
return
|
|
93
|
+
}
|
|
94
|
+
if (es.readyState === EventSource.CLOSED) {
|
|
95
|
+
es.close()
|
|
96
|
+
status.value = 'closed'
|
|
97
|
+
source = undefined
|
|
98
|
+
const maxRetries = options?.maxRetries ?? (hasOpened ? DEFAULT_MAX_RETRIES : DEFAULT_INITIAL_MAX_RETRIES)
|
|
99
|
+
if (attempt >= maxRetries)
|
|
100
|
+
return
|
|
101
|
+
const base = options?.baseDelayMs ?? DEFAULT_BASE_DELAY_MS
|
|
102
|
+
const max = options?.maxDelayMs ?? DEFAULT_MAX_DELAY_MS
|
|
103
|
+
const exp = Math.min(max, base * 2 ** attempt++)
|
|
104
|
+
const maxJitter = options?.jitterMs ?? Math.max(1, Math.floor(exp * 0.3))
|
|
105
|
+
const jitter = maxJitter > 0 ? Math.floor(Math.random() * maxJitter) : 0
|
|
106
|
+
reconnectTimer = setTimeout(() => {
|
|
107
|
+
reconnectTimer = undefined
|
|
108
|
+
connect()
|
|
109
|
+
}, exp + jitter)
|
|
110
|
+
}
|
|
111
|
+
else {
|
|
112
|
+
status.value = 'connecting'
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const handleEvent = (ev: Event) => {
|
|
117
|
+
if (source !== es || manuallyClosed)
|
|
118
|
+
return
|
|
119
|
+
const data = (ev as MessageEvent<unknown>).data
|
|
120
|
+
if (typeof data !== 'string')
|
|
121
|
+
return
|
|
122
|
+
try {
|
|
123
|
+
const parsed = JSON.parse(data) as TMessage
|
|
124
|
+
last.value = parsed
|
|
125
|
+
onMessage?.(parsed)
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
// Ignore malformed non-JSON SSE frames.
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
es.onmessage = handleEvent
|
|
133
|
+
if (options?.events !== undefined) {
|
|
134
|
+
const seen = new Set(options.events)
|
|
135
|
+
seen.delete('message')
|
|
136
|
+
for (const name of seen)
|
|
137
|
+
es.addEventListener(name, handleEvent)
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
onMount(() => {
|
|
142
|
+
manuallyClosed = false
|
|
143
|
+
connect()
|
|
144
|
+
return close
|
|
145
|
+
})
|
|
146
|
+
|
|
147
|
+
return { status, last, close }
|
|
148
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
// @prunellejs/live — Zero-dependency typed real-time rooms, coalesced presence, and SSE streaming for Prunelle.
|
|
2
|
+
// Built strictly on Web Streams (text/event-stream) + PrunellePlugin (`api.route`) — zero core WebSocket coupling.
|
|
3
|
+
|
|
4
|
+
import type { PrunellePlugin } from 'prunelle/config'
|
|
5
|
+
import type { RequestContext } from 'prunelle/server'
|
|
6
|
+
import { definePlugin } from 'prunelle/config'
|
|
7
|
+
|
|
8
|
+
export interface Subscriber<TMember> {
|
|
9
|
+
readonly id: string
|
|
10
|
+
readonly member: TMember
|
|
11
|
+
send(chunk: Uint8Array): void
|
|
12
|
+
close(): void
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export type LiveAuthorizeHook = (
|
|
16
|
+
ctx: RequestContext,
|
|
17
|
+
room: string,
|
|
18
|
+
) => boolean | Response | Promise<boolean | Response>
|
|
19
|
+
|
|
20
|
+
export interface ConnectionLimits {
|
|
21
|
+
/** Maximum concurrent subscribers per room (default: 1000). */
|
|
22
|
+
maxConnectionsPerRoom?: number | undefined
|
|
23
|
+
/** Maximum concurrent subscribers per client key / IP (default: 10). */
|
|
24
|
+
maxConnectionsPerClient?: number | undefined
|
|
25
|
+
/** Maximum concurrent subscribers across all rooms (default: 10000). */
|
|
26
|
+
maxTotalConnections?: number | undefined
|
|
27
|
+
/** Derive a client key for per-client caps (defaults to ctx.ip; skipped when unavailable). */
|
|
28
|
+
clientKey?: ((ctx: RequestContext) => string | undefined) | undefined
|
|
29
|
+
/** ReadableStream queue high-water mark in bytes before dropping stalled subscribers (default: 65536). */
|
|
30
|
+
highWaterMark?: number | undefined
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
interface RoomsBaseOptions extends ConnectionLimits {
|
|
34
|
+
/** Optional authorization hook checked before opening an SSE stream. */
|
|
35
|
+
authorize?: LiveAuthorizeHook | undefined
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** The SSE endpoint the rooms plugin mounts at `path`, the member it streams as read from each request. */
|
|
39
|
+
export interface RoomsEndpointOptions<TMember> extends RoomsBaseOptions {
|
|
40
|
+
path: string
|
|
41
|
+
room?: string | ((ctx: RequestContext) => string) | undefined
|
|
42
|
+
member: (ctx: RequestContext) => TMember | Promise<TMember>
|
|
43
|
+
pingMs?: number | undefined
|
|
44
|
+
onJoin?: ((room: string, member: TMember) => void) | undefined
|
|
45
|
+
onLeave?: ((room: string, member: TMember) => void) | undefined
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Without `path`, no endpoint is mounted and routes open streams with `rooms.stream()`. */
|
|
49
|
+
export type RoomsOptions<TMember = undefined> = RoomsEndpointOptions<TMember> | (RoomsBaseOptions & { path?: undefined })
|
|
50
|
+
|
|
51
|
+
export interface StreamOptions<TMember> extends ConnectionLimits {
|
|
52
|
+
room: string
|
|
53
|
+
member: TMember
|
|
54
|
+
pingMs?: number | undefined
|
|
55
|
+
onJoin?: ((room: string, member: TMember) => void) | undefined
|
|
56
|
+
onLeave?: ((room: string, member: TMember) => void) | undefined
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** The plugin `prunelle.config.ts` registers (mounting the endpoint when `path` is set), and the handle routes publish with. */
|
|
60
|
+
export interface Rooms<TMessage, TMember = undefined> extends PrunellePlugin {
|
|
61
|
+
join(room: string, sub: Subscriber<TMember>): void
|
|
62
|
+
leave(room: string, sub: Subscriber<TMember>): void
|
|
63
|
+
members(room: string): TMember[]
|
|
64
|
+
size(room: string): number
|
|
65
|
+
publish(room: string, message: TMessage, event?: string, id?: string): void
|
|
66
|
+
/** Coalesce burst presence updates into a single microtask broadcast per room. */
|
|
67
|
+
coalesce(build: (room: string) => TMessage, event?: string): (room: string) => void
|
|
68
|
+
/** Create a streaming SSE Response for a room with automatic keepalive, caps, backpressure drop, and disconnect cleanup. */
|
|
69
|
+
stream(ctx: RequestContext, options: StreamOptions<TMember>): Response
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const DEFAULT_MAX_PER_ROOM = 1_000
|
|
73
|
+
const DEFAULT_MAX_PER_CLIENT = 10
|
|
74
|
+
const DEFAULT_MAX_TOTAL = 10_000
|
|
75
|
+
const DEFAULT_HIGH_WATER_MARK = 64 * 1024
|
|
76
|
+
|
|
77
|
+
const encoder = new TextEncoder()
|
|
78
|
+
const CR_LF_RE = /[\r\n]/
|
|
79
|
+
|
|
80
|
+
function assertSafeSseField(value: string | undefined, label: string): void {
|
|
81
|
+
if (value !== undefined && CR_LF_RE.test(value))
|
|
82
|
+
throw new RangeError(`@prunellejs/live: SSE ${label} must not contain CR or LF characters`)
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function encodeEvent(message: unknown, event?: string, id?: string): Uint8Array {
|
|
86
|
+
assertSafeSseField(event, 'event name')
|
|
87
|
+
assertSafeSseField(id, 'event id')
|
|
88
|
+
let frame = ''
|
|
89
|
+
if (id)
|
|
90
|
+
frame += `id: ${id}\n`
|
|
91
|
+
if (event)
|
|
92
|
+
frame += `event: ${event}\n`
|
|
93
|
+
const serialized = JSON.stringify(message) ?? 'null'
|
|
94
|
+
frame += `data: ${serialized}\n\n`
|
|
95
|
+
return encoder.encode(frame)
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// ctx.ip already honours `trustProxy`; a forwarded header read here would let any client pick its own key.
|
|
99
|
+
// Missing IPs return undefined rather than pooling unrelated users into one shared 'anonymous' bucket.
|
|
100
|
+
function defaultClientKey(ctx: RequestContext): string | undefined {
|
|
101
|
+
return ctx.ip || undefined
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const PING_CHUNK = encoder.encode(': ping\n\n')
|
|
105
|
+
const RETRY_CHUNK = encoder.encode('retry: 2000\n\n')
|
|
106
|
+
|
|
107
|
+
interface RoomState<TMember> {
|
|
108
|
+
readonly defaultOpts: RoomsOptions<TMember>
|
|
109
|
+
readonly clientCounts: Map<string, number>
|
|
110
|
+
join(room: string, sub: Subscriber<TMember>): void
|
|
111
|
+
leave(room: string, sub: Subscriber<TMember>): void
|
|
112
|
+
size(room: string): number
|
|
113
|
+
getActiveConnections(): number
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function openRoomStream<TMember>(
|
|
117
|
+
state: RoomState<TMember>,
|
|
118
|
+
ctx: RequestContext,
|
|
119
|
+
opts: StreamOptions<TMember>,
|
|
120
|
+
): Response {
|
|
121
|
+
const { room, member, pingMs = 20_000, onJoin, onLeave } = opts
|
|
122
|
+
const { defaultOpts, clientCounts } = state
|
|
123
|
+
const maxPerRoom = opts.maxConnectionsPerRoom ?? defaultOpts.maxConnectionsPerRoom ?? DEFAULT_MAX_PER_ROOM
|
|
124
|
+
const maxPerClient = opts.maxConnectionsPerClient ?? defaultOpts.maxConnectionsPerClient ?? DEFAULT_MAX_PER_CLIENT
|
|
125
|
+
const maxTotal = opts.maxTotalConnections ?? defaultOpts.maxTotalConnections ?? DEFAULT_MAX_TOTAL
|
|
126
|
+
const highWaterMark = opts.highWaterMark ?? defaultOpts.highWaterMark ?? DEFAULT_HIGH_WATER_MARK
|
|
127
|
+
const resolveClientKey = opts.clientKey ?? defaultOpts.clientKey ?? defaultClientKey
|
|
128
|
+
const rawClientId = resolveClientKey(ctx)
|
|
129
|
+
const clientId = rawClientId !== undefined && rawClientId.length > 0 ? rawClientId : undefined
|
|
130
|
+
|
|
131
|
+
if (clientId !== undefined && maxPerClient > 0 && (clientCounts.get(clientId) ?? 0) >= maxPerClient) {
|
|
132
|
+
return new Response('Too Many Requests', {
|
|
133
|
+
status: 429,
|
|
134
|
+
headers: { 'retry-after': '5' },
|
|
135
|
+
})
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
if ((maxPerRoom > 0 && state.size(room) >= maxPerRoom) || (maxTotal > 0 && state.getActiveConnections() >= maxTotal)) {
|
|
139
|
+
return new Response('Service Unavailable', {
|
|
140
|
+
status: 503,
|
|
141
|
+
headers: { 'retry-after': '5' },
|
|
142
|
+
})
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
let cleaned = false
|
|
146
|
+
let joined = false
|
|
147
|
+
let timer: ReturnType<typeof setInterval> | undefined
|
|
148
|
+
let sub: Subscriber<TMember> | undefined
|
|
149
|
+
let countedClient = false
|
|
150
|
+
let abortHandler: (() => void) | undefined
|
|
151
|
+
|
|
152
|
+
const cleanup = () => {
|
|
153
|
+
if (cleaned)
|
|
154
|
+
return
|
|
155
|
+
cleaned = true
|
|
156
|
+
if (abortHandler !== undefined) {
|
|
157
|
+
ctx.request.signal.removeEventListener('abort', abortHandler)
|
|
158
|
+
abortHandler = undefined
|
|
159
|
+
}
|
|
160
|
+
if (timer !== undefined) {
|
|
161
|
+
clearInterval(timer)
|
|
162
|
+
timer = undefined
|
|
163
|
+
}
|
|
164
|
+
if (countedClient && clientId !== undefined) {
|
|
165
|
+
countedClient = false
|
|
166
|
+
const remaining = (clientCounts.get(clientId) ?? 1) - 1
|
|
167
|
+
if (remaining <= 0)
|
|
168
|
+
clientCounts.delete(clientId)
|
|
169
|
+
else
|
|
170
|
+
clientCounts.set(clientId, remaining)
|
|
171
|
+
}
|
|
172
|
+
if (sub !== undefined) {
|
|
173
|
+
state.leave(room, sub)
|
|
174
|
+
if (joined)
|
|
175
|
+
onLeave?.(room, member)
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const body = new ReadableStream<Uint8Array>({
|
|
180
|
+
start(controller) {
|
|
181
|
+
const drop = () => {
|
|
182
|
+
cleanup()
|
|
183
|
+
try {
|
|
184
|
+
controller.close()
|
|
185
|
+
}
|
|
186
|
+
catch {
|
|
187
|
+
// Stream may already be closed or errored by the consumer.
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
sub = {
|
|
192
|
+
id: crypto.randomUUID(),
|
|
193
|
+
member,
|
|
194
|
+
send(chunk) {
|
|
195
|
+
if (cleaned)
|
|
196
|
+
return
|
|
197
|
+
if (controller.desiredSize !== null && controller.desiredSize <= 0) {
|
|
198
|
+
drop()
|
|
199
|
+
return
|
|
200
|
+
}
|
|
201
|
+
try {
|
|
202
|
+
controller.enqueue(chunk)
|
|
203
|
+
}
|
|
204
|
+
catch {
|
|
205
|
+
drop()
|
|
206
|
+
}
|
|
207
|
+
},
|
|
208
|
+
close: drop,
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
if (clientId !== undefined) {
|
|
212
|
+
clientCounts.set(clientId, (clientCounts.get(clientId) ?? 0) + 1)
|
|
213
|
+
countedClient = true
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
try {
|
|
217
|
+
controller.enqueue(RETRY_CHUNK)
|
|
218
|
+
state.join(room, sub)
|
|
219
|
+
joined = true
|
|
220
|
+
onJoin?.(room, member)
|
|
221
|
+
}
|
|
222
|
+
catch (err) {
|
|
223
|
+
joined = false
|
|
224
|
+
cleanup()
|
|
225
|
+
throw err
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
if (cleaned)
|
|
229
|
+
return
|
|
230
|
+
|
|
231
|
+
if (pingMs > 0) {
|
|
232
|
+
timer = setInterval(() => {
|
|
233
|
+
sub?.send(PING_CHUNK)
|
|
234
|
+
}, pingMs)
|
|
235
|
+
;(timer as unknown as { unref?: () => void }).unref?.()
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
if (ctx.request.signal.aborted) {
|
|
239
|
+
drop()
|
|
240
|
+
}
|
|
241
|
+
else {
|
|
242
|
+
abortHandler = drop
|
|
243
|
+
ctx.request.signal.addEventListener('abort', drop, { once: true })
|
|
244
|
+
}
|
|
245
|
+
},
|
|
246
|
+
cancel() {
|
|
247
|
+
cleanup()
|
|
248
|
+
},
|
|
249
|
+
}, { highWaterMark, size: chunk => chunk?.byteLength ?? 0 })
|
|
250
|
+
|
|
251
|
+
return new Response(body, {
|
|
252
|
+
status: 200,
|
|
253
|
+
headers: {
|
|
254
|
+
'content-type': 'text/event-stream; charset=utf-8',
|
|
255
|
+
'cache-control': 'no-cache, no-transform',
|
|
256
|
+
'x-accel-buffering': 'no',
|
|
257
|
+
},
|
|
258
|
+
})
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
export function createRooms<TMessage, TMember = undefined>(
|
|
262
|
+
options: RoomsOptions<TMember> = {},
|
|
263
|
+
): Rooms<TMessage, TMember> {
|
|
264
|
+
const defaultOpts: RoomsOptions<TMember> = options
|
|
265
|
+
|
|
266
|
+
const map = new Map<string, Set<Subscriber<TMember>>>()
|
|
267
|
+
const clientCounts = new Map<string, number>()
|
|
268
|
+
let activeConnections = 0
|
|
269
|
+
|
|
270
|
+
function join(room: string, sub: Subscriber<TMember>): void {
|
|
271
|
+
let set = map.get(room)
|
|
272
|
+
if (set === undefined) {
|
|
273
|
+
set = new Set()
|
|
274
|
+
map.set(room, set)
|
|
275
|
+
}
|
|
276
|
+
if (!set.has(sub)) {
|
|
277
|
+
set.add(sub)
|
|
278
|
+
activeConnections++
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function leave(room: string, sub: Subscriber<TMember>): void {
|
|
283
|
+
const set = map.get(room)
|
|
284
|
+
if (set === undefined)
|
|
285
|
+
return
|
|
286
|
+
if (set.delete(sub))
|
|
287
|
+
activeConnections--
|
|
288
|
+
if (set.size === 0)
|
|
289
|
+
map.delete(room)
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function members(room: string): TMember[] {
|
|
293
|
+
const set = map.get(room)
|
|
294
|
+
if (set === undefined)
|
|
295
|
+
return []
|
|
296
|
+
const out: TMember[] = []
|
|
297
|
+
for (const sub of set)
|
|
298
|
+
out.push(sub.member)
|
|
299
|
+
return out
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function size(room: string): number {
|
|
303
|
+
return map.get(room)?.size ?? 0
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
function publish(room: string, message: TMessage, event?: string, eventId?: string): void {
|
|
307
|
+
// Validate event & id eagerly even if room is empty so injection attempts always fail fast
|
|
308
|
+
assertSafeSseField(event, 'event name')
|
|
309
|
+
assertSafeSseField(eventId, 'event id')
|
|
310
|
+
const set = map.get(room)
|
|
311
|
+
if (set === undefined || set.size === 0)
|
|
312
|
+
return
|
|
313
|
+
const chunk = encodeEvent(message, event, eventId)
|
|
314
|
+
for (const sub of [...set]) {
|
|
315
|
+
try {
|
|
316
|
+
sub.send(chunk)
|
|
317
|
+
}
|
|
318
|
+
catch {
|
|
319
|
+
sub.close()
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function coalesce(build: (room: string) => TMessage, event?: string): (room: string) => void {
|
|
325
|
+
assertSafeSseField(event, 'event name')
|
|
326
|
+
const pending = new Set<string>()
|
|
327
|
+
return (room: string) => {
|
|
328
|
+
if (pending.has(room))
|
|
329
|
+
return
|
|
330
|
+
pending.add(room)
|
|
331
|
+
queueMicrotask(() => {
|
|
332
|
+
pending.delete(room)
|
|
333
|
+
if (size(room) > 0)
|
|
334
|
+
publish(room, build(room), event)
|
|
335
|
+
})
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
const roomState: RoomState<TMember> = {
|
|
340
|
+
defaultOpts,
|
|
341
|
+
clientCounts,
|
|
342
|
+
join,
|
|
343
|
+
leave,
|
|
344
|
+
size,
|
|
345
|
+
getActiveConnections: () => activeConnections,
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
function stream(ctx: RequestContext, opts: StreamOptions<TMember>): Response {
|
|
349
|
+
return openRoomStream(roomState, ctx, opts)
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
// An open stream would hold a graceful stop until its timeout.
|
|
353
|
+
function closeAll(): void {
|
|
354
|
+
for (const set of [...map.values()]) {
|
|
355
|
+
for (const sub of [...set])
|
|
356
|
+
sub.close()
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
function endpoint(opts: RoomsEndpointOptions<TMember>): PrunellePlugin {
|
|
361
|
+
if (typeof opts.member !== 'function')
|
|
362
|
+
throw new TypeError(`@prunellejs/live: createRooms({ path: '${opts.path}' }) needs member(ctx), the member each stream joins as`)
|
|
363
|
+
return definePlugin({
|
|
364
|
+
name: `@prunellejs/live(${opts.path})`,
|
|
365
|
+
server(api) {
|
|
366
|
+
api.onShutdown(closeAll)
|
|
367
|
+
api.route('GET', opts.path, async (ctx) => {
|
|
368
|
+
const room = typeof opts.room === 'function' ? opts.room(ctx) : (opts.room ?? 'default')
|
|
369
|
+
if (opts.authorize !== undefined) {
|
|
370
|
+
const decision = await opts.authorize(ctx, room)
|
|
371
|
+
if (decision instanceof Response)
|
|
372
|
+
return decision
|
|
373
|
+
if (decision === false)
|
|
374
|
+
return new Response('Forbidden', { status: 403 })
|
|
375
|
+
}
|
|
376
|
+
const member = await opts.member(ctx)
|
|
377
|
+
return stream(ctx, { ...opts, room, member })
|
|
378
|
+
})
|
|
379
|
+
},
|
|
380
|
+
})
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
const plugin = options.path === undefined ? definePlugin({ name: '@prunellejs/live', server: api => api.onShutdown(closeAll) }) : endpoint(options)
|
|
384
|
+
return { ...plugin, join, leave, members, size, publish, coalesce, stream }
|
|
385
|
+
}
|
package/README.md
DELETED