diff --git a/server/src/nest/notifications/channel-gate.ts b/server/src/nest/notifications/channel-gate.ts new file mode 100644 index 000000000..0ff2ba9f5 --- /dev/null +++ b/server/src/nest/notifications/channel-gate.ts @@ -0,0 +1,44 @@ +import { + ADMIN_SCOPED_EVENTS, + isAdminGlobalChannel, + type ExternalChannel, + type NotifEventType, +} from './notification-events'; +import type { NotificationPreferencesService } from './notification-preferences.service'; + +/** + * Should this channel deliver this event to this recipient? + * + * Encodes, unchanged, the gating the four hand-written dispatch blocks used to do: + * - admin-scoped events (version_available) reach recipients only over a channel + * that bypasses the `notification_channels` toggle (email), gated by the admin + * global pref rather than the per-user opt-out. Their webhook/ntfy copies go out + * once, globally, via sendGlobal() in NotificationsService, not per recipient. + * - everything else: the admin enabled the channel, the user didn't opt out of this + * event on it, and the user has credentials for it. + */ +export async function shouldSendToUser( + channel: ExternalChannel, + event: NotifEventType, + recipientId: number, + activeChannels: string[], + prefs: NotificationPreferencesService, +): Promise { + if (!channel.supportsEvent(event)) return false; + + if (ADMIN_SCOPED_EVENTS.has(event)) { + if (!channel.bypassesActiveToggleForAdminEvents) return false; + if (!isAdminGlobalChannel(channel.id)) return false; + if (!(await prefs.getAdminGlobalPref(event, channel.id))) return false; + } else { + // A built-in needs the admin's explicit switch; a plugin channel is on because the + // admin enabled the plugin; that IS the opt-in (see getActiveChannels). + if (channel.source === 'builtin' && !activeChannels.includes(channel.id)) return false; + if (!(await prefs.isEnabledForEvent(recipientId, event, channel.id))) return false; + } + + if (!(await channel.isConfiguredFor(recipientId))) return false; + // Last, since it is the costly check: Web Push reads and verifies the server's + // key pair. Every check here is a plain AND, so the order changes no answer. + return !channel.isInstanceConfigured || (await channel.isInstanceConfigured()); +} diff --git a/server/src/nest/notifications/in-flight-sends.ts b/server/src/nest/notifications/in-flight-sends.ts new file mode 100644 index 000000000..67a6d22b6 --- /dev/null +++ b/server/src/nest/notifications/in-flight-sends.ts @@ -0,0 +1,26 @@ +/** + * The notification sends still running. Most callers start a send without + * waiting for it (the change it reports is already committed, and email or a + * webhook should not hold the response), so nothing else knows when one ends. + * This set does: `settled()` resolves once every send started before the call + * has finished, whether it delivered or failed. + */ +export class InFlightSends { + private readonly running = new Set>(); + + /** Tracks `send` until it settles and hands it back unchanged. */ + track(send: Promise): Promise { + const settled = send.then( + () => undefined, + () => undefined, + ); + this.running.add(settled); + void settled.then(() => this.running.delete(settled)); + return send; + } + + /** Resolves once every send tracked so far has settled; never rejects. */ + async settled(): Promise { + await Promise.all([...this.running]); + } +} diff --git a/server/src/nest/notifications/notifications.service.ts b/server/src/nest/notifications/notifications.service.ts index cfd9ea16f..04b067285 100644 --- a/server/src/nest/notifications/notifications.service.ts +++ b/server/src/nest/notifications/notifications.service.ts @@ -5,13 +5,14 @@ import { logDebug, logError } from '../audit/audit-log.logger'; import { avatarUrl } from '../common/avatarUrl'; import { UnitOfWork } from '../database/unit-of-work'; import { RealtimeService } from '../realtime/realtime.service'; +import { shouldSendToUser } from './channel-gate'; import { getChannel, listChannels } from './channel-registry'; import { registerBuiltinChannels } from './channels/builtins'; import { getAction, registerAction } from './in-app-actions'; +import { InFlightSends } from './in-flight-sends'; import { getEventText } from './mailer/email-html'; import { MailerService } from './mailer/mailer.service'; import { - ADMIN_SCOPED_EVENTS, isAdminGlobalChannel, type ChannelMessage, type ExternalChannel, @@ -361,43 +362,6 @@ export interface NotificationDelivery { delivered: number; } -/** - * Should this channel deliver this event to this recipient? - * - * Encodes, unchanged, the gating the four hand-written dispatch blocks used to do: - * - admin-scoped events (version_available) reach recipients only over a channel - * that bypasses the `notification_channels` toggle (email), gated by the admin - * global pref rather than the per-user opt-out. Their webhook/ntfy copies go out - * once, globally, via sendGlobal() below — not per recipient. - * - everything else: the admin enabled the channel, the user didn't opt out of this - * event on it, and the user has credentials for it. - */ -async function shouldSendToUser( - channel: ExternalChannel, - event: NotifEventType, - recipientId: number, - activeChannels: string[], - prefs: NotificationPreferencesService, -): Promise { - if (!channel.supportsEvent(event)) return false; - - if (ADMIN_SCOPED_EVENTS.has(event)) { - if (!channel.bypassesActiveToggleForAdminEvents) return false; - if (!isAdminGlobalChannel(channel.id)) return false; - if (!(await prefs.getAdminGlobalPref(event, channel.id))) return false; - } else { - // A built-in needs the admin's explicit switch; a plugin channel is on because the - // admin enabled the plugin — that IS the opt-in (see getActiveChannels). - if (channel.source === 'builtin' && !activeChannels.includes(channel.id)) return false; - if (!(await prefs.isEnabledForEvent(recipientId, event, channel.id))) return false; - } - - if (!(await channel.isConfiguredFor(recipientId))) return false; - // Last, since it is the costly check: Web Push reads and verifies the server's - // key pair. Every check here is a plain AND, so the order changes no answer. - return !channel.isInstanceConfigured || (await channel.isInstanceConfigured()); -} - /** * DI-native notifications domain service. The in-app notification SQL moved * 1:1 from the legacy `services/inAppNotifications.ts` (identical statements, @@ -419,6 +383,8 @@ async function shouldSendToUser( */ @Injectable() export class NotificationsService { + private readonly inFlight = new InFlightSends(); + constructor( private readonly realtime: RealtimeService, private readonly mailer: MailerService, @@ -794,13 +760,23 @@ export class NotificationsService { // ── Unified dispatcher (from services/notificationService.ts) ───────────── /** - * Resolves the recipients of one event and delivers it on every active channel. + * Resolves the recipients of one event and delivers it on every active + * channel. A caller may leave the send running; `settled()` waits for it. * * @txStandalone a notification reports a change after it is written; email * and webhook delivery are network I/O, which never runs inside a transaction. - * @txIndependent each recipient's row is written on its own, between deliveries. */ - async send(payload: NotificationPayload): Promise { + send(payload: NotificationPayload): Promise { + return this.inFlight.track(this.deliver(payload)); + } + + /** Resolves once every send started before the call has finished, delivered or not. */ + settled(): Promise { + return this.inFlight.settled(); + } + + /** @txIndependent each recipient's row is written on its own, between deliveries. */ + private async deliver(payload: NotificationPayload): Promise { const { event, actorId, params, scope, targetId, inApp } = payload; const delivery: NotificationDelivery = { attempted: 0, delivered: 0 }; diff --git a/server/tests/unit/nest/notifications.service.test.ts b/server/tests/unit/nest/notifications.service.test.ts index bd1f2a3b7..968e743ec 100644 --- a/server/tests/unit/nest/notifications.service.test.ts +++ b/server/tests/unit/nest/notifications.service.test.ts @@ -896,6 +896,41 @@ describe('send() reports what it delivered', () => { }), ).resolves.toEqual({ attempted: 0, delivered: 0 }); }); + + it('NSVC-025: settled() waits for a send its caller left running', async () => { + const { user } = createUser(testDb); + setSmtp(); + setNotificationChannels(testDb, 'email'); + await setRecipientEmail(user.id); + const tripId = await newTrip('Trip', user.id); + let release = () => {}; + sendMailMock.mockImplementationOnce( + () => + new Promise((resolve) => { + release = () => resolve({ accepted: ['test@test.com'] }); + }), + ); + + const running = send({ + event: 'trip_reminder', + actorId: null, + scope: 'user', + targetId: user.id, + params: { trip: 'Trip', tripId: String(tripId) }, + }); + let settled = false; + const waiting = notifications.settled().then(() => { + settled = true; + }); + await vi.waitFor(() => expect(sendMailMock).toHaveBeenCalledTimes(1)); + expect(settled).toBe(false); + + release(); + await waiting; + await expect(running).resolves.toEqual({ attempted: 2, delivered: 2 }); + // Nothing left running: it resolves at once. + await expect(notifications.settled()).resolves.toBeUndefined(); + }); }); // ── Ntfy dispatch ───────────────────────────────────────────────────────────── diff --git a/server/tests/unit/nest/notifications/in-flight-sends.test.ts b/server/tests/unit/nest/notifications/in-flight-sends.test.ts new file mode 100644 index 000000000..2e3d555ff --- /dev/null +++ b/server/tests/unit/nest/notifications/in-flight-sends.test.ts @@ -0,0 +1,51 @@ +import { InFlightSends } from '../../../../src/nest/notifications/in-flight-sends'; + +import { describe, expect, it } from 'vitest'; + +/** A promise the test settles by hand. */ +function deferred() { + let resolve: (value: T) => void = () => undefined; + let reject: (reason: unknown) => void = () => undefined; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { promise, resolve, reject }; +} + +describe('InFlightSends', () => { + it('INFLIGHT-001: hands each send back unchanged, its value and its failure', async () => { + const sends = new InFlightSends(); + await expect(sends.track(Promise.resolve(7))).resolves.toBe(7); + const failure = new Error('smtp down'); + await expect(sends.track(Promise.reject(failure))).rejects.toBe(failure); + }); + + it('INFLIGHT-002: settled() waits for every send tracked so far, failed ones included, and never rejects', async () => { + const sends = new InFlightSends(); + const ok = deferred(); + const failing = deferred(); + sends.track(ok.promise).catch(() => undefined); + sends.track(failing.promise).catch(() => undefined); + let settled = false; + const waiting = sends.settled().then(() => { + settled = true; + }); + + ok.resolve(1); + await ok.promise; + await Promise.resolve(); + expect(settled).toBe(false); + + failing.reject(new Error('webhook timed out')); + await waiting; + expect(settled).toBe(true); + }); + + it('INFLIGHT-003: with nothing running, or once everything ended, settled() resolves at once', async () => { + const sends = new InFlightSends(); + await expect(sends.settled()).resolves.toBeUndefined(); + await sends.track(Promise.resolve('done')); + await expect(sends.settled()).resolves.toBeUndefined(); + }); +});