Fase 1a: microservicio tcef-notifications (workers FCM v1 + email)

Sustituye el envío de push por la API legacy de GCM (muerta desde jun-2024) y
saca el envío del observer de Meteor a una cola BullMQ controlada.

- poller: consume 'notifications' pendientes (campos correctos; el cron viejo
  tenía un typo nofitied/emailNofitied que nunca casaba)
- fcm-worker: firebase-admin (FCM HTTP v1), payload compatible con la app
  Flutter (FLUTTER_NOTIFICATION_CLICK, collapseKey=_id, data); purga tokens
  muertos sin reintentar
- email-worker: nodemailer + plantillas new-fire portadas verbatim
- idempotencia persistente: notification_sends, indice unico (notificationId,
  channel) -> sobrevive reinicios y replays
- salvaguardas anti-spam: modos dry-run/shadow/canary/full, exclusion mutua por
  canal (OWNED_CHANNELS + notifDisabledChannels en Meteor), kill switch,
  limites por usuario/dia y circuit breaker por batch
- docs/legacy-behavior.md (caracterizacion) + docs/rollout.md
- 47 tests (vitest + mongodb-memory-server), typecheck y build OK
- deploy: systemd + pm2 (Node 22 standalone)

Falta el service account de Firebase para envio real de push (pedir al usuario).
This commit is contained in:
vjrj 2026-07-13 00:10:29 +02:00
commit d20e168c90
39 changed files with 8378 additions and 0 deletions

32
test/config.test.ts Normal file
View file

@ -0,0 +1,32 @@
import { describe, expect, it } from 'vitest';
import { loadConfig } from '../src/config.js';
const base = { MONGO_URL: 'mongodb://localhost/fuegos', CONFIG_FILE: '/nonexistent.json' };
describe('loadConfig', () => {
it('defaults to the safest mode (dry-run) with no channels owned', () => {
const cfg = loadConfig({ ...base } as NodeJS.ProcessEnv);
expect(cfg.mode).toBe('dry-run');
expect(cfg.ownedChannels).toEqual([]);
expect(cfg.killSwitch).toBe(false);
});
it('requires MONGO_URL', () => {
expect(() => loadConfig({ CONFIG_FILE: '/nonexistent.json' } as NodeJS.ProcessEnv)).toThrow(/MONGO_URL/);
});
it('rejects an invalid mode', () => {
expect(() => loadConfig({ ...base, MODE: 'nuke' } as NodeJS.ProcessEnv)).toThrow(/Invalid MODE/);
});
it('parses OWNED_CHANNELS and rejects unknown channels', () => {
expect(loadConfig({ ...base, OWNED_CHANNELS: 'fcm,email' } as NodeJS.ProcessEnv).ownedChannels).toEqual(['fcm', 'email']);
expect(() => loadConfig({ ...base, OWNED_CHANNELS: 'fcm,telegram' } as NodeJS.ProcessEnv)).toThrow(/Invalid channel/);
});
it('parses KILL_SWITCH and canary lists', () => {
const cfg = loadConfig({ ...base, KILL_SWITCH: '1', CANARY_USER_IDS: 'a, b ,c', MODE: 'canary' } as NodeJS.ProcessEnv);
expect(cfg.killSwitch).toBe(true);
expect(cfg.canary.userIds).toEqual(['a', 'b', 'c']);
});
});

218
test/handlers.test.ts Normal file
View file

