@cslug/realtime 0.0.0-stage → 0.19.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/README.md +9 -2
- package/docs/README.md +101 -0
- package/docs/api.md +37 -0
- package/package.json +51 -4
- package/src/channels.ts +78 -0
- package/src/client/index.ts +340 -0
- package/src/connection.ts +181 -0
- package/src/endpoints.ts +120 -0
- package/src/events.ts +9 -0
- package/src/fake.ts +54 -0
- package/src/history.ts +110 -0
- package/src/index.ts +31 -0
- package/src/provider.ts +103 -0
- package/src/realtime.ts +73 -0
- package/src/vue.ts +157 -0
package/README.md
CHANGED
|
@@ -1,3 +1,10 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @cslug/realtime
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Channels for browsers, over server-sent events or WebSockets. Declare who may join in `routes/channels.ts`, publish
|
|
4
|
+
from anywhere (a request, a queued job, a scheduled task) with `realtime.channel('chats.42').send('message', data)`
|
|
5
|
+
or `.stream(agent.stream({ input }))`, and the browsers subscribed to that channel get it, on whichever web process
|
|
6
|
+
they are connected to (Redis pub/sub with `@cslug/redis`). A client that reconnects resumes from the last message it
|
|
7
|
+
saw. In the browser, `useChat()` streams a chatbot's reply and `useChannel()` joins a channel
|
|
8
|
+
(`@cslug/realtime/vue`), or `@cslug/realtime/client` without Vue.
|
|
9
|
+
|
|
10
|
+
Part of [cslug](https://github.com/cslugts/cslug). Docs: [docs/README.md](docs/README.md), [docs/api.md](docs/api.md).
|
package/docs/README.md
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
# @cslug/realtime
|
|
2
|
+
|
|
3
|
+
## Setup
|
|
4
|
+
|
|
5
|
+
`RealtimeProvider` (after `HttpProvider`; with `@cslug/redis` for several processes) and `config/realtime.ts`:
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { defineConfig } from '@cslug/core'
|
|
9
|
+
|
|
10
|
+
export default defineConfig({
|
|
11
|
+
path: '/realtime', // /realtime/sse and /realtime/ws; false: no endpoints (a worker-only app)
|
|
12
|
+
history: { size: 200, ttl: '10m' }, // per channel, for resuming; false: none
|
|
13
|
+
maxConnectionTime: '1h', // an SSE stream ends and the browser reconnects (proxies, deploys)
|
|
14
|
+
heartbeat: 15_000, // ms, SSE comments that keep proxies from closing idle streams
|
|
15
|
+
limits: { channels: 50, whispersPerSecond: 10 },
|
|
16
|
+
})
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Channels
|
|
20
|
+
|
|
21
|
+
`routes/channels.ts` (loaded at boot):
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
import { defineChannels } from '@cslug/realtime'
|
|
25
|
+
|
|
26
|
+
export default defineChannels((c) => {
|
|
27
|
+
c.public('status')
|
|
28
|
+
c.private('chats.:chatId', async (user, { chatId }) => (await chats.find(chatId))?.userId === user.id)
|
|
29
|
+
})
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Names are letters, digits and `_ - . : = @` (200 at most); `:name` segments of a pattern match one dot-separated
|
|
33
|
+
segment and become `params`. A channel that matches no pattern cannot be joined (`unknown_channel`). A private
|
|
34
|
+
channel needs a signed-in user (`unauthenticated`) for whom the authorizer returns true or an object
|
|
35
|
+
(`forbidden` otherwise); the object is kept as the subscriber's info.
|
|
36
|
+
|
|
37
|
+
## Publishing
|
|
38
|
+
|
|
39
|
+
`resolve(Realtime).channel(name)`:
|
|
40
|
+
- `send(event, data)` → the message id. Stored in the history, then published on `PubSub` topic `realtime:<name>`.
|
|
41
|
+
- `stream(asyncIterable, { event = 'token', done = 'done', doneData })` sends each item, then `done`; on a failure,
|
|
42
|
+
an `error` event `{ message }`, and the error is thrown again. Returns the count.
|
|
43
|
+
|
|
44
|
+
Messages: `{ id, channel, event, data }`. Ids are `<ms>-<seq>` (Redis stream ids with Redis), ordered.
|
|
45
|
+
|
|
46
|
+
## History
|
|
47
|
+
|
|
48
|
+
With `@cslug/redis` bound: `XADD <prefix>realtime:history:<channel> MAXLEN ~ size`, expiring `ttl` after the last
|
|
49
|
+
message, shared by every process. Without: an in-process ring per channel (one web process). A client that sends
|
|
50
|
+
`Last-Event-ID` (SSE does it on reconnect) or `lastId` (WebSocket subscribe) gets the messages after it, then live
|
|
51
|
+
ones, none twice.
|
|
52
|
+
|
|
53
|
+
## Endpoints
|
|
54
|
+
|
|
55
|
+
With the web group's middleware (`session()`, `csrf()`, and what packages add, such as `@cslug/auth`'s
|
|
56
|
+
`authenticate()`), so a session cookie or a Bearer token identifies the user.
|
|
57
|
+
|
|
58
|
+
**`GET /realtime/sse?channels=a,b`**: events `connected` `{ id }` (with `retry: 2000`), `subscribed` /
|
|
59
|
+
`denied` `{ channel, reason }` per channel, then `message` with `id` and `{ channel, event, data }`. Heartbeat
|
|
60
|
+
comments; ends after `maxConnectionTime`.
|
|
61
|
+
|
|
62
|
+
**`GET /realtime/ws`**: the client sends JSON `{ type: 'subscribe', channel, lastId? }`, `{ type: 'unsubscribe',
|
|
63
|
+
channel }`, `{ type: 'whisper', channel, event, data }`, `{ type: 'ping' }`; the server sends `connected`,
|
|
64
|
+
`subscribed`, `unsubscribed`, `denied`, `message` `{ message }`, `pong`, `error` `{ reason }` (`invalid_json`,
|
|
65
|
+
`unknown_message`, `whisper_not_allowed`, `too_many_whispers`).
|
|
66
|
+
|
|
67
|
+
A **whisper** is a client event (typing…) relayed to the channel's other subscribers: only on a private channel the
|
|
68
|
+
connection joined, at most `whispersPerSecond`, never stored, `whisper: true` on the message.
|
|
69
|
+
|
|
70
|
+
At most `limits.channels` channels per connection (`too_many_channels`).
|
|
71
|
+
|
|
72
|
+
## Each process
|
|
73
|
+
|
|
74
|
+
`Hub` holds one `PubSub` subscription per channel with local subscribers, shared, dropped with the last one.
|
|
75
|
+
`ClientSubscribed` / `ClientUnsubscribed` `{ channel, userId, connectionId, transport }`. Subscriptions, denials,
|
|
76
|
+
publishes and whispers are reported to `Instrumentation` as `realtime` (`/_inspector`).
|
|
77
|
+
|
|
78
|
+
## Testing
|
|
79
|
+
|
|
80
|
+
`fakes: ['realtime']` → `RealtimeFake`: nothing is published; `messages`, `sent(channel, event?)`, `text(channel,
|
|
81
|
+
event = 'token')` (streamed tokens joined), `assertSent(channel, event?, match?)`, `assertNothingSent(channel?)`.
|
|
82
|
+
|
|
83
|
+
## Browser
|
|
84
|
+
|
|
85
|
+
**`@cslug/realtime/client`** (no framework, no server imports):
|
|
86
|
+
- `readSse(body, signal?)`: `{ event, id?, data }` from a `text/event-stream` body (`data` parsed as JSON when it is).
|
|
87
|
+
- `streamPost(url, body, { signal?, headers?, fetch? })`: POST JSON (with `<meta name="csrf-token">` as
|
|
88
|
+
`X-CSRF-Token`) and read the answer as events; `StreamError` (status, message) for an error response.
|
|
89
|
+
- `connect({ url = '/realtime', transport = 'sse' | 'ws', backoff, origin, fetch, WebSocket })` → `RealtimeClient`:
|
|
90
|
+
`channel(name)` → `ClientChannel` (`on(event | '*', fn)`, `whisper()`, `leave()`, `onState()`, `state`, `reason`);
|
|
91
|
+
`onStatus()`, `status`, `close()`. One connection for all channels: SSE reopens with the new set (debounced),
|
|
92
|
+
WebSocket subscribes on the open socket. On a drop or an ended stream it reconnects (doubling backoff with jitter)
|
|
93
|
+
and resumes from the last message id.
|
|
94
|
+
|
|
95
|
+
**`@cslug/realtime/vue`** (vue is an optional peer; safe in server rendering, connects in the browser only, cleans up
|
|
96
|
+
with the component's scope):
|
|
97
|
+
- `useChat({ url, initial?, body?, fetch? })` → `messages` (`{ id, role, content }`), `input`, `status` (`idle`,
|
|
98
|
+
`streaming`, `error`), `error`, `send(text?)`, `stop()`. Reads `message` / `token` events as text, `done` ends,
|
|
99
|
+
`error` sets `error`. Works with `@cslug/ai`'s `sse()` and `@cslug/http`'s.
|
|
100
|
+
- `useChannel(name, connectOptions?)` → `on`, `whisper`, `last`, `status`, `denied`. `sharedClient(options)` is the
|
|
101
|
+
page's client for these options.
|
package/docs/api.md
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
# @cslug/realtime: API
|
|
2
|
+
|
|
3
|
+
```ts
|
|
4
|
+
import { RealtimeProvider, Realtime, ChannelPublisher, Channels, defineChannels, Hub, Connection, History,
|
|
5
|
+
MemoryHistory, RedisHistory, NoHistory, RealtimeFake, installRealtimeFake, ClientSubscribed, ClientUnsubscribed,
|
|
6
|
+
realtimeRoutes, compareIds, nextId, topicOf, CHANNEL_NAME, type RealtimeConfig, type RealtimeMessage,
|
|
7
|
+
type RealtimeUser, type ChannelAuthorizer, type ChannelRegistrar, type Authorization, type Outgoing } from '@cslug/realtime'
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
| | |
|
|
11
|
+
|---|---|
|
|
12
|
+
| `RealtimeProvider` | Binds `Realtime`, `Channels`, `Hub`, `History`; loads `routes/channels.ts`; the endpoints |
|
|
13
|
+
| `RealtimeConfig` | `{ path?, history?: { size?, ttl? } \| false, maxConnectionTime?, heartbeat?, limits?: { channels?, whispersPerSecond? } }` |
|
|
14
|
+
| `defineChannels((c) => …)` | `c.public(pattern)`, `c.private(pattern, (user, params) => boolean \| info)` |
|
|
15
|
+
| `Channels` | `load(fn)`, `authorize(name, user)` → `{ allowed, private, info? }` or `{ allowed: false, reason }`, `match(name)`, `patterns` |
|
|
16
|
+
| `Realtime` | `channel(name)` → `ChannelPublisher` |
|
|
17
|
+
| `ChannelPublisher` | `send(event, data?)` → id; `stream(source, { event?, done?, doneData? })` → count |
|
|
18
|
+
| `History` | `append(channel, { event, data })` → id; `since(channel, lastId)`. `MemoryHistory(size, ttlMs)`, `RedisHistory(redis, size, ttlSeconds)`, `NoHistory` |
|
|
19
|
+
| `Hub` | `join(channel, listener)` → leave; `size`; `close()` |
|
|
20
|
+
| `Connection` | `subscribe(channel, lastId?)`, `unsubscribe(channel)`, `whisper(channel, event, data)`, `close()`, `channels`, `id` |
|
|
21
|
+
| `RealtimeMessage` | `{ id, channel, event, data, from?, whisper? }` |
|
|
22
|
+
| `ClientSubscribed`, `ClientUnsubscribed` | `{ channel, userId, connectionId, transport: 'sse' \| 'ws' }` |
|
|
23
|
+
| `RealtimeFake` | `messages`, `sent()`, `text()`, `assertSent()`, `assertNothingSent()` |
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
import { connect, streamPost, readSse, RealtimeClient, ClientChannel, StreamError, type StreamEvent,
|
|
27
|
+
type ChannelMessage, type ConnectOptions, type Status } from '@cslug/realtime/client'
|
|
28
|
+
import { useChat, useChannel, sharedClient, type ChatMessage, type UseChatOptions } from '@cslug/realtime/vue'
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
| | |
|
|
32
|
+
|---|---|
|
|
33
|
+
| `connect(options)` | `RealtimeClient`: `channel(name)`, `leave(name)`, `whisper(channel, event, data)`, `onStatus(fn)`, `status`, `close()` |
|
|
34
|
+
| `ClientChannel` | `on(event, fn)` → off, `whisper(event, data)`, `leave()`, `onState(fn)`, `state`, `reason` |
|
|
35
|
+
| `streamPost(url, body, options)`, `readSse(body, signal?)` | Async iterables of `StreamEvent` |
|
|
36
|
+
| `useChat(options)` | `{ messages, input, status, error, send, stop }` |
|
|
37
|
+
| `useChannel(name, options?)` | `{ on, whisper, last, status, denied }` |
|
package/package.json
CHANGED
|
@@ -1,6 +1,53 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cslug/realtime",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.19.0",
|
|
4
|
+
"description": "Realtime channels over WebSockets and server-sent events: authorization, publishing from any process, resuming.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/cslugts/cslug.git",
|
|
10
|
+
"directory": "packages/realtime"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/cslugts/cslug/tree/main/packages/realtime",
|
|
13
|
+
"keywords": [
|
|
14
|
+
"cslug",
|
|
15
|
+
"bun",
|
|
16
|
+
"framework",
|
|
17
|
+
"realtime",
|
|
18
|
+
"websocket",
|
|
19
|
+
"sse"
|
|
20
|
+
],
|
|
21
|
+
"exports": {
|
|
22
|
+
".": "./src/index.ts",
|
|
23
|
+
"./client": "./src/client/index.ts",
|
|
24
|
+
"./vue": "./src/vue.ts"
|
|
25
|
+
},
|
|
26
|
+
"files": [
|
|
27
|
+
"src",
|
|
28
|
+
"docs",
|
|
29
|
+
"README.md"
|
|
30
|
+
],
|
|
31
|
+
"engines": {
|
|
32
|
+
"bun": ">=1.3.14"
|
|
33
|
+
},
|
|
34
|
+
"peerDependencies": {
|
|
35
|
+
"@cslug/core": "0.19.0",
|
|
36
|
+
"@cslug/http": "0.19.0",
|
|
37
|
+
"@cslug/redis": "0.19.0",
|
|
38
|
+
"vue": "^3.5.0"
|
|
39
|
+
},
|
|
40
|
+
"peerDependenciesMeta": {
|
|
41
|
+
"@cslug/redis": {
|
|
42
|
+
"optional": true
|
|
43
|
+
},
|
|
44
|
+
"vue": {
|
|
45
|
+
"optional": true
|
|
46
|
+
}
|
|
47
|
+
},
|
|
48
|
+
"devDependencies": {
|
|
49
|
+
"@cslug/testing": "workspace:*",
|
|
50
|
+
"@cslug/validation": "workspace:*",
|
|
51
|
+
"vue": "^3.5.0"
|
|
52
|
+
}
|
|
53
|
+
}
|
package/src/channels.ts
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { CslugError } from '@cslug/core'
|
|
2
|
+
|
|
3
|
+
/** A signed-in user, as `ctx.auth.userOrNull()` returns it (anything with an `id`). */
|
|
4
|
+
export type RealtimeUser = { id: unknown }
|
|
5
|
+
|
|
6
|
+
/** May this user join? `true`/`false`, or a value kept as the subscriber's info (shown to others later). */
|
|
7
|
+
export type ChannelAuthorizer = (
|
|
8
|
+
user: RealtimeUser,
|
|
9
|
+
params: Record<string, string>,
|
|
10
|
+
) => boolean | Record<string, unknown> | Promise<boolean | Record<string, unknown>>
|
|
11
|
+
|
|
12
|
+
type Definition = { pattern: string; regex: RegExp; private: boolean; authorize?: ChannelAuthorizer }
|
|
13
|
+
|
|
14
|
+
/** A channel name: letters, digits and `_ - . : = @`, at most 200 characters. */
|
|
15
|
+
export const CHANNEL_NAME = /^[A-Za-z0-9_\-.:=@]{1,200}$/
|
|
16
|
+
|
|
17
|
+
/** What `routes/channels.ts` receives. */
|
|
18
|
+
export type ChannelRegistrar = {
|
|
19
|
+
/** Anyone may listen (status pages, public feeds). */
|
|
20
|
+
public(pattern: string): void
|
|
21
|
+
/** Only signed-in users for whom `authorize` says yes. `:name` segments become `params`. */
|
|
22
|
+
private(pattern: string, authorize: ChannelAuthorizer): void
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** `export default defineChannels((c) => { c.private('chats.:chatId', …) })` in `routes/channels.ts`. */
|
|
26
|
+
export const defineChannels = (fn: (c: ChannelRegistrar) => void) => fn
|
|
27
|
+
|
|
28
|
+
export type Authorization =
|
|
29
|
+
| { allowed: true; private: boolean; info?: Record<string, unknown> }
|
|
30
|
+
| { allowed: false; reason: 'unknown_channel' | 'unauthenticated' | 'forbidden' | 'invalid_name' }
|
|
31
|
+
|
|
32
|
+
/** The channels an app defines, and who may join them. Undefined channels cannot be joined. */
|
|
33
|
+
export class Channels {
|
|
34
|
+
private readonly definitions: Definition[] = []
|
|
35
|
+
|
|
36
|
+
load(fn: (c: ChannelRegistrar) => void): this {
|
|
37
|
+
fn({
|
|
38
|
+
public: (pattern) => this.add(pattern, false),
|
|
39
|
+
private: (pattern, authorize) => this.add(pattern, true, authorize),
|
|
40
|
+
})
|
|
41
|
+
return this
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
private add(pattern: string, isPrivate: boolean, authorize?: ChannelAuthorizer) {
|
|
45
|
+
const source = pattern
|
|
46
|
+
.split('.')
|
|
47
|
+
.map((part) => (part.startsWith(':') ? `(?<${part.slice(1)}>[^.]+)` : part.replace(/[\\^$*+?()[\]{}|]/g, '\\$&')))
|
|
48
|
+
.join('\\.')
|
|
49
|
+
if (!CHANNEL_NAME.test(pattern.replace(/:/g, 'x')))
|
|
50
|
+
throw new CslugError('realtime.bad_pattern', `Channel pattern "${pattern}" has characters a channel cannot have`)
|
|
51
|
+
this.definitions.push({ pattern, regex: new RegExp(`^${source}$`), private: isPrivate, authorize })
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
get patterns(): { pattern: string; private: boolean }[] {
|
|
55
|
+
return this.definitions.map((d) => ({ pattern: d.pattern, private: d.private }))
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The definition and params for a channel name. */
|
|
59
|
+
match(name: string): { definition: Definition; params: Record<string, string> } | undefined {
|
|
60
|
+
for (const definition of this.definitions) {
|
|
61
|
+
const m = definition.regex.exec(name)
|
|
62
|
+
if (m) return { definition, params: { ...m.groups } }
|
|
63
|
+
}
|
|
64
|
+
return undefined
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** May `user` (null: a guest) join `name`? */
|
|
68
|
+
async authorize(name: string, user: RealtimeUser | null): Promise<Authorization> {
|
|
69
|
+
if (!CHANNEL_NAME.test(name)) return { allowed: false, reason: 'invalid_name' }
|
|
70
|
+
const found = this.match(name)
|
|
71
|
+
if (!found) return { allowed: false, reason: 'unknown_channel' }
|
|
72
|
+
if (!found.definition.private) return { allowed: true, private: false }
|
|
73
|
+
if (!user) return { allowed: false, reason: 'unauthenticated' }
|
|
74
|
+
const result = await (found.definition.authorize as ChannelAuthorizer)(user, found.params)
|
|
75
|
+
if (!result) return { allowed: false, reason: 'forbidden' }
|
|
76
|
+
return { allowed: true, private: true, ...(typeof result === 'object' ? { info: result } : {}) }
|
|
77
|
+
}
|
|
78
|
+
}
|
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @cslug/realtime/client: the browser side, without a framework. `streamPost()` reads a reply streamed as
|
|
3
|
+
* server-sent events (a chat answer); `connect()` joins channels over SSE or a WebSocket, reconnecting and resuming.
|
|
4
|
+
* It imports nothing from the server packages.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/** One server-sent event: `data` parsed as JSON when it is JSON. */
|
|
8
|
+
export type StreamEvent = { event: string; id?: string; data: unknown }
|
|
9
|
+
|
|
10
|
+
/** Server-sent events from a response body (`text/event-stream`). */
|
|
11
|
+
export async function* readSse(body: ReadableStream<Uint8Array>, signal?: AbortSignal): AsyncGenerator<StreamEvent> {
|
|
12
|
+
const reader = body.getReader()
|
|
13
|
+
const decoder = new TextDecoder()
|
|
14
|
+
let buffer = ''
|
|
15
|
+
const onAbort = () => void reader.cancel().catch(() => {})
|
|
16
|
+
signal?.addEventListener('abort', onAbort)
|
|
17
|
+
try {
|
|
18
|
+
for (;;) {
|
|
19
|
+
const { value, done } = await reader.read()
|
|
20
|
+
if (done) break
|
|
21
|
+
buffer += decoder.decode(value, { stream: true }).replace(/\r\n?/g, '\n')
|
|
22
|
+
let end = buffer.indexOf('\n\n')
|
|
23
|
+
while (end >= 0) {
|
|
24
|
+
const block = buffer.slice(0, end)
|
|
25
|
+
buffer = buffer.slice(end + 2)
|
|
26
|
+
const event = parseBlock(block)
|
|
27
|
+
if (event) yield event
|
|
28
|
+
end = buffer.indexOf('\n\n')
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
} finally {
|
|
32
|
+
signal?.removeEventListener('abort', onAbort)
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function parseBlock(block: string): StreamEvent | undefined {
|
|
37
|
+
let event = 'message'
|
|
38
|
+
let id: string | undefined
|
|
39
|
+
const data: string[] = []
|
|
40
|
+
let any = false
|
|
41
|
+
for (const line of block.split('\n')) {
|
|
42
|
+
if (!line || line.startsWith(':')) continue
|
|
43
|
+
const i = line.indexOf(':')
|
|
44
|
+
const field = i < 0 ? line : line.slice(0, i)
|
|
45
|
+
const value = i < 0 ? '' : line.slice(i + 1).replace(/^ /, '')
|
|
46
|
+
if (field === 'event') event = value
|
|
47
|
+
else if (field === 'id') id = value
|
|
48
|
+
else if (field === 'data') {
|
|
49
|
+
data.push(value)
|
|
50
|
+
any = true
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
if (!any) return undefined
|
|
54
|
+
const text = data.join('\n')
|
|
55
|
+
let parsed: unknown = text
|
|
56
|
+
try {
|
|
57
|
+
parsed = JSON.parse(text)
|
|
58
|
+
} catch {}
|
|
59
|
+
return { event, ...(id !== undefined ? { id } : {}), data: parsed }
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** The page's CSRF token (`<meta name="csrf-token">`, rendered by @cslug/vue), for POSTs. */
|
|
63
|
+
function csrfToken(): string | undefined {
|
|
64
|
+
if (typeof document === 'undefined') return undefined
|
|
65
|
+
return document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') ?? undefined
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export class StreamError extends Error {
|
|
69
|
+
constructor(
|
|
70
|
+
readonly status: number,
|
|
71
|
+
message: string,
|
|
72
|
+
) {
|
|
73
|
+
super(message)
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* POST `body` as JSON and read the answer as server-sent events (what `EventSource` cannot do): a chat message,
|
|
79
|
+
* then its reply token by token. `signal` stops it; the server's stream ends too.
|
|
80
|
+
*/
|
|
81
|
+
export async function* streamPost(
|
|
82
|
+
url: string,
|
|
83
|
+
body: unknown,
|
|
84
|
+
options: { signal?: AbortSignal; headers?: Record<string, string>; fetch?: typeof fetch } = {},
|
|
85
|
+
): AsyncGenerator<StreamEvent> {
|
|
86
|
+
const token = csrfToken()
|
|
87
|
+
const res = await (options.fetch ?? fetch)(url, {
|
|
88
|
+
method: 'POST',
|
|
89
|
+
headers: {
|
|
90
|
+
'content-type': 'application/json',
|
|
91
|
+
accept: 'text/event-stream',
|
|
92
|
+
...(token ? { 'x-csrf-token': token } : {}),
|
|
93
|
+
...options.headers,
|
|
94
|
+
},
|
|
95
|
+
body: JSON.stringify(body),
|
|
96
|
+
signal: options.signal,
|
|
97
|
+
credentials: 'same-origin',
|
|
98
|
+
})
|
|
99
|
+
if (!res.ok || !res.body) {
|
|
100
|
+
let message = `${res.status} ${res.statusText}`
|
|
101
|
+
try {
|
|
102
|
+
const problem = (await res.json()) as { title?: string; detail?: string }
|
|
103
|
+
message = problem.detail ?? problem.title ?? message
|
|
104
|
+
} catch {}
|
|
105
|
+
throw new StreamError(res.status, message)
|
|
106
|
+
}
|
|
107
|
+
yield* readSse(res.body, options.signal)
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// ── channels ────────────────────────────────────────────────────────────────────────────────────────
|
|
111
|
+
|
|
112
|
+
/** A message on a channel, as clients receive it. */
|
|
113
|
+
export type ChannelMessage = { id?: string; channel: string; event: string; data: unknown; whisper?: boolean }
|
|
114
|
+
export type Status = 'connecting' | 'open' | 'closed'
|
|
115
|
+
type Handler = (data: unknown, message: ChannelMessage) => void
|
|
116
|
+
|
|
117
|
+
export type ConnectOptions = {
|
|
118
|
+
/** Where `RealtimeProvider` serves the endpoints (default `/realtime`). */
|
|
119
|
+
url?: string
|
|
120
|
+
/** `sse` (default: plain HTTP, through any proxy) or `ws` (also sends whispers). */
|
|
121
|
+
transport?: 'sse' | 'ws'
|
|
122
|
+
/** Reconnection delays in ms (doubling, with jitter). */
|
|
123
|
+
backoff?: { min?: number; max?: number }
|
|
124
|
+
/** For tests and other runtimes. */
|
|
125
|
+
fetch?: typeof fetch
|
|
126
|
+
WebSocket?: typeof WebSocket
|
|
127
|
+
/** The page's origin, for building absolute URLs (default `location.origin`). */
|
|
128
|
+
origin?: string
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** A joined channel: `on(event, fn)` (`'*'` for all), `whisper()` (WebSocket, private channels), `leave()`. */
|
|
132
|
+
export class ClientChannel {
|
|
133
|
+
/** @internal */
|
|
134
|
+
readonly handlers = new Map<string, Set<Handler>>()
|
|
135
|
+
/** Whether the server let this client in (`denied` carries the reason). */
|
|
136
|
+
state: 'pending' | 'subscribed' | 'denied' = 'pending'
|
|
137
|
+
reason?: string
|
|
138
|
+
private readonly stateHandlers = new Set<(state: ClientChannel['state'], reason?: string) => void>()
|
|
139
|
+
|
|
140
|
+
constructor(
|
|
141
|
+
readonly name: string,
|
|
142
|
+
private readonly client: RealtimeClient,
|
|
143
|
+
) {}
|
|
144
|
+
|
|
145
|
+
on(event: string, handler: Handler): () => void {
|
|
146
|
+
let set = this.handlers.get(event)
|
|
147
|
+
if (!set) {
|
|
148
|
+
set = new Set()
|
|
149
|
+
this.handlers.set(event, set)
|
|
150
|
+
}
|
|
151
|
+
set.add(handler)
|
|
152
|
+
return () => set.delete(handler)
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
whisper(event: string, data?: unknown): void {
|
|
156
|
+
this.client.whisper(this.name, event, data)
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Called when the server accepts or refuses this channel. */
|
|
160
|
+
onState(handler: (state: ClientChannel['state'], reason?: string) => void): () => void {
|
|
161
|
+
this.stateHandlers.add(handler)
|
|
162
|
+
return () => this.stateHandlers.delete(handler)
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** @internal */
|
|
166
|
+
setState(state: ClientChannel['state'], reason?: string) {
|
|
167
|
+
this.state = state
|
|
168
|
+
this.reason = reason
|
|
169
|
+
for (const h of [...this.stateHandlers]) h(state, reason)
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
leave(): void {
|
|
173
|
+
this.client.leave(this.name)
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** @internal */
|
|
177
|
+
dispatch(message: ChannelMessage) {
|
|
178
|
+
for (const key of [message.event, '*'])
|
|
179
|
+
for (const h of [...(this.handlers.get(key) ?? [])]) {
|
|
180
|
+
try {
|
|
181
|
+
h(message.data, message)
|
|
182
|
+
} catch (error) {
|
|
183
|
+
console.error(error)
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* One connection to the realtime endpoints for all of a page's channels. It reconnects with backoff and resumes
|
|
191
|
+
* from the last message id it saw, so nothing published meanwhile (within the server's history) is missed.
|
|
192
|
+
*/
|
|
193
|
+
export class RealtimeClient {
|
|
194
|
+
readonly channels = new Map<string, ClientChannel>()
|
|
195
|
+
status: Status = 'connecting'
|
|
196
|
+
private readonly statusHandlers = new Set<(s: Status) => void>()
|
|
197
|
+
private lastId?: string
|
|
198
|
+
private closed = false
|
|
199
|
+
private attempt = 0
|
|
200
|
+
private abort?: AbortController
|
|
201
|
+
private socket?: WebSocket
|
|
202
|
+
private reopen?: ReturnType<typeof setTimeout>
|
|
203
|
+
|
|
204
|
+
constructor(private readonly options: ConnectOptions = {}) {}
|
|
205
|
+
|
|
206
|
+
private get base(): string {
|
|
207
|
+
const origin = this.options.origin ?? (typeof location !== 'undefined' ? location.origin : 'http://localhost')
|
|
208
|
+
return new URL(this.options.url ?? '/realtime', origin).toString().replace(/\/$/, '')
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Join a channel (the connection opens or is updated). */
|
|
212
|
+
channel(name: string): ClientChannel {
|
|
213
|
+
let channel = this.channels.get(name)
|
|
214
|
+
if (!channel) {
|
|
215
|
+
channel = new ClientChannel(name, this)
|
|
216
|
+
this.channels.set(name, channel)
|
|
217
|
+
if (this.options.transport === 'ws' && this.socket?.readyState === 1)
|
|
218
|
+
this.socket.send(JSON.stringify({ type: 'subscribe', channel: name, lastId: this.lastId }))
|
|
219
|
+
else this.schedule()
|
|
220
|
+
}
|
|
221
|
+
return channel
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
leave(name: string): void {
|
|
225
|
+
if (!this.channels.delete(name)) return
|
|
226
|
+
if (this.options.transport === 'ws') this.socket?.send(JSON.stringify({ type: 'unsubscribe', channel: name }))
|
|
227
|
+
else this.schedule()
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
whisper(channel: string, event: string, data?: unknown): void {
|
|
231
|
+
if (this.options.transport !== 'ws') throw new Error('Whispers need the WebSocket transport (transport: "ws")')
|
|
232
|
+
this.socket?.send(JSON.stringify({ type: 'whisper', channel, event, data }))
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
onStatus(handler: (s: Status) => void): () => void {
|
|
236
|
+
this.statusHandlers.add(handler)
|
|
237
|
+
return () => this.statusHandlers.delete(handler)
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
close(): void {
|
|
241
|
+
this.closed = true
|
|
242
|
+
clearTimeout(this.reopen)
|
|
243
|
+
this.abort?.abort()
|
|
244
|
+
this.socket?.close()
|
|
245
|
+
this.setStatus('closed')
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
private setStatus(status: Status) {
|
|
249
|
+
if (this.status === status) return
|
|
250
|
+
this.status = status
|
|
251
|
+
for (const h of [...this.statusHandlers]) h(status)
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** Open (or reopen with the new channel set) soon: several `channel()` calls in a row make one request. */
|
|
255
|
+
private schedule(delay = 10) {
|
|
256
|
+
if (this.closed) return
|
|
257
|
+
clearTimeout(this.reopen)
|
|
258
|
+
this.reopen = setTimeout(() => void this.open(), delay)
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
private retry() {
|
|
262
|
+
if (this.closed) return
|
|
263
|
+
const min = this.options.backoff?.min ?? 500
|
|
264
|
+
const max = this.options.backoff?.max ?? 15_000
|
|
265
|
+
const delay = Math.min(max, min * 2 ** this.attempt++) * (0.75 + Math.random() * 0.5)
|
|
266
|
+
this.setStatus('connecting')
|
|
267
|
+
this.schedule(delay)
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
private handle(frame: { type: string; channel?: string; reason?: string; message?: ChannelMessage }) {
|
|
271
|
+
const channel = frame.channel ? this.channels.get(frame.channel) : undefined
|
|
272
|
+
if (frame.type === 'subscribed' && channel) channel.setState('subscribed')
|
|
273
|
+
else if (frame.type === 'denied' && channel) channel.setState('denied', frame.reason)
|
|
274
|
+
else if (frame.type === 'message' && frame.message) {
|
|
275
|
+
if (frame.message.id && !frame.message.whisper) this.lastId = frame.message.id
|
|
276
|
+
this.channels.get(frame.message.channel)?.dispatch(frame.message)
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
private async open() {
|
|
281
|
+
if (this.closed) return
|
|
282
|
+
this.abort?.abort()
|
|
283
|
+
this.socket?.close()
|
|
284
|
+
if (!this.channels.size) return
|
|
285
|
+
if (this.options.transport === 'ws') this.openSocket()
|
|
286
|
+
else await this.openStream()
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
private async openStream() {
|
|
290
|
+
const controller = new AbortController()
|
|
291
|
+
this.abort = controller
|
|
292
|
+
const url = new URL(`${this.base}/sse`)
|
|
293
|
+
url.searchParams.set('channels', [...this.channels.keys()].join(','))
|
|
294
|
+
if (this.lastId) url.searchParams.set('lastEventId', this.lastId)
|
|
295
|
+
try {
|
|
296
|
+
const res = await (this.options.fetch ?? fetch)(url, {
|
|
297
|
+
headers: { accept: 'text/event-stream', ...(this.lastId ? { 'last-event-id': this.lastId } : {}) },
|
|
298
|
+
signal: controller.signal,
|
|
299
|
+
credentials: 'same-origin',
|
|
300
|
+
})
|
|
301
|
+
if (!res.ok || !res.body) throw new Error(`status ${res.status}`)
|
|
302
|
+
this.attempt = 0
|
|
303
|
+
this.setStatus('open')
|
|
304
|
+
for await (const e of readSse(res.body, controller.signal)) {
|
|
305
|
+
if (e.event === 'message')
|
|
306
|
+
this.handle({ type: 'message', message: { ...(e.data as ChannelMessage), id: e.id } })
|
|
307
|
+
else this.handle(e.data as { type: string })
|
|
308
|
+
}
|
|
309
|
+
} catch {
|
|
310
|
+
if (controller.signal.aborted) return
|
|
311
|
+
}
|
|
312
|
+
// the stream ended (rotation, a deploy) or failed: come back, resuming from the last id
|
|
313
|
+
if (!controller.signal.aborted) this.retry()
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
private openSocket() {
|
|
317
|
+
const Ws = this.options.WebSocket ?? WebSocket
|
|
318
|
+
const socket = new Ws(`${this.base.replace(/^http/, 'ws')}/ws`)
|
|
319
|
+
this.socket = socket
|
|
320
|
+
socket.onopen = () => {
|
|
321
|
+
this.attempt = 0
|
|
322
|
+
this.setStatus('open')
|
|
323
|
+
for (const name of this.channels.keys())
|
|
324
|
+
socket.send(JSON.stringify({ type: 'subscribe', channel: name, lastId: this.lastId }))
|
|
325
|
+
}
|
|
326
|
+
socket.onmessage = (e) => {
|
|
327
|
+
try {
|
|
328
|
+
this.handle(JSON.parse(String(e.data)))
|
|
329
|
+
} catch {}
|
|
330
|
+
}
|
|
331
|
+
socket.onclose = () => {
|
|
332
|
+
if (this.socket === socket) this.retry()
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/** Connect to the app's realtime endpoints: `const rt = connect(); rt.channel('chats.42').on('message', …)`. */
|
|
338
|
+
export function connect(options: ConnectOptions = {}): RealtimeClient {
|
|
339
|
+
return new RealtimeClient(options)
|
|
340
|
+
}
|