feat: type-safe SSE rewrite

This commit is contained in:
2026-04-09 04:52:14 +07:00 Unverified
parent a59784e9d2
commit 94af52648c
16 changed files with 263 additions and 271 deletions
+4 -4
View File
@@ -7,6 +7,7 @@ import SearchBox, { type Filters, type ParsedQuery } from "@/components/search";
import { SimpleTooltip } from "@/components/tooltip";
import { Button } from "@/components/ui/button";
import type { auditLog } from "@/lib/db/schema";
import { sse } from "@/lib/db/sse-endpoints";
type AuditLog = typeof auditLog.$inferSelect;
@@ -22,10 +23,9 @@ export default function AuditLogViewer({
const entryRefs = useRef(new Map<string, HTMLDivElement>());
useEffect(() => {
const es = new EventSource("/api/ev/log");
es.onmessage = (res) =>
updateLogs((x) => [...x.slice(-999), JSON.parse(res.data)]);
return () => es.close();
return sse.log.sub("update", (res) =>
updateLogs((x) => [...x.slice(-999), res]),
).clean;
}, []);
const filters: Filters = {
+4 -4
View File
@@ -5,6 +5,7 @@ import { Lock, Unlock } from "lucide-react";
import Link from "next/link";
import { useParams, useRouter } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import {
@@ -22,7 +23,6 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { toast } from "sonner";
import { Input } from "@/components/ui/input";
import {
SidebarMenu,
@@ -37,6 +37,7 @@ import {
} from "@/components/ui/tooltip";
import { setLimit, toggleCheck, toggleLock } from "@/lib/api";
import { shared } from "@/lib/comms";
import { sse } from "@/lib/db/sse-endpoints";
import { cn } from "@/lib/utils";
export function SidebarLink({
@@ -219,8 +220,7 @@ export function Watcher() {
shared.signal("sync", () => router.refresh());
useEffect(() => {
const es = new EventSource(`/api/artifact/ev`);
es.addEventListener("update", () => router.refresh());
const { clean } = sse.artifact.sub("update", () => router.refresh());
const interval = setInterval(() => {
fetch("/api/artifact/count")
.then((r) => r.json())
@@ -232,7 +232,7 @@ export function Watcher() {
.catch((e) => console.error("Fetching artifact count failed", e));
}, 120000);
return () => {
es.close();
clean();
clearInterval(interval);
};
}, [router]);
+4 -4
View File
@@ -5,6 +5,7 @@ import { Lock, Logs, Unlock } from "lucide-react";
import Link from "next/link";
import { useParams, useRouter } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import {
@@ -22,7 +23,6 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { toast } from "sonner";
import { Input } from "@/components/ui/input";
import {
SidebarMenu,
@@ -38,6 +38,7 @@ import {
import { shared } from "@/lib/comms";
import { cn } from "@/lib/utils";
import { setFree, setLimit, toggleCheck, toggleLock } from "../api";
import { sse } from "@/lib/db/sse-endpoints";
export function SidebarLink({
submission,
@@ -287,8 +288,7 @@ export function Watcher() {
shared.signal("sync", () => router.refresh());
useEffect(() => {
const es = new EventSource(`/api/rubgram/ev`);
es.addEventListener("update", () => router.refresh());
const { clean } = sse.rubgram.sub("update", () => router.refresh());
const interval = setInterval(() => {
fetch("/api/rubgram/count")
.then((r) => r.json())
@@ -300,7 +300,7 @@ export function Watcher() {
.catch((e) => console.error("Fetching rubgram count failed", e));
}, 60000);
return () => {
es.close();
clean();
clearInterval(interval);
};
}, [router]);
+10 -16
View File
@@ -8,7 +8,6 @@ import { redirect } from "next/navigation";
import { actionLog } from "@/lib/api";
import { adminCheck } from "@/lib/auth";
import { db } from "@/lib/db";
import { ps } from "@/lib/db/redis";
import {
endgameArchive,
endgameDiscord,
@@ -19,6 +18,7 @@ import {
endgameTypes,
settings,
} from "@/lib/db/schema";
import { sse } from "@/lib/db/sse-endpoints";
import type { TypedFormData } from "./type";
const {
@@ -51,7 +51,7 @@ export async function wipe() {
revalidatePath("/rubgram/admin");
revalidatePath("/rubgram");
ps.publish({ type: "wipe" }, { topic: "rubgram", event: "update" });
sse.rubgram.pub("update", { type: "wipe" });
await actionLog(`Deleted rubgram submissions`);
redirect("/rubgram/admin");
@@ -80,7 +80,7 @@ export async function toggleCheck(submissionId: string) {
revalidatePath("/rubgram/admin");
revalidatePath("/rubgram");
ps.publish({ type: "toggleCheck" }, { topic: "rubgram", event: "update" });
sse.rubgram.pub("update", { type: "toggleCheck" });
await actionLog(`Toggled an rubgram submission check mark`);
}
@@ -98,7 +98,7 @@ export async function toggleLock() {
revalidatePath("/rubgram/admin");
revalidatePath("/rubgram");
ps.publish({ type: "toggleLock" }, { topic: "rubgram", event: "update" });
sse.rubgram.pub("update", { type: "toggleLock" });
await actionLog(
`${(existing.length ? existing[0].locked : true) ? "Locked" : "Unlocked"} rubgram submission`,
@@ -122,7 +122,7 @@ export async function setLimit(limit: number) {
revalidatePath("/rubgram/admin");
revalidatePath("/rubgram");
ps.publish({ type: "setLimit" }, { topic: "rubgram", event: "update" });
sse.rubgram.pub("update", { type: "setLimit" });
await actionLog(
`Set rubgram submit limit to ${limit < 0 ? "unlimited" : limit}`,
@@ -146,7 +146,7 @@ export async function setFree(free: number) {
revalidatePath("/rubgram/admin");
revalidatePath("/rubgram");
ps.publish({ type: "setFree" }, { topic: "rubgram", event: "update" });
sse.rubgram.pub("update", { type: "setFree" });
await actionLog(`Set rubgram submit limit to ${free}`);
}
@@ -226,10 +226,7 @@ export async function submitEndgame(formData: EndgameFormData) {
})
.returning({ queue: endgameSubmissions.queue, id: endgameSubmissions.id });
revalidatePath("/rubgram/admin");
ps.publish(
{ type: "submit", sub: queue.id },
{ topic: "rubgram", event: "update" },
);
sse.rubgram.pub("update", { type: "submit", sub: queue.id });
return queue;
}
@@ -300,10 +297,7 @@ export async function submitEndgamePayment(formData: EndgamePaymentFormData) {
});
revalidatePath("/rubgram/admin");
if (Array.isArray(queue))
ps.publish(
{ type: "paid", sub: queue[0].id },
{ topic: "rubgram", event: "update" },
);
sse.rubgram.pub("update", { type: "paid", sub: queue[0].id });
return Array.isArray(queue) ? queue[0] : queue;
}
@@ -418,7 +412,7 @@ export async function cancel(sid: string) {
await removeExpiredSubmissions();
ps.publish({ type: "cancel" }, { topic: "rubgram", event: "update" });
sse.rubgram.pub("update", { type: "cancel" });
revalidatePath("/rubgram");
}
@@ -467,7 +461,7 @@ export async function debugUploadSlip(sid: string, image: File) {
.where(eq(endgameSubmissions.id, sid));
});
ps.publish({ type: "uploadSlip" }, { topic: "rubgram", event: "update" });
sse.rubgram.pub("update", { type: "uploadSlip" });
revalidatePath("/rubgram/admin");
}
+2 -3
View File
@@ -23,7 +23,7 @@ import {
calcPrice,
cancel,
type getDiscordSession,
getEndgameConfig,
type getEndgameConfig,
loginDiscord,
} from "./api";
import { RulesDialog } from "./rules";
@@ -105,8 +105,7 @@ export function ServiceSelector({
</>
) : (
<>
{t.price} {" "}
<span className="opacity-50">บาท</span>
{t.price} <span className="opacity-50">บาท</span>
</>
)}
</Kbd>
+11 -8
View File
@@ -79,6 +79,7 @@ import { cn } from "@/lib/utils";
import { TierListCell } from "./cell";
import { Draggable } from "./character";
import { TierListContext } from "./context";
import { tlSse } from "@/lib/db/sse-endpoints";
function Untiered({
children,
@@ -179,14 +180,16 @@ export function TierList({
useEffect(() => {
setEvStatus((x) => ({ ...x, ev: "connecting" }));
const es = new EventSource(`/api/tl/${version.id}/ev`);
es.onopen = () => setEvStatus((x) => ({ ...x, ev: "ready" }));
es.addEventListener("update_states", (d) => setStates(JSON.parse(d.data)));
es.addEventListener("update_placements", (d) =>
setPlacements(JSON.parse(d.data)),
);
es.onerror = () => setEvStatus((x) => ({ ...x, ev: "unknown" }));
return () => es.close();
return tlSse(version.id).subMany(
{
update_states: setStates,
update_placements: setPlacements,
},
{
onopen: () => setEvStatus((x) => ({ ...x, ev: "ready" })),
onerror: () => setEvStatus((x) => ({ ...x, ev: "unknown" })),
},
).clean;
}, [version.id]);
//#endregion
+3 -3
View File
@@ -1,10 +1,10 @@
import { ps } from "@/lib/db/redis";
import { sse } from "@/lib/db/sse-endpoints";
const version = Bun.file(".version");
export async function GET(req: Request) {
if (process.env.ENVIRONMENT === "development")
return ps.new("active", {
return sse.active.stream({
motd: {
data: "DEV",
event: "version",
@@ -17,7 +17,7 @@ export async function GET(req: Request) {
ver = crypto.randomUUID();
await version.write(crypto.randomUUID());
}
return ps.new("active", {
return sse.active.stream({
motd: {
data: ver,
event: "version",
-5
View File
@@ -1,5 +0,0 @@
import { ps } from "@/lib/db/redis";
export async function GET() {
return ps.new("artifact");
}
-12
View File
@@ -1,12 +0,0 @@
import { adminCheck } from "@/lib/auth";
import { ps } from "@/lib/db/redis";
export async function GET(
_req: Request,
{ params }: { params: Promise<{ topic: string }> },
) {
if (!(await adminCheck()))
return new Response("Unauthorized", { status: 401 });
const { topic } = await params;
return ps.new(topic);
}
-5
View File
@@ -1,5 +0,0 @@
import { ps } from "@/lib/db/redis";
export async function GET() {
return ps.new("rubgram");
}
+42 -38
View File
@@ -3,11 +3,11 @@
import { ProgressProvider } from "@bprogress/next/app";
import { use, useEffect, useRef, useState } from "react";
import { useKey } from "react-use";
import ReconnectingEventSource from "reconnecting-eventsource";
import { toast } from "sonner";
import { stringify } from "yaml";
import { CdnChooserProvider } from "@/components/chooser";
import IccProvider, { IccContext, shared } from "@/lib/comms";
import { sse } from "@/lib/db/sse-endpoints";
export default function Providers({ children }: { children: React.ReactNode }) {
return (
@@ -47,45 +47,49 @@ export function VersionCheck({ headless = false }: { headless?: boolean }) {
window.history.replaceState("", "", url);
}
const es = new ReconnectingEventSource(`/api/active`, {});
es.addEventListener("version", (d) => {
setConnected(true);
emit("sync");
const newVersion = JSON.parse(d.data);
const version = ver.current;
if (!version) console.log("Client version:", newVersion);
console.log("Server version:", newVersion);
if (version && newVersion !== version) {
setReadyForUpdate(true);
window.location.hash = "#update";
if (headless) window.location.reload();
else
toast("มีอัปเดตใหม่พร้อมใช้งาน", {
description: "รีโหลดเพื่ออัปเดตเป็นเวอร์ชันล่าสุด",
action: {
label: "รีโหลด",
// Do a full reload
onClick: () => window.location.reload(),
const { clean, es } = sse.active.sub(
"version",
(newVersion) => {
setConnected(true);
emit("sync");
const version = ver.current;
if (!version) console.log("Client version:", newVersion);
console.log("Server version:", newVersion);
if (version && newVersion !== version) {
setReadyForUpdate(true);
window.location.hash = "#update";
if (headless) window.location.reload();
else
toast("มีอัปเดตใหม่พร้อมใช้งาน", {
description: "รีโหลดเพื่ออัปเดตเป็นเวอร์ชันล่าสุด",
action: {
label: "รีโหลด",
// Do a full reload
onClick: () => window.location.reload(),
},
duration: Infinity,
});
}
if (newVersion !== version) ver.current = newVersion;
},
{
endpoint: "/api/active",
onerror() {
setConnected(false);
toast.promise(
new Promise((r) => {
es.onopen = r;
}),
{
loading: "กำลังพยายามเชื่อมต่อใหม่...",
success: () => "เชื่อมต่อสำเร็จ",
duration: 500,
},
duration: Infinity,
});
}
if (newVersion !== version) ver.current = newVersion;
});
es.onerror = () => {
setConnected(false);
toast.promise(
new Promise((r) => {
es.onopen = r;
}),
{
loading: "กำลังพยายามเชื่อมต่อใหม่...",
success: () => "เชื่อมต่อสำเร็จ",
duration: 500,
);
},
);
};
return () => es.close();
},
);
return clean;
}, [headless, setConnected, setUpdated, readyForUpdate, emit]);
return debug ? (
+21
View File
@@ -0,0 +1,21 @@
import { sse, tlSse } from "@/lib/db/sse-endpoints";
function isValidKey<T extends { [x: string]: unknown }>(
map: T,
key: string | number | symbol,
): key is keyof T {
return Object.hasOwn(map, key);
}
const tlRegex = /^tl\.([a-z0-9.-_]+)$/;
export async function GET(
_req: Request,
{ params }: { params: Promise<{ topic: string }> },
) {
const { topic } = await params;
if (tlRegex.test(topic)) return tlSse(topic.match(tlRegex)![1]).stream();
if (!isValidKey(sse, topic))
return new Response("Invalid SSE Endpoint", { status: 404 });
return sse[topic].stream();
}
+10 -10
View File
@@ -9,7 +9,6 @@ import z from "zod";
import { adminCheck } from "./auth";
import { uidRegex } from "./const";
import { db } from "./db";
import { ps } from "./db/redis";
import { cdnReferences } from "./db/references";
import {
artifactSettings,
@@ -22,6 +21,7 @@ import {
tierlistStates,
tierlistVersions,
} from "./db/schema";
import { sse, tlSse } from "./db/sse-endpoints";
import { b2s } from "./utils";
export async function getCharacters(chars: string[]) {
@@ -120,7 +120,7 @@ export async function submitArtifact(
// clear card cache
await db.delete(cards).where(eq(cards.submission, queue.id));
revalidatePath("/artifact/admin");
ps.publish({ type: "submit" }, { topic: "artifact", event: "update" });
sse.artifact.pub("update", { type: "submit" });
return queue;
}
const [queue] = await db
@@ -131,7 +131,7 @@ export async function submitArtifact(
})
.returning({ queue: submissions.queue, id: submissions.id });
revalidatePath("/artifact/admin");
ps.publish({ type: "submit" }, { topic: "artifact", event: "update" });
sse.artifact.pub("update", { type: "submit" });
return queue;
}
@@ -158,7 +158,7 @@ export async function toggleCheck(submissionId: string) {
revalidatePath("/artifact/admin");
revalidatePath("/artifact");
ps.publish({ type: "toggleCheck" }, { topic: "artifact", event: "update" });
sse.artifact.pub("update", { type: "toggleCheck" });
await actionLog(`Toggled an artifact submission check mark`);
}
@@ -175,7 +175,7 @@ export async function toggleLock() {
revalidatePath("/artifact/admin");
revalidatePath("/artifact");
ps.publish({ type: "toggleLock" }, { topic: "artifact", event: "update" });
sse.artifact.pub("update", { type: "toggleLock" });
await actionLog(
`${(existing.length ? existing[0].locked : true) ? "Locked" : "Unlocked"} artifact submission`,
);
@@ -198,7 +198,7 @@ export async function setLimit(limit: number) {
revalidatePath("/artifact/admin");
revalidatePath("/artifact");
ps.publish({ type: "setLimit" }, { topic: "artifact", event: "update" });
sse.artifact.pub("update", { type: "setLimit" });
await actionLog(
`Set artifact submit limit to ${limit < 0 ? "unlimited" : limit}`,
);
@@ -212,7 +212,7 @@ export async function wipe() {
);
revalidatePath("/artifact");
ps.publish({ type: "wipe" }, { topic: "artifact", event: "update" });
sse.artifact.pub("update", { type: "wipe" });
await actionLog(`Deleted artifact submissions`);
redirect("/artifact/admin");
}
@@ -263,7 +263,7 @@ export async function tlState(
revalidatePath(`/api/tl/${list}/states`);
await actionLog(`Updated a state in tierlist ${list}`, data);
ps.publish(states, { topic: `tl.${list}`, event: "update_states" });
tlSse(list).pub("update_states", states);
}
export async function tlPlacements(
@@ -284,7 +284,7 @@ export async function tlPlacements(
revalidatePath(`/api/tl/${list}`);
await actionLog(`Updated a placement in tierlist ${list}`);
ps.publish(placements, { topic: `tl.${list}`, event: "update_placements" });
tlSse(list).pub("update_placements", placements);
}
export async function cdnDelete(ids: string[], force = false) {
@@ -376,5 +376,5 @@ export async function actionLog(text: string, details?: unknown) {
revalidatePath("/admin/log");
} catch {}
if (res) ps.publish(res, { topic: "log" });
if (res) sse.log.pub("update", res);
}
+105 -35
View File
@@ -1,37 +1,22 @@
export const redis = Bun.redis;
import ReconnectingEventSource from "reconnecting-eventsource";
import type z from "zod";
type PubMOTD = { event?: string; data: string };
export const redis = typeof Bun !== "undefined" ? Bun.redis : null;
export function optionalStringify(data: unknown | string) {
try {
if (typeof data !== "string") throw "";
JSON.parse(data);
return data;
} catch {
return JSON.stringify(data);
}
}
export function optionalParse(data: unknown | string) {
if (typeof data === "string") {
try {
return { parsed: true, data: JSON.parse(data) };
} catch {}
}
return { parsed: false, data };
}
type PubPayload = { event?: string; data: unknown };
export class PubSubManager {
private pub;
private sub;
private readonly prefix = "sse:";
constructor() {
if (!redis) throw new Error("Redis is not available in this environment.");
this.pub = redis.duplicate();
this.sub = redis.duplicate();
}
private constructMessage(data: string, event?: string) {
return `${event ? `event: ${event}\n` : ""}data: ${optionalStringify(data)}\n\n`;
private constructMessage(data: unknown, event?: string) {
return `${event ? `event: ${event}\n` : ""}data: ${JSON.stringify(data)}\n\n`;
}
async publish(
@@ -43,7 +28,7 @@ export class PubSubManager {
const pub = await this.pub;
return pub.publish(
`${this.prefix}${topic}`,
JSON.stringify({ data, event }),
JSON.stringify({ data, event } satisfies PubPayload),
);
}
@@ -54,7 +39,7 @@ export class PubSubManager {
motd,
}: {
signal?: AbortSignal;
motd?: PubMOTD | PubMOTD[];
motd?: PubPayload | PubPayload[];
} = {},
) {
console.log(` SUB ${topic}`);
@@ -71,15 +56,9 @@ export class PubSubManager {
ping();
}, 90000); // cloudflare timeout = 100s
}
const write: (payload: {
data: string;
event?: string;
}) => void | ((data: string, event?: string) => void) = (
p: { data: string; event?: string } | string,
event?: string,
) => {
if (typeof p === "string") writer.write(this.constructMessage(p, event));
else writer.write(this.constructMessage(p.data, p.event));
const write = (payload: PubPayload) => {
writer.write(this.constructMessage(payload.data, payload.event));
ping();
};
@@ -91,7 +70,7 @@ export class PubSubManager {
timeout = setTimeout(() => close(), 1.8e6); // 30 minutes
};
const handler = (payload: string) => {
const p = JSON.parse(payload);
const p: PubPayload = JSON.parse(payload);
write(p);
resetTimer();
};
@@ -121,4 +100,95 @@ export class PubSubManager {
}
}
export const ps = new PubSubManager();
export type EventSourceEventMap = Record<string, z.ZodTypeAny>;
export type SubOption = {
endpoint?: URL | string;
onerror?: () => void;
onopen?: () => void;
};
export class EventSourceEndpoint<T extends EventSourceEventMap> {
private manager = ps;
private readonly defaultEndpointUrl = new URL(
`/sse/${this.endpoint}`,
typeof location === "undefined" ? process.env.BASE_URL : location.href,
);
constructor(
private endpoint: string,
private eventMap: T,
) {}
pub<K extends keyof T>(event: K, data: z.infer<T[K]>) {
if (!this.manager)
throw new Error(
"EventSourceEndpoint.pub(...) can only be called on the server.",
);
return this.manager.publish(this.eventMap[event].parse(data), {
topic: this.endpoint,
event: String(event),
});
}
subMany(
events: Partial<{ [K in keyof T]: (data: z.infer<T[K]>) => void }>,
{
endpoint = this.defaultEndpointUrl,
onerror = () => {},
onopen = () => {},
}: SubOption = {},
) {
const es = new ReconnectingEventSource(endpoint);
for (const [event, callback] of Object.entries(events)) {
const listener = (e: MessageEvent<string>) =>
callback?.(JSON.parse(e.data));
es.addEventListener(event, listener);
}
es.onerror = onerror;
es.onopen = onopen;
return { clean: () => es.close(), es };
}
sub<K extends keyof T>(
event: K,
callback: (data: z.infer<T[K]>) => void,
{
endpoint = this.defaultEndpointUrl,
onerror = () => {},
onopen = () => {},
}: SubOption = {},
) {
const listener = (e: MessageEvent<string>) => callback(JSON.parse(e.data));
const es = new ReconnectingEventSource(endpoint);
es.addEventListener(String(event), listener);
es.onerror = onerror;
es.onopen = onopen;
return { clean: () => es.close(), es };
}
stream(opt?: {
signal?: AbortSignal | undefined;
motd?: PubPayload | PubPayload[] | undefined;
}) {
return this.manager?.new(this.endpoint, opt);
}
}
export function sseEndpoint<M extends EventSourceEventMap>(
endpoint: string,
eventMap: M,
): EventSourceEndpoint<M> {
return new EventSourceEndpoint(endpoint, eventMap);
}
export function sseEndpointMap<M extends Record<string, EventSourceEventMap>>(
map: M,
): { [K in keyof M]: EventSourceEndpoint<M[K]> } {
const endpoints = {} as { [K in keyof M]: EventSourceEndpoint<M[K]> };
for (const key in map) {
endpoints[key] = new EventSourceEndpoint(key, map[key]);
}
return endpoints;
}
export const ps = redis === null ? null : new PubSubManager();
+47
View File
@@ -0,0 +1,47 @@
import z from "zod/v4";
import { sseEndpoint, sseEndpointMap } from "./redis";
import type { auditLog, tierlistStates } from "./schema";
export const sse = sseEndpointMap({
// Artifact Admin Listener
artifact: {
update: z.object({
type: z.enum(["setLimit", "wipe", "submit", "toggleCheck", "toggleLock"]),
}),
},
// Rubgram Admin Listener
rubgram: {
update: z
.object({
type: z.enum([
"setLimit",
"wipe",
"toggleCheck",
"toggleLock",
"setFree",
"cancel",
"uploadSlip",
]),
})
.or(
z.object({
type: z.enum(["submit", "paid"]),
sub: z.string(),
}),
),
},
// Passive Update Checker
active: {
version: z.string(),
},
// Admin Live Log
log: {
update: z.custom<typeof auditLog.$inferSelect>(),
},
});
export function tlSse<T extends string>(list: T) {
return sseEndpoint(`tl.${list}`, {
update_states: z.custom<(typeof tierlistStates.$inferSelect)[]>(),
update_placements: z.record(z.string(), z.string().array()),
});
}
-124
View File
@@ -5,130 +5,6 @@ export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
type ServerEventSource = {
send: (data: unknown, event?: string) => void;
write: (msg: string) => void;
close: () => void;
topic: string;
id: number;
};
type EventSourceMOTD = { event?: string; data: string };
export class EventSourceManager {
private list: ServerEventSource[] = [];
private id = 0;
new(
topic = "_global",
{
onDisconnect,
signal,
motd,
}: {
onDisconnect?: () => void;
signal?: AbortSignal;
motd?: EventSourceMOTD | EventSourceMOTD[];
} = {},
): Response {
let timeout: NodeJS.Timeout | undefined;
this.id++;
if (this.id > 100000) this.id = 0;
const id = this.id;
console.log(` SUB ${topic}#${id} (C${this.list.length})`);
const push = (s: ServerEventSource) => {
this.list.push(s);
// Send MOTD
if (Array.isArray(motd)) motd.map((m) => s.send(m.data, m.event));
else if (motd) s.send(motd.data, motd.event);
};
const remove = (id: number) => {
if (this.list.findIndex((e) => e.id === id) < 0) return;
console.log(` DSC ${topic}#${id}`);
this.list = this.list.toSpliced(
this.list.findIndex((e) => e.id === id),
1,
);
onDisconnect?.();
};
signal?.addEventListener("abort", () => {
clearInterval(timeout);
remove(id);
});
return new Response(
new ReadableStream({
start(controller) {
const encoder = new TextEncoder();
// Register this client
const res = {
send: (data: unknown, event?: string) =>
res.write(
`${event ? `event: ${event}\n` : ""}data: ${JSON.stringify(data)}\n\n`,
),
write: (msg: string) => controller.enqueue(encoder.encode(msg)),
close: () => {
try {
controller.close();
} catch {}
clearTimeout(timeout);
remove(res.id);
},
topic,
id,
};
timeout = setInterval(() => {
if (controller.desiredSize === null) return res.close();
try {
res.write(`:ping\n\n`);
} catch {
res.close();
}
}, 5000);
push(res);
},
cancel() {
clearTimeout(timeout);
remove(id);
},
}),
{
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
"X-Accel-Buffering": "no",
},
},
);
}
publish(
data: unknown,
{ event, topic = "_global" }: { event?: string; topic?: string },
) {
console.log(` PUB #${topic}`);
queueMicrotask(() => {
for (const s of this.list) {
if (s.topic !== topic) continue;
try {
s.send(data, event);
} catch (error) {
console.error(` ERR #${topic}#${s.id}, ${error}`);
}
}
});
}
count(topic = "_global") {
return this.list.reduce((c, s) => c + (s.topic === topic ? 1 : 0), 0);
}
}
export const sse = new EventSourceManager();
export const b2s = (t: number) => {
let e = (Math.log2(t) / 10) | 0;
return `${(t / 1024 ** (e = e <= 0 ? 0 : e)).toFixed(1)}${" KMGP"[e]}B`;