@ -0,0 +1,218 @@
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
import type { MongoMemoryServer } from 'mongodb-memory-server';
import type { Repos } from '../src/db.js';
import type { Config } from '../src/config.js';
import { processEmailJob, processFcmJob, type Deps } from '../src/handlers.js';
import { aNotif, aUser, fakeFcm, fakeMailer, silentLog, startMongo } from './helpers.js';
let server: MongoMemoryServer;
let repos: Repos;
let baseCfg: Config;
beforeAll(async () => {
const s = await startMongo();
server = s.server;
repos = s.repos;
baseCfg = s.cfg;
});
afterAll(async () => {
await repos.close();
await server.stop();
});
beforeEach(async () => {
await repos.notifications.deleteMany({});
await repos.users.deleteMany({});
await repos.sends.deleteMany({});
});
function deps(over: Partial<Deps> = {}): Deps {
return { cfg: baseCfg, repos, log: silentLog, ...over };
}
describe('FCM handler', () => {
it('sends push and marks the doc notified (full mode)', async () => {
const notif = aNotif();
await repos.notifications.insertOne(notif);
await repos.users.insertOne(aUser());
const fcm = fakeFcm({ ok: true, messageId: 'mid-1' });
await processFcmJob(deps({ fcm }), notif._id.toHexString());
expect(fcm.calls).toHaveLength(1);
expect(fcm.calls[0]!.token).toBe('tok-abc');
const after = await repos.notifications.findOne({ _id: notif._id });
expect(after?.notified).toBe(true);
expect(after?.notifiedAt).toBeInstanceOf(Date);
const send = await repos.sends.findOne({ notificationId: notif._id, channel: 'fcm' });
expect(send?.status).toBe('sent');
});
it('idempotent across a simulated restart: never double-sends', async () => {
const notif = aNotif();
await repos.notifications.insertOne(notif);
await repos.users.insertOne(aUser());
const fcm = fakeFcm({ ok: true, messageId: 'mid-1' });
// First run sends and marks notified.
await processFcmJob(deps({ fcm }), notif._id.toHexString());
// Simulate a replay/restart: the doc is already notified -> guard skips.
await processFcmJob(deps({ fcm }), notif._id.toHexString());
// Even if the notified flag were somehow cleared, the send record blocks it.
await repos.notifications.updateOne({ _id: notif._id }, { $unset: { notified: '' } });
await processFcmJob(deps({ fcm }), notif._id.toHexString());
expect(fcm.calls).toHaveLength(1); // only ONE real send, ever
});
it('dry-run does not send and does not mark the doc', async () => {
const notif = aNotif();
await repos.notifications.insertOne(notif);
await repos.users.insertOne(aUser());
const fcm = fakeFcm({ ok: true, messageId: 'x' });
await processFcmJob(deps({ cfg: { ...baseCfg, mode: 'dry-run' }, fcm }), notif._id.toHexString());
expect(fcm.calls).toHaveLength(0);
const after = await repos.notifications.findOne({ _id: notif._id });
expect(after?.notified).toBeUndefined();
expect(await repos.sends.countDocuments({})).toBe(0); // no reservation in dry-run
});
it('kill switch stops sending', async () => {
const notif = aNotif();
await repos.notifications.insertOne(notif);
await repos.users.insertOne(aUser());
const fcm = fakeFcm({ ok: true, messageId: 'x' });
await processFcmJob(deps({ cfg: { ...baseCfg, killSwitch: true }, fcm }), notif._id.toHexString());
expect(fcm.calls).toHaveLength(0);
});
it('canary sends only to the cohort', async () => {
const inCohort = aNotif({ userId: 'u1' });
const outCohort = aNotif({ userId: 'u2', subsId: undefined });
await repos.notifications.insertMany([inCohort, outCohort]);
await repos.users.insertMany([aUser({ _id: 'u1' }), aUser({ _id: 'u2' })]);
const fcm = fakeFcm({ ok: true, messageId: 'x' });
const cfg = { ...baseCfg, mode: 'canary' as const, canary: { userIds: ['u1'], subsIds: [] } };
await processFcmJob(deps({ cfg, fcm }), inCohort._id.toHexString());
await processFcmJob(deps({ cfg, fcm }), outCohort._id.toHexString());
expect(fcm.calls).toHaveLength(1);
expect(fcm.calls[0]!.token).toBe('tok-abc');
});
it('purges dead FCM tokens and does not retry', async () => {
const notif = aNotif();
await repos.notifications.insertOne(notif);
await repos.users.insertOne(aUser());
const fcm = fakeFcm({ ok: false, deadToken: true, error: 'messaging/registration-token-not-registered' });
await processFcmJob(deps({ fcm }), notif._id.toHexString());
const user = await repos.users.findOne({ _id: 'u1' });
expect(user?.fireBaseToken).toBeNull();
expect(user?.fireBaseTokenDeadAt).toBeInstanceOf(Date);
const send = await repos.sends.findOne({ notificationId: notif._id, channel: 'fcm' });
expect(send?.status).toBe('dead-token'); // recorded -> won't retry
const after = await repos.notifications.findOne({ _id: notif._id });
expect(after?.notified).toBeUndefined(); // not marked as notified
});
it('transient error releases the reservation so it can retry', async () => {
const notif = aNotif();
await repos.notifications.insertOne(notif);
await repos.users.insertOne(aUser());
const fcm = fakeFcm({ ok: false, deadToken: false, error: 'UNAVAILABLE' });
await expect(processFcmJob(deps({ fcm }), notif._id.toHexString())).rejects.toThrow();
// reservation released -> a later retry can proceed
expect(await repos.sends.countDocuments({ notificationId: notif._id })).toBe(0);
const fcm2 = fakeFcm({ ok: true, messageId: 'ok' });
await processFcmJob(deps({ fcm: fcm2 }), notif._id.toHexString());
expect(fcm2.calls).toHaveLength(1);
});
it('skips users without a fireBaseToken', async () => {
const notif = aNotif();
await repos.notifications.insertOne(notif);
await repos.users.insertOne(aUser({ fireBaseToken: null }));
const fcm = fakeFcm({ ok: true, messageId: 'x' });
await processFcmJob(deps({ fcm }), notif._id.toHexString());
expect(fcm.calls).toHaveLength(0);
const after = await repos.notifications.findOne({ _id: notif._id });
expect(after?.notified).toBeUndefined();
});
it('enforces the per-user/day limit', async () => {
await repos.users.insertOne(aUser());
const cfg = { ...baseCfg, limits: { ...baseCfg.limits, perUserPerDay: 2 } };
const fcm = fakeFcm({ ok: true, messageId: 'x' });
// Three pending notifs for the same user.
const notifs = [aNotif(), aNotif(), aNotif()];
await repos.notifications.insertMany(notifs);
for (const n of notifs) {
await processFcmJob(deps({ cfg, fcm }), n._id.toHexString());
}
expect(fcm.calls).toHaveLength(2); // third blocked by limit
});
});
describe('Email handler', () => {
it('sends email and marks emailNotified', async () => {
const notif = aNotif({ type: 'web' });
await repos.notifications.insertOne(notif);
await repos.users.insertOne(aUser());
const mailer = fakeMailer();
await processEmailJob(deps({ mailer }), notif._id.toHexString());
expect(mailer.calls).toHaveLength(1);
expect(mailer.calls[0]!.to).toBe('ana@example.com');
expect(mailer.calls[0]!.content.subject.length).toBeGreaterThan(0);
const after = await repos.notifications.findOne({ _id: notif._id });
expect(after?.emailNotified).toBe(true);
});
it('removes the doc when there is no verified recipient (full mode)', async () => {
const notif = aNotif({ type: 'web' });
await repos.notifications.insertOne(notif);
await repos.users.insertOne(aUser({ emails: [{ address: 'ana@example.com', verified: false }] }));
const mailer = fakeMailer();
await processEmailJob(deps({ mailer }), notif._id.toHexString());
expect(mailer.calls).toHaveLength(0);
expect(await repos.notifications.findOne({ _id: notif._id })).toBeNull(); // removed
});
it('does not remove the doc for missing recipient in shadow mode', async () => {
const notif = aNotif({ type: 'web' });
await repos.notifications.insertOne(notif);
await repos.users.insertOne(aUser({ emails: [{ address: 'x@y', verified: false }] }));
const mailer = fakeMailer();
await processEmailJob(deps({ cfg: { ...baseCfg, mode: 'shadow' }, mailer }), notif._id.toHexString());
expect(await repos.notifications.findOne({ _id: notif._id })).not.toBeNull();
});
it('transient SMTP error releases reservation and rethrows', async () => {
const notif = aNotif({ type: 'web' });
await repos.notifications.insertOne(notif);
await repos.users.insertOne(aUser());
const mailer = fakeMailer({ fail: true });
await expect(processEmailJob(deps({ mailer }), notif._id.toHexString())).rejects.toThrow();
expect(await repos.sends.countDocuments({ notificationId: notif._id })).toBe(0);
});
});

