@cslug/realtime 0.0.0-stage → 0.18.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
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import type { Instrumentation, PubSub } from '@cslug/core'
|
|
2
|
+
import type { Channels, RealtimeUser } from './channels'
|
|
3
|
+
import { ClientSubscribed, ClientUnsubscribed } from './events'
|
|
4
|
+
import { compareIds, type History, type RealtimeMessage } from './history'
|
|
5
|
+
import { type Realtime, topicOf } from './realtime'
|
|
6
|
+
|
|
7
|
+
type Listener = (message: RealtimeMessage) => void
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* This process's subscriptions: one `PubSub` subscription per channel that has local listeners, shared by them,
|
|
11
|
+
* removed with the last one.
|
|
12
|
+
*/
|
|
13
|
+
export class Hub {
|
|
14
|
+
private readonly channels = new Map<string, { listeners: Set<Listener>; off: Promise<() => Promise<void>> }>()
|
|
15
|
+
|
|
16
|
+
constructor(private readonly pubsub: () => PubSub) {}
|
|
17
|
+
|
|
18
|
+
/** Listen to a channel; resolves once the subscription is active. Returns the leave function. */
|
|
19
|
+
async join(channel: string, listener: Listener): Promise<() => Promise<void>> {
|
|
20
|
+
let entry = this.channels.get(channel)
|
|
21
|
+
if (!entry) {
|
|
22
|
+
const listeners = new Set<Listener>()
|
|
23
|
+
const off = this.pubsub().subscribe(topicOf(channel), (raw) => {
|
|
24
|
+
let message: RealtimeMessage
|
|
25
|
+
try {
|
|
26
|
+
message = JSON.parse(raw) as RealtimeMessage
|
|
27
|
+
} catch {
|
|
28
|
+
return
|
|
29
|
+
}
|
|
30
|
+
for (const l of [...listeners]) l(message)
|
|
31
|
+
})
|
|
32
|
+
entry = { listeners, off }
|
|
33
|
+
this.channels.set(channel, entry)
|
|
34
|
+
}
|
|
35
|
+
entry.listeners.add(listener)
|
|
36
|
+
const joined = entry
|
|
37
|
+
await joined.off
|
|
38
|
+
return async () => {
|
|
39
|
+
joined.listeners.delete(listener)
|
|
40
|
+
if (joined.listeners.size || this.channels.get(channel) !== joined) return
|
|
41
|
+
this.channels.delete(channel)
|
|
42
|
+
await (await joined.off)()
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Channels with listeners in this process. */
|
|
47
|
+
get size(): number {
|
|
48
|
+
return this.channels.size
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async close(): Promise<void> {
|
|
52
|
+
const all = [...this.channels.values()]
|
|
53
|
+
this.channels.clear()
|
|
54
|
+
for (const e of all) await (await e.off)().catch(() => {})
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** What a connection sends its client. */
|
|
59
|
+
export type Outgoing =
|
|
60
|
+
| { type: 'message'; message: RealtimeMessage }
|
|
61
|
+
| { type: 'subscribed'; channel: string }
|
|
62
|
+
| { type: 'unsubscribed'; channel: string }
|
|
63
|
+
| { type: 'denied'; channel: string; reason: string }
|
|
64
|
+
| { type: 'error'; reason: string }
|
|
65
|
+
|
|
66
|
+
export type ConnectionLimits = { channels: number; whispersPerSecond: number }
|
|
67
|
+
|
|
68
|
+
/** One client (an SSE stream or a socket): its channels, authorized, with replay and live messages in order. */
|
|
69
|
+
export class Connection {
|
|
70
|
+
readonly id = Bun.randomUUIDv7()
|
|
71
|
+
private readonly joined = new Map<string, { leave: () => Promise<void>; private: boolean }>()
|
|
72
|
+
private whispers: number[] = []
|
|
73
|
+
private closed = false
|
|
74
|
+
|
|
75
|
+
constructor(
|
|
76
|
+
private readonly deps: {
|
|
77
|
+
hub: Hub
|
|
78
|
+
channels: Channels
|
|
79
|
+
history: () => History
|
|
80
|
+
realtime: Realtime
|
|
81
|
+
instrumentation: Instrumentation
|
|
82
|
+
},
|
|
83
|
+
readonly user: RealtimeUser | null,
|
|
84
|
+
readonly transport: 'sse' | 'ws',
|
|
85
|
+
private readonly send: (out: Outgoing) => void,
|
|
86
|
+
private readonly limits: ConnectionLimits,
|
|
87
|
+
) {}
|
|
88
|
+
|
|
89
|
+
get channels(): string[] {
|
|
90
|
+
return [...this.joined.keys()]
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
private get userId(): string | null {
|
|
94
|
+
return this.user ? String(this.user.id) : null
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Join a channel if allowed; replay what came after `lastId`, then live messages (none twice, in order). */
|
|
98
|
+
async subscribe(channel: string, lastId?: string): Promise<boolean> {
|
|
99
|
+
if (this.closed || this.joined.has(channel)) return this.joined.has(channel)
|
|
100
|
+
if (this.joined.size >= this.limits.channels) {
|
|
101
|
+
this.send({ type: 'denied', channel, reason: 'too_many_channels' })
|
|
102
|
+
return false
|
|
103
|
+
}
|
|
104
|
+
const auth = await this.deps.channels.authorize(channel, this.user)
|
|
105
|
+
this.deps.instrumentation.report('realtime', () => ({
|
|
106
|
+
operation: 'subscribe',
|
|
107
|
+
channel,
|
|
108
|
+
transport: this.transport,
|
|
109
|
+
denied: !auth.allowed,
|
|
110
|
+
...(auth.allowed ? {} : { reason: auth.reason }),
|
|
111
|
+
}))
|
|
112
|
+
if (!auth.allowed) {
|
|
113
|
+
this.send({ type: 'denied', channel, reason: auth.reason })
|
|
114
|
+
return false
|
|
115
|
+
}
|
|
116
|
+
// live messages wait while the history is replayed, then only those after it go out
|
|
117
|
+
let replaying = true
|
|
118
|
+
const buffered: RealtimeMessage[] = []
|
|
119
|
+
let last = lastId
|
|
120
|
+
const deliver = (message: RealtimeMessage) => {
|
|
121
|
+
if (message.from === this.id) return // a whisper is for the others
|
|
122
|
+
if (last && !message.whisper && compareIds(message.id, last) <= 0) return
|
|
123
|
+
if (!message.whisper) last = message.id
|
|
124
|
+
this.send({ type: 'message', message })
|
|
125
|
+
}
|
|
126
|
+
const leave = await this.deps.hub.join(channel, (message) => {
|
|
127
|
+
if (replaying) buffered.push(message)
|
|
128
|
+
else deliver(message)
|
|
129
|
+
})
|
|
130
|
+
if (this.closed) {
|
|
131
|
+
await leave()
|
|
132
|
+
return false
|
|
133
|
+
}
|
|
134
|
+
this.joined.set(channel, { leave, private: auth.private })
|
|
135
|
+
this.send({ type: 'subscribed', channel })
|
|
136
|
+
if (lastId) for (const message of await this.deps.history().since(channel, lastId)) deliver(message)
|
|
137
|
+
replaying = false
|
|
138
|
+
for (const message of buffered) deliver(message)
|
|
139
|
+
await ClientSubscribed.emit({ channel, userId: this.userId, connectionId: this.id, transport: this.transport })
|
|
140
|
+
return true
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
async unsubscribe(channel: string): Promise<void> {
|
|
144
|
+
const entry = this.joined.get(channel)
|
|
145
|
+
if (!entry) return
|
|
146
|
+
this.joined.delete(channel)
|
|
147
|
+
await entry.leave()
|
|
148
|
+
this.send({ type: 'unsubscribed', channel })
|
|
149
|
+
await ClientUnsubscribed.emit({ channel, userId: this.userId, connectionId: this.id, transport: this.transport })
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* A client event (typing…) for the channel's other subscribers: only on a private channel this connection joined,
|
|
154
|
+
* at most `whispersPerSecond`, never stored.
|
|
155
|
+
*/
|
|
156
|
+
async whisper(channel: string, event: string, data: unknown): Promise<void> {
|
|
157
|
+
const entry = this.joined.get(channel)
|
|
158
|
+
if (!entry?.private) {
|
|
159
|
+
this.send({ type: 'error', reason: 'whisper_not_allowed' })
|
|
160
|
+
return
|
|
161
|
+
}
|
|
162
|
+
const now = Date.now()
|
|
163
|
+
this.whispers = this.whispers.filter((t) => now - t < 1000)
|
|
164
|
+
if (this.whispers.length >= this.limits.whispersPerSecond) {
|
|
165
|
+
this.send({ type: 'error', reason: 'too_many_whispers' })
|
|
166
|
+
return
|
|
167
|
+
}
|
|
168
|
+
this.whispers.push(now)
|
|
169
|
+
await this.deps.realtime.publish(channel, event, data, { from: this.id, whisper: true })
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
async close(): Promise<void> {
|
|
173
|
+
if (this.closed) return
|
|
174
|
+
this.closed = true
|
|
175
|
+
for (const [channel, entry] of [...this.joined]) {
|
|
176
|
+
this.joined.delete(channel)
|
|
177
|
+
await entry.leave()
|
|
178
|
+
await ClientUnsubscribed.emit({ channel, userId: this.userId, connectionId: this.id, transport: this.transport })
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
package/src/endpoints.ts
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { type HttpContext, type RouteRegistrar, SseEvent, sse, websocket } from '@cslug/http'
|
|
2
|
+
import type { RealtimeUser } from './channels'
|
|
3
|
+
import type { Connection, Outgoing } from './connection'
|
|
4
|
+
|
|
5
|
+
/** What the endpoints need (`RealtimeProvider` builds it). */
|
|
6
|
+
export type EndpointDeps = {
|
|
7
|
+
connect(user: RealtimeUser | null, transport: 'sse' | 'ws', send: (out: Outgoing) => void): Connection
|
|
8
|
+
maxConnectionMs: number
|
|
9
|
+
heartbeatMs: number
|
|
10
|
+
maxChannels: number
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** The signed-in user, when @cslug/auth ran on the route (`ctx.auth`, typed locally: auth is optional). */
|
|
14
|
+
const userOf = (ctx: HttpContext): RealtimeUser | null =>
|
|
15
|
+
(ctx as unknown as { auth?: { userOrNull(): RealtimeUser | null } }).auth?.userOrNull() ?? null
|
|
16
|
+
|
|
17
|
+
/** A push queue read as an async iterable; `return()` (the client left) runs `onClose`. */
|
|
18
|
+
class Queue<T> implements AsyncIterable<T> {
|
|
19
|
+
private items: T[] = []
|
|
20
|
+
private waiting?: (r: IteratorResult<T>) => void
|
|
21
|
+
private ended = false
|
|
22
|
+
|
|
23
|
+
constructor(private readonly onClose: () => unknown) {}
|
|
24
|
+
|
|
25
|
+
push(item: T) {
|
|
26
|
+
if (this.ended) return
|
|
27
|
+
if (this.waiting) {
|
|
28
|
+
const w = this.waiting
|
|
29
|
+
this.waiting = undefined
|
|
30
|
+
w({ value: item, done: false })
|
|
31
|
+
} else this.items.push(item)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
end() {
|
|
35
|
+
if (this.ended) return
|
|
36
|
+
this.ended = true
|
|
37
|
+
void this.onClose()
|
|
38
|
+
this.waiting?.({ value: undefined, done: true })
|
|
39
|
+
this.waiting = undefined
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
[Symbol.asyncIterator](): AsyncIterator<T> {
|
|
43
|
+
return {
|
|
44
|
+
next: () => {
|
|
45
|
+
const item = this.items.shift()
|
|
46
|
+
if (item !== undefined) return Promise.resolve({ value: item, done: false })
|
|
47
|
+
if (this.ended) return Promise.resolve({ value: undefined, done: true })
|
|
48
|
+
return new Promise((resolve) => {
|
|
49
|
+
this.waiting = resolve
|
|
50
|
+
})
|
|
51
|
+
},
|
|
52
|
+
return: async () => {
|
|
53
|
+
this.end()
|
|
54
|
+
return { value: undefined, done: true }
|
|
55
|
+
},
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const toSse = (out: Outgoing): SseEvent =>
|
|
61
|
+
out.type === 'message'
|
|
62
|
+
? new SseEvent({
|
|
63
|
+
event: 'message',
|
|
64
|
+
// whispers carry no id: they are not stored, so a reconnect must not resume from one
|
|
65
|
+
...(out.message.whisper ? {} : { id: out.message.id }),
|
|
66
|
+
data: { channel: out.message.channel, event: out.message.event, data: out.message.data },
|
|
67
|
+
})
|
|
68
|
+
: new SseEvent({ event: out.type, data: out })
|
|
69
|
+
|
|
70
|
+
/** `GET <path>/sse?channels=a,b` and `GET <path>/ws`. */
|
|
71
|
+
export function realtimeRoutes(deps: EndpointDeps) {
|
|
72
|
+
return (r: RouteRegistrar) => {
|
|
73
|
+
r.get('/sse', async (ctx) => {
|
|
74
|
+
const names = [...new Set((ctx.request.query('channels') ?? '').split(',').filter(Boolean))]
|
|
75
|
+
let connection: Connection | undefined
|
|
76
|
+
const queue = new Queue<SseEvent>(() => connection?.close())
|
|
77
|
+
connection = deps.connect(userOf(ctx), 'sse', (out) => queue.push(toSse(out)))
|
|
78
|
+
queue.push(new SseEvent({ retry: 2000, event: 'connected', data: { id: connection.id } }))
|
|
79
|
+
const lastId = ctx.request.lastEventId()
|
|
80
|
+
for (const name of names) await connection.subscribe(name, lastId)
|
|
81
|
+
// rotate long-lived streams (proxies, deploys): the browser reconnects with Last-Event-ID
|
|
82
|
+
const rotate = setTimeout(() => queue.end(), deps.maxConnectionMs)
|
|
83
|
+
rotate.unref?.()
|
|
84
|
+
return sse(queue, { heartbeat: deps.heartbeatMs })
|
|
85
|
+
}).name('stream')
|
|
86
|
+
|
|
87
|
+
r.get('/ws', (ctx) => {
|
|
88
|
+
type Data = { user: RealtimeUser | null; connection?: Connection }
|
|
89
|
+
return websocket<Data>(
|
|
90
|
+
{
|
|
91
|
+
open(socket) {
|
|
92
|
+
socket.data.connection = deps.connect(socket.data.user, 'ws', (out) => socket.send(out))
|
|
93
|
+
socket.send({ type: 'connected', id: socket.data.connection.id })
|
|
94
|
+
},
|
|
95
|
+
async message(socket, raw) {
|
|
96
|
+
const connection = socket.data.connection
|
|
97
|
+
if (!connection) return
|
|
98
|
+
let msg: { type?: string; channel?: string; lastId?: string; event?: string; data?: unknown }
|
|
99
|
+
try {
|
|
100
|
+
msg = JSON.parse(String(raw))
|
|
101
|
+
} catch {
|
|
102
|
+
socket.send({ type: 'error', reason: 'invalid_json' })
|
|
103
|
+
return
|
|
104
|
+
}
|
|
105
|
+
if (msg.type === 'ping') socket.send({ type: 'pong' })
|
|
106
|
+
else if (msg.type === 'subscribe' && msg.channel) await connection.subscribe(msg.channel, msg.lastId)
|
|
107
|
+
else if (msg.type === 'unsubscribe' && msg.channel) await connection.unsubscribe(msg.channel)
|
|
108
|
+
else if (msg.type === 'whisper' && msg.channel && msg.event)
|
|
109
|
+
await connection.whisper(msg.channel, msg.event, msg.data)
|
|
110
|
+
else socket.send({ type: 'error', reason: 'unknown_message' })
|
|
111
|
+
},
|
|
112
|
+
async close(socket) {
|
|
113
|
+
await socket.data.connection?.close()
|
|
114
|
+
},
|
|
115
|
+
},
|
|
116
|
+
{ data: { user: userOf(ctx) } },
|
|
117
|
+
)
|
|
118
|
+
}).name('socket')
|
|
119
|
+
}
|
|
120
|
+
}
|
package/src/events.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { Event } from '@cslug/core'
|
|
2
|
+
|
|
3
|
+
type Payload = { channel: string; userId: string | null; connectionId: string; transport: 'sse' | 'ws' }
|
|
4
|
+
|
|
5
|
+
/** A client joined a channel (after its authorization). */
|
|
6
|
+
export class ClientSubscribed extends Event<Payload>('realtime.client_subscribed') {}
|
|
7
|
+
|
|
8
|
+
/** A client left a channel (or disconnected). */
|
|
9
|
+
export class ClientUnsubscribed extends Event<Payload>('realtime.client_unsubscribed') {}
|
package/src/fake.ts
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { Application } from '@cslug/core'
|
|
2
|
+
import { NoHistory, type RealtimeMessage } from './history'
|
|
3
|
+
import { Realtime } from './realtime'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* `fakes: ['realtime']`: nothing is published; every send is recorded. `t.realtime.assertSent('chats.42', 'token')`.
|
|
7
|
+
*/
|
|
8
|
+
export class RealtimeFake extends Realtime {
|
|
9
|
+
readonly messages: RealtimeMessage[] = []
|
|
10
|
+
|
|
11
|
+
constructor(app: Application) {
|
|
12
|
+
const history = new NoHistory()
|
|
13
|
+
super(app, () => history)
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
override async publish(channel: string, event: string, data: unknown): Promise<string> {
|
|
17
|
+
const id = `${this.messages.length + 1}`
|
|
18
|
+
this.messages.push({ id, channel, event, data })
|
|
19
|
+
return id
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** What was sent on a channel, in order. */
|
|
23
|
+
sent(channel: string, event?: string): RealtimeMessage[] {
|
|
24
|
+
return this.messages.filter((m) => m.channel === channel && (!event || m.event === event))
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The `data` of each event of this name on the channel, joined when they are strings (streamed tokens). */
|
|
28
|
+
text(channel: string, event = 'token'): string {
|
|
29
|
+
return this.sent(channel, event)
|
|
30
|
+
.map((m) => (typeof m.data === 'string' ? m.data : JSON.stringify(m.data)))
|
|
31
|
+
.join('')
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
assertSent(channel: string, event?: string, match?: (data: unknown) => boolean): void {
|
|
35
|
+
if (!this.sent(channel, event).some((m) => !match || match(m.data)))
|
|
36
|
+
throw new Error(
|
|
37
|
+
`Expected ${event ? `"${event}" ` : 'a message '}on ${channel}, got ${
|
|
38
|
+
this.messages.map((m) => `${m.channel}:${m.event}`).join(', ') || 'nothing'
|
|
39
|
+
}`,
|
|
40
|
+
)
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
assertNothingSent(channel?: string): void {
|
|
44
|
+
const found = channel ? this.messages.filter((m) => m.channel === channel) : this.messages
|
|
45
|
+
if (found.length) throw new Error(`Expected nothing sent${channel ? ` on ${channel}` : ''}, got ${found.length}`)
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** `fakes: ['realtime']`. */
|
|
50
|
+
export function installRealtimeFake(app: Application): RealtimeFake {
|
|
51
|
+
const fake = new RealtimeFake(app)
|
|
52
|
+
app.swap(Realtime, fake)
|
|
53
|
+
return fake
|
|
54
|
+
}
|
package/src/history.ts
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/** A message on a channel. `id` orders messages ("<ms>-<seq>", as Redis stream ids); `from` marks a whisper's sender. */
|
|
2
|
+
export type RealtimeMessage = {
|
|
3
|
+
id: string
|
|
4
|
+
channel: string
|
|
5
|
+
event: string
|
|
6
|
+
data: unknown
|
|
7
|
+
from?: string
|
|
8
|
+
whisper?: boolean
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** "<ms>-<seq>" ids compare by time, then sequence. */
|
|
12
|
+
export function compareIds(a: string, b: string): number {
|
|
13
|
+
const [am = 0, as = 0] = a.split('-').map(Number)
|
|
14
|
+
const [bm = 0, bs = 0] = b.split('-').map(Number)
|
|
15
|
+
return am - bm || as - bs
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
let lastMs = 0
|
|
19
|
+
let seq = 0
|
|
20
|
+
/** A new id after every id this process made. */
|
|
21
|
+
export function nextId(now = Date.now()): string {
|
|
22
|
+
if (now > lastMs) {
|
|
23
|
+
lastMs = now
|
|
24
|
+
seq = 0
|
|
25
|
+
} else seq++
|
|
26
|
+
return `${lastMs}-${seq}`
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Recent messages per channel, so a client that reconnects gets what it missed (`Last-Event-ID`). */
|
|
30
|
+
export abstract class History {
|
|
31
|
+
/** Store a message; its id. */
|
|
32
|
+
abstract append(channel: string, message: { event: string; data: unknown }): Promise<string>
|
|
33
|
+
/** The messages after `lastId`, oldest first. */
|
|
34
|
+
abstract since(channel: string, lastId: string): Promise<RealtimeMessage[]>
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** No history: ids only. */
|
|
38
|
+
export class NoHistory extends History {
|
|
39
|
+
async append(): Promise<string> {
|
|
40
|
+
return nextId()
|
|
41
|
+
}
|
|
42
|
+
async since(): Promise<RealtimeMessage[]> {
|
|
43
|
+
return []
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** In this process: the last `size` messages of each channel, for `ttlMs` (one web process only). */
|
|
48
|
+
export class MemoryHistory extends History {
|
|
49
|
+
private readonly channels = new Map<string, { at: number; message: RealtimeMessage }[]>()
|
|
50
|
+
|
|
51
|
+
constructor(
|
|
52
|
+
private readonly size = 200,
|
|
53
|
+
private readonly ttlMs = 10 * 60_000,
|
|
54
|
+
) {
|
|
55
|
+
super()
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async append(channel: string, message: { event: string; data: unknown }): Promise<string> {
|
|
59
|
+
const id = nextId()
|
|
60
|
+
const list = this.channels.get(channel) ?? []
|
|
61
|
+
list.push({ at: Date.now(), message: { id, channel, ...message } })
|
|
62
|
+
if (list.length > this.size) list.splice(0, list.length - this.size)
|
|
63
|
+
this.channels.set(channel, list)
|
|
64
|
+
return id
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async since(channel: string, lastId: string): Promise<RealtimeMessage[]> {
|
|
68
|
+
const fresh = Date.now() - this.ttlMs
|
|
69
|
+
const list = (this.channels.get(channel) ?? []).filter((e) => e.at >= fresh)
|
|
70
|
+
this.channels.set(channel, list)
|
|
71
|
+
return list.filter((e) => compareIds(e.message.id, lastId) > 0).map((e) => e.message)
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** The part of `@cslug/redis`'s `Redis` used here (an optional peer). */
|
|
76
|
+
export type RedisLike = { key(k: string): string; send(command: string, args?: (string | number)[]): Promise<unknown> }
|
|
77
|
+
|
|
78
|
+
/** In Redis: a capped stream per channel (`XADD … MAXLEN ~ size`), expiring `ttl` after its last message. */
|
|
79
|
+
export class RedisHistory extends History {
|
|
80
|
+
constructor(
|
|
81
|
+
private readonly redis: RedisLike,
|
|
82
|
+
private readonly size = 200,
|
|
83
|
+
private readonly ttlSeconds = 600,
|
|
84
|
+
) {
|
|
85
|
+
super()
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
private key(channel: string) {
|
|
89
|
+
return this.redis.key(`realtime:history:${channel}`)
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async append(channel: string, message: { event: string; data: unknown }): Promise<string> {
|
|
93
|
+
const key = this.key(channel)
|
|
94
|
+
const id = String(await this.redis.send('XADD', [key, 'MAXLEN', '~', this.size, '*', 'm', JSON.stringify(message)]))
|
|
95
|
+
await this.redis.send('EXPIRE', [key, this.ttlSeconds])
|
|
96
|
+
return id
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async since(channel: string, lastId: string): Promise<RealtimeMessage[]> {
|
|
100
|
+
if (!/^\d+-\d+$/.test(lastId)) return []
|
|
101
|
+
const entries = (await this.redis.send('XRANGE', [this.key(channel), `(${lastId}`, '+', 'COUNT', this.size])) as
|
|
102
|
+
| [string, string[]][]
|
|
103
|
+
| null
|
|
104
|
+
return (entries ?? []).map(([id, fields]) => {
|
|
105
|
+
const raw = fields[fields.indexOf('m') + 1] ?? '{}'
|
|
106
|
+
const { event, data } = JSON.parse(raw) as { event: string; data: unknown }
|
|
107
|
+
return { id, channel, event, data }
|
|
108
|
+
})
|
|
109
|
+
}
|
|
110
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @cslug/realtime: channels for browsers over server-sent events or WebSockets. Define who may join in
|
|
3
|
+
* `routes/channels.ts`; publish from any process with `realtime.channel(name).send(event, data)`; clients resume
|
|
4
|
+
* from the last id they saw. Messages go through core's `PubSub` (Redis across processes).
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
export {
|
|
8
|
+
type Authorization,
|
|
9
|
+
CHANNEL_NAME,
|
|
10
|
+
type ChannelAuthorizer,
|
|
11
|
+
type ChannelRegistrar,
|
|
12
|
+
Channels,
|
|
13
|
+
defineChannels,
|
|
14
|
+
type RealtimeUser,
|
|
15
|
+
} from './channels'
|
|
16
|
+
export { Connection, type ConnectionLimits, Hub, type Outgoing } from './connection'
|
|
17
|
+
export { type EndpointDeps, realtimeRoutes } from './endpoints'
|
|
18
|
+
export { ClientSubscribed, ClientUnsubscribed } from './events'
|
|
19
|
+
export { installRealtimeFake, RealtimeFake } from './fake'
|
|
20
|
+
export {
|
|
21
|
+
compareIds,
|
|
22
|
+
History,
|
|
23
|
+
MemoryHistory,
|
|
24
|
+
NoHistory,
|
|
25
|
+
nextId,
|
|
26
|
+
type RealtimeMessage,
|
|
27
|
+
RedisHistory,
|
|
28
|
+
type RedisLike,
|
|
29
|
+
} from './history'
|
|
30
|
+
export { type RealtimeConfig, RealtimeProvider } from './provider'
|
|
31
|
+
export { ChannelPublisher, Realtime, topicOf } from './realtime'
|
package/src/provider.ts
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import { CslugError, Instrumentation, PubSub, parseDuration, ServiceProvider } from '@cslug/core'
|
|
4
|
+
import { HttpKernel, HttpProvider, type Middleware, Router, WEB_MIDDLEWARE } from '@cslug/http'
|
|
5
|
+
import { csrf, session } from '@cslug/http/middleware'
|
|
6
|
+
import { type ChannelRegistrar, Channels } from './channels'
|
|
7
|
+
import { Connection, Hub } from './connection'
|
|
8
|
+
import { realtimeRoutes } from './endpoints'
|
|
9
|
+
import { History, MemoryHistory, NoHistory, RedisHistory, type RedisLike } from './history'
|
|
10
|
+
import { Realtime } from './realtime'
|
|
11
|
+
|
|
12
|
+
/** `config/realtime.ts`. */
|
|
13
|
+
export type RealtimeConfig = {
|
|
14
|
+
/** Where the endpoints are (default `/realtime`: `/realtime/sse`, `/realtime/ws`); false: none (a worker). */
|
|
15
|
+
path?: string | false
|
|
16
|
+
/** Recent messages kept per channel for clients that reconnect (default 200 for 10 minutes); false: none. */
|
|
17
|
+
history?: { size?: number; ttl?: string | number } | false
|
|
18
|
+
/** An SSE stream ends after this long and the browser reconnects (default `1h`). */
|
|
19
|
+
maxConnectionTime?: string | number
|
|
20
|
+
/** SSE heartbeat (ms, default 15000). */
|
|
21
|
+
heartbeat?: number
|
|
22
|
+
limits?: { channels?: number; whispersPerSecond?: number }
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const importOptional = <M>(name: string): Promise<M> => import(name)
|
|
26
|
+
type RedisModule = { Redis: new (...a: never[]) => RedisLike }
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Realtime channels: binds `Realtime`, `Channels` and the hub; loads `routes/channels.ts`; adds `/realtime/sse` and
|
|
30
|
+
* `/realtime/ws` with the web group's middleware (session, auth), so a channel's authorization knows the user. With
|
|
31
|
+
* `@cslug/redis`, the history is a Redis stream per channel (shared by the web processes).
|
|
32
|
+
*/
|
|
33
|
+
export class RealtimeProvider extends ServiceProvider {
|
|
34
|
+
static dependsOn = [HttpProvider]
|
|
35
|
+
private history?: History
|
|
36
|
+
|
|
37
|
+
private get config(): RealtimeConfig {
|
|
38
|
+
return this.app.config<RealtimeConfig | undefined>('realtime') ?? {}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
register() {
|
|
42
|
+
this.app.singleton(Channels, () => new Channels())
|
|
43
|
+
this.app.singleton(Hub, () => new Hub(() => this.app.resolve(PubSub)))
|
|
44
|
+
this.app.singleton(History, () => this.history ?? new MemoryHistory())
|
|
45
|
+
this.app.singleton(Realtime, (c) => new Realtime(this.app, () => c.resolve(History)))
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async boot() {
|
|
49
|
+
const config = this.config
|
|
50
|
+
const history = config.history
|
|
51
|
+
if (history === false) this.history = new NoHistory()
|
|
52
|
+
else {
|
|
53
|
+
const size = history?.size ?? 200
|
|
54
|
+
const ttl = parseDuration(history?.ttl ?? '10m')
|
|
55
|
+
const redis = await importOptional<RedisModule>('@cslug/redis').catch(() => undefined)
|
|
56
|
+
this.history =
|
|
57
|
+
redis && this.app.has(redis.Redis as never)
|
|
58
|
+
? new RedisHistory(this.app.resolve(redis.Redis as never) as RedisLike, size, Math.ceil(ttl / 1000))
|
|
59
|
+
: new MemoryHistory(size, ttl)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const file = join(this.app.rootDir, 'routes/channels.ts')
|
|
63
|
+
if (existsSync(file)) {
|
|
64
|
+
const mod = (await import(file)) as { default?: (c: ChannelRegistrar) => void }
|
|
65
|
+
if (typeof mod.default !== 'function')
|
|
66
|
+
throw new CslugError(
|
|
67
|
+
'realtime.channels_file',
|
|
68
|
+
'routes/channels.ts must `export default defineChannels((c) => { … })`',
|
|
69
|
+
)
|
|
70
|
+
this.app.resolve(Channels).load(mod.default)
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const path = config.path ?? '/realtime'
|
|
74
|
+
if (path === false || !this.app.has(Router)) return
|
|
75
|
+
const limits = {
|
|
76
|
+
channels: config.limits?.channels ?? 50,
|
|
77
|
+
whispersPerSecond: config.limits?.whispersPerSecond ?? 10,
|
|
78
|
+
}
|
|
79
|
+
const deps = {
|
|
80
|
+
hub: this.app.resolve(Hub),
|
|
81
|
+
channels: this.app.resolve(Channels),
|
|
82
|
+
history: () => this.app.resolve(History),
|
|
83
|
+
realtime: this.app.resolve(Realtime),
|
|
84
|
+
instrumentation: this.app.resolve(Instrumentation),
|
|
85
|
+
}
|
|
86
|
+
// the web group's middleware: the session and @cslug/auth's authenticate(), so channels know the user
|
|
87
|
+
const middleware: Middleware[] = [session(), csrf(), ...this.app.tagged<Middleware>(WEB_MIDDLEWARE)]
|
|
88
|
+
this.app.resolve(Router).load(
|
|
89
|
+
realtimeRoutes({
|
|
90
|
+
connect: (user, transport, send) => new Connection(deps, user, transport, send, limits),
|
|
91
|
+
maxConnectionMs: parseDuration(config.maxConnectionTime ?? '1h'),
|
|
92
|
+
heartbeatMs: config.heartbeat ?? 15_000,
|
|
93
|
+
maxChannels: limits.channels,
|
|
94
|
+
}),
|
|
95
|
+
{ prefix: path, as: 'realtime', middleware },
|
|
96
|
+
)
|
|
97
|
+
this.app.resolve(HttpKernel).compile()
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async shutdown() {
|
|
101
|
+
await this.app.resolve(Hub).close()
|
|
102
|
+
}
|
|
103
|
+
}
|
package/src/realtime.ts
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { type Application, CslugError, Instrumentation, PubSub } from '@cslug/core'
|
|
2
|
+
import { CHANNEL_NAME } from './channels'
|
|
3
|
+
import { type History, nextId, type RealtimeMessage } from './history'
|
|
4
|
+
|
|
5
|
+
export const topicOf = (channel: string) => `realtime:${channel}`
|
|
6
|
+
|
|
7
|
+
/** Publishing to one channel: `realtime.channel('chats.42').send('message', { text })`. */
|
|
8
|
+
export class ChannelPublisher {
|
|
9
|
+
constructor(
|
|
10
|
+
private readonly realtime: Realtime,
|
|
11
|
+
readonly name: string,
|
|
12
|
+
) {}
|
|
13
|
+
|
|
14
|
+
/** Send one event to everyone on the channel, in every process. Its id (for resuming). */
|
|
15
|
+
send(event: string, data?: unknown): Promise<string> {
|
|
16
|
+
return this.realtime.publish(this.name, event, data)
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Send each item of `source` as an event (`token` by default), then `done` (or a `error` event with `{ message }`
|
|
21
|
+
* when it fails, and the error is thrown again). An AI run in a job reaches the browser this way:
|
|
22
|
+
* `await realtime.channel(`chats.${id}`).stream(agent.stream({ input }))`.
|
|
23
|
+
*/
|
|
24
|
+
async stream(
|
|
25
|
+
source: AsyncIterable<unknown>,
|
|
26
|
+
options: { event?: string; done?: string | false; doneData?: unknown } = {},
|
|
27
|
+
): Promise<number> {
|
|
28
|
+
let count = 0
|
|
29
|
+
try {
|
|
30
|
+
for await (const item of source) {
|
|
31
|
+
await this.send(options.event ?? 'token', item)
|
|
32
|
+
count++
|
|
33
|
+
}
|
|
34
|
+
} catch (error) {
|
|
35
|
+
await this.send('error', { message: error instanceof Error ? error.message : String(error) })
|
|
36
|
+
throw error
|
|
37
|
+
}
|
|
38
|
+
if (options.done !== false) await this.send(options.done ?? 'done', options.doneData ?? {})
|
|
39
|
+
return count
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Channels for browsers: `channel(name).send(event, data)` from any process (a web request, a job, a scheduled
|
|
45
|
+
* task). Messages go through core's `PubSub` (Redis across processes) to the web processes, which hand them to the
|
|
46
|
+
* subscribed connections; recent ones are kept for clients that reconnect.
|
|
47
|
+
*/
|
|
48
|
+
export class Realtime {
|
|
49
|
+
constructor(
|
|
50
|
+
protected readonly app: Application,
|
|
51
|
+
private readonly history: () => History,
|
|
52
|
+
) {}
|
|
53
|
+
|
|
54
|
+
channel(name: string): ChannelPublisher {
|
|
55
|
+
if (!CHANNEL_NAME.test(name))
|
|
56
|
+
throw new CslugError('realtime.invalid_channel', `"${name}" is not a channel name (letters, digits, _-.:=@)`)
|
|
57
|
+
return new ChannelPublisher(this, name)
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** @internal Store (unless a whisper) and publish one message. */
|
|
61
|
+
async publish(channel: string, event: string, data: unknown, options: { from?: string; whisper?: boolean } = {}) {
|
|
62
|
+
const id = options.whisper ? nextId() : await this.history().append(channel, { event, data })
|
|
63
|
+
const message: RealtimeMessage = { id, channel, event, data, ...options }
|
|
64
|
+
await this.app.resolve(PubSub).publish(topicOf(channel), JSON.stringify(message))
|
|
65
|
+
this.app.resolve(Instrumentation).report('realtime', () => ({
|
|
66
|
+
operation: options.whisper ? 'whisper' : 'publish',
|
|
67
|
+
channel,
|
|
68
|
+
event,
|
|
69
|
+
data,
|
|
70
|
+
}))
|
|
71
|
+
return id
|
|
72
|
+
}
|
|
73
|
+
}
|