From 74c31db1c9d51a26f3feaf981235bda0f5960d51 Mon Sep 17 00:00:00 2001 From: SURYANSH-RAI Date: Mon, 19 Oct 2026 09:22:08 +0530 Subject: [PATCH 01/20] Deliver intro notifications through a durable outbox (R23 part 1) Notification e-mails were sent inline after the action and a failure was only logged, so a mail outage lost the message. - Migration 0014: notification_outbox (unique dedupe key, attempts, lease, last error) and location_requests (used by part 2); the sweep removes sent notifications after 30 days and location requests after a day - An intro request and its notification, and an acceptance and its notice to the requester, commit in one transaction - The worker delivers queued notifications with a 2-minute lease and backoff retries (30s ... 15 min, 5 attempts); details are read at send time and an interaction that no longer applies is closed without sending; replays never send twice - E-mails carry a deep link to the connection on the Connections page; the notifier gains location-request and reply messages - Real-Postgres tests: queued once with the request, delivered with the link, acceptance notice, and a failed send kept for retry --- .../web/src/application/ports/notification.ts | 16 +++- .../application/use-cases/request-intro.ts | 13 +--- .../application/use-cases/respond-to-intro.ts | 16 +--- .../notifications/realtime.notifier.ts | 32 +++++--- .../src/infrastructure/postgres/intro.repo.ts | 46 ++++++----- .../0014_outbox_location_requests.sql | 48 ++++++++++++ packages/db/src/index.ts | 1 + packages/db/src/repositories/events.ts | 6 ++ packages/db/src/repositories/housekeeping.ts | 4 + packages/db/src/repositories/outbox.ts | 76 +++++++++++++++++++ packages/db/workers/notification.worker.ts | 55 ++++++++++++++ packages/db/workers/worker.ts | 4 +- tests/integration/notification-outbox.test.ts | 74 ++++++++++++++++++ 13 files changed, 333 insertions(+), 58 deletions(-) create mode 100644 packages/db/migrations/0014_outbox_location_requests.sql create mode 100644 packages/db/src/repositories/outbox.ts create mode 100644 packages/db/workers/notification.worker.ts create mode 100644 tests/integration/notification-outbox.test.ts diff --git a/apps/web/src/application/ports/notification.ts b/apps/web/src/application/ports/notification.ts index 7db58ee..8bdd3bf 100644 --- a/apps/web/src/application/ports/notification.ts +++ b/apps/web/src/application/ports/notification.ts @@ -1,5 +1,17 @@ +/** One delivered message: who it goes to and the page it links to. */ +export interface NotificationTarget { + recipientEmail: string; + recipientName: string; + otherName: string; + eventName: string; + /** Deep link to the interaction, e.g. the connection on the Connections page. */ + link: string; +} + export interface NotificationPort { invitation(input: { email: string; name: string | null; eventName: string; organizationName: string; eventUrl: string }): Promise; - introRequested(input: { recipientEmail: string; recipientName: string; requesterName: string; eventName: string; introId: string }): Promise; - introResponded(input: { recipientEmail: string; recipientName: string; requesterName: string; eventName: string; accepted: boolean }): Promise; + introRequested(input: NotificationTarget): Promise; + introAccepted(input: NotificationTarget): Promise; + locationRequested(input: NotificationTarget): Promise; + locationAnswered(input: NotificationTarget & { zone: string | null }): Promise; } diff --git a/apps/web/src/application/use-cases/request-intro.ts b/apps/web/src/application/use-cases/request-intro.ts index ed31eee..7be99a7 100644 --- a/apps/web/src/application/use-cases/request-intro.ts +++ b/apps/web/src/application/use-cases/request-intro.ts @@ -1,13 +1,12 @@ import type { IntroRepository } from "../ports/intro-repository"; import type { ParticipantRepository } from "../ports/participant-repository"; -import type { NotificationPort } from "../ports/notification"; import { boundedText, LIMITS } from "../../domain/shared/validation"; import { INTRO_LIMITS, introRequestRefusal } from "../../domain/connection/connection.rules"; import type { RateLimiter } from "../ports/rate-limiter"; export async function requestIntro( input: { eventId: string; requesterId: string; recipientId: string; message?: string | null; eventName?: string }, - dependencies: { participants: ParticipantRepository; intros: IntroRepository; notifications?: NotificationPort; limiter?: RateLimiter } + dependencies: { participants: ParticipantRepository; intros: IntroRepository; limiter?: RateLimiter } ) { if (input.requesterId === input.recipientId) throw new Error("You cannot request an intro to yourself"); if (!(await dependencies.participants.hasEventAccess(input.eventId, input.requesterId))) throw new Error("You are not registered for this event"); @@ -26,15 +25,7 @@ export async function requestIntro( if (dependencies.limiter && !(await dependencies.limiter.consume(`intro:${input.eventId}:${input.requesterId}`, INTRO_LIMITS.perHour, 3600))) { throw new Error("You have sent many introduction requests this hour. Please try again later."); } + // The notification is queued with the request (outbox) and delivered by the worker. const intro = await dependencies.intros.create({ ...input, message }); - if (recipient.email && dependencies.notifications) { - await dependencies.notifications.introRequested({ - recipientEmail: recipient.email, - recipientName: recipient.name, - requesterName: requester.name, - eventName: input.eventName ?? "your event", - introId: intro.id, - }).catch((error) => console.warn("[intro] notification failed", error)); - } return intro; } diff --git a/apps/web/src/application/use-cases/respond-to-intro.ts b/apps/web/src/application/use-cases/respond-to-intro.ts index fe9492d..5f67aea 100644 --- a/apps/web/src/application/use-cases/respond-to-intro.ts +++ b/apps/web/src/application/use-cases/respond-to-intro.ts @@ -1,11 +1,10 @@ import type { IntroRepository } from "../ports/intro-repository"; -import type { NotificationPort } from "../ports/notification"; import type { ParticipantRepository } from "../ports/participant-repository"; import type { AuditLog } from "../ports/audit-log"; export async function respondToIntro( input: { eventId: string; introId: string; actorId: string; accept: boolean; eventName?: string }, - dependencies: { intros: IntroRepository; participants: ParticipantRepository; notifications?: NotificationPort; audit?: AuditLog } + dependencies: { intros: IntroRepository; participants: ParticipantRepository; audit?: AuditLog } ) { const existing = await dependencies.intros.findById(input.eventId, input.introId); if (!existing) throw new Error("Intro request not found"); @@ -16,18 +15,5 @@ export async function respondToIntro( if (updated.status === "accepted") { await dependencies.audit?.record({ eventId: input.eventId, actorId: input.actorId, action: "contacts.revealed", subjectId: updated.requesterId }); } - if (updated.status === "accepted" && dependencies.notifications) { - const requester = await dependencies.participants.findProfile(input.eventId, updated.requesterId); - const recipient = await dependencies.participants.findProfile(input.eventId, updated.recipientId); - if (requester?.email) { - await dependencies.notifications.introResponded({ - recipientEmail: requester.email, - recipientName: requester.name, - requesterName: recipient?.name ?? "Your connection", - eventName: input.eventName ?? "your event", - accepted: true, - }).catch((error) => console.warn("[intro] notification failed", error)); - } - } return updated; } diff --git a/apps/web/src/infrastructure/notifications/realtime.notifier.ts b/apps/web/src/infrastructure/notifications/realtime.notifier.ts index b5ca8fa..4b61de9 100644 --- a/apps/web/src/infrastructure/notifications/realtime.notifier.ts +++ b/apps/web/src/infrastructure/notifications/realtime.notifier.ts @@ -1,27 +1,35 @@ import { renderInvitationEmail, sendNotificationEmail } from "@match-maker/email"; -import type { NotificationPort } from "../../application/ports/notification"; +import type { NotificationPort, NotificationTarget } from "../../application/ports/notification"; export class RealtimeNotifier implements NotificationPort { async invitation(input: { email: string; name: string | null; eventName: string; organizationName: string; eventUrl: string }): Promise { await sendNotificationEmail({ to: input.email, ...renderInvitationEmail(input) }); } - async introRequested(input: { recipientEmail: string; recipientName: string; requesterName: string; eventName: string; introId: string }): Promise { - const subject = `${input.requesterName} would like to meet at ${input.eventName}`; - const text = `Hi ${input.recipientName},\n\n${input.requesterName} requested an introduction at ${input.eventName}. Sign in to Mr. Bridge to respond.`; - await sendNotificationEmail({ to: input.recipientEmail, subject, text, html: emailHtml(input.recipientName, input.requesterName, input.eventName, "requested an introduction. Sign in to Mr. Bridge to respond.") }); + introRequested(input: NotificationTarget): Promise { + return send(input, `${input.otherName} would like to meet at ${input.eventName}`, `${input.otherName} requested an introduction. Accept to share contact details.`, "Respond"); } - async introResponded(input: { recipientEmail: string; recipientName: string; requesterName: string; eventName: string; accepted: boolean }): Promise { - const status = input.accepted ? "accepted" : "declined"; - const subject = `Your introduction request was ${status}`; - const text = `Hi ${input.recipientName},\n\n${input.requesterName} ${status} your introduction request for ${input.eventName}.`; - await sendNotificationEmail({ to: input.recipientEmail, subject, text, html: emailHtml(input.recipientName, input.requesterName, input.eventName, `${status} your introduction request.`) }); + introAccepted(input: NotificationTarget): Promise { + return send(input, `${input.otherName} accepted your introduction`, `${input.otherName} accepted your introduction request. Their contact details are now on your Connections page.`, "See contact"); + } + + locationRequested(input: NotificationTarget): Promise { + return send(input, `${input.otherName} is asking where you are`, `${input.otherName} would like to find you at ${input.eventName}. Sharing your venue zone is up to you.`, "Reply"); + } + + locationAnswered(input: NotificationTarget & { zone: string | null }): Promise { + const text = input.zone ? `${input.otherName} is at ${input.zone}.` : `${input.otherName} would rather not share their location right now.`; + return send(input, input.zone ? `${input.otherName} is at ${input.zone}` : `${input.otherName} replied to your location request`, text, "Open connections"); } } -function emailHtml(name: string, otherPerson: string, event: string, action: string): string { - return `

Mr. Bridge

Hi ${escapeHtml(name)},

${escapeHtml(otherPerson)} ${escapeHtml(action)}

Event: ${escapeHtml(event)}

Open Mr. Bridge to view your connections.

`; +async function send(input: NotificationTarget, subject: string, line: string, action: string): Promise { + const text = `Hi ${input.recipientName},\n\n${line}\n\n${action}: ${input.link}`; + const html = `

Mr. Bridge

` + + `

Hi ${escapeHtml(input.recipientName)},

${escapeHtml(line)}

Event: ${escapeHtml(input.eventName)}

` + + `

${escapeHtml(action)}

`; + await sendNotificationEmail({ to: input.recipientEmail, subject, text, html }); } function escapeHtml(value: string): string { diff --git a/apps/web/src/infrastructure/postgres/intro.repo.ts b/apps/web/src/infrastructure/postgres/intro.repo.ts index 88595fe..652c159 100644 --- a/apps/web/src/infrastructure/postgres/intro.repo.ts +++ b/apps/web/src/infrastructure/postgres/intro.repo.ts @@ -1,4 +1,4 @@ -import { query } from "@match-maker/db"; +import { outbox, query, transaction } from "@match-maker/db"; import type { IntroRepository } from "../../application/ports/intro-repository"; import type { IntroRequest, IntroStatus } from "../../domain/connection/intro-request.entity"; @@ -20,14 +20,20 @@ export class PostgresIntroRepository implements IntroRepository { async create(input: { eventId: string; requesterId: string; recipientId: string; message?: string | null }): Promise { if (input.requesterId === input.recipientId) throw new Error("You cannot request an intro to yourself"); const message = input.message?.trim().slice(0, 500) || null; - const { rows } = await query( - `insert into intro_requests (event_id, requester_id, recipient_id, message) - values ($1, $2, $3, $4) - on conflict (event_id, requester_id, recipient_id) do nothing - returning ${INTRO_COLUMNS}`, - [input.eventId, input.requesterId, input.recipientId, message] - ); - if (rows[0]) return mapIntro(rows[0]); + // The request and its notification commit together, so neither is lost. + const created = await transaction(async (client) => { + const { rows } = await client.query( + `insert into intro_requests (event_id, requester_id, recipient_id, message) + values ($1, $2, $3, $4) + on conflict (event_id, requester_id, recipient_id) do nothing + returning ${INTRO_COLUMNS}`, + [input.eventId, input.requesterId, input.recipientId, message] + ); + if (!rows[0]) return null; + await outbox.enqueue({ eventId: input.eventId, recipientId: input.recipientId, kind: "intro.requested", subjectId: rows[0].id, dedupeKey: `intro.requested:${rows[0].id}` }, client); + return rows[0]; + }); + if (created) return mapIntro(created); throw new Error("An intro request already exists between these participants"); } @@ -40,14 +46,20 @@ export class PostgresIntroRepository implements IntroRepository { } async respond(eventId: string, introId: string, actorId: string, status: Extract): Promise { - const { rows } = await query( - `update intro_requests set status = $4, responded_at = now() - where event_id = $1 and id = $2 and recipient_id = $3 and status = 'pending' - returning ${INTRO_COLUMNS}`, - [eventId, introId, actorId, status] - ); - if (!rows[0]) throw new Error("Only the recipient can respond to a pending intro request"); - return mapIntro(rows[0]); + const updated = await transaction(async (client) => { + const { rows } = await client.query( + `update intro_requests set status = $4, responded_at = now() + where event_id = $1 and id = $2 and recipient_id = $3 and status = 'pending' + returning ${INTRO_COLUMNS}`, + [eventId, introId, actorId, status] + ); + if (rows[0]?.status === "accepted") { + await outbox.enqueue({ eventId, recipientId: rows[0].requester_id, kind: "intro.accepted", subjectId: rows[0].id, dedupeKey: `intro.accepted:${rows[0].id}` }, client); + } + return rows[0] ?? null; + }); + if (!updated) throw new Error("Only the recipient can respond to a pending intro request"); + return mapIntro(updated); } async findBetween(eventId: string, a: string, b: string): Promise { diff --git a/packages/db/migrations/0014_outbox_location_requests.sql b/packages/db/migrations/0014_outbox_location_requests.sql new file mode 100644 index 0000000..4cbc7e0 --- /dev/null +++ b/packages/db/migrations/0014_outbox_location_requests.sql @@ -0,0 +1,48 @@ +-- Reliable notifications and venue location requests. +-- +-- notification_outbox: written in the same transaction as the interaction it +-- announces (an intro request, an acceptance, a location request or reply), +-- then delivered by the worker with retries. dedupe_key makes each +-- notification unique, so retries and replays never send duplicates. +-- Sent rows are swept after 30 days. +-- +-- location_requests: "where are you?" between two accepted connections. The +-- recipient may reply with a configured venue zone or decline; the reply is +-- visible only to the person who asked, for 15 minutes. Pending requests +-- expire after 30 minutes. Rows are swept after a day. + +create table if not exists notification_outbox ( + id bigserial primary key, + event_id uuid references events(id) on delete cascade, + recipient_id uuid not null, + kind text not null, + subject_id uuid not null, + dedupe_key text not null unique, + status text not null default 'pending' check (status in ('pending', 'running', 'sent', 'failed')), + attempts integer not null default 0, + available_at timestamptz not null default now(), + lease_until timestamptz, + last_error text, + created_at timestamptz not null default now(), + sent_at timestamptz +); +create index if not exists idx_notification_outbox_due on notification_outbox (available_at) where status in ('pending', 'running'); + +create table if not exists location_requests ( + id uuid primary key default gen_random_uuid(), + event_id uuid not null references events(id) on delete cascade, + intro_id uuid not null references intro_requests(id) on delete cascade, + requester_id uuid not null, + recipient_id uuid not null, + status text not null default 'pending' check (status in ('pending', 'answered', 'declined')), + zone text, + created_at timestamptz not null default now(), + expires_at timestamptz not null, + answered_at timestamptz, + zone_expires_at timestamptz, + check (requester_id <> recipient_id) +); +-- One open request per direction of a connection. +create unique index if not exists idx_location_requests_one_pending + on location_requests (intro_id, requester_id) where status = 'pending'; +create index if not exists idx_location_requests_people on location_requests (event_id, recipient_id, created_at desc); diff --git a/packages/db/src/index.ts b/packages/db/src/index.ts index 94bc070..a13636c 100644 --- a/packages/db/src/index.ts +++ b/packages/db/src/index.ts @@ -14,3 +14,4 @@ export * as matchingJobs from "./repositories/matching-jobs"; export * as housekeeping from "./repositories/housekeeping"; export * as audit from "./repositories/audit"; export * as modelUsage from "./repositories/model-usage"; +export * as outbox from "./repositories/outbox"; diff --git a/packages/db/src/repositories/events.ts b/packages/db/src/repositories/events.ts index 979dc01..f848286 100644 --- a/packages/db/src/repositories/events.ts +++ b/packages/db/src/repositories/events.ts @@ -126,6 +126,12 @@ export async function update(input: { return findBySlug(old.organization_slug, old.slug); } +/** Name and public slug, for notification text and links. */ +export async function basics(eventId: string): Promise<{ name: string; slug: string } | null> { + const { rows } = await query<{ name: string; slug: string }>(`select name, slug from events where id = $1`, [eventId]); + return rows[0] ?? null; +} + /** 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]); diff --git a/packages/db/src/repositories/housekeeping.ts b/packages/db/src/repositories/housekeeping.ts index c6798bb..f918561 100644 --- a/packages/db/src/repositories/housekeeping.ts +++ b/packages/db/src/repositories/housekeeping.ts @@ -2,6 +2,7 @@ import { query } from "../client"; import { deleteExpired as deleteExpiredChallenges } from "./login-challenges"; import { AUDIT_RETENTION_DAYS } from "./audit"; import { USAGE_RETENTION_DAYS } from "./model-usage"; +import { SENT_RETENTION_DAYS } from "./outbox"; /** How long a dead row is kept before the sweep removes it. */ export const RETENTION = { @@ -30,6 +31,9 @@ export async function sweepExpired(): Promise { const explanations = await query(`delete from pair_explanations where expires_at < now()`); await query(`delete from cache_locks where expires_at < now()`); await query(`delete from model_usage where created_at < now() - make_interval(days => $1)`, [USAGE_RETENTION_DAYS]); + await query(`delete from notification_outbox where status = 'sent' and sent_at < now() - make_interval(days => $1)`, [SENT_RETENTION_DAYS]); + // Venue locations are only meaningful during the event day. + await query(`delete from location_requests where created_at < now() - interval '1 day'`); const audits = await query(`delete from audit_events where created_at < now() - make_interval(days => $1)`, [AUDIT_RETENTION_DAYS]); return { loginChallenges, rateLimitBuckets: buckets.rowCount ?? 0, retrievalCache: cache.rowCount ?? 0, diff --git a/packages/db/src/repositories/outbox.ts b/packages/db/src/repositories/outbox.ts new file mode 100644 index 0000000..ec6fa35 --- /dev/null +++ b/packages/db/src/repositories/outbox.ts @@ -0,0 +1,76 @@ +import { query, transaction } from "../client"; + +export type NotificationKind = "intro.requested" | "intro.accepted" | "location.requested" | "location.answered"; + +export interface OutboxItem { + id: number; + event_id: string | null; + recipient_id: string; + kind: NotificationKind; + subject_id: string; + attempts: number; +} + +export const MAX_ATTEMPTS = 5; +const LEASE_SECONDS = 120; +/** Sent notifications are kept this long, then swept. */ +export const SENT_RETENTION_DAYS = 30; + +/** + * Queues a notification. Pass the transaction's client so it commits or + * rolls back with the interaction it announces. A repeated dedupe key is + * ignored, so the same notification is never queued twice. + */ +export async function enqueue( + item: { eventId: string; recipientId: string; kind: NotificationKind; subjectId: string; dedupeKey: string }, + client: { query: typeof query } = { query } +): Promise { + await client.query( + `insert into notification_outbox (event_id, recipient_id, kind, subject_id, dedupe_key) + values ($1, $2, $3, $4, $5) on conflict (dedupe_key) do nothing`, + [item.eventId, item.recipientId, item.kind, item.subjectId, item.dedupeKey] + ); +} + +/** Claims the oldest due notification (or one whose sender crashed) for delivery. */ +export async function claim(onlyEventId: string | null = null): Promise { + return transaction(async (client) => { + await client.query( + `update notification_outbox set status = 'failed', last_error = coalesce(last_error, 'sender stopped responding') + where status = 'running' and lease_until < now() and attempts >= $1`, [MAX_ATTEMPTS]); + const { rows } = await client.query( + `with next_item as ( + select id from notification_outbox + where attempts < $1 and ($3::uuid is null or event_id = $3) + and ((status = 'pending' and available_at <= now()) or (status = 'running' and lease_until < now())) + order by available_at, id for update skip locked limit 1 + ) + update notification_outbox o set status = 'running', attempts = attempts + 1, lease_until = now() + make_interval(secs => $2) + from next_item where o.id = next_item.id + returning o.id::int as id, o.event_id, o.recipient_id, o.kind, o.subject_id, o.attempts`, + [MAX_ATTEMPTS, LEASE_SECONDS, onlyEventId] + ); + return rows[0] ?? null; + }); +} + +export async function markSent(id: number): Promise { + await query(`update notification_outbox set status = 'sent', sent_at = now(), lease_until = null where id = $1`, [id]); +} + +/** Retries after 30s, 60s, 120s... (capped at 15 minutes); fails for good after the last attempt. */ +export async function fail(id: number, error: string): Promise { + await query( + `update notification_outbox + set status = case when attempts >= $3 then 'failed' else 'pending' end, + available_at = now() + make_interval(secs => least(30 * power(2, greatest(attempts - 1, 0)), 900)), + lease_until = null, last_error = left($2, 1000) + where id = $1`, + [id, error, MAX_ATTEMPTS] + ); +} + +/** Nothing left to send (e.g. the interaction was deleted): close it without delivery. */ +export async function skip(id: number, reason: string): Promise { + await query(`update notification_outbox set status = 'sent', sent_at = now(), lease_until = null, last_error = $2 where id = $1`, [id, reason]); +} diff --git a/packages/db/workers/notification.worker.ts b/packages/db/workers/notification.worker.ts new file mode 100644 index 0000000..061844b --- /dev/null +++ b/packages/db/workers/notification.worker.ts @@ -0,0 +1,55 @@ +import { events, outbox, query } from "../src/index"; +import { getContainer } from "../../../apps/web/src/composition/container"; + +/** + * Delivers one queued notification. Details are read at send time, so the + * message reflects the current state; an interaction that no longer exists + * is closed without sending. Failures retry with backoff (see outbox.fail). + */ +export async function processNotification(onlyEventId: string | null = null): Promise { + const item = await outbox.claim(onlyEventId); + if (!item) return false; + try { + const delivered = await deliver(item); + if (delivered) await outbox.markSent(item.id); + else await outbox.skip(item.id, "nothing to send any more"); + } catch (error) { + console.error(`[worker:notify] ${item.kind} #${item.id} failed`, error); + await outbox.fail(item.id, error instanceof Error ? error.message : String(error)); + } + return true; +} + +async function deliver(item: outbox.OutboxItem): Promise { + if (!item.event_id) return false; + const { participants, notifications } = getContainer(); + const event = await events.basics(item.event_id); + const recipient = await participants.findProfile(item.event_id, item.recipient_id); + if (!event || !recipient?.email) return false; + + const base = (process.env.APP_BASE_URL || "").replace(/\/$/, ""); + if (item.kind === "intro.requested" || item.kind === "intro.accepted") { + const { rows: [intro] } = await query<{ requester_id: string; recipient_id: string; status: string }>( + `select requester_id, recipient_id, status from intro_requests where id = $1`, [item.subject_id]); + if (!intro || (item.kind === "intro.accepted" && intro.status !== "accepted")) return false; + const otherId = intro.requester_id === item.recipient_id ? intro.recipient_id : intro.requester_id; + const other = await participants.findProfile(item.event_id, otherId); + const target = { recipientEmail: recipient.email, recipientName: recipient.name, otherName: other?.name ?? "A participant", eventName: event.name, link: `${base}/e/${event.slug}/connections#intro-${item.subject_id}` }; + await (item.kind === "intro.requested" ? notifications.introRequested(target) : notifications.introAccepted(target)); + return true; + } + + const { rows: [request] } = await query<{ intro_id: string; requester_id: string; recipient_id: string; status: string; zone: string | null }>( + `select intro_id, requester_id, recipient_id, status, zone from location_requests where id = $1`, [item.subject_id]); + if (!request) return false; + const otherId = request.requester_id === item.recipient_id ? request.recipient_id : request.requester_id; + const other = await participants.findProfile(item.event_id, otherId); + const target = { recipientEmail: recipient.email, recipientName: recipient.name, otherName: other?.name ?? "A participant", eventName: event.name, link: `${base}/e/${event.slug}/connections#intro-${request.intro_id}` }; + if (item.kind === "location.requested") { + if (request.status !== "pending") return false; + await notifications.locationRequested(target); + } else { + await notifications.locationAnswered({ ...target, zone: request.status === "answered" ? request.zone : null }); + } + return true; +} diff --git a/packages/db/workers/worker.ts b/packages/db/workers/worker.ts index 5650e2d..80af71c 100644 --- a/packages/db/workers/worker.ts +++ b/packages/db/workers/worker.ts @@ -4,6 +4,7 @@ import { closePool } from "../src/client"; import { processEmbedJob } from "./embed.worker"; import { processMatchJob } from "./match.worker"; import { sweepIfDue } from "./housekeeping.worker"; +import { processNotification } from "./notification.worker"; let stopping = false; process.on("SIGINT", () => { stopping = true; }); @@ -16,7 +17,8 @@ async function main() { await sweepIfDue(); const embedded = await processEmbedJob(); const matched = await processMatchJob(); - if (!embedded && !matched) await new Promise((resolve) => setTimeout(resolve, 1200)); + const notified = await processNotification(); + if (!embedded && !matched && !notified) await new Promise((resolve) => setTimeout(resolve, 1200)); } await closePool(); console.info("[worker] stopped"); diff --git a/tests/integration/notification-outbox.test.ts b/tests/integration/notification-outbox.test.ts new file mode 100644 index 0000000..d917c70 --- /dev/null +++ b/tests/integration/notification-outbox.test.ts @@ -0,0 +1,74 @@ +/** + * Notifications go through an outbox written with the interaction, and are + * delivered with retries. Real Postgres; delivery uses the e-mail dev + * fallback. Claims are scoped to this test's event. Skipped without DATABASE_URL. + */ +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { attendees, closePool, events, outbox, query } from "@match-maker/db"; +import { migrate } from "../../packages/db/src/migrate"; +import { PostgresIntroRepository } from "../../apps/web/src/infrastructure/postgres/intro.repo"; +import { processNotification } from "../../packages/db/workers/notification.worker"; +import { getContainer } from "../../apps/web/src/composition/container"; + +const describeDb = process.env.DATABASE_URL ? describe : describe.skip; +const RUN = Date.now().toString(36); +const ORG = `outbox-${RUN}`; +const email = (key: string) => `outbox-${key}-${RUN}@example.com`; + +describeDb("notification outbox", () => { + const intros = new PostgresIntroRepository(); + const ids: Record = {}; + let eventId: string; + let introId: string; + const queued = async () => (await query<{ kind: string; recipient_id: string; status: string; attempts: number; last_error: string | null }>( + `select kind, recipient_id, status, attempts, last_error from notification_outbox where event_id = $1 order by id`, [eventId])).rows; + + beforeAll(async () => { + process.env.EMAIL_DEV_FALLBACK = "true"; + await migrate(); + await attendees.upsertMany(["amy", "ben"].map((key) => ({ name: `Outbox ${key}`, email: email(key) }))); + for (const key of ["amy", "ben"]) ids[key] = (await attendees.findByEmail(email(key)))!.id; + const { rows: [org] } = await query<{ id: string }>(`insert into organizations (name, slug) values ($1, $1) returning id`, [ORG]); + eventId = (await query<{ id: string }>(`insert into events (organization_id, name, slug, status) values ($1, $2, $2, 'open') returning id`, [org.id, ORG])).rows[0].id; + await events.attachRoster(eventId, Object.values(ids)); + }); + + afterAll(async () => { + await query(`delete from organizations where slug = $1`, [ORG]); + await query(`delete from registered_attendees where email like $1`, [`outbox-%-${RUN}@example.com`]); + await closePool(); + }); + + it("queues the notification with the request, once", async () => { + introId = (await intros.create({ eventId, requesterId: ids.amy, recipientId: ids.ben })).id; + await outbox.enqueue({ eventId, recipientId: ids.ben, kind: "intro.requested", subjectId: introId, dedupeKey: `intro.requested:${introId}` }); + expect(await queued()).toEqual([expect.objectContaining({ kind: "intro.requested", recipient_id: ids.ben, status: "pending" })]); + }); + + it("delivers it with a link to the connection", async () => { + const info = vi.spyOn(console, "info").mockImplementation(() => {}); + expect(await processNotification(eventId)).toBe(true); + expect((await queued())[0].status).toBe("sent"); + const message = info.mock.calls.map((call) => String(call[0])).find((line) => line.includes(email("ben"))); + expect(message).toContain(`/e/${ORG}/connections#intro-${introId}`); + info.mockRestore(); + }); + + it("queues an acceptance notice for the requester", async () => { + await intros.respond(eventId, introId, ids.ben, "accepted"); + expect((await queued()).at(-1)).toMatchObject({ kind: "intro.accepted", recipient_id: ids.amy, status: "pending" }); + }); + + it("keeps a failed delivery for retry instead of losing it", async () => { + const container = getContainer(); + const failing = vi.spyOn(container.notifications, "introAccepted").mockRejectedValueOnce(new Error("Resend failed (503)")); + vi.spyOn(console, "error").mockImplementation(() => {}); + await processNotification(eventId); + expect((await queued()).at(-1)).toMatchObject({ status: "pending", attempts: 1, last_error: "Resend failed (503)" }); + failing.mockRestore(); + await query(`update notification_outbox set available_at = now() where event_id = $1 and status = 'pending'`, [eventId]); + vi.spyOn(console, "info").mockImplementation(() => {}); + await processNotification(eventId); + expect((await queued()).at(-1)).toMatchObject({ status: "sent", attempts: 2 }); + }); +}); From 0a9deda89b0ecb801b8e5befdc93a6e66c34c641 Mon Sep 17 00:00:00 2001 From: SURYANSH-RAI Date: Mon, 19 Oct 2026 09:25:44 +0530 Subject: [PATCH 02/20] Add "where are you?" location requests with voluntary replies (R23 part 2) "Ping zone" only overwrote the sender's own zone for every connection; there was no way to ask a connection where they are, and no reply. - domain/connection/location.rules.ts: a request is a question, not tracking. One open request per direction of an accepted connection; unanswered requests expire after 30 minutes; a shared zone is visible only to the person who asked, for 15 minutes; 10 requests per person and hour - LocationRepository (Postgres): creating a request and answering it (a configured zone, or "not now") each queue their notification in the same transaction, so the interaction is never lost - Connections page: "Ask where they are", an incoming request with "Share with " / "Not now", the reply or decline for the asker, and the existing broadcast labelled "Share with all my connections"; each connection has an anchor for e-mail deep links - Tests: state and rules, the use cases, real-Postgres visibility, expiry and replacement, and a browser run where the worker e-mails the request, acceptance, location request and reply --- .../e/[eventSlug]/connections/page.tsx | 32 ++++++-- apps/web/app/actions/intro.actions.ts | 37 ++++++++- .../application/ports/location-repository.ts | 14 ++++ .../use-cases/location-requests.ts | 34 ++++++++ apps/web/src/composition/container.ts | 2 + .../src/domain/connection/location.rules.ts | 33 ++++++++ .../infrastructure/postgres/location.repo.ts | 77 +++++++++++++++++++ tests/integration/location-requests.test.ts | 74 ++++++++++++++++++ tests/unit/location-requests.test.ts | 57 ++++++++++++++ 9 files changed, 353 insertions(+), 7 deletions(-) create mode 100644 apps/web/src/application/ports/location-repository.ts create mode 100644 apps/web/src/application/use-cases/location-requests.ts create mode 100644 apps/web/src/domain/connection/location.rules.ts create mode 100644 apps/web/src/infrastructure/postgres/location.repo.ts create mode 100644 tests/integration/location-requests.test.ts create mode 100644 tests/unit/location-requests.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 f95bc06..e961833 100644 --- a/apps/web/app/(participant)/e/[eventSlug]/connections/page.tsx +++ b/apps/web/app/(participant)/e/[eventSlug]/connections/page.tsx @@ -1,13 +1,13 @@ import Link from "next/link"; import SignOutButton from "@/components/ui/SignOutButton"; -import { getParticipantConnections, respondToParticipantIntro, shareVenueZoneAction } from "../../../../actions/intro.actions"; +import { answerLocationAction, getParticipantConnections, requestLocationAction, 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 }>; - searchParams: Promise<{ requested?: string; location?: string }>; + searchParams: Promise<{ requested?: string; location?: string; asked?: string; replied?: string; declined?: string }>; }) { const { eventSlug } = await params; const notice = await searchParams; @@ -18,9 +18,12 @@ export default async function ConnectionsPage({ params, searchParams }: { INTRODUCTIONS · {event.name}

Connections

{notice.requested &&

Intro request sent. You will see their contact details once they accept.

} - {notice.location &&

Your venue zone is shared with your accepted connections.

} + {notice.location &&

Your venue zone is shared with all your accepted connections for 15 minutes.

} + {notice.asked &&

Request sent. They decide whether to share where they are.

} + {notice.replied &&

Your zone is shared with them for 15 minutes.

} + {notice.declined &&

Request declined. They have been told you would rather not share right now.

} {!connections.length ?

Your intro requests will show up here. Find someone you would like to meet from your matches or search.

:
- {connections.map((connection) =>
+ {connections.map((connection) =>

{connection.participant.name}

{[connection.participant.designation, connection.participant.domain].filter(Boolean).join(" · ")}

@@ -31,7 +34,25 @@ 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 && eventAllows(event.status, "shareZone") && + {connection.locationAsked?.status === "answered" &&
Replied: at {connection.locationAsked.zone}
} + {connection.locationAsked?.status === "pending" &&
Asked where they are. Waiting for a reply.
} + {connection.locationAsked?.status === "declined" &&
They would rather not share where they are right now.
} + {event.zones.length > 0 && eventAllows(event.status, "shareZone") && <> + {connection.locationIncoming &&
+ {connection.participant.name} is asking where you are. Sharing is up to you; only they will see it, for 15 minutes. +
+ + + + + +
+
} + {connection.locationAsked?.status !== "pending" && } + } + {event.zones.length > 0 && eventAllows(event.status, "shareZone") &&