89
test/helpers.ts Normal file
View file

@ -0,0 +1,89 @@
import { MongoMemoryServer } from 'mongodb-memory-server';
import { pino } from 'pino';
import { ObjectId } from 'mongodb';
import { connect, ensureIndexes, type Repos } from '../src/db.js';
import type { Config } from '../src/config.js';
import type { FcmClient, FcmSendResult } from '../src/fcm.js';
import type { Mailer } from '../src/mailer.js';
import type { EmailContent, PushPayload } from '../src/messages.js';
import type { NotificationDoc, UserDoc } from '../src/types.js';
export const silentLog = pino({ level: 'silent' });
export async function startMongo(): Promise<{ server: MongoMemoryServer; repos: Repos; cfg: Config }> {
const server = await MongoMemoryServer.create();
const cfg = testCfg({ mongoUrl: server.getUri(), dbName: 'fuegos' });
const repos = await connect(cfg);
await ensureIndexes(repos);
return { server, repos, cfg };
}
export function testCfg(over: Partial<Config> = {}): Config {
return {
mode: 'full',
killSwitch: false,
ownedChannels: ['fcm', 'email'],
mongoUrl: 'mongodb://x',
dbName: 'fuegos',
redis: { host: 'x', port: 6379, db: 0 },
poll: { intervalMs: 1000, batchSize: 500 },
limits: { perUserPerDay: 20, maxPerBatch: 2000 },
canary: { userIds: [], subsIds: [] },
retries: { attempts: 3, backoffMs: 100 },
fcm: {},
email: { from: 'test <t@x>' },
rootUrl: 'https://fuegos.comunes.org/',
gmaps: {},
logLevel: 'silent',
serviceName: 'tcef-notifications',
...over,
};
}
export function aNotif(over: Partial<NotificationDoc> = {}): NotificationDoc {
return {
_id: new ObjectId(),
userId: 'u1',
subsId: new ObjectId(),
content: '🔥 Fuego cerca:',
geo: { type: 'Point', coordinates: [-8.5, 42.3] },
type: 'mobile',
when: new Date('2026-07-12T18:30:00Z'),
sealed: 'fire-1',
...over,
};
}
export function aUser(over: Partial<UserDoc> = {}): UserDoc {
return {
_id: 'u1',
lang: 'es',
fireBaseToken: 'tok-abc',
profile: { name: { first: 'Ana' } },
emails: [{ address: 'ana@example.com', verified: true }],
...over,
};
}
/** Recording FCM fake with programmable result. */
export function fakeFcm(result: FcmSendResult | (() => FcmSendResult)): FcmClient & { calls: Array<{ token: string; payload: PushPayload }> } {
const calls: Array<{ token: string; payload: PushPayload }> = [];
return {
calls,
async send(token, payload) {
calls.push({ token, payload });
return typeof result === 'function' ? result() : result;
},
};
}
export function fakeMailer(opts: { fail?: boolean } = {}): Mailer & { calls: Array<{ to: string; content: EmailContent }> } {
const calls: Array<{ to: string; content: EmailContent }> = [];
return {
calls,
async send(to, content) {
if (opts.fail) throw new Error('smtp down');
calls.push({ to, content });
},
};
}

