@prunellejs/live 0.7.4 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/llms.txt CHANGED
@@ -21,6 +21,8 @@
21
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
22
  - `ConnectionLimits`: `maxConnectionsPerRoom` (`1000`), `maxConnectionsPerClient` (`10`, returns `429`), `maxTotalConnections` (`10000`, returns `503`), `clientKey(ctx)` (defaults to `ctx.ip`), `highWaterMark` (`64`).
23
23
 
24
+ - `replay` (default `0`, none): events with an `id` each room keeps (at most 1000 rooms). A client reconnecting with `Last-Event-ID` or `?lastEventId=` (what `useLive` sends on a new connection) first gets the kept events published after that id; an id no longer kept replays nothing. Rooms and buffers are per process: a restart or another replica starts empty, and a message published on one process never reaches another.
25
+
24
26
  ## Handle Methods & Client Hook
25
27
 
26
28
  - `rooms.publish(room, message, event?, id?)`: broadcasts JSON-serialized SSE frames to all room subscribers.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prunellejs/live",
3
- "version": "0.7.4",
3
+ "version": "0.8.0",
4
4
  "description": "Zero-dependency typed SSE rooms and coalesced presence plugin for Prunelle",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -22,6 +22,6 @@
22
22
  "directory": "packages/plugin-live"
23
23
  },
24
24
  "peerDependencies": {
25
- "prunelle": "^0.7.4"
25
+ "prunelle": "^0.8.0"
26
26
  }
27
27
  }
