commit
Serve the live socket from the system site
Fronting, mental state and force refresh events now go out on this site's own LiveHub Durable Object at /api/plural/ws instead of the api Worker's hub. src/worker.ts wraps the SvelteKit build to export the Durable Object and answer the socket path; wrangler.adapter.jsonc tells the adapter where to write its worker so the wrapper isn't overwritten. Co-Authored-By: Sandrone <[email protected]>
diff --git a/src/lib/api.ts b/src/lib/api.ts
index 761657b..5894cbc 100644
--- a/src/lib/api.ts
+++ b/src/lib/api.ts
@@ -34,7 +34,7 @@ export function apiBase(origin: string): string {
}
// Live updates come from the shared hub on the api Worker
-export const socketUrl = "wss://doughmination.uk/v2/ws";
+export const socketUrl = "wss://doughmination.co.uk/api/plural/ws";
/** A client for load functions: SvelteKit's fetch, no token */
export function publicClient(fetcher: typeof fetch, origin: string): DoughminationClient {
diff --git a/src/lib/live.svelte.ts b/src/lib/live.svelte.ts
index 20dc7c6..c0a2f84 100644
--- a/src/lib/live.svelte.ts
+++ b/src/lib/live.svelte.ts
@@ -7,7 +7,7 @@
import { invalidate } from "$app/navigation";
import { socketUrl } from "./api.ts";
-// The API's socket: fronters and mental state changes, and admin "reload everyone"
+// This site's own socket (/api/plural/ws): fronters, mental state and admin "reload everyone"
const PING_MS = 30_000;
const PONG_TIMEOUT_MS = 10_000;
const MAX_BACKOFF_MS = 30_000;
diff --git a/src/lib/server/plural/app.ts b/src/lib/server/plural/app.ts
index 091d332..b8439f8 100644
--- a/src/lib/server/plural/app.ts
+++ b/src/lib/server/plural/app.ts
@@ -91,7 +91,7 @@ app.doc31("/openapi.json", {
version: "3.0.0",
description:
"The plural system behind doughmination.co.uk. Live updates (fronters_update, mental_state_update, force_refresh) " +
- "arrive on the WebSocket at wss://doughmination.uk/v2/ws.",
+ "arrive on the WebSocket at wss://doughmination.co.uk/api/plural/ws.",
},
servers: [
{
diff --git a/src/lib/server/plural/config.ts b/src/lib/server/plural/config.ts
index 2305071..aefdcdc 100644
--- a/src/lib/server/plural/config.ts
+++ b/src/lib/server/plural/config.ts
@@ -98,3 +98,9 @@ export function corsOrigins(): string[] {
.filter(Boolean);
return [...new Set([...defaults, ...extra])];
}
+
+// The public live socket, answered in src/worker.ts before SvelteKit sees the request
+export const LIVE_SOCKET_PATH = "/api/plural/ws";
+
+// One LiveHub instance holds every socket, so a broadcast reaches all of them
+export const LIVE_HUB_NAME = "live";
diff --git a/src/lib/server/plural/hub.ts b/src/lib/server/plural/hub.ts
new file mode 100644
index 0000000..0146431
--- /dev/null
+++ b/src/lib/server/plural/hub.ts
@@ -0,0 +1,51 @@
+/* src/lib/server/plural/hub.ts
+ * Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+ * Licensed under the DASL-1.2 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+
+import { DurableObject } from "cloudflare:workers";
+
+export class LiveHub extends DurableObject<Env> {
+ constructor(ctx: DurableObjectState, env: Env) {
+ super(ctx, env);
+
+ // Keepalive answered without waking the object from hibernation
+ ctx.setWebSocketAutoResponse(new WebSocketRequestResponsePair("ping", "pong"));
+ }
+
+ override async fetch(request: Request): Promise<Response> {
+ if (request.headers.get("Upgrade") !== "websocket") {
+ return new Response("Expected WebSocket upgrade", { status: 426 });
+ }
+
+ const pair = new WebSocketPair();
+ const [client, server] = [pair[0], pair[1]];
+
+ this.ctx.acceptWebSocket(server);
+ server.send(
+ JSON.stringify({
+ type: "connection_established",
+ timestamp: new Date().toISOString(),
+ }),
+ );
+
+ return new Response(null, {
+ status: 101,
+ webSocket: client,
+ });
+ }
+
+ // RPC from the plural API: fan a { type, data } event out to every socket
+ async broadcast(data: unknown): Promise<void> {
+ const payload = JSON.stringify(data);
+
+ for (const socket of this.ctx.getWebSockets()) {
+ try {
+ socket.send(payload);
+ } catch {
+ // A socket that died mid-send is cleaned up by the runtime
+ }
+ }
+ }
+}
diff --git a/src/lib/server/plural/runtime.ts b/src/lib/server/plural/runtime.ts
index 3761651..7fb0acd 100644
--- a/src/lib/server/plural/runtime.ts
+++ b/src/lib/server/plural/runtime.ts
@@ -4,6 +4,7 @@
* See LICENCE.md in the project root for full licence information.
*/
+import { LIVE_HUB_NAME } from "./config";
import type { PluralEnv } from "./types";
// JSON blob store over the D1 `kv` table, the same shape the old DO store had
@@ -74,7 +75,7 @@ export function setRuntime(env: PluralEnv): void {
store: d1Store(env.DB),
broadcast: async (data) => {
try {
- await env.HUB.broadcast(data);
+ await env.LIVE.get(env.LIVE.idFromName(LIVE_HUB_NAME)).broadcast(data);
} catch (err) {
// A dropped live update must never fail the write that caused it
console.error(`Realtime broadcast failed: ${String(err)}`);
diff --git a/src/lib/server/plural/types.ts b/src/lib/server/plural/types.ts
index 6333df0..c072ffe 100644
--- a/src/lib/server/plural/types.ts
+++ b/src/lib/server/plural/types.ts
@@ -4,15 +4,13 @@
* See LICENCE.md in the project root for full licence information.
*/
-// The api Worker's `Hub` entrypoint, reached over the HUB service binding
-export interface HubRpc {
- broadcast(data: unknown): Promise<void>;
-}
+import type { LiveHub } from "./hub";
export interface PluralEnv {
DB: D1Database;
MEDIA: R2Bucket;
- HUB: Fetcher & HubRpc;
+ // This site's own live socket hub (src/lib/server/plural/hub.ts)
+ LIVE: DurableObjectNamespace<LiveHub>;
// Secrets
JWT_SECRET?: string;
diff --git a/src/lib/server/plural/ws.ts b/src/lib/server/plural/ws.ts
index 5cf0841..c13b186 100644
--- a/src/lib/server/plural/ws.ts
+++ b/src/lib/server/plural/ws.ts
@@ -4,7 +4,7 @@
* See LICENCE.md in the project root for full licence information.
*/
-// Live events go out on the api Worker's /v2/ws hub, which every site already listens to
+// Live events go out on this site's own hub at /api/plural/ws (see hub.ts)
import { rt } from "./runtime";
export function broadcastFrontingUpdate(frontersData: unknown): Promise<void> {
diff --git a/src/worker.ts b/src/worker.ts
new file mode 100644
index 0000000..2cd169b
--- /dev/null
+++ b/src/worker.ts
@@ -0,0 +1,28 @@
+/* src/worker.ts
+ * Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+ * Licensed under the DASL-1.2 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+
+// Wraps the SvelteKit build so the Worker can also export the LiveHub Durable Object
+// @ts-ignore: generated by `vite build`, so it's missing until the first build
+import sveltekit from "../.svelte-kit/cloudflare/_worker.js";
+
+import { LIVE_HUB_NAME, LIVE_SOCKET_PATH } from "./lib/server/plural/config.ts";
+import { LiveHub } from "./lib/server/plural/hub.ts";
+
+export { LiveHub };
+
+const kit = sveltekit as unknown as {
+ fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response>;
+};
+
+export default {
+ fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
+ if (new URL(request.url).pathname === LIVE_SOCKET_PATH) {
+ return env.LIVE.get(env.LIVE.idFromName(LIVE_HUB_NAME)).fetch(request);
+ }
+
+ return kit.fetch(request, env, ctx);
+ },
+} satisfies ExportedHandler<Env>;
diff --git a/vite.config.ts b/vite.config.ts
index cc5f73e..7fb383d 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -16,7 +16,13 @@ export default defineConfig({
// Runes everywhere except libraries
runes: ({ filename }) => (filename.split(/[/\\]/).includes("node_modules") ? undefined : true),
},
- adapter: adapter(),
+ // The adapter writes its worker per wrangler.adapter.jsonc; wrangler.jsonc deploys the src/worker.ts wrapper
+ adapter: adapter({
+ config: "wrangler.adapter.jsonc",
+ platformProxy: {
+ configPath: "wrangler.jsonc",
+ },
+ }),
// /api is bearer-token only (no cookies) and the site has no form actions, so the origin check guards nothing
// and would block body-less calls from the app and other sites
csrf: {
diff --git a/wrangler.adapter.jsonc b/wrangler.adapter.jsonc
new file mode 100644
index 0000000..c7de587
--- /dev/null
+++ b/wrangler.adapter.jsonc
@@ -0,0 +1,13 @@
+// wrangler.adapter.jsonc
+// Build-only: tells adapter-cloudflare where to write the SvelteKit worker.
+// The real config (wrangler.jsonc) deploys src/worker.ts, which wraps that output.
+{
+ "$schema": "node_modules/wrangler/config-schema.json",
+ "name": "doughmination-system",
+ "main": ".svelte-kit/cloudflare/_worker.js",
+ "compatibility_date": "2026-10-01",
+ "assets": {
+ "binding": "ASSETS",
+ "directory": ".svelte-kit/cloudflare"
+ }
+}
diff --git a/wrangler.jsonc b/wrangler.jsonc
index d974b16..82e56b5 100644
--- a/wrangler.jsonc
+++ b/wrangler.jsonc
@@ -2,7 +2,8 @@
{
"$schema": "node_modules/wrangler/config-schema.json",
"name": "doughmination-system",
- "main": ".svelte-kit/cloudflare/_worker.js",
+ // Wraps the SvelteKit build so it can export the LiveHub Durable Object
+ "main": "src/worker.ts",
"account_id": "f87ee4b9600f437b8da1104d077418c3",
"compatibility_date": "2026-10-01",
"compatibility_flags": [
@@ -31,12 +32,21 @@
"bucket_name": "doughmination-system-media"
}
],
- // The api Worker's realtime hub (/v2/ws). RPC only, never public
- "services": [
+ // The live socket at /api/plural/ws: fronting, mental state and force refresh
+ "durable_objects": {
+ "bindings": [
+ {
+ "name": "LIVE",
+ "class_name": "LiveHub"
+ }
+ ]
+ },
+ "migrations": [
{
- "binding": "HUB",
- "service": "api",
- "entrypoint": "Hub"
+ "tag": "v1",
+ "new_sqlite_classes": [
+ "LiveHub"
+ ]
}
],
"vars": {