36
test/mailer.test.ts Normal file
View file

@ -0,0 +1,36 @@
import { describe, expect, it } from 'vitest';
import { ObjectId } from 'mongodb';
import { renderEmail } from '../src/mailer.js';
import { buildEmail } from '../src/messages.js';
import type { NotificationDoc } from '../src/types.js';
const notif: NotificationDoc = {
_id: new ObjectId(),
userId: 'u1',
content: '🔥 Incendio en Ourense:',
geo: { type: 'Point', coordinates: [-7.86, 42.34] },
type: 'web',
when: new Date('2026-07-12T18:30:00Z'),
sealed: 'fire-xyz',
};
describe('renderEmail with ported new-fire templates', () => {
it('renders es html + text with the message and links', () => {
const content = buildEmail(notif, 'es', 'Ana', { rootUrl: 'https://fuegos.comunes.org/' });
const { html, text } = renderEmail('new-fire', content);
expect(html).toContain('Ana');
expect(html).toContain('Incendio en Ourense');
expect(html).toContain('https://fuegos.comunes.org/fire/fire-xyz');
// juice should inline styles (style attribute present on elements)
expect(html).toMatch(/style=/);
expect(text).toContain('Ana');
expect(text).toContain('https://fuegos.comunes.org/fire/fire-xyz');
});
it('renders en template', () => {
const content = buildEmail(notif, 'en', 'Bob', { rootUrl: 'https://fires.comunes.org/' });
const { html } = renderEmail('new-fire', content);
expect(html).toContain('Bob');
expect(html).toContain('fires.comunes.org/fire/fire-xyz');
});
});

