Files
superlist/apps/api/src/modules/lists/events/route.ts
Jose Selesan 4ed6432f60 feat: push live list changes over server-sent events
Every member viewing a list opens one SSE stream
(`GET /api/lists/:listId/events`) and refreshes the affected queries when
somebody else adds or buys an item, invites a person or renames the list, so
shared lists stay in sync without a reload.

- `@superlist/shared`: `ListEvent` / `ListEventType` contract.
- API: in-process `ListEvents` pub/sub keyed by list id; a `requireListMembership`
  middleware; a `streamSSE` route with a reconnect `ready` frame and a heartbeat,
  plus `server.timeout(req, 0)` so Bun does not close the quiet stream. Use cases
  publish `item.created`, `item.updated`, `list.updated`, `member.added` and
  `invitation.created` after their writes.
- Web: `useListEvents` subscribes with `EventSource` (`withCredentials`) and
  invalidates the matching TanStack Query keys, mounted where a list is shown and
  in the list settings page.

The API is reached through the same-origin `/api` prefix: every module is mounted
under `/api/*`, `apiBaseUrl` always appends `/api` to the optional `VITE_API_URL`,
the BetterAuth client points at the page origin, and Vite proxies `/api` to the
Bun API in dev (nginx does in production).
2026-10-16 14:58:31 -03:00

76 lines
2.2 KiB
TypeScript

import type { ListEvent } from '@superlist/shared'
import { Hono } from 'hono'
import { streamSSE } from 'hono/streaming'
import { requireSession } from '@/lib/auth-session'
import { listEvents } from '@/lib/events'
import { requireListMembership } from '@/lib/list-access'
import { validate } from '@/lib/validate'
import { ListParamsSchema } from '@/modules/lists/schema'
import type { AppEnv } from '@/types'
/** Maximum silence between frames; a comment heartbeat is sent in between. */
const HEARTBEAT_MS = 20_000
/**
* GET /lists/:listId/events — Server-Sent Events stream with the changes
* happening on a list (items, members, invitations). Members only.
*
* Events are buffered and written as they arrive; while the list is quiet a
* comment heartbeat keeps the connection open through Bun's idle timeout and
* any proxy in between.
*/
export const listEventsRoute = new Hono<AppEnv>().get(
'/',
requireSession,
validate.param(ListParamsSchema),
requireListMembership,
(c) => {
const { listId } = c.req.valid('param')
return streamSSE(c, async (stream) => {
const pending: ListEvent[] = []
// Resolves a pending wait as soon as an event is buffered, so nothing has
// to wait for the heartbeat interval.
let wake: (() => void) | undefined
const unsubscribe = listEvents.subscribe(listId, (event) => {
pending.push(event)
wake?.()
})
stream.onAbort(() => unsubscribe())
const waitForEvent = () =>
new Promise<void>((resolve) => {
wake = resolve
})
await stream.writeSSE({ event: 'ready', data: JSON.stringify({ listId }) })
while (!stream.aborted) {
const event = pending.shift()
if (event) {
await stream.writeSSE({ event: event.type, data: JSON.stringify(event) })
continue
}
let timer: ReturnType<typeof setTimeout> | undefined
await Promise.race([
waitForEvent(),
new Promise<void>((resolve) => {
timer = setTimeout(resolve, HEARTBEAT_MS)
}),
])
clearTimeout(timer)
wake = undefined
if (pending.length === 0 && !stream.aborted) {
await stream.write(': ping\n\n')
}
}
})
},
)