⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
fix(ws): reconcile access across authenticated routes and Redis recovery
Tin8875c5d9e313
diff --git a/apps/api/src/ws/broadcast-adapter.ts b/apps/api/src/ws/broadcast-adapter.tsindex 9b602aded..1be928b87 100644--- a/apps/api/src/ws/broadcast-adapter.ts+++ b/apps/api/src/ws/broadcast-adapter.ts@@ -35,7 +35,10 @@ export type BroadcastAdapter = {handler: (msg: BroadcastMessage) => void | Promise<void>,): Promise<void>;- subscribeToUser(handler: (msg: UserBroadcast) => void): Promise<void>;+ subscribeToUser(+ handler: (msg: UserBroadcast) => void,+ onRecovery?: () => Promise<void>,+ ): Promise<void>;/** Cleanup on shutdown */shutdown(): Promise<void>;diff --git a/apps/api/src/ws/index.ts b/apps/api/src/ws/index.tsindex e7babcd5a..b6094db39 100644--- a/apps/api/src/ws/index.ts+++ b/apps/api/src/ws/index.ts@@ -1,3 +1,4 @@+import { syncWorkspaceAccess } from "./workspace-access";import { createRevocationDelivery } from "./revocation-delivery";import { randomUUID } from "node:crypto";import { and, eq, inArray } from "drizzle-orm";@@ -165,12 +166,21 @@ export async function initializeWebSocketAdapter() {msg.authorizationBatch,);});- await nextAdapter.subscribeToUser((msg: UserBroadcast) => {- if (msg.origin === INSTANCE_ID) {- return;- }- deliverToLocalUserConnections(msg.userId, msg.message);- });+ await nextAdapter.subscribeToUser(+ (msg: UserBroadcast) => {+ if (msg.origin === INSTANCE_ID) {+ return;+ }+ deliverToLocalUserConnections(msg.userId, msg.message);+ },+ async () => {+ await Promise.all(+ [...userConnections].flatMap(([userId, connections]) =>+ [...connections].map(({ ws }) => syncWorkspaceAccess(userId, ws)),+ ),+ );+ },+ );} catch (err) {await nextAdapter.shutdown().catch(() => {});throw err;diff --git a/apps/api/src/ws/redis-broadcast-adapter.ts b/apps/api/src/ws/redis-broadcast-adapter.tsindex 535f1a59f..cbb2908c4 100644--- a/apps/api/src/ws/redis-broadcast-adapter.ts+++ b/apps/api/src/ws/redis-broadcast-adapter.ts@@ -34,6 +34,7 @@ const userBroadcastSchema = v.object({});export class RedisBroadcastAdapter implements BroadcastAdapter {+ private recoveryHandler: (() => void) | null = null;private subscribed = false;private userSubscribed = false;private _pmessageHandler:@@ -88,7 +89,10 @@ export class RedisBroadcastAdapter implements BroadcastAdapter {await getRedisSub().psubscribe(CHANNEL_PATTERN);}- async subscribeToUser(handler: (msg: UserBroadcast) => void): Promise<void> {+ async subscribeToUser(+ handler: (msg: UserBroadcast) => void,+ onRecovery?: () => Promise<void>,+ ): Promise<void> {if (this.userSubscribed) return;this.userSubscribed = true;@@ -114,11 +118,35 @@ export class RedisBroadcastAdapter implements BroadcastAdapter {}};(getRedisSub() as Redis).on("pmessage", this._userPmessageHandler);+ if (onRecovery) {+ this.recoveryHandler = () => {+ if (!this.userSubscribed) return;+ // A browser socket can stay open while this subscriber misses messages.+ // Restore the subscription before taking an authoritative snapshot.+ void getRedisSub()+ .psubscribe(USER_CHANNEL_PATTERN)+ .then(async () => {+ if (this.userSubscribed) await onRecovery();+ })+ .catch((error) => {+ console.error(+ "Failed to recover user broadcast subscription:",+ error,+ );+ });+ };+ getRedisSub().on("ready", this.recoveryHandler);+ }await getRedisSub().psubscribe(USER_CHANNEL_PATTERN);}async shutdown(): Promise<void> {const sub = getRedisSub() as Redis;+ this.userSubscribed = false;+ if (this.recoveryHandler) {+ sub.off("ready", this.recoveryHandler);+ this.recoveryHandler = null;+ }if (this._pmessageHandler) {sub.off("pmessage", this._pmessageHandler);diff --git a/apps/web/src/components/workspace-switcher.tsx b/apps/web/src/components/workspace-switcher.tsxindex 15eb51313..e164dc3d5 100644--- a/apps/web/src/components/workspace-switcher.tsx+++ b/apps/web/src/components/workspace-switcher.tsx@@ -27,7 +27,6 @@ import {getModifierKeyText,useRegisterShortcuts,} from "@/hooks/use-keyboard-shortcuts";-import { useUserWebSocket } from "@/hooks/use-user-websocket";import { authClient } from "@/lib/auth-client";import { hasInstanceAdminRole } from "@/lib/instance-admin";import type { Workspace } from "@/types/workspace";@@ -38,7 +37,6 @@ export function WorkspaceSwitcher() {const { data: workspace } = useActiveWorkspace();// User-scoped WebSocket for real-time events (e.g. NOTIFICATION_CREATED)- useUserWebSocket();const { data: workspaces } = useGetWorkspaces();const { data: session } = authClient.useSession();const { data: config } = useGetConfig();diff --git a/apps/web/src/routes/_layout/_authenticated.tsx b/apps/web/src/routes/_layout/_authenticated.tsxindex e7dd42f64..ecfb36d98 100644--- a/apps/web/src/routes/_layout/_authenticated.tsx+++ b/apps/web/src/routes/_layout/_authenticated.tsx@@ -1,8 +1,10 @@-import { createFileRoute, redirect } from "@tanstack/react-router";+import { createFileRoute, Outlet, redirect } from "@tanstack/react-router";+import { useUserWebSocket } from "@/hooks/use-user-websocket";import { authClient } from "@/lib/auth-client";// protects all child routes, must be logged inexport const Route = createFileRoute("/_layout/_authenticated")({+ component: AuthenticatedLayout,beforeLoad: async ({ location }) => {let session = null;let sessionError = false;@@ -30,3 +32,8 @@ export const Route = createFileRoute("/_layout/_authenticated")({return { session, sessionError };},});++function AuthenticatedLayout() {+ useUserWebSocket();+ return <Outlet />;+}diff --git a/tests/api/ws/user-broadcast-redis-failure.test.ts b/tests/api/ws/user-broadcast-redis-failure.test.tsindex 64f301a6a..5fddba683 100644--- a/tests/api/ws/user-broadcast-redis-failure.test.ts+++ b/tests/api/ws/user-broadcast-redis-failure.test.ts@@ -12,6 +12,10 @@ vi.mock("../../../apps/api/src/events", () => ({publishEvent: vi.fn(),}));+const accessSync = vi.hoisted(() => vi.fn(async () => undefined));+vi.mock("../../../apps/api/src/ws/workspace-access", () => ({+ syncWorkspaceAccess: accessSync,+}));const publish = vi.fn();const listeners: Array<(p: string, c: string, d: string) => void> = [];const subscriber = {@@ -156,3 +160,21 @@ describe("broadcastToUser with the redis adapter", () => {removeUserConnection("user-1", conn);});});++it("resynchronizes healthy browser sockets after the Redis subscriber recovers", async () => {+ await initializeWebSocketAdapter();+ const ws = makeFakeWs();+ const conn = addUserConnection("user-1", ws);+ const ready = subscriber.on.mock.calls.find(+ ([event]) => event === "ready",+ )?.[1];+ expect(ready).toBeDefined();+ ready?.("", "", "");+ await vi.waitFor(() => expect(accessSync).toHaveBeenCalledWith("user-1", ws));+ removeUserConnection("user-1", conn);+ await shutdownWebSocketAdapter();+ accessSync.mockClear();+ ready?.("", "", "");+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(accessSync).not.toHaveBeenCalled();+});