137
test/messages.test.ts Normal file
View file

@ -0,0 +1,137 @@
import { describe, expect, it } from 'vitest';
import { ObjectId } from 'mongodb';
import {
buildEmail,
buildPush,
dateLongFormat,
normalizeLang,
staticMapUrl,
subjectTruncate,
t,
trim,
} from '../src/messages.js';
import type { NotificationDoc } from '../src/types.js';
function fakeNotif(overrides: Partial<NotificationDoc> = {}): NotificationDoc {
return {
_id: new ObjectId('0123456789abcdef01234567'),
userId: 'user-1',
subsId: new ObjectId('aaaaaaaaaaaaaaaaaaaaaaaa'),
content: '🔥 Fuego cerca de tu zona en Galicia:',
geo: { type: 'Point', coordinates: [-8.5, 42.3] }, // [lng, lat]
type: 'mobile',
when: new Date('2026-07-12T18:30:00Z'),
sealed: 'fire-abc',
...overrides,
};
}
describe('trim (ported from NotificationsObserver/util.js)', () => {
it('strips leading 🔥 and trailing colon', () => {
expect(trim('🔥 Fuego cerca:')).toBe('Fuego cerca');
});
it('leaves other text intact', () => {
expect(trim('Fuego en el monte')).toBe('Fuego en el monte');
});
});
describe('i18n strings (pinned from Meteor locales)', () => {
it('title per language', () => {
expect(t('Alerta de fuego', 'es')).toBe('Alerta de fuego');
expect(t('Alerta de fuego', 'en')).toBe('Alert of fire');
});
it('AppName per language', () => {
expect(t('AppName', 'es')).toBe('Tod@s contra el Fuego');
expect(t('AppName', 'en')).toBe('All Against the Fire');
});
it('fireDetectedAt interpolates {{when}}', () => {
expect(t('fireDetectedAt', 'es', { when: 'X' })).toBe('fuego detectado el X');
expect(t('fireDetectedAt', 'en', { when: 'X' })).toBe('fire detected on X');
});
});
describe('normalizeLang', () => {
it('maps unknown langs to es', () => {
expect(normalizeLang('fr')).toBe('es');
expect(normalizeLang(undefined)).toBe('es');
expect(normalizeLang('en-US')).toBe('en');
expect(normalizeLang('gl')).toBe('gl');
});
});
describe('subjectTruncate (ported)', () => {
it('keeps short strings', () => {
expect(subjectTruncate('short', 70)).toBe('short');
});
it('truncates on word boundary with ellipsis', () => {
const s = 'a'.repeat(40) + ' ' + 'b'.repeat(40);
const out = subjectTruncate(s, 70);
expect(out.endsWith('...')).toBe(true);
expect(out.length).toBeLessThanOrEqual(73);
});
});
describe('buildPush (equivalent to old gcm.Message)', () => {
it('produces title/body and full data payload', () => {
const p = buildPush(fakeNotif(), 'es');
expect(p.title).toBe('Alerta de fuego');
expect(p.body).toBe('Fuego cerca de tu zona en Galicia'); // trimmed
expect(p.clickAction).toBe('FLUTTER_NOTIFICATION_CLICK');
expect(p.sound).toBe('default');
expect(p.icon).toBe('launch_image');
expect(p.collapseKey).toBe('0123456789abcdef01234567');
expect(p.data.id).toBe('0123456789abcdef01234567');
expect(p.data.description).toBe('Fuego cerca de tu zona en Galicia');
expect(p.data.lat).toBe('42.3'); // coordinates[1]
expect(p.data.lon).toBe('-8.5'); // coordinates[0]
expect(p.data.sealed).toBe('fire-abc');
expect(p.data.subsId).toBe('aaaaaaaaaaaaaaaaaaaaaaaa');
});
it('handles missing subsId', () => {
const p = buildPush(fakeNotif({ subsId: undefined }), 'en');
expect(p.data.subsId).toBe('');
expect(p.title).toBe('Alert of fire');
});
});
describe('buildEmail (equivalent to old processNotif web branch)', () => {
it('builds subject, message and template vars', () => {
const notif = fakeNotif({ type: 'web', content: '🔥 Incendio en A Coruña:' });
const e = buildEmail(notif, 'es', 'Ana', {
rootUrl: 'https://fuegos.comunes.org/',
gmapsKey: 'KEY',
fireIconUrl: 'https://x/icon.png',
});
expect(e.templateVars.firstName).toBe('Ana');
expect(e.templateVars.applicationName).toBe('Tod@s contra el Fuego');
expect(e.templateVars.message).toMatch(/^Incendio en A Coruña \(fuego detectado el .+\)\.$/);
expect(e.templateVars.fireUrl).toBe('https://fuegos.comunes.org/fire/fire-abc');
expect(e.templateVars.subsUrl).toBe('https://fuegos.comunes.org/subscriptions');
expect(e.templateVars.img).toContain('maps.googleapis.com');
expect(e.subject.length).toBeLessThanOrEqual(73);
});
it('normalizes rootUrl without trailing slash', () => {
const e = buildEmail(fakeNotif({ type: 'web' }), 'en', 'Bob', {
rootUrl: 'https://fires.comunes.org',
});
expect(e.templateVars.fireUrl).toBe('https://fires.comunes.org/fire/fire-abc');
});
});
describe('staticMapUrl', () => {
it('includes fire icon marker and coordinates', () => {
const url = staticMapUrl(42.3, -8.5, { key: 'K', fireIconUrl: 'https://x/i.png' });
expect(url).toContain('center=42.3%2C-8.5');
expect(url).toContain('maptype=hybrid');
expect(url).toContain('zoom=16');
expect(url).toContain('key=K');
});
});
describe('dateLongFormat', () => {
it('returns a localized long date with zone', () => {
const s = dateLongFormat(new Date('2026-07-12T18:30:00Z'), 'es', 'Europe/Madrid');
expect(s).toMatch(/2026/);
expect(s).toMatch(/\(.+\)$/); // zone in parens
});
});

