@prunellejs/live 0.0.0-stage → 0.7.2
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/LICENSE +21 -0
- package/llms.txt +57 -0
- package/package.json +25 -4
- package/src/client.ts +153 -0
- package/src/index.ts +443 -0
- package/README.md +0 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Kaynooo
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/llms.txt
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
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`); runs after the connection caps (`429` per client, `503` per room or total). Without it the channel is public and `prunelle check` warns `[live/authorize]`: pass `authorize: () => true` to say so.
|
|
19
|
+
- `pingMs`: keepalive interval in ms (default `20000`, `0` disables); one timer per interval serves every subscriber. A throwing `onJoin` or `onLeave` is logged, and the stream still closes and frees its slot.
|
|
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; a `build` that throws, or a message JSON cannot encode (a BigInt), is logged and dropped.
|
|
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() }` and closes on unmount. `onMessage(message, type)` gets the SSE event type (`'message'` or a name from `events`) and its errors are not caught; a frame that is not JSON is skipped. Options: `baseDelayMs` (1000), `maxDelayMs` (30000), `maxRetries`, `events`, `withCredentials`. Reconnect waits a random delay up to the doubling backoff capped at `maxDelayMs`, without end once the stream has opened (2 retries if it never did, which stops a wrong URL), none while the page is hidden, and at once when the page is shown again or back `online`.
|
|
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
|
+
authorize: ctx => ctx.locals.user !== undefined,
|
|
41
|
+
room: ctx => ctx.url.searchParams.get('room') ?? 'general',
|
|
42
|
+
member: ctx => ({ name: ctx.locals.user?.name ?? 'guest' }),
|
|
43
|
+
})
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
```tsx
|
|
47
|
+
// src/components/ChatFeed.tsx (auto-island)
|
|
48
|
+
import { signal } from 'prunelle'
|
|
49
|
+
import { useLive } from '@prunellejs/live/client'
|
|
50
|
+
import type { ChatMsg } from '../rooms'
|
|
51
|
+
|
|
52
|
+
export function ChatFeed({ room }: { room: string }) {
|
|
53
|
+
const messages = signal<ChatMsg[]>([])
|
|
54
|
+
const live = useLive<ChatMsg>(`/api/chat?room=${room}`, m => { messages.value = [...messages.value, m] })
|
|
55
|
+
return <section data-status={live.status.value}>{messages.value.map((m, i) => <p key={i}>{m.from}: {m.text}</p>)}</section>
|
|
56
|
+
}
|
|
57
|
+
```
|
package/package.json
CHANGED
|
@@ -1,6 +1,27 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prunellejs/live",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.7.2",
|
|
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.7.2"
|
|
26
|
+
}
|
|
27
|
+
}
|
package/src/client.ts
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
// Browser client helper for @prunellejs/live SSE rooms (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
|
+
/** Cap of the exponential backoff in milliseconds; each delay is a random value up to it (default: 30000). */
|
|
18
|
+
maxDelayMs?: number | undefined
|
|
19
|
+
/** Consecutive failed reconnects before staying closed (default: unlimited once opened, 2 before; resets on open). */
|
|
20
|
+
maxRetries?: number | undefined
|
|
21
|
+
/** Named SSE `event:` types to listen for in addition to default unnamed `message` events. */
|
|
22
|
+
events?: readonly string[] | undefined
|
|
23
|
+
/** Send cookies / credentials on cross-origin EventSource connections. */
|
|
24
|
+
withCredentials?: boolean | undefined
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const DEFAULT_BASE_DELAY_MS = 1_000
|
|
28
|
+
const DEFAULT_MAX_DELAY_MS = 30_000
|
|
29
|
+
const DEFAULT_INITIAL_MAX_RETRIES = 2
|
|
30
|
+
|
|
31
|
+
export function useLive<TMessage>(
|
|
32
|
+
url: string,
|
|
33
|
+
onMessage?: (message: TMessage, type: string) => void,
|
|
34
|
+
options?: UseLiveOptions,
|
|
35
|
+
): LiveConnection<TMessage> {
|
|
36
|
+
const status = signal<LiveStatus>('connecting')
|
|
37
|
+
const last = signal<TMessage | undefined>(undefined)
|
|
38
|
+
let source: EventSource | undefined
|
|
39
|
+
let reconnectTimer: ReturnType<typeof setTimeout> | undefined
|
|
40
|
+
let attempt = 0
|
|
41
|
+
let hasOpened = false
|
|
42
|
+
let manuallyClosed = false
|
|
43
|
+
let exhausted = false
|
|
44
|
+
|
|
45
|
+
const clearReconnectTimer = () => {
|
|
46
|
+
if (reconnectTimer !== undefined) {
|
|
47
|
+
clearTimeout(reconnectTimer)
|
|
48
|
+
reconnectTimer = undefined
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const detachWake = () => {
|
|
53
|
+
removeEventListener('online', wake)
|
|
54
|
+
document.removeEventListener('visibilitychange', wake)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// A closed connection the app did not close reconnects now; a hidden page waits until it is shown.
|
|
58
|
+
const wake = () => {
|
|
59
|
+
if (source !== undefined || document.hidden || manuallyClosed || exhausted)
|
|
60
|
+
return
|
|
61
|
+
connect()
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const close = () => {
|
|
65
|
+
manuallyClosed = true
|
|
66
|
+
clearReconnectTimer()
|
|
67
|
+
source?.close()
|
|
68
|
+
source = undefined
|
|
69
|
+
status.value = 'closed'
|
|
70
|
+
detachWake()
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const scheduleReconnect = () => {
|
|
74
|
+
const maxRetries = options?.maxRetries ?? (hasOpened ? Infinity : DEFAULT_INITIAL_MAX_RETRIES)
|
|
75
|
+
if (attempt >= maxRetries) {
|
|
76
|
+
exhausted = true
|
|
77
|
+
detachWake()
|
|
78
|
+
return
|
|
79
|
+
}
|
|
80
|
+
const exp = Math.min(attempt++, 30)
|
|
81
|
+
const cap = Math.min(options?.maxDelayMs ?? DEFAULT_MAX_DELAY_MS, (options?.baseDelayMs ?? DEFAULT_BASE_DELAY_MS) * 2 ** exp)
|
|
82
|
+
reconnectTimer = setTimeout(() => {
|
|
83
|
+
reconnectTimer = undefined
|
|
84
|
+
wake()
|
|
85
|
+
}, Math.random() * cap)
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const connect = () => {
|
|
89
|
+
clearReconnectTimer()
|
|
90
|
+
status.value = 'connecting'
|
|
91
|
+
const es = options?.withCredentials !== undefined
|
|
92
|
+
? new EventSource(url, { withCredentials: options.withCredentials })
|
|
93
|
+
: new EventSource(url)
|
|
94
|
+
source = es
|
|
95
|
+
|
|
96
|
+
es.onopen = () => {
|
|
97
|
+
if (source !== es || manuallyClosed)
|
|
98
|
+
return
|
|
99
|
+
hasOpened = true
|
|
100
|
+
attempt = 0
|
|
101
|
+
status.value = 'open'
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
es.onerror = () => {
|
|
105
|
+
if (source !== es || manuallyClosed)
|
|
106
|
+
return
|
|
107
|
+
if (es.readyState !== EventSource.CLOSED) {
|
|
108
|
+
status.value = 'connecting'
|
|
109
|
+
return
|
|
110
|
+
}
|
|
111
|
+
es.close()
|
|
112
|
+
status.value = 'closed'
|
|
113
|
+
source = undefined
|
|
114
|
+
scheduleReconnect()
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const handleEvent = (ev: Event) => {
|
|
118
|
+
if (source !== es || manuallyClosed)
|
|
119
|
+
return
|
|
120
|
+
const data = (ev as MessageEvent<unknown>).data
|
|
121
|
+
if (typeof data !== 'string')
|
|
122
|
+
return
|
|
123
|
+
let parsed: TMessage
|
|
124
|
+
try {
|
|
125
|
+
parsed = JSON.parse(data) as TMessage
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
return // a frame that is not JSON carries no message
|
|
129
|
+
}
|
|
130
|
+
last.value = parsed
|
|
131
|
+
onMessage?.(parsed, ev.type)
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
es.onmessage = handleEvent
|
|
135
|
+
if (options?.events !== undefined) {
|
|
136
|
+
const seen = new Set(options.events)
|
|
137
|
+
seen.delete('message')
|
|
138
|
+
for (const name of seen)
|
|
139
|
+
es.addEventListener(name, handleEvent)
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
onMount(() => {
|
|
144
|
+
manuallyClosed = false
|
|
145
|
+
exhausted = false
|
|
146
|
+
addEventListener('online', wake)
|
|
147
|
+
document.addEventListener('visibilitychange', wake)
|
|
148
|
+
connect()
|
|
149
|
+
return close
|
|
150
|
+
})
|
|
151
|
+
|
|
152
|
+
return { status, last, close }
|
|
153
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,443 @@
|
|
|
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
|
+
/** Pings `sub` every `ms` on the timer all subscribers of that interval share; returns the call that stops it. */
|
|
111
|
+
schedulePing(ms: number, sub: Subscriber<TMember>): () => void
|
|
112
|
+
join(room: string, sub: Subscriber<TMember>): void
|
|
113
|
+
leave(room: string, sub: Subscriber<TMember>): void
|
|
114
|
+
size(room: string): number
|
|
115
|
+
getActiveConnections(): number
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function clientIdOf<TMember>(state: RoomState<TMember>, ctx: RequestContext, opts: ConnectionLimits): string | undefined {
|
|
119
|
+
const rawClientId = (opts.clientKey ?? state.defaultOpts.clientKey ?? defaultClientKey)(ctx)
|
|
120
|
+
return rawClientId !== undefined && rawClientId.length > 0 ? rawClientId : undefined
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** The 429 or 503 a request meets when a cap is full, undefined while it fits: counts only, so it can run before `authorize`. */
|
|
124
|
+
function refusalForCaps<TMember>(state: RoomState<TMember>, ctx: RequestContext, room: string, opts: ConnectionLimits): Response | undefined {
|
|
125
|
+
const { defaultOpts, clientCounts } = state
|
|
126
|
+
const maxPerRoom = opts.maxConnectionsPerRoom ?? defaultOpts.maxConnectionsPerRoom ?? DEFAULT_MAX_PER_ROOM
|
|
127
|
+
const maxPerClient = opts.maxConnectionsPerClient ?? defaultOpts.maxConnectionsPerClient ?? DEFAULT_MAX_PER_CLIENT
|
|
128
|
+
const maxTotal = opts.maxTotalConnections ?? defaultOpts.maxTotalConnections ?? DEFAULT_MAX_TOTAL
|
|
129
|
+
const clientId = clientIdOf(state, ctx, opts)
|
|
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
|
+
return undefined
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function openRoomStream<TMember>(
|
|
148
|
+
state: RoomState<TMember>,
|
|
149
|
+
ctx: RequestContext,
|
|
150
|
+
opts: StreamOptions<TMember>,
|
|
151
|
+
): Response {
|
|
152
|
+
const { room, member, pingMs = 20_000, onJoin, onLeave } = opts
|
|
153
|
+
const { defaultOpts, clientCounts } = state
|
|
154
|
+
const highWaterMark = opts.highWaterMark ?? defaultOpts.highWaterMark ?? DEFAULT_HIGH_WATER_MARK
|
|
155
|
+
const clientId = clientIdOf(state, ctx, opts)
|
|
156
|
+
|
|
157
|
+
const refused = refusalForCaps(state, ctx, room, opts)
|
|
158
|
+
if (refused !== undefined)
|
|
159
|
+
return refused
|
|
160
|
+
|
|
161
|
+
let cleaned = false
|
|
162
|
+
let joined = false
|
|
163
|
+
let stopPing: (() => void) | undefined
|
|
164
|
+
let sub: Subscriber<TMember> | undefined
|
|
165
|
+
let countedClient = false
|
|
166
|
+
let abortHandler: (() => void) | undefined
|
|
167
|
+
|
|
168
|
+
const cleanup = () => {
|
|
169
|
+
if (cleaned)
|
|
170
|
+
return
|
|
171
|
+
cleaned = true
|
|
172
|
+
if (abortHandler !== undefined) {
|
|
173
|
+
ctx.request.signal.removeEventListener('abort', abortHandler)
|
|
174
|
+
abortHandler = undefined
|
|
175
|
+
}
|
|
176
|
+
stopPing?.()
|
|
177
|
+
stopPing = undefined
|
|
178
|
+
if (countedClient && clientId !== undefined) {
|
|
179
|
+
countedClient = false
|
|
180
|
+
const remaining = (clientCounts.get(clientId) ?? 1) - 1
|
|
181
|
+
if (remaining <= 0)
|
|
182
|
+
clientCounts.delete(clientId)
|
|
183
|
+
else
|
|
184
|
+
clientCounts.set(clientId, remaining)
|
|
185
|
+
}
|
|
186
|
+
if (sub !== undefined) {
|
|
187
|
+
state.leave(room, sub)
|
|
188
|
+
// A throwing hook of the app must not stop the stream from closing.
|
|
189
|
+
if (joined) {
|
|
190
|
+
try {
|
|
191
|
+
onLeave?.(room, member)
|
|
192
|
+
}
|
|
193
|
+
catch (error) {
|
|
194
|
+
console.error(`@prunellejs/live: onLeave of room "${room}" threw:`, error)
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
const body = new ReadableStream<Uint8Array>({
|
|
201
|
+
start(controller) {
|
|
202
|
+
const drop = () => {
|
|
203
|
+
cleanup()
|
|
204
|
+
try {
|
|
205
|
+
controller.close()
|
|
206
|
+
}
|
|
207
|
+
catch {
|
|
208
|
+
// Stream may already be closed or errored by the consumer.
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
sub = {
|
|
213
|
+
id: crypto.randomUUID(),
|
|
214
|
+
member,
|
|
215
|
+
send(chunk) {
|
|
216
|
+
if (cleaned)
|
|
217
|
+
return
|
|
218
|
+
if (controller.desiredSize !== null && controller.desiredSize <= 0) {
|
|
219
|
+
drop()
|
|
220
|
+
return
|
|
221
|
+
}
|
|
222
|
+
try {
|
|
223
|
+
controller.enqueue(chunk)
|
|
224
|
+
}
|
|
225
|
+
catch {
|
|
226
|
+
drop()
|
|
227
|
+
}
|
|
228
|
+
},
|
|
229
|
+
close: drop,
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
if (clientId !== undefined) {
|
|
233
|
+
clientCounts.set(clientId, (clientCounts.get(clientId) ?? 0) + 1)
|
|
234
|
+
countedClient = true
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
try {
|
|
238
|
+
controller.enqueue(RETRY_CHUNK)
|
|
239
|
+
state.join(room, sub)
|
|
240
|
+
joined = true
|
|
241
|
+
onJoin?.(room, member)
|
|
242
|
+
}
|
|
243
|
+
catch (err) {
|
|
244
|
+
joined = false
|
|
245
|
+
cleanup()
|
|
246
|
+
throw err
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
if (cleaned)
|
|
250
|
+
return
|
|
251
|
+
|
|
252
|
+
if (pingMs > 0)
|
|
253
|
+
stopPing = state.schedulePing(pingMs, sub)
|
|
254
|
+
|
|
255
|
+
if (ctx.request.signal.aborted) {
|
|
256
|
+
drop()
|
|
257
|
+
}
|
|
258
|
+
else {
|
|
259
|
+
abortHandler = drop
|
|
260
|
+
ctx.request.signal.addEventListener('abort', drop, { once: true })
|
|
261
|
+
}
|
|
262
|
+
},
|
|
263
|
+
cancel() {
|
|
264
|
+
cleanup()
|
|
265
|
+
},
|
|
266
|
+
}, { highWaterMark, size: chunk => chunk?.byteLength ?? 0 })
|
|
267
|
+
|
|
268
|
+
return new Response(body, {
|
|
269
|
+
status: 200,
|
|
270
|
+
headers: {
|
|
271
|
+
'content-type': 'text/event-stream; charset=utf-8',
|
|
272
|
+
'cache-control': 'no-cache, no-transform',
|
|
273
|
+
'x-accel-buffering': 'no',
|
|
274
|
+
},
|
|
275
|
+
})
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
export function createRooms<TMessage, TMember = undefined>(
|
|
279
|
+
options: RoomsOptions<TMember> = {},
|
|
280
|
+
): Rooms<TMessage, TMember> {
|
|
281
|
+
const defaultOpts: RoomsOptions<TMember> = options
|
|
282
|
+
|
|
283
|
+
const map = new Map<string, Set<Subscriber<TMember>>>()
|
|
284
|
+
const clientCounts = new Map<string, number>()
|
|
285
|
+
let activeConnections = 0
|
|
286
|
+
|
|
287
|
+
function join(room: string, sub: Subscriber<TMember>): void {
|
|
288
|
+
let set = map.get(room)
|
|
289
|
+
if (set === undefined) {
|
|
290
|
+
set = new Set()
|
|
291
|
+
map.set(room, set)
|
|
292
|
+
}
|
|
293
|
+
if (!set.has(sub)) {
|
|
294
|
+
set.add(sub)
|
|
295
|
+
activeConnections++
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function leave(room: string, sub: Subscriber<TMember>): void {
|
|
300
|
+
const set = map.get(room)
|
|
301
|
+
if (set === undefined)
|
|
302
|
+
return
|
|
303
|
+
if (set.delete(sub))
|
|
304
|
+
activeConnections--
|
|
305
|
+
if (set.size === 0)
|
|
306
|
+
map.delete(room)
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
function members(room: string): TMember[] {
|
|
310
|
+
const set = map.get(room)
|
|
311
|
+
if (set === undefined)
|
|
312
|
+
return []
|
|
313
|
+
const out: TMember[] = []
|
|
314
|
+
for (const sub of set)
|
|
315
|
+
out.push(sub.member)
|
|
316
|
+
return out
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
function size(room: string): number {
|
|
320
|
+
return map.get(room)?.size ?? 0
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function publish(room: string, message: TMessage, event?: string, eventId?: string): void {
|
|
324
|
+
// Validate event & id eagerly even if room is empty so injection attempts always fail fast
|
|
325
|
+
assertSafeSseField(event, 'event name')
|
|
326
|
+
assertSafeSseField(eventId, 'event id')
|
|
327
|
+
const set = map.get(room)
|
|
328
|
+
if (set === undefined || set.size === 0)
|
|
329
|
+
return
|
|
330
|
+
const chunk = encodeEvent(message, event, eventId)
|
|
331
|
+
for (const sub of [...set]) {
|
|
332
|
+
try {
|
|
333
|
+
sub.send(chunk)
|
|
334
|
+
}
|
|
335
|
+
catch {
|
|
336
|
+
sub.close()
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
function coalesce(build: (room: string) => TMessage, event?: string): (room: string) => void {
|
|
342
|
+
assertSafeSseField(event, 'event name')
|
|
343
|
+
const pending = new Set<string>()
|
|
344
|
+
return (room: string) => {
|
|
345
|
+
if (pending.has(room))
|
|
346
|
+
return
|
|
347
|
+
pending.add(room)
|
|
348
|
+
// Nothing awaits this microtask, so a throwing builder or an unencodable message (a BigInt) would exit the process.
|
|
349
|
+
queueMicrotask(() => {
|
|
350
|
+
pending.delete(room)
|
|
351
|
+
if (size(room) === 0)
|
|
352
|
+
return
|
|
353
|
+
try {
|
|
354
|
+
publish(room, build(room), event)
|
|
355
|
+
}
|
|
356
|
+
catch (error) {
|
|
357
|
+
console.error(`@prunellejs/live: coalesced message for room "${room}" was dropped:`, error)
|
|
358
|
+
}
|
|
359
|
+
})
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
// One timer per ping interval, however many subscribers share it; it stops with the last of them.
|
|
364
|
+
const pingers = new Map<number, { subs: Set<Subscriber<TMember>>, timer: ReturnType<typeof setInterval> }>()
|
|
365
|
+
function schedulePing(ms: number, sub: Subscriber<TMember>): () => void {
|
|
366
|
+
let pinger = pingers.get(ms)
|
|
367
|
+
if (pinger === undefined) {
|
|
368
|
+
const subs = new Set<Subscriber<TMember>>()
|
|
369
|
+
const timer = setInterval(() => {
|
|
370
|
+
for (const each of [...subs])
|
|
371
|
+
each.send(PING_CHUNK)
|
|
372
|
+
}, ms)
|
|
373
|
+
;(timer as unknown as { unref?: () => void }).unref?.()
|
|
374
|
+
pinger = { subs, timer }
|
|
375
|
+
pingers.set(ms, pinger)
|
|
376
|
+
}
|
|
377
|
+
const held = pinger
|
|
378
|
+
held.subs.add(sub)
|
|
379
|
+
return () => {
|
|
380
|
+
held.subs.delete(sub)
|
|
381
|
+
if (held.subs.size === 0 && pingers.get(ms) === held) {
|
|
382
|
+
clearInterval(held.timer)
|
|
383
|
+
pingers.delete(ms)
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
const roomState: RoomState<TMember> = {
|
|
389
|
+
defaultOpts,
|
|
390
|
+
clientCounts,
|
|
391
|
+
schedulePing,
|
|
392
|
+
join,
|
|
393
|
+
leave,
|
|
394
|
+
size,
|
|
395
|
+
getActiveConnections: () => activeConnections,
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
function stream(ctx: RequestContext, opts: StreamOptions<TMember>): Response {
|
|
399
|
+
return openRoomStream(roomState, ctx, opts)
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
// An open stream would hold a graceful stop until its timeout.
|
|
403
|
+
function closeAll(): void {
|
|
404
|
+
for (const set of [...map.values()]) {
|
|
405
|
+
for (const sub of [...set])
|
|
406
|
+
sub.close()
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
function endpoint(opts: RoomsEndpointOptions<TMember>): PrunellePlugin {
|
|
411
|
+
if (typeof opts.member !== 'function')
|
|
412
|
+
throw new TypeError(`@prunellejs/live: createRooms({ path: '${opts.path}' }) needs member(ctx), the member each stream joins as`)
|
|
413
|
+
return definePlugin({
|
|
414
|
+
name: `@prunellejs/live(${opts.path})`,
|
|
415
|
+
check(ctx) {
|
|
416
|
+
if (opts.authorize === undefined)
|
|
417
|
+
ctx.warn(`prunelle.config.ts:1:1: warning: [live/authorize] the channel at ${opts.path} has no authorize, so anyone who can reach it joins the room and reads what it publishes: pass authorize(ctx, room) to say who may join, or authorize: () => true to say the channel is public.`)
|
|
418
|
+
},
|
|
419
|
+
server(api) {
|
|
420
|
+
api.onShutdown(closeAll)
|
|
421
|
+
api.route('GET', opts.path, async (ctx) => {
|
|
422
|
+
const room = typeof opts.room === 'function' ? opts.room(ctx) : (opts.room ?? 'default')
|
|
423
|
+
// Counts first: a flood of requests a full cap would refuse anyway never reaches the app's authorize.
|
|
424
|
+
const refused = refusalForCaps(roomState, ctx, room, opts)
|
|
425
|
+
if (refused !== undefined)
|
|
426
|
+
return refused
|
|
427
|
+
if (opts.authorize !== undefined) {
|
|
428
|
+
const decision = await opts.authorize(ctx, room)
|
|
429
|
+
if (decision instanceof Response)
|
|
430
|
+
return decision
|
|
431
|
+
if (decision === false)
|
|
432
|
+
return new Response('Forbidden', { status: 403 })
|
|
433
|
+
}
|
|
434
|
+
const member = await opts.member(ctx)
|
|
435
|
+
return stream(ctx, { ...opts, room, member })
|
|
436
|
+
})
|
|
437
|
+
},
|
|
438
|
+
})
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
const plugin = options.path === undefined ? definePlugin({ name: '@prunellejs/live', server: api => api.onShutdown(closeAll) }) : endpoint(options)
|
|
442
|
+
return { ...plugin, join, leave, members, size, publish, coalesce, stream }
|
|
443
|
+
}
|
package/README.md
DELETED