From 2ddb90fc643abe5713e9c904897a1af5f84f1af4 Mon Sep 17 00:00:00 2001 From: SURYANSH-RAI Date: Sun, 18 Oct 2026 15:05:45 +0530 Subject: [PATCH 01/56] Apply one event lifecycle policy to every action (R08 part 1) Only profile saves and search checked that the event was open; refresh, intros, zone sharing and match views ignored the status, and "compute matches" silently reopened closed events. - domain/shared/event-lifecycle.ts: one table of what draft, open and closed events allow, with messages explaining why something is off - Open only: profile, search, refresh, new intros, zone sharing - Open or closed: viewing matches/connections, replying to intros - Compute matches opens a draft first and refuses a closed event - Participant pages an event does not allow redirect to the event landing page, which now explains draft vs closed - Workers complete and skip jobs whose event is not open (statusOf) --- .../e/[eventSlug]/connections/page.tsx | 2 +- .../e/[eventSlug]/matches/page.tsx | 2 +- .../app/(participant)/e/[eventSlug]/page.tsx | 10 ++- .../e/[eventSlug]/profile/page.tsx | 3 +- .../e/[eventSlug]/search/page.tsx | 2 +- apps/web/app/actions/intro.actions.ts | 5 ++ apps/web/app/actions/match.actions.ts | 7 ++- apps/web/app/actions/organizer.actions.ts | 4 +- apps/web/app/actions/participant.actions.ts | 5 +- apps/web/src/domain/shared/event-lifecycle.ts | 55 ++++++++++++++++ apps/web/src/lib/auth.ts | 5 +- packages/db/src/repositories/events.ts | 6 ++ packages/db/workers/embed.worker.ts | 9 ++- packages/db/workers/match.worker.ts | 9 ++- tests/unit/event-lifecycle.test.ts | 63 +++++++++++++++++++ 15 files changed, 172 insertions(+), 15 deletions(-) create mode 100644 apps/web/src/domain/shared/event-lifecycle.ts create mode 100644 tests/unit/event-lifecycle.test.ts diff --git a/apps/web/app/(participant)/e/[eventSlug]/connections/page.tsx b/apps/web/app/(participant)/e/[eventSlug]/connections/page.tsx index 859a57c..c92809b 100644 --- a/apps/web/app/(participant)/e/[eventSlug]/connections/page.tsx +++ b/apps/web/app/(participant)/e/[eventSlug]/connections/page.tsx @@ -9,7 +9,7 @@ export default async function ConnectionsPage({ params, searchParams }: { }) { const { eventSlug } = await params; const notice = await searchParams; - const { event } = await requireParticipantEvent(eventSlug, `/e/${eventSlug}/connections`); + const { event } = await requireParticipantEvent(eventSlug, `/e/${eventSlug}/connections`, "viewMatches"); const connections = await getParticipantConnections(eventSlug); return
diff --git a/apps/web/app/(participant)/e/[eventSlug]/matches/page.tsx b/apps/web/app/(participant)/e/[eventSlug]/matches/page.tsx index c52c374..a42bfa3 100644 --- a/apps/web/app/(participant)/e/[eventSlug]/matches/page.tsx +++ b/apps/web/app/(participant)/e/[eventSlug]/matches/page.tsx @@ -12,7 +12,7 @@ export default async function MatchesPage({ params, searchParams }: { }) { const { eventSlug } = await params; const notice = await searchParams; - const { session, event, container } = await requireParticipantEvent(eventSlug, `/e/${eventSlug}/matches`); + const { session, event, container } = await requireParticipantEvent(eventSlug, `/e/${eventSlug}/matches`, "viewMatches"); const viewer = await container.participants.findProfile(event.id, session.attendeeId); if (!viewer?.profileComplete) redirect(`/e/${eventSlug}/profile`); const matches = await getMyMatches({ eventId: event.id, participantId: session.attendeeId, limit: 12 }, container.matches); diff --git a/apps/web/app/(participant)/e/[eventSlug]/page.tsx b/apps/web/app/(participant)/e/[eventSlug]/page.tsx index 71dd33c..dc08191 100644 --- a/apps/web/app/(participant)/e/[eventSlug]/page.tsx +++ b/apps/web/app/(participant)/e/[eventSlug]/page.tsx @@ -3,6 +3,7 @@ import { notFound, redirect } from "next/navigation"; import { getSession } from "@/lib/session"; import { getContainer } from "@/src/composition/container"; import { signOutCurrentUser } from "../../../actions/participant.actions"; +import { eventAllows } from "@/src/domain/shared/event-lifecycle"; export default async function EventLandingPage({ params }: { params: Promise<{ eventSlug: string }> }) { const { eventSlug } = await params; @@ -37,8 +38,13 @@ export default async function EventLandingPage({ params }: { params: Promise<{ e return
{event.status.toUpperCase()}

{event.name}

-

This event is not accepting profiles right now.

- View your matches + {eventAllows(event.status, "viewMatches") + ? <> +

This event has closed. Your matches and accepted connections stay available, and you can still reply to pending introductions.

+ View your matches{" "} + Connections + + :

This event has not opened yet. Come back when the organizer opens registration.

}
; } diff --git a/apps/web/app/(participant)/e/[eventSlug]/profile/page.tsx b/apps/web/app/(participant)/e/[eventSlug]/profile/page.tsx index 7e2497f..c99ba23 100644 --- a/apps/web/app/(participant)/e/[eventSlug]/profile/page.tsx +++ b/apps/web/app/(participant)/e/[eventSlug]/profile/page.tsx @@ -6,8 +6,7 @@ import ProfileForm from "@/components/participant/ProfileForm"; export default async function ProfilePage({ params }: { params: Promise<{ eventSlug: string }> }) { const { eventSlug } = await params; - const { session, event, container } = await requireParticipantEvent(eventSlug, `/e/${eventSlug}/profile`); - if (event.status !== "open") notFound(); + const { session, event, container } = await requireParticipantEvent(eventSlug, `/e/${eventSlug}/profile`, "saveProfile"); const profile = await container.participants.findProfile(event.id, session.attendeeId); if (!profile) notFound(); const intents = event.intents?.length ? event.intents : ["NETWORKING"]; diff --git a/apps/web/app/(participant)/e/[eventSlug]/search/page.tsx b/apps/web/app/(participant)/e/[eventSlug]/search/page.tsx index 2384eaf..e4eac77 100644 --- a/apps/web/app/(participant)/e/[eventSlug]/search/page.tsx +++ b/apps/web/app/(participant)/e/[eventSlug]/search/page.tsx @@ -4,7 +4,7 @@ import SearchForm from "./SearchForm"; export default async function SearchPage({ params }: { params: Promise<{ eventSlug: string }> }) { const { eventSlug } = await params; - await requireParticipantEvent(eventSlug, `/e/${eventSlug}/search`); + await requireParticipantEvent(eventSlug, `/e/${eventSlug}/search`, "search"); return

Search your event

diff --git a/apps/web/app/actions/intro.actions.ts b/apps/web/app/actions/intro.actions.ts index 3a21f20..7876609 100644 --- a/apps/web/app/actions/intro.actions.ts +++ b/apps/web/app/actions/intro.actions.ts @@ -5,6 +5,7 @@ import { requestIntro } from "../../src/application/use-cases/request-intro"; import { respondToIntro } from "../../src/application/use-cases/respond-to-intro"; import { shareVenueZone } from "../../src/application/use-cases/share-venue-zone"; import { getContainer } from "../../src/composition/container"; +import { assertEventAllows } from "../../src/domain/shared/event-lifecycle"; import { getSession } from "../../lib/session"; import { runFormAction, type FormState } from "../../lib/form-state"; @@ -18,6 +19,7 @@ async function requestIntroFor(eventSlug: string, formData: FormData) { const container = getContainer(); const event = await container.events.findByEventSlug(eventSlug); if (!event) throw new Error("Event not found"); + assertEventAllows(event.status, "requestIntro"); const recipientId = String(formData.get("recipientId") || ""); if (!recipientId) throw new Error("Choose a participant"); await requestIntro({ @@ -40,6 +42,7 @@ async function respondToIntroFor(eventSlug: string, introId: string, accept: boo const container = getContainer(); const event = await container.events.findByEventSlug(eventSlug); if (!event || !(await container.participants.hasEventAccess(event.id, session.attendeeId))) throw new Error("You are not registered for this event"); + assertEventAllows(event.status, "respondToIntro"); await respondToIntro({ eventId: event.id, introId, actorId: session.attendeeId, accept, eventName: event.name }, container); redirect(`/e/${eventSlug}/connections`); } @@ -54,6 +57,7 @@ async function shareZoneFor(eventSlug: string, introId: string, formData: FormDa const container = getContainer(); const event = await container.events.findByEventSlug(eventSlug); if (!event || !(await container.participants.hasEventAccess(event.id, session.attendeeId))) throw new Error("You are not registered for this event"); + assertEventAllows(event.status, "shareZone"); await shareVenueZone({ eventId: event.id, introId, @@ -70,6 +74,7 @@ export async function getParticipantConnections(eventSlug: string) { const container = getContainer(); const event = await container.events.findByEventSlug(eventSlug); if (!event || !(await container.participants.hasEventAccess(event.id, session.attendeeId))) throw new Error("You are not registered for this event"); + assertEventAllows(event.status, "viewMatches"); const requests = await container.intros.listForParticipant(event.id, session.attendeeId); const revealed = await container.intros.getRevealedContacts(event.id, session.attendeeId); const contacts = new Map(revealed.map(({ intro, contact }) => [intro.id, contact])); diff --git a/apps/web/app/actions/match.actions.ts b/apps/web/app/actions/match.actions.ts index 6e160f6..6fbd2e2 100644 --- a/apps/web/app/actions/match.actions.ts +++ b/apps/web/app/actions/match.actions.ts @@ -4,6 +4,7 @@ import { redirect } from "next/navigation"; import { searchParticipants } from "../../src/application/use-cases/search-participants"; import { getMyMatches } from "../../src/application/use-cases/get-my-matches"; import { getContainer } from "../../src/composition/container"; +import { assertEventAllows } from "../../src/domain/shared/event-lifecycle"; import { getSession } from "../../lib/session"; import { runFormAction, userMessage, type FormState } from "../../lib/form-state"; @@ -20,8 +21,8 @@ async function searchEvent(eventSlug: string, searchText: string) { if (!session) throw new Error("Sign in to search this event"); const container = getContainer(); const event = await container.events.findByEventSlug(eventSlug); - if (!event || event.status !== "open") throw new Error("This event is not open for matching"); - if (!(await container.participants.hasEventAccess(event.id, session.attendeeId))) throw new Error("You are not registered for this event"); + if (!event || !(await container.participants.hasEventAccess(event.id, session.attendeeId))) throw new Error("You are not registered for this event"); + assertEventAllows(event.status, "search"); const results = await searchParticipants({ eventId: event.id, participantId: session.attendeeId, query: searchText }, container); return results.map((match) => ({ id: match.participant.attendeeId, @@ -43,6 +44,7 @@ export async function getParticipantMatches(eventSlug: string) { const container = getContainer(); const event = await container.events.findByEventSlug(eventSlug); if (!event || !(await container.participants.hasEventAccess(event.id, session.attendeeId))) throw new Error("You are not registered for this event"); + assertEventAllows(event.status, "viewMatches"); const results = await getMyMatches({ eventId: event.id, participantId: session.attendeeId }, container.matches); return results.map((match) => ({ id: match.participant.attendeeId, @@ -69,6 +71,7 @@ async function queueRefresh(eventSlug: string) { const container = getContainer(); const event = await container.events.findByEventSlug(eventSlug); if (!event || !(await container.participants.hasEventAccess(event.id, session.attendeeId))) throw new Error("You are not registered for this event"); + assertEventAllows(event.status, "refreshMatches"); await container.enqueueEmbedding(event.id, session.attendeeId); redirect(`/e/${eventSlug}/matches?queued=1`); } diff --git a/apps/web/app/actions/organizer.actions.ts b/apps/web/app/actions/organizer.actions.ts index fca1421..2d9ac92 100644 --- a/apps/web/app/actions/organizer.actions.ts +++ b/apps/web/app/actions/organizer.actions.ts @@ -3,6 +3,7 @@ import { redirect } from "next/navigation"; import { createEvent, importEventRoster, queueEventMatches, updateEvent } from "../../src/application/use-cases/manage-event"; import { getContainer } from "../../src/composition/container"; +import { assertEventAllows } from "../../src/domain/shared/event-lifecycle"; import { LIMITS, ValidationError } from "../../src/domain/shared/validation"; import { runFormAction, type FormState } from "../../lib/form-state"; import { parseRosterWorkbook } from "../../src/lib/excel-importer"; @@ -80,7 +81,8 @@ async function queueMatches(organizationSlug: string, eventSlug: string) { const container = getContainer(); const event = await container.events.findBySlug(organizationSlug, eventSlug); if (!event) throw new Error("Event not found"); - if (event.status !== "open") await updateEvent({ eventId: event.id, organizerId: session.attendeeId, status: "open" }, container.events); + assertEventAllows(event.status, "computeMatches"); + if (event.status === "draft") await updateEvent({ eventId: event.id, organizerId: session.attendeeId, status: "open" }, container.events); const queued = await queueEventMatches({ eventId: event.id, organizerId: session.attendeeId }, container.events, container.enqueueEmbedding); redirect(`/orgs/${organizationSlug}/events/${eventSlug}/matching?queued=${queued}`); } diff --git a/apps/web/app/actions/participant.actions.ts b/apps/web/app/actions/participant.actions.ts index d73d322..c98e189 100644 --- a/apps/web/app/actions/participant.actions.ts +++ b/apps/web/app/actions/participant.actions.ts @@ -2,6 +2,7 @@ import { upsertParticipant } from "../../src/application/use-cases/upsert-participant"; import { getContainer } from "../../src/composition/container"; +import { assertEventAllows } from "../../src/domain/shared/event-lifecycle"; import { Intent } from "../../src/domain/participant/intent"; import { ValidationError } from "../../src/domain/shared/validation"; import { clearSession, getSession } from "../../lib/session"; @@ -20,10 +21,10 @@ async function saveProfile(eventSlug: string, formData: FormData) { if (!session) throw new Error("Sign in before saving your profile"); const container = getContainer(); const event = await container.events.findByEventSlug(eventSlug); - if (!event || event.status !== "open") throw new Error("This event is not accepting profiles"); - if (!(await container.participants.hasEventAccess(event.id, session.attendeeId))) { + if (!event || !(await container.participants.hasEventAccess(event.id, session.attendeeId))) { throw new Error("You are not on this event's registration list"); } + assertEventAllows(event.status, "saveProfile"); const intentValue = String(formData.get("intent") || Intent.NETWORKING); if (!event.intents.includes(intentValue) || !Object.values(Intent).includes(intentValue as Intent)) { diff --git a/apps/web/src/domain/shared/event-lifecycle.ts b/apps/web/src/domain/shared/event-lifecycle.ts new file mode 100644 index 0000000..c523bfb --- /dev/null +++ b/apps/web/src/domain/shared/event-lifecycle.ts @@ -0,0 +1,55 @@ +/** + * What each event status permits. Every participant action, the organizer's + * compute button, and the background worker check this one table, so draft, + * open, and closed events behave the same way everywhere. + */ +export type EventStatus = "draft" | "open" | "closed"; + +export type EventAction = + | "saveProfile" + | "search" + | "refreshMatches" + | "requestIntro" + | "shareZone" + | "viewMatches" + | "respondToIntro" + | "computeMatches" + | "processJob"; + +const ALLOWED: Record = { + saveProfile: ["open"], + search: ["open"], + refreshMatches: ["open"], + requestIntro: ["open"], + shareZone: ["open"], + // After an event closes, people keep their results and can answer requests already sent. + viewMatches: ["open", "closed"], + respondToIntro: ["open", "closed"], + // Computing on a draft opens it first; a closed event is never silently reopened. + computeMatches: ["draft", "open"], + processJob: ["open"], +}; + +const LABELS: Record = { + saveProfile: "Profile editing", + search: "Search", + refreshMatches: "Refreshing matches", + requestIntro: "Requesting introductions", + shareZone: "Sharing your venue zone", + viewMatches: "Matches", + respondToIntro: "Replying to introductions", + computeMatches: "Computing matches", + processJob: "Matching", +}; + +export function eventAllows(status: EventStatus, action: EventAction): boolean { + return ALLOWED[action].includes(status); +} + +export function assertEventAllows(status: EventStatus, action: EventAction): void { + if (eventAllows(status, action)) return; + const label = LABELS[action]; + throw new Error(status === "draft" + ? `${label} becomes available when the event opens.` + : `${label} ended when the event closed.`); +} diff --git a/apps/web/src/lib/auth.ts b/apps/web/src/lib/auth.ts index 95956fb..e95b9fd 100644 --- a/apps/web/src/lib/auth.ts +++ b/apps/web/src/lib/auth.ts @@ -1,8 +1,10 @@ import { notFound, redirect } from "next/navigation"; import { getSession } from "../../lib/session"; import { getContainer } from "../composition/container"; +import { eventAllows, type EventAction } from "../domain/shared/event-lifecycle"; -export async function requireParticipantEvent(eventSlug: string, returnPath?: string) { +/** With `action`, a page the event status does not allow sends the participant to the event landing page, which explains why. */ +export async function requireParticipantEvent(eventSlug: string, returnPath?: string, action?: EventAction) { const target = returnPath || `/e/${eventSlug}`; const session = await getSession(); if (!session) redirect(`/login?returnTo=${encodeURIComponent(target)}`); @@ -11,6 +13,7 @@ export async function requireParticipantEvent(eventSlug: string, returnPath?: st if (!event) notFound(); const registered = await container.participants.hasEventAccess(event.id, session.attendeeId); if (!registered) notFound(); + if (action && !eventAllows(event.status, action)) redirect(`/e/${eventSlug}`); return { session, event, container }; } diff --git a/packages/db/src/repositories/events.ts b/packages/db/src/repositories/events.ts index f460f61..55e88db 100644 --- a/packages/db/src/repositories/events.ts +++ b/packages/db/src/repositories/events.ts @@ -97,6 +97,12 @@ export async function update(input: { return findBySlug(old.organization_slug, old.slug); } +/** The event's status, or null when the event no longer exists. */ +export async function statusOf(eventId: string): Promise { + const { rows } = await query<{ status: EventRecord["status"] }>(`select status from events where id = $1`, [eventId]); + return rows[0]?.status ?? null; +} + export async function isOrganizer(eventId: string, attendeeId: string): Promise { const { rows } = await query<{ allowed: boolean }>( `select exists(select 1 from event_organizers where event_id = $1 and attendee_id = $2) as allowed`, diff --git a/packages/db/workers/embed.worker.ts b/packages/db/workers/embed.worker.ts index e8e8af7..14f0673 100644 --- a/packages/db/workers/embed.worker.ts +++ b/packages/db/workers/embed.worker.ts @@ -1,11 +1,18 @@ -import { matchingJobs } from "../src/index"; +import { events, matchingJobs } from "../src/index"; import { getContainer } from "../../../apps/web/src/composition/container"; import { profileText } from "../../../apps/web/src/domain/participant/participant.entity"; +import { eventAllows } from "../../../apps/web/src/domain/shared/event-lifecycle"; export async function processEmbedJob(): Promise { const job = await matchingJobs.claim("embed"); if (!job) return false; try { + const status = await events.statusOf(job.event_id); + if (!status || !eventAllows(status, "processJob")) { + console.info(`[worker:embed] job ${job.id} skipped: event is ${status ?? "gone"}`); + await matchingJobs.complete(job.id); + return true; + } const container = getContainer(); const profile = await container.participants.findProfile(job.event_id, job.participant_id); if (profile) { diff --git a/packages/db/workers/match.worker.ts b/packages/db/workers/match.worker.ts index 40c4d11..7eeec83 100644 --- a/packages/db/workers/match.worker.ts +++ b/packages/db/workers/match.worker.ts @@ -1,11 +1,18 @@ -import { matchingJobs } from "../src/index"; +import { events, matchingJobs } from "../src/index"; import { getContainer } from "../../../apps/web/src/composition/container"; import { computeMatches } from "../../../apps/web/src/application/use-cases/compute-matches"; +import { eventAllows } from "../../../apps/web/src/domain/shared/event-lifecycle"; export async function processMatchJob(): Promise { const job = await matchingJobs.claim("match"); if (!job) return false; try { + const status = await events.statusOf(job.event_id); + if (!status || !eventAllows(status, "processJob")) { + console.info(`[worker:match] job ${job.id} skipped: event is ${status ?? "gone"}`); + await matchingJobs.complete(job.id); + return true; + } const { pipeline } = getContainer(); await computeMatches({ eventId: job.event_id, participantId: job.participant_id }, pipeline); await matchingJobs.complete(job.id); diff --git a/tests/unit/event-lifecycle.test.ts b/tests/unit/event-lifecycle.test.ts new file mode 100644 index 0000000..717c876 --- /dev/null +++ b/tests/unit/event-lifecycle.test.ts @@ -0,0 +1,63 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { assertEventAllows, eventAllows, type EventAction, type EventStatus } from "@/src/domain/shared/event-lifecycle"; + +const mocks = vi.hoisted(() => ({ + claim: vi.fn(), complete: vi.fn(), fail: vi.fn(), statusOf: vi.fn(), computeMatches: vi.fn(), +})); +vi.mock("../../packages/db/src/index", () => ({ + events: { statusOf: mocks.statusOf }, + matchingJobs: { claim: mocks.claim, complete: mocks.complete, fail: mocks.fail }, +})); +vi.mock("../../apps/web/src/composition/container", () => ({ getContainer: () => ({ pipeline: {} }) })); +vi.mock("../../apps/web/src/application/use-cases/compute-matches", () => ({ computeMatches: mocks.computeMatches })); + +import { processMatchJob } from "../../packages/db/workers/match.worker"; + +// The agreed policy, row by row: [action, draft, open, closed]. +const POLICY: Array<[EventAction, boolean, boolean, boolean]> = [ + ["saveProfile", false, true, false], + ["search", false, true, false], + ["refreshMatches", false, true, false], + ["requestIntro", false, true, false], + ["shareZone", false, true, false], + ["viewMatches", false, true, true], + ["respondToIntro", false, true, true], + ["computeMatches", true, true, false], + ["processJob", false, true, false], +]; + +describe("event lifecycle policy", () => { + it.each(POLICY)("%s: draft=%s open=%s closed=%s", (action, draft, open, closed) => { + const allowed = (status: EventStatus) => eventAllows(status, action); + expect([allowed("draft"), allowed("open"), allowed("closed")]).toEqual([draft, open, closed]); + }); + + it("explains why an action is unavailable", () => { + expect(() => assertEventAllows("draft", "search")).toThrow("Search becomes available when the event opens."); + expect(() => assertEventAllows("closed", "requestIntro")).toThrow("Requesting introductions ended when the event closed."); + expect(() => assertEventAllows("open", "search")).not.toThrow(); + }); +}); + +describe("match worker", () => { + const job = { id: 7, event_id: "event", participant_id: "attendee", attempts: 1, job_type: "match" }; + beforeEach(() => { + vi.clearAllMocks(); + vi.spyOn(console, "info").mockImplementation(() => {}); + mocks.claim.mockResolvedValue(job); + }); + + it.each(["draft", "closed", null])("skips and completes a job when the event is %s", async (status) => { + mocks.statusOf.mockResolvedValue(status); + await expect(processMatchJob()).resolves.toBe(true); + expect(mocks.computeMatches).not.toHaveBeenCalled(); + expect(mocks.complete).toHaveBeenCalledWith(7); + }); + + it("computes matches while the event is open", async () => { + mocks.statusOf.mockResolvedValue("open"); + await processMatchJob(); + expect(mocks.computeMatches).toHaveBeenCalledWith({ eventId: "event", participantId: "attendee" }, {}); + expect(mocks.complete).toHaveBeenCalledWith(7); + }); +}); From 7d45469ede0960ab2dd474975a40d3ed60ab307e Mon Sep 17 00:00:00 2001 From: SURYANSH-RAI Date: Sun, 18 Oct 2026 15:07:15 +0530 Subject: [PATCH 02/56] Track where background matching stands (R08 part 2) - Migration 0005: matching_jobs.started_at (set when a worker claims a job) and an index for each participant's latest job - domain/matching/match-status.ts: a participant's latest job maps to none / queued / running / stuck (running over 10 minutes) / failed / done; a finished embed job counts as queued since its match job follows; summarizeQueue counts states across an event - MatchQueue port with a Postgres adapter and get-match-status use cases, registered in the container - Unit tests for the states and a real-Postgres test that the latest job is chosen per participant and events stay separate --- apps/web/src/application/ports/match-queue.ts | 7 ++ .../application/use-cases/get-match-status.ts | 10 +++ apps/web/src/composition/container.ts | 2 + apps/web/src/domain/matching/match-status.ts | 44 ++++++++++ .../postgres/match-queue.repo.ts | 18 +++++ packages/db/migrations/0005_job_status.sql | 11 +++ packages/db/src/repositories/matching-jobs.ts | 33 +++++++- tests/integration/match-queue.test.ts | 80 +++++++++++++++++++ tests/unit/match-status.test.ts | 39 +++++++++ 9 files changed, 243 insertions(+), 1 deletion(-) create mode 100644 apps/web/src/application/ports/match-queue.ts create mode 100644 apps/web/src/application/use-cases/get-match-status.ts create mode 100644 apps/web/src/domain/matching/match-status.ts create mode 100644 apps/web/src/infrastructure/postgres/match-queue.repo.ts create mode 100644 packages/db/migrations/0005_job_status.sql create mode 100644 tests/integration/match-queue.test.ts create mode 100644 tests/unit/match-status.test.ts diff --git a/apps/web/src/application/ports/match-queue.ts b/apps/web/src/application/ports/match-queue.ts new file mode 100644 index 0000000..d8b91d9 --- /dev/null +++ b/apps/web/src/application/ports/match-queue.ts @@ -0,0 +1,7 @@ +import type { JobSnapshot } from "../../domain/matching/match-status"; + +/** Read side of the background matching queue. */ +export interface MatchQueue { + latestJob(eventId: string, participantId: string): Promise; + latestJobsForEvent(eventId: string): Promise; +} diff --git a/apps/web/src/application/use-cases/get-match-status.ts b/apps/web/src/application/use-cases/get-match-status.ts new file mode 100644 index 0000000..113c2e4 --- /dev/null +++ b/apps/web/src/application/use-cases/get-match-status.ts @@ -0,0 +1,10 @@ +import { queueState, summarizeQueue } from "../../domain/matching/match-status"; +import type { MatchQueue } from "../ports/match-queue"; + +export async function getMatchStatus(input: { eventId: string; participantId: string }, queue: MatchQueue) { + return queueState(await queue.latestJob(input.eventId, input.participantId)); +} + +export async function getEventQueueSummary(input: { eventId: string }, queue: MatchQueue) { + return summarizeQueue(await queue.latestJobsForEvent(input.eventId)); +} diff --git a/apps/web/src/composition/container.ts b/apps/web/src/composition/container.ts index 3e974de..d0f73be 100644 --- a/apps/web/src/composition/container.ts +++ b/apps/web/src/composition/container.ts @@ -4,6 +4,7 @@ import { PostgresMatchRepository } from "../infrastructure/postgres/match.repo"; import { PostgresParticipantRepository } from "../infrastructure/postgres/participant.repo"; import { PostgresRateLimiter } from "../infrastructure/cache/postgres-rate-limiter"; import { PostgresEventRepository } from "../infrastructure/postgres/event.repo"; +import { PostgresMatchQueue } from "../infrastructure/postgres/match-queue.repo"; import { PostgresCandidateCache } from "../infrastructure/cache/postgres-candidate-cache"; import { UpstashCandidateCache } from "../infrastructure/cache/upstash-candidate-cache"; import { RealtimeNotifier } from "../infrastructure/notifications/realtime.notifier"; @@ -28,6 +29,7 @@ function buildContainer() { embeddings, llm, candidateCache, + matchQueue: new PostgresMatchQueue(), notifications: new RealtimeNotifier(), limiter: new PostgresRateLimiter(), pipeline: new MatchingPipeline(participants, matches, embeddings, llm, candidateCache), diff --git a/apps/web/src/domain/matching/match-status.ts b/apps/web/src/domain/matching/match-status.ts new file mode 100644 index 0000000..a1a9f75 --- /dev/null +++ b/apps/web/src/domain/matching/match-status.ts @@ -0,0 +1,44 @@ +/** + * Where background matching stands for one participant, derived from their + * latest job. Lets the UI tell "still working" apart from "failed" and from + * "finished with nobody to match". + */ +export type QueueState = "none" | "queued" | "running" | "stuck" | "failed" | "done"; + +/** A running job older than this is treated as stuck (crashed worker). */ +export const STUCK_AFTER_MS = 10 * 60 * 1000; + +export interface JobSnapshot { + type: "embed" | "match"; + status: "pending" | "running" | "done" | "failed"; + startedAt: Date | null; +} + +export function queueState(job: JobSnapshot | null, now = Date.now()): QueueState { + if (!job) return "none"; + switch (job.status) { + case "pending": + return "queued"; + case "running": + return job.startedAt && now - job.startedAt.getTime() > STUCK_AFTER_MS ? "stuck" : "running"; + case "failed": + return "failed"; + case "done": + // A finished embed job is immediately followed by its match job. + return job.type === "embed" ? "queued" : "done"; + } +} + +/** True while results may still change without anyone acting. */ +export function isInProgress(state: QueueState): boolean { + return state === "queued" || state === "running"; +} + +export function summarizeQueue(jobs: JobSnapshot[], now = Date.now()): Record, number> { + const counts = { queued: 0, running: 0, stuck: 0, failed: 0, done: 0 }; + for (const job of jobs) { + const state = queueState(job, now); + if (state !== "none") counts[state] += 1; + } + return counts; +} diff --git a/apps/web/src/infrastructure/postgres/match-queue.repo.ts b/apps/web/src/infrastructure/postgres/match-queue.repo.ts new file mode 100644 index 0000000..e35ac76 --- /dev/null +++ b/apps/web/src/infrastructure/postgres/match-queue.repo.ts @@ -0,0 +1,18 @@ +import { matchingJobs } from "@match-maker/db"; +import type { MatchQueue } from "../../application/ports/match-queue"; +import type { JobSnapshot } from "../../domain/matching/match-status"; + +export class PostgresMatchQueue implements MatchQueue { + async latestJob(eventId: string, participantId: string): Promise { + const row = await matchingJobs.latestForParticipant(eventId, participantId); + return row ? toSnapshot(row) : null; + } + + async latestJobsForEvent(eventId: string): Promise { + return (await matchingJobs.latestForEvent(eventId)).map(toSnapshot); + } +} + +function toSnapshot(row: matchingJobs.JobSnapshot): JobSnapshot { + return { type: row.job_type, status: row.status, startedAt: row.started_at }; +} diff --git a/packages/db/migrations/0005_job_status.sql b/packages/db/migrations/0005_job_status.sql new file mode 100644 index 0000000..a334ab7 --- /dev/null +++ b/packages/db/migrations/0005_job_status.sql @@ -0,0 +1,11 @@ +-- Show participants and organizers where matching stands. +-- +-- `started_at` records when a worker claimed the job, so a job still +-- "running" long after that (a crashed worker) can be shown as stuck instead +-- of pending forever. The index serves "latest job for this participant", +-- which the matches page and the organizer queue summary read. + +alter table matching_jobs add column if not exists started_at timestamptz; + +create index if not exists idx_matching_jobs_participant_latest + on matching_jobs(event_id, participant_id, created_at desc); diff --git a/packages/db/src/repositories/matching-jobs.ts b/packages/db/src/repositories/matching-jobs.ts index ec40615..8a09534 100644 --- a/packages/db/src/repositories/matching-jobs.ts +++ b/packages/db/src/repositories/matching-jobs.ts @@ -25,7 +25,7 @@ export async function claim(jobType: "embed" | "match"): Promise { + const { rows } = await query( + `select participant_id, job_type, status, started_at from matching_jobs + where event_id = $1 and participant_id = $2 + order by ${LATEST_ORDER} limit 1`, + [eventId, participantId] + ); + return rows[0] ?? null; +} + +/** The latest job of every participant in the event that has one. */ +export async function latestForEvent(eventId: string): Promise { + const { rows } = await query( + `select distinct on (participant_id) participant_id, job_type, status, started_at from matching_jobs + where event_id = $1 + order by participant_id, ${LATEST_ORDER}`, + [eventId] + ); + return rows; +} + export async function complete(id: number): Promise { await query(`update matching_jobs set status = 'done' where id = $1`, [id]); } diff --git a/tests/integration/match-queue.test.ts b/tests/integration/match-queue.test.ts new file mode 100644 index 0000000..4a3d320 --- /dev/null +++ b/tests/integration/match-queue.test.ts @@ -0,0 +1,80 @@ +/** + * The queue status reads the latest job per participant, scoped to one event. + * Rows are inserted directly (no claim()), so jobs belonging to other local + * data are never touched. Skipped when DATABASE_URL is unset. + */ +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { query, closePool, attendees } from "@match-maker/db"; +import { migrate } from "../../packages/db/src/migrate"; +import { PostgresMatchQueue } from "../../apps/web/src/infrastructure/postgres/match-queue.repo"; + +const hasDatabase = Boolean(process.env.DATABASE_URL); +const describeDb = hasDatabase ? describe : describe.skip; + +const ORG_SLUG = "integration-match-queue"; +const KEYS = ["a", "b", "c"] as const; +const emailOf = (key: string) => `queue-${key}@example.com`; + +describeDb("match queue status", () => { + const queue = new PostgresMatchQueue(); + let eventId: string; + let otherEventId: string; + let ids: Record; + + async function job(event: string, key: string, type: string, status: string, minutesAgo: number, startedMinutesAgo?: number) { + await query( + `insert into matching_jobs (event_id, participant_id, job_type, status, created_at, started_at) + values ($1, $2, $3, $4, now() - make_interval(mins => $5), case when $6::int is null then null else now() - make_interval(mins => $6::int) end)`, + [event, ids[key], type, status, minutesAgo, startedMinutesAgo ?? null] + ); + } + + beforeAll(async () => { + await migrate(); + await attendees.upsertMany(KEYS.map((key) => ({ name: key, email: emailOf(key) }))); + const found = await attendees.findIdsByEmails(KEYS.map(emailOf)); + ids = Object.fromEntries(KEYS.map((key) => [key, found.find((row) => row.email === emailOf(key))!.id])); + const { rows: [org] } = await query<{ id: string }>( + `insert into organizations (name, slug) values ('Queue test', $1) + on conflict (slug) do update set name = excluded.name returning id`, [ORG_SLUG] + ); + const event = async (slug: string) => (await query<{ id: string }>( + `insert into events (organization_id, name, slug, status) values ($1, $2, $2, 'open') + on conflict (organization_id, slug) do update set status = 'open' returning id`, [org.id, slug] + )).rows[0].id; + eventId = await event(ORG_SLUG); + otherEventId = await event(`${ORG_SLUG}-other`); + await query(`delete from matching_jobs where event_id = any($1::uuid[])`, [[eventId, otherEventId]]); + + // a: an old failure, then a newer match job finished. + await job(eventId, "a", "match", "failed", 30); + await job(eventId, "a", "match", "done", 5); + // b: running for 20 minutes (stuck). + await job(eventId, "b", "embed", "running", 25, 20); + // c: only has jobs in another event. + await job(otherEventId, "c", "match", "pending", 1); + }); + + afterAll(async () => { + await query(`delete from organizations where slug = $1`, [ORG_SLUG]); + await query(`delete from registered_attendees where email = any($1::text[])`, [KEYS.map(emailOf)]); + await closePool(); + }); + + it("returns a participant's newest job", async () => { + expect(await queue.latestJob(eventId, ids.a)).toEqual({ type: "match", status: "done", startedAt: null }); + const stuck = await queue.latestJob(eventId, ids.b); + expect(stuck).toMatchObject({ type: "embed", status: "running" }); + expect(Date.now() - stuck!.startedAt!.getTime()).toBeGreaterThan(19 * 60_000); + }); + + it("keeps events apart", async () => { + expect(await queue.latestJob(eventId, ids.c)).toBeNull(); + expect(await queue.latestJob(otherEventId, ids.c)).toMatchObject({ status: "pending" }); + }); + + it("lists one latest job per participant in the event", async () => { + const jobs = await queue.latestJobsForEvent(eventId); + expect(jobs.map((row) => row.status).sort()).toEqual(["done", "running"]); + }); +}); diff --git a/tests/unit/match-status.test.ts b/tests/unit/match-status.test.ts new file mode 100644 index 0000000..9fcf81c --- /dev/null +++ b/tests/unit/match-status.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, it } from "vitest"; +import { isInProgress, queueState, STUCK_AFTER_MS, summarizeQueue, type JobSnapshot } from "@/src/domain/matching/match-status"; + +const NOW = Date.parse("2026-10-18T12:00:00Z"); +const job = (overrides: Partial): JobSnapshot => ({ type: "match", status: "pending", startedAt: null, ...overrides }); +const startedAgo = (ms: number) => new Date(NOW - ms); + +describe("queueState", () => { + it.each([ + ["no job yet", null, "none"], + ["a pending job", job({ status: "pending" }), "queued"], + ["a job that just started", job({ status: "running", startedAt: startedAgo(60_000) }), "running"], + ["a job running past the limit", job({ status: "running", startedAt: startedAgo(STUCK_AFTER_MS + 1) }), "stuck"], + ["a job with retries used up", job({ status: "failed" }), "failed"], + ["a finished match job", job({ status: "done" }), "done"], + ["a finished embed job (match job follows)", job({ type: "embed", status: "done" }), "queued"], + ] as const)("reports %s as %s", (_label, snapshot, expected) => { + expect(queueState(snapshot, NOW)).toBe(expected); + }); + + it("only treats queued and running as in progress", () => { + expect((["queued", "running"] as const).every(isInProgress)).toBe(true); + expect((["none", "stuck", "failed", "done"] as const).some(isInProgress)).toBe(false); + }); +}); + +describe("summarizeQueue", () => { + it("counts each participant's latest job by state", () => { + expect(summarizeQueue([ + job({ status: "pending" }), + job({ type: "embed", status: "done" }), + job({ status: "running", startedAt: startedAgo(1000) }), + job({ status: "running", startedAt: startedAgo(STUCK_AFTER_MS * 2) }), + job({ status: "failed" }), + job({ status: "done" }), + job({ status: "done" }), + ], NOW)).toEqual({ queued: 2, running: 1, stuck: 1, failed: 1, done: 2 }); + }); +}); From a6a1b632b5e96786b570a7d2642d08688fdbf36c Mon Sep 17 00:00:00 2001 From: SURYANSH-RAI Date: Sun, 18 Oct 2026 15:10:02 +0530 Subject: [PATCH 03/56] Show participants and organizers where matching stands (R08 part 3) - Matches page tells apart: not started, queued, running, stuck, failed, and finished with nobody to match, each with its own message; stuck/failed/empty offer "Try again"; existing matches stay visible with an "updating" or "last update failed" notice - While matching is queued or running the page refreshes itself every 10 seconds for up to 3 minutes (AutoRefresh) - Closed events: matches stay readable with a notice, but intro buttons, refresh, profile/search links and zone sharing are hidden - Organizer matching page: per-participant queue counts (queued, running, stuck, failed, finished); compute button reflects draft / open / closed instead of always "Open registration" - enqueue() releases that participant's job stuck "running" over 10 minutes, which otherwise blocked "Try again" via the one-active-job index; crash recovery proper stays in R21 --- .../events/[eventSlug]/matching/page.tsx | 25 +++++++++-- .../e/[eventSlug]/connections/page.tsx | 3 +- .../e/[eventSlug]/matches/page.tsx | 28 +++++++----- apps/web/app/actions/match.actions.ts | 2 +- .../components/participant/AutoRefresh.tsx | 21 +++++++++ .../components/participant/MatchStatus.tsx | 44 +++++++++++++++++++ packages/db/src/repositories/matching-jobs.ts | 11 +++++ tests/integration/match-queue.test.ts | 16 ++++++- 8 files changed, 131 insertions(+), 19 deletions(-) create mode 100644 apps/web/components/participant/AutoRefresh.tsx create mode 100644 apps/web/components/participant/MatchStatus.tsx diff --git a/apps/web/app/(organizer)/orgs/[orgSlug]/events/[eventSlug]/matching/page.tsx b/apps/web/app/(organizer)/orgs/[orgSlug]/events/[eventSlug]/matching/page.tsx index c893fa7..c12ac21 100644 --- a/apps/web/app/(organizer)/orgs/[orgSlug]/events/[eventSlug]/matching/page.tsx +++ b/apps/web/app/(organizer)/orgs/[orgSlug]/events/[eventSlug]/matching/page.tsx @@ -2,6 +2,12 @@ import Link from "next/link"; import { computeEventMatchesAction } from "../../../../../../actions/organizer.actions"; import { requireOrganizerEvent } from "@/src/lib/auth"; import { ActionForm } from "@/components/ui/form"; +import { getEventQueueSummary } from "@/src/application/use-cases/get-match-status"; +import { eventAllows } from "@/src/domain/shared/event-lifecycle"; + +const QUEUE_LABELS = [ + ["queued", "Queued"], ["running", "Running"], ["stuck", "Stuck (running over 10 min)"], ["failed", "Failed"], ["done", "Finished"], +] as const; export default async function MatchingPage({ params, searchParams }: { params: Promise<{ orgSlug: string; eventSlug: string }>; @@ -10,7 +16,10 @@ export default async function MatchingPage({ params, searchParams }: { const { orgSlug, eventSlug } = await params; const query = await searchParams; const { event, container } = await requireOrganizerEvent(orgSlug, eventSlug); - const analytics = await container.events.analytics(event.id); + const [analytics, queue] = await Promise.all([ + container.events.analytics(event.id), + getEventQueueSummary({ eventId: event.id }, container.matchQueue), + ]); const action = computeEventMatchesAction.bind(null, orgSlug, eventSlug); return
@@ -19,11 +28,21 @@ export default async function MatchingPage({ params, searchParams }: { {query.queued &&

Queued profile matching for {query.queued} attendee(s).

}
{analytics.profiles} completed profiles
{analytics.matches} saved match results
- + {eventAllows(event.status, "computeMatches") + ? + :

This event is closed. Reopen it from the dashboard to compute matches again.

}
- {event.status !== "open" &&

Registration is currently {event.status}. Starting matching opens the event to participants.

} + {event.status === "draft" &&

Registration is currently draft. Starting matching opens the event to participants.

} +

Queue

+

Where each participant's latest matching job stands.

+
+ {QUEUE_LABELS.map(([key, label]) =>
{label}
{queue[key]}
)} +
+ {(queue.failed > 0 || queue.stuck > 0) &&

Some participants have no fresh matches. “Compute matches” queues failed and stuck participants again.

}
; } const shell = { minHeight: "100vh", maxWidth: 900, margin: "0 auto", padding: "36px 24px", color: "#f4f4f5" } as const; const card = { display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: 20, alignItems: "center", padding: 24, background: "#151519", border: "1px solid #333", borderRadius: 12, marginTop: 24 } as const; +const grid = { display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(140px,1fr))", gap: 12, margin: "16px 0" } as const; +const stat = { display: "grid", gap: 6, padding: 16, borderRadius: 12, background: "#151519", border: "1px solid #333" } as const; diff --git a/apps/web/app/(participant)/e/[eventSlug]/connections/page.tsx b/apps/web/app/(participant)/e/[eventSlug]/connections/page.tsx index c92809b..7e65b69 100644 --- a/apps/web/app/(participant)/e/[eventSlug]/connections/page.tsx +++ b/apps/web/app/(participant)/e/[eventSlug]/connections/page.tsx @@ -2,6 +2,7 @@ import Link from "next/link"; import { getParticipantConnections, respondToParticipantIntro, shareVenueZoneAction } from "../../../../actions/intro.actions"; import { requireParticipantEvent } from "@/src/lib/auth"; import { ActionForm } from "@/components/ui/form"; +import { eventAllows } from "@/src/domain/shared/event-lifecycle"; export default async function ConnectionsPage({ params, searchParams }: { params: Promise<{ eventSlug: string }>; @@ -29,7 +30,7 @@ export default async function ConnectionsPage({ params, searchParams }: { {connection.contact.email && } {connection.contact.phone && } {connection.contact.venueZone &&
At the venue: {connection.contact.venueZone}
} - {event.zones.length > 0 && + {event.zones.length > 0 && eventAllows(event.status, "shareZone") &&