1
0
Fork 0
polaris-task-force/src/lib/realtime/bus.ts
Z8MB1E 4c6d34e868 feat(realtime): anchor SSE client set on globalThis for cross-bundle delivery
Next.js dev bundles server packages per route, so a module-level Set forks
into one copy per bundle: a broadcast issued from a server action or registry
bundle would never reach a client subscribed through the /api/realtime route
bundle. Anchoring the client set on globalThis unifies every bundle copy within
the single dev process, the same trick blackjack/poker already use. It is a
no-op in production, which has one module instance anyway.
2026-10-16 00:32:42 -04:00

78 lines
2.4 KiB
TypeScript

export interface SSEEventClient {
send: (data: string) => void;
events?: Set<string>;
userId?: number;
presenceChannel?: string;
}
/**
* The connected-client set is anchored on `globalThis`, not module scope. Next.js
* dev bundles server packages per route (`devBundleServerPackages`), so a plain
* module-level Set forks into one copy per bundle: a broadcast issued from a
* server-action or registry bundle would never reach a client subscribed through
* the `/api/realtime` route bundle. Sharing it via `globalThis` (the same trick
* the blackjack/poker stores use, and how Payload caches its instance) unifies
* every bundle within the single dev process. In production there is one module
* instance anyway, so this is a no-op there.
*/
interface BusRegistry {
__ptfSseClients?: Set<SSEEventClient>;
}
const globalBus = globalThis as typeof globalThis & BusRegistry;
const clients: Set<SSEEventClient> = (globalBus.__ptfSseClients ??= new Set<SSEEventClient>());
export function subscribe(client: SSEEventClient): () => void {
clients.add(client);
return () => clients.delete(client);
}
export function unsubscribe(client: SSEEventClient): void {
clients.delete(client);
}
export function clientCount(): number {
return clients.size;
}
export function broadcast(event: string, data: unknown): number {
const payload = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
const presenceChannel =
event === "presence" &&
typeof data === "object" &&
data !== null &&
"channel" in data &&
typeof data.channel === "string"
? data.channel
: undefined;
for (const client of clients) {
if (client.events && !client.events.has(event)) continue;
if (
event === "presence" &&
client.presenceChannel !== undefined &&
client.presenceChannel !== presenceChannel
) {
continue;
}
try {
client.send(payload);
} catch {
clients.delete(client);
}
}
return clients.size;
}
export function broadcastToUser(event: string, userId: number, data: unknown): number {
const payload = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
const targetUserId = Number(userId);
for (const client of clients) {
if (client.userId !== targetUserId) continue;
if (client.events && !client.events.has(event)) continue;
try {
client.send(payload);
} catch {
clients.delete(client);
}
}
return clients.size;
}