import type { LoaderFunctionArgs } from "react-router"; import { CatalogError, foundationErrors } from "@hivegrid/foundation"; import { loadProjectBoard } from "~/utils/integrations/projects/projectService.server"; import { loadProjectContext, PROJECT_READ_PERMISSIONS, projectNotFoundResponse, requireAnyProjectPermission, } from "~/utils/integrations/projects/projectAccess.server"; import { eventStream } from "~/utils/stream/event-stream"; import { subscribeToProjectBoard } from "~/utils/integrations/projects/projectBoardEvents.server"; import { PROJECT_BOARD_SSE_EVENT } from "~/utils/integrations/projects/projectBoardEvents.shared"; export async function loader({ request, params }: LoaderFunctionArgs) { const ctx = requireAnyProjectPermission(await loadProjectContext({ request, params, requireModule: true }), PROJECT_READ_PERMISSIONS); const pipelineId = params.pipelineId; if (!pipelineId) throw new CatalogError(foundationErrors.notFound); const board = await loadProjectBoard({ tenantId: ctx.tenantId, ctx, pipelineId }).catch((error) => { if (error instanceof CatalogError) throw projectNotFoundResponse(); throw error; }); return eventStream(request.signal, (send) => { // 1) Snapshot-on-connect so a late subscriber has the current board. send({ event: "projects.board.snapshot", data: JSON.stringify(board) }); // 2) Real change-events: subscribe to the in-process board channel. Every // board mutation (stage move, bulk move, create, update, undo, archive) // publishes here, so connected clients revalidate immediately instead of // waiting for the next heartbeat. Only forward changes for this pipeline. const unsubscribe = subscribeToProjectBoard(ctx.tenantId, pipelineId, (data) => { send({ event: PROJECT_BOARD_SSE_EVENT, data }); }); // 3) Heartbeat keeps intermediaries from closing an idle connection. const heartbeat = setInterval(() => { send({ event: "projects.board.heartbeat", data: JSON.stringify({ pipelineId, at: new Date().toISOString() }) }); }, 30_000); return () => { unsubscribe(); clearInterval(heartbeat); }; }); }