package/src/client.ts CHANGED
@@ -37,6 +37,7 @@ export function useLive<TMessage>(
37
37
  const last = signal<TMessage | undefined>(undefined)
38
38
  let source: EventSource | undefined
39
39
  let reconnectTimer: ReturnType<typeof setTimeout> | undefined
40
+ let lastEventId: string | undefined
40
41
  let attempt = 0
41
42
  let hasOpened = false
42
43
  let manuallyClosed = false
@@ -88,9 +89,11 @@ export function useLive<TMessage>(
88
89
  const connect = () => {
89
90
  clearReconnectTimer()
90
91
  status.value = 'connecting'
92
+ // A new EventSource cannot send Last-Event-ID, so the last id seen goes in the query for the server's replay.
93
+ const target = lastEventId === undefined ? url : `${url}${url.includes('?') ? '&' : '?'}lastEventId=${encodeURIComponent(lastEventId)}`
91
94
  const es = options?.withCredentials !== undefined
92
- ? new EventSource(url, { withCredentials: options.withCredentials })
93
- : new EventSource(url)
95
+ ? new EventSource(target, { withCredentials: options.withCredentials })
96
+ : new EventSource(target)
94
97
  source = es
95
98
 
96
99
  es.onopen = () => {
@@ -120,6 +123,9 @@ export function useLive<TMessage>(
120
123
  const data = (ev as MessageEvent<unknown>).data
121
124
  if (typeof data !== 'string')
122
125
  return
126
+ const id = (ev as MessageEvent<unknown>).lastEventId
127
+ if (id)
128
+ lastEventId = id
123
129
  let parsed: TMessage
124
130
  try {
125
131
  parsed = JSON.parse(data) as TMessage
package/src/index.ts CHANGED
@@ -31,6 +31,12 @@ export interface ConnectionLimits {
31
31
  }
32
32
 
33
33
  interface RoomsBaseOptions extends ConnectionLimits {
34
+ /**
35
+ * How many recent events with an `id` each room keeps for a client that reconnects with `Last-Event-ID` (default: 0, none kept).
36
+ * A reconnecting client gets the kept events published after its id, and nothing when its id is no longer kept.
37
+ * The buffer lives in this process: another process or a restart starts empty.
38
+ */
39
+ replay?: number | undefined
34
40
  /** Optional authorization hook checked before opening an SSE stream. */
35
41
  authorize?: LiveAuthorizeHook | undefined
36
42
  }
@@ -73,6 +79,7 @@ const DEFAULT_MAX_PER_ROOM = 1_000
73
79
  const DEFAULT_MAX_PER_CLIENT = 10
74
80
  const DEFAULT_MAX_TOTAL = 10_000
75
81
  const DEFAULT_HIGH_WATER_MARK = 64 * 1024
82
+ const MAX_REPLAY_ROOMS = 1_000
76
83
 
77
84
  const encoder = new TextEncoder()
78
85
  const CR_LF_RE = /[\r\n]/
@@ -113,6 +120,8 @@ interface RoomState<TMember> {
113
120
  leave(room: string, sub: Subscriber<TMember>): void
114
121
  size(room: string): number
115
122
  getActiveConnections(): number
123
+ /** The kept events of `room` published after the one with `lastEventId`, none when that id is not kept. */
124
+ missedSince(room: string, lastEventId: string): Uint8Array[]
116
125
  }
117
126
 
118
127
  function clientIdOf<TMember>(state: RoomState<TMember>, ctx: RequestContext, opts: ConnectionLimits): string | undefined {
@@ -236,6 +245,11 @@ function openRoomStream<TMember>(
236
245
 
237
246
  try {
238
247
  controller.enqueue(RETRY_CHUNK)
248
+ // Replayed before joining, so a live event cannot land between the replay and the first live chunk.
249
+ const lastEventId = ctx.request.headers.get('last-event-id') ?? ctx.url.searchParams.get('lastEventId')
250
+ if (lastEventId)
251
+ for (const chunk of state.missedSince(room, lastEventId))
252
+ controller.enqueue(chunk)
239
253
  state.join(room, sub)
240
254
  joined = true
241
255
  onJoin?.(room, member)
@@ -275,6 +289,58 @@ function openRoomStream<TMember>(
275
289
  })
276
290
  }
277
291
 
292
+ // One timer per ping interval, however many subscribers share it; it stops with the last of them.
293
+ function createPingScheduler<TMember>(): (ms: number, sub: Subscriber<TMember>) => () => void {
294
+ const pingers = new Map<number, { subs: Set<Subscriber<TMember>>, timer: ReturnType<typeof setInterval> }>()
295
+ return (ms, sub) => {
296
+ let pinger = pingers.get(ms)
297
+ if (pinger === undefined) {
298
+ const subs = new Set<Subscriber<TMember>>()
299
+ const timer = setInterval(() => {
300
+ for (const each of [...subs])
301
+ each.send(PING_CHUNK)
302
+ }, ms)
303
+ ;(timer as unknown as { unref?: () => void }).unref?.()
304
+ pinger = { subs, timer }
305
+ pingers.set(ms, pinger)
306
+ }
307
+ const held = pinger
308
+ held.subs.add(sub)
309
+ return () => {
310
+ held.subs.delete(sub)
311
+ if (held.subs.size === 0 && pingers.get(ms) === held) {
312
+ clearInterval(held.timer)
313
+ pingers.delete(ms)
314
+ }
315
+ }
316
+ }
317
+ }
318
+
319
+ // Recent events with an id, per room, for `Last-Event-ID`. Bounded twice: `limit` events a room, and MAX_REPLAY_ROOMS rooms (the least recently published goes first).
320
+ function createReplayBuffer(limit: number): {
321
+ remember: (room: string, id: string, chunk: Uint8Array) => void
322
+ missedSince: (room: string, lastEventId: string) => Uint8Array[]
323
+ } {
324
+ const buffers = new Map<string, { id: string, chunk: Uint8Array }[]>()
325
+ return {
326
+ remember(room, id, chunk) {
327
+ const buffer = buffers.get(room) ?? []
328
+ buffers.delete(room)
329
+ buffers.set(room, buffer)
330
+ buffer.push({ id, chunk })
331
+ if (buffer.length > limit)
332
+ buffer.shift()
333
+ if (buffers.size > MAX_REPLAY_ROOMS)
334
+ buffers.delete(buffers.keys().next().value!)
335
+ },
336
+ missedSince(room, lastEventId) {
337
+ const buffer = buffers.get(room)
338
+ const at = buffer?.findLastIndex(entry => entry.id === lastEventId) ?? -1
339
+ return at < 0 ? [] : buffer!.slice(at + 1).map(entry => entry.chunk)
340
+ },
341
+ }
342
+ }
343
+
278
344
  export function createRooms<TMessage, TMember = undefined>(
279
345
  options: RoomsOptions<TMember> = {},
280
346
  ): Rooms<TMessage, TMember> {
@@ -320,14 +386,22 @@ export function createRooms<TMessage, TMember = undefined>(
320
386
  return map.get(room)?.size ?? 0
321
387
  }
322
388
 
389
+ const replayLimit = Math.max(0, Math.floor(options.replay ?? 0))
390
+ const { remember, missedSince } = createReplayBuffer(replayLimit)
391
+
323
392
  function publish(room: string, message: TMessage, event?: string, eventId?: string): void {
324
393
  // Validate event & id eagerly even if room is empty so injection attempts always fail fast
325
394
  assertSafeSseField(event, 'event name')
326
395
  assertSafeSseField(eventId, 'event id')
327
396
  const set = map.get(room)
328
- if (set === undefined || set.size === 0)
397
+ const keep = eventId !== undefined && eventId !== '' && replayLimit > 0
398
+ if (!keep && (set === undefined || set.size === 0))
329
399
  return
330
400
  const chunk = encodeEvent(message, event, eventId)
401
+ if (keep)
402
+ remember(room, eventId, chunk)
403
+ if (set === undefined)
404
+ return
331
405
  for (const sub of [...set]) {
332
406
  try {
333
407
  sub.send(chunk)
@@ -360,30 +434,7 @@ export function createRooms<TMessage, TMember = undefined>(
360
434
  }
361
435
  }
362
436
 
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
- }
437
+ const schedulePing = createPingScheduler<TMember>()
387
438
 
388
439
  const roomState: RoomState<TMember> = {
389
440
  defaultOpts,
@@ -393,6 +444,7 @@ export function createRooms<TMessage, TMember = undefined>(
393
444
  leave,
394
445
  size,
395
446
  getActiveConnections: () => activeConnections,
447
+ missedSince,
396
448
  }
397
449
 
398
450
  function stream(ctx: RequestContext, opts: StreamOptions<TMember>): Response {