76
test/mode.test.ts Normal file
View file

@ -0,0 +1,76 @@
import { describe, expect, it } from 'vitest';
import { ObjectId } from 'mongodb';
import { decideSend } from '../src/mode.js';
import { assertBatchWithinLimit, BatchTooLargeError } from '../src/limits.js';
import type { Config } from '../src/config.js';
import type { NotificationDoc } from '../src/types.js';
function baseCfg(over: Partial<Config> = {}): Config {
return {
mode: 'full',
killSwitch: false,
ownedChannels: ['fcm'],
mongoUrl: 'mongodb://x',
dbName: 'fuegos',
redis: { host: 'x', port: 6379, db: 0 },
poll: { intervalMs: 1000, batchSize: 100 },
limits: { perUserPerDay: 20, maxPerBatch: 2000 },
canary: { userIds: [], subsIds: [] },
retries: { attempts: 3, backoffMs: 100 },
fcm: {},
email: { from: 'x' },
rootUrl: 'https://x/',
gmaps: {},
logLevel: 'silent',
serviceName: 'test',
...over,
};
}
const notif: NotificationDoc = {
_id: new ObjectId(),
userId: 'u1',
subsId: new ObjectId('bbbbbbbbbbbbbbbbbbbbbbbb'),
content: 'x',
geo: { type: 'Point', coordinates: [0, 0] },
type: 'mobile',
when: new Date(),
sealed: 's',
};
describe('decideSend', () => {
it('kill switch overrides every mode', () => {
for (const mode of ['dry-run', 'shadow', 'canary', 'full'] as const) {
const d = decideSend(baseCfg({ mode, killSwitch: true }), notif);
expect(d).toEqual({ send: false, reason: 'kill-switch' });
}
});
it('dry-run never sends', () => {
expect(decideSend(baseCfg({ mode: 'dry-run' }), notif)).toEqual({ send: false, reason: 'dry-run' });
});
it('shadow never sends', () => {
expect(decideSend(baseCfg({ mode: 'shadow' }), notif)).toEqual({ send: false, reason: 'shadow' });
});
it('canary sends only to cohort by userId', () => {
expect(decideSend(baseCfg({ mode: 'canary', canary: { userIds: ['u1'], subsIds: [] } }), notif)).toEqual({ send: true });
expect(decideSend(baseCfg({ mode: 'canary', canary: { userIds: ['other'], subsIds: [] } }), notif)).toEqual({ send: false, reason: 'not-in-canary' });
});
it('canary sends to cohort by subsId', () => {
expect(decideSend(baseCfg({ mode: 'canary', canary: { userIds: [], subsIds: ['bbbbbbbbbbbbbbbbbbbbbbbb'] } }), notif)).toEqual({ send: true });
});
it('full always sends', () => {
expect(decideSend(baseCfg({ mode: 'full' }), notif)).toEqual({ send: true });
});
});
describe('circuit breaker', () => {
it('throws when batch exceeds max', () => {
expect(() => assertBatchWithinLimit(2001, 2000)).toThrow(BatchTooLargeError);
});
it('passes when within max', () => {
expect(() => assertBatchWithinLimit(2000, 2000)).not.toThrow();
});
it('unlimited when max is 0', () => {
expect(() => assertBatchWithinLimit(999999, 0)).not.toThrow();
});
});

