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();
}