93
test/poller.test.ts Normal file
View file

@ -0,0 +1,93 @@
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
import type { Queue } from 'bullmq';
import type { MongoMemoryServer } from 'mongodb-memory-server';
import type { Repos } from '../src/db.js';
import type { Config } from '../src/config.js';
import { createPoller } from '../src/poller.js';
import { pendingFilter } from '../src/poller.js';
import type { Channel, SendJob } from '../src/types.js';
import { aNotif, silentLog, startMongo } from './helpers.js';
let server: MongoMemoryServer;
let repos: Repos;
let baseCfg: Config;
beforeAll(async () => {
const s = await startMongo();
server = s.server;
repos = s.repos;
baseCfg = s.cfg;
});
afterAll(async () => {
await repos.close();
await server.stop();
});
beforeEach(async () => {
await repos.notifications.deleteMany({});
});
/** Fake queue recording add() calls. */
function fakeQueues() {
const added: Record<Channel, SendJob[]> = { fcm: [], email: [] };
const make = (ch: Channel) =>
({
async add(_name: string, job: SendJob) {
added[ch].push(job);
},
}) as unknown as Queue<SendJob>;
return { queues: { fcm: make('fcm'), email: make('email') } as Record<Channel, Queue<SendJob>>, added };
}
describe('pendingFilter', () => {
it('uses the CORRECT field names (old cron had a typo)', () => {
expect(pendingFilter('fcm')).toEqual({ type: 'mobile', notified: { $ne: true } });
expect(pendingFilter('email')).toEqual({ type: 'web', emailNotified: { $ne: true } });
});
});
describe('poller.runOnce', () => {
it('enqueues only pending docs of owned channels and claims them', async () => {
await repos.notifications.insertMany([
aNotif({ type: 'mobile' }), // pending fcm
aNotif({ type: 'mobile', notified: true }), // already done
aNotif({ type: 'web' }), // pending email
aNotif({ type: 'web', emailNotified: true }), // already done
]);
const { queues, added } = fakeQueues();
const poller = createPoller(baseCfg, repos, queues, silentLog);
const res = await poller.runOnce();
expect(res).toEqual({ fcm: 1, email: 1 });
expect(added.fcm).toHaveLength(1);
expect(added.email).toHaveLength(1);
// claimedBy provenance set
expect(await repos.notifications.countDocuments({ claimedBy: baseCfg.serviceName })).toBe(2);
});
it('only polls owned channels', async () => {
await repos.notifications.insertMany([aNotif({ type: 'mobile' }), aNotif({ type: 'web' })]);
const { queues, added } = fakeQueues();
const cfg = { ...baseCfg, ownedChannels: ['fcm'] as Channel[] };
const poller = createPoller(cfg, repos, queues, silentLog);
const res = await poller.runOnce();
expect(res.fcm).toBe(1);
expect(added.email).toHaveLength(0);
});
it('circuit breaker halts on oversized batch', async () => {
const many = Array.from({ length: 5 }, () => aNotif({ type: 'mobile' }));
await repos.notifications.insertMany(many);
const { queues, added } = fakeQueues();
const cfg = { ...baseCfg, ownedChannels: ['fcm'] as Channel[], limits: { ...baseCfg.limits, maxPerBatch: 3 } };
const poller = createPoller(cfg, repos, queues, silentLog);
const res = await poller.runOnce();
// Batch of 5 > max 3 -> nothing enqueued, poller halted.
expect(res.fcm).toBe(0);
expect(added.fcm).toHaveLength(0);
});
});