refactor(notifications, place-photos, backup): async DB-touching methods; transactions through UnitOfWork

This commit is contained in:
jubnl
2026-09-22 00:22:11 +02:00
parent fac181f45b
commit 4df2d83137
24 changed files with 285 additions and 250 deletions
+1 -1
View File
@@ -109,7 +109,7 @@ beforeAll(async () => {
new PasskeyService(dbs, auth, webauthn),
auth,
permissions,
makeNotificationsService(dbs, realtime),
await makeNotificationsService(dbs, realtime),
userCleanup,
realtime,
);
@@ -87,7 +87,7 @@ beforeAll(async () => {
new PasskeyService(dbs, auth, webauthn),
auth,
permissions,
makeNotificationsService(dbs, realtime),
await makeNotificationsService(dbs, realtime),
userCleanup,
realtime,
);
@@ -53,12 +53,14 @@ import { createUser, createAdmin, setAppSetting, setNotificationChannels } from
// (notifications.instance.ts died with the last cycle-dodge bridge); a
// hand-constructed instance still shares the module-scoped channel registry,
// which is exactly what CHOVR-015 pins.
import type { NotificationPayload } from '../../../src/nest/notifications/notifications.service';
import type { NotificationPayload, NotificationsService } from '../../../src/nest/notifications/notifications.service';
import { makeNotificationsService } from '../../helpers/notifications';
// One instance, built at module load like the old import-time singleton: its
// constructor is what registers the built-in channels the registry cases read.
const notifications = makeNotificationsService(new DatabaseService(testDb));
// Built in beforeAll: the service now takes a UnitOfWork, which is async to build.
// Its constructor is still what registers the built-in channels the registry cases read.
let notifications: NotificationsService;
const send = (payload: NotificationPayload) => notifications.send(payload);
import { NtfyService } from '../../../src/nest/notifications/transports/ntfy.service';
import { WebhookService } from '../../../src/nest/notifications/transports/webhook.service';
@@ -66,6 +68,7 @@ import { DatabaseService } from '../../../src/nest/database/database.service';
import { createPluginRuntime } from '../../helpers/plugin-host';
import { MailerService } from '../../../src/nest/notifications/mailer/mailer.service';
import { NotificationPreferencesService } from '../../../src/nest/notifications/notification-preferences.service';
import { createTestUnitOfWork } from '../../helpers/test-uow';
import {
setPluginChannelSource,
@@ -77,7 +80,7 @@ import {
import type { ExternalChannel } from '../../../src/nest/notifications/notification-events';
const prefsDbs = new DatabaseService(testDb);
const prefsSvc = new NotificationPreferencesService(prefsDbs, new MailerService(prefsDbs));
let prefsSvc: NotificationPreferencesService;
// An arrow forwarder rather than `.bind(prefsSvc)`: under `strictBindCallApply: false`
// a bound alias is typed `any`, which hides a missing `await` from tsc and the lint
// rules alike (recipe R4).
@@ -85,7 +88,12 @@ const getPreferencesMatrix = (...a: Parameters<NotificationPreferencesService['g
prefsSvc.getPreferencesMatrix(...a);
void WebhookService; void NtfyService;
beforeAll(() => { createTables(testDb); runMigrations(testDb); });
beforeAll(async () => {
createTables(testDb);
runMigrations(testDb);
prefsSvc = new NotificationPreferencesService(prefsDbs, new MailerService(prefsDbs), await createTestUnitOfWork(testDb));
notifications = await makeNotificationsService(new DatabaseService(testDb));
});
beforeEach(() => { resetTestDb(testDb); setPluginChannelSource(null); });
const rogueSend = vi.fn().mockResolvedValue(true);
@@ -43,11 +43,13 @@ import { registerBuiltinChannels } from '../../../src/nest/notifications/channel
import { NtfyService } from '../../../src/nest/notifications/transports/ntfy.service';
import { WebhookService } from '../../../src/nest/notifications/transports/webhook.service';
import { __resetChannelsForTest } from '../../../src/nest/notifications/channel-registry';
import { createTestUnitOfWork } from '../../helpers/test-uow';
const dbs = new DatabaseService(testDb);
const mailer = new MailerService(dbs);
registerBuiltinChannels({ mailer, webhook: new WebhookService(dbs), ntfy: new NtfyService(dbs) });
const svc = new NotificationPreferencesService(dbs, mailer);
// Constructed in beforeAll: the service now takes a UnitOfWork, which is async to build.
let svc: NotificationPreferencesService;
// Legacy free-function names bound to the service, so the moved cases read as before.
// Arrow forwarders rather than `.bind(svc)`: under `strictBindCallApply: false` a bound
@@ -64,9 +66,10 @@ const isSmtpConfigured = (...a: Parameters<Svc['isSmtpConfigured']>) => svc.isSm
const isWebhookConfigured = (...a: Parameters<Svc['isWebhookConfigured']>) => svc.isWebhookConfigured(...a);
beforeAll(() => {
beforeAll(async () => {
createTables(testDb);
runMigrations(testDb);
svc = new NotificationPreferencesService(dbs, mailer, await createTestUnitOfWork(testDb));
});
beforeEach(() => {
@@ -82,23 +85,23 @@ afterAll(() => {
// ─────────────────────────────────────────────────────────────────────────────
describe('isEnabledForEvent', () => {
it('NPREF-001 — returns true when no row exists (default enabled)', () => {
it('NPREF-001 — returns true when no row exists (default enabled)', async () => {
const { user } = createUser(testDb);
expect(isEnabledForEvent(user.id, 'trip_invite', 'email')).toBe(true);
expect(await isEnabledForEvent(user.id, 'trip_invite', 'email')).toBe(true);
});
it('NPREF-002 — returns true when row exists with enabled=1', () => {
it('NPREF-002 — returns true when row exists with enabled=1', async () => {
const { user } = createUser(testDb);
testDb.prepare(
'INSERT INTO notification_channel_preferences (user_id, event_type, channel, enabled) VALUES (?, ?, ?, 1)'
).run(user.id, 'trip_invite', 'email');
expect(isEnabledForEvent(user.id, 'trip_invite', 'email')).toBe(true);
expect(await isEnabledForEvent(user.id, 'trip_invite', 'email')).toBe(true);
});
it('NPREF-003 — returns false when row exists with enabled=0', () => {
it('NPREF-003 — returns false when row exists with enabled=0', async () => {
const { user } = createUser(testDb);
disableNotificationPref(testDb, user.id, 'trip_invite', 'email');
expect(isEnabledForEvent(user.id, 'trip_invite', 'email')).toBe(false);
expect(await isEnabledForEvent(user.id, 'trip_invite', 'email')).toBe(false);
});
});
@@ -189,9 +192,9 @@ describe('getPreferencesMatrix', () => {
// ─────────────────────────────────────────────────────────────────────────────
describe('setPreferences', () => {
it('NPREF-012 — disabling a preference inserts a row with enabled=0', () => {
it('NPREF-012 — disabling a preference inserts a row with enabled=0', async () => {
const { user } = createUser(testDb);
setPreferences(user.id, { trip_invite: { email: false } });
await setPreferences(user.id, { trip_invite: { email: false } });
const row = testDb.prepare(
'SELECT enabled FROM notification_channel_preferences WHERE user_id = ? AND event_type = ? AND channel = ?'
).get(user.id, 'trip_invite', 'email') as { enabled: number } | undefined;
@@ -199,12 +202,12 @@ describe('setPreferences', () => {
expect(row!.enabled).toBe(0);
});
it('NPREF-013 — re-enabling a preference removes the disabled row', () => {
it('NPREF-013 — re-enabling a preference removes the disabled row', async () => {
const { user } = createUser(testDb);
// First disable
disableNotificationPref(testDb, user.id, 'trip_invite', 'email');
// Then re-enable
setPreferences(user.id, { trip_invite: { email: true } });
await setPreferences(user.id, { trip_invite: { email: true } });
const row = testDb.prepare(
'SELECT enabled FROM notification_channel_preferences WHERE user_id = ? AND event_type = ? AND channel = ?'
).get(user.id, 'trip_invite', 'email');
@@ -212,16 +215,16 @@ describe('setPreferences', () => {
expect(row).toBeUndefined();
});
it('NPREF-014 — bulk update handles multiple event+channel combos', () => {
it('NPREF-014 — bulk update handles multiple event+channel combos', async () => {
const { user } = createUser(testDb);
setPreferences(user.id, {
await setPreferences(user.id, {
trip_invite: { email: false, webhook: false },
booking_change: { email: false },
trip_reminder: { webhook: true },
});
expect(isEnabledForEvent(user.id, 'trip_invite', 'email')).toBe(false);
expect(isEnabledForEvent(user.id, 'trip_invite', 'webhook')).toBe(false);
expect(isEnabledForEvent(user.id, 'booking_change', 'email')).toBe(false);
expect(await isEnabledForEvent(user.id, 'trip_invite', 'email')).toBe(false);
expect(await isEnabledForEvent(user.id, 'trip_invite', 'webhook')).toBe(false);
expect(await isEnabledForEvent(user.id, 'booking_change', 'email')).toBe(false);
// trip_reminder webhook was set to true → no row, default enabled
const row = testDb.prepare(
'SELECT enabled FROM notification_channel_preferences WHERE user_id = ? AND event_type = ? AND channel = ?'
@@ -263,9 +266,9 @@ describe('getActiveChannels', () => {
// ─────────────────────────────────────────────────────────────────────────────
describe('channel availability', () => {
it('NPREF-019 — detects SMTP config from app_settings.smtp_host', () => {
it('NPREF-019 — detects SMTP config from app_settings.smtp_host', async () => {
setAppSetting(testDb, 'smtp_host', 'mail.example.com');
expect(isSmtpConfigured()).toBe(true);
expect(await isSmtpConfigured()).toBe(true);
});
it('NPREF-020 — webhook is active when admin has enabled the webhook channel', async () => {
@@ -273,11 +276,11 @@ describe('channel availability', () => {
expect(await getActiveChannels()).toContain('webhook');
});
it('NPREF-021 — detects SMTP config from env var SMTP_HOST', () => {
it('NPREF-021 — detects SMTP config from env var SMTP_HOST', async () => {
const original = process.env.SMTP_HOST;
process.env.SMTP_HOST = 'env-mail.example.com';
try {
expect(isSmtpConfigured()).toBe(true);
expect(await isSmtpConfigured()).toBe(true);
} finally {
if (original === undefined) delete process.env.SMTP_HOST;
else process.env.SMTP_HOST = original;
@@ -296,17 +299,17 @@ describe('channel availability', () => {
// ─────────────────────────────────────────────────────────────────────────────
describe('setAdminPreferences', () => {
it('NPREF-022 — disabling email for version_available stores global pref in app_settings', () => {
it('NPREF-022 — disabling email for version_available stores global pref in app_settings', async () => {
const { user } = createAdmin(testDb);
setAdminPreferences(user.id, { version_available: { email: false } });
expect(getAdminGlobalPref('version_available', 'email')).toBe(false);
await setAdminPreferences(user.id, { version_available: { email: false } });
expect(await getAdminGlobalPref('version_available', 'email')).toBe(false);
const row = testDb.prepare("SELECT value FROM app_settings WHERE key = ?").get('admin_notif_pref_version_available_email') as { value: string } | undefined;
expect(row?.value).toBe('0');
});
it('NPREF-023 — disabling inapp for version_available stores per-user row in notification_channel_preferences', () => {
it('NPREF-023 — disabling inapp for version_available stores per-user row in notification_channel_preferences', async () => {
const { user } = createAdmin(testDb);
setAdminPreferences(user.id, { version_available: { inapp: false } });
await setAdminPreferences(user.id, { version_available: { inapp: false } });
const row = testDb.prepare(
'SELECT enabled FROM notification_channel_preferences WHERE user_id = ? AND event_type = ? AND channel = ?'
).get(user.id, 'version_available', 'inapp') as { enabled: number } | undefined;
@@ -317,24 +320,24 @@ describe('setAdminPreferences', () => {
expect(globalRow).toBeUndefined();
});
it('NPREF-024 — re-enabling inapp removes the disabled per-user row', () => {
it('NPREF-024 — re-enabling inapp removes the disabled per-user row', async () => {
const { user } = createAdmin(testDb);
// First disable
disableNotificationPref(testDb, user.id, 'version_available', 'inapp');
// Then re-enable via setAdminPreferences
setAdminPreferences(user.id, { version_available: { inapp: true } });
await setAdminPreferences(user.id, { version_available: { inapp: true } });
const row = testDb.prepare(
'SELECT enabled FROM notification_channel_preferences WHERE user_id = ? AND event_type = ? AND channel = ?'
).get(user.id, 'version_available', 'inapp');
expect(row).toBeUndefined();
});
it('NPREF-025 — enabling email stores global pref as "1" in app_settings', () => {
it('NPREF-025 — enabling email stores global pref as "1" in app_settings', async () => {
const { user } = createAdmin(testDb);
// First disable, then re-enable
setAdminPreferences(user.id, { version_available: { email: false } });
setAdminPreferences(user.id, { version_available: { email: true } });
expect(getAdminGlobalPref('version_available', 'email')).toBe(true);
await setAdminPreferences(user.id, { version_available: { email: false } });
await setAdminPreferences(user.id, { version_available: { email: true } });
expect(await getAdminGlobalPref('version_available', 'email')).toBe(true);
const row = testDb.prepare("SELECT value FROM app_settings WHERE key = ?").get('admin_notif_pref_version_available_email') as { value: string } | undefined;
expect(row?.value).toBe('1');
});
@@ -32,11 +32,11 @@ describe('NotificationsController (parity with the legacy /api/notifications rou
expect(getPreferences).toHaveBeenCalledWith(4, 'user');
});
it('PUT saves then returns the refreshed matrix', () => {
it('PUT saves then returns the refreshed matrix', async () => {
const setPreferences = vi.fn();
const getPreferences = vi.fn().mockReturnValue({ preferences: { a: { inapp: true } } });
const body = { a: { inapp: true } };
expect(makeController({ setPreferences, getPreferences }).setPreferences(user, body)).toEqual({ preferences: { a: { inapp: true } } });
expect(await makeController({ setPreferences, getPreferences }).setPreferences(user, body)).toEqual({ preferences: { a: { inapp: true } } });
expect(setPreferences).toHaveBeenCalledWith(4, body);
});
});
@@ -141,33 +141,33 @@ describe('NotificationsController (parity with the legacy /api/notifications rou
});
describe('in-app list + counts', () => {
it('clamps limit to 50 and defaults offset/unread', () => {
it('clamps limit to 50 and defaults offset/unread', async () => {
const listInApp = vi.fn().mockReturnValue({ notifications: [], total: 0, unread_count: 0 });
makeController({ listInApp }).listInApp(user, '100', '5', 'true');
await makeController({ listInApp }).listInApp(user, '100', '5', 'true');
expect(listInApp).toHaveBeenCalledWith(4, { limit: 50, offset: 5, unreadOnly: true });
});
it('defaults limit to 20 when absent/non-numeric', () => {
it('defaults limit to 20 when absent/non-numeric', async () => {
const listInApp = vi.fn().mockReturnValue({ notifications: [], total: 0, unread_count: 0 });
makeController({ listInApp }).listInApp(user, undefined, undefined, undefined);
await makeController({ listInApp }).listInApp(user, undefined, undefined, undefined);
expect(listInApp).toHaveBeenCalledWith(4, { limit: 20, offset: 0, unreadOnly: false });
});
it('GET unread-count wraps the number', () => {
it('GET unread-count wraps the number', async () => {
const unreadCount = vi.fn().mockReturnValue(7);
expect(makeController({ unreadCount }).unreadCount(user)).toEqual({ count: 7 });
expect(await makeController({ unreadCount }).unreadCount(user)).toEqual({ count: 7 });
});
});
describe('bulk + single mutations', () => {
it('read-all returns success + count', () => {
it('read-all returns success + count', async () => {
const markAllRead = vi.fn().mockReturnValue(3);
expect(makeController({ markAllRead }).readAll(user)).toEqual({ success: true, count: 3 });
expect(await makeController({ markAllRead }).readAll(user)).toEqual({ success: true, count: 3 });
});
it('delete-all returns success + count', () => {
it('delete-all returns success + count', async () => {
const deleteAll = vi.fn().mockReturnValue(5);
expect(makeController({ deleteAll }).deleteAll(user)).toEqual({ success: true, count: 5 });
expect(await makeController({ deleteAll }).deleteAll(user)).toEqual({ success: true, count: 5 });
});
it('400 on a non-numeric id', () => {
@@ -183,15 +183,15 @@ describe('NotificationsController (parity with the legacy /api/notifications rou
});
});
it('mark-read success', () => {
it('mark-read success', async () => {
const markRead = vi.fn().mockReturnValue(true);
expect(makeController({ markRead }).markRead(user, '5')).toEqual({ success: true });
expect(await makeController({ markRead }).markRead(user, '5')).toEqual({ success: true });
expect(markRead).toHaveBeenCalledWith(5, 4);
});
it('delete single success', () => {
it('delete single success', async () => {
const deleteOne = vi.fn().mockReturnValue(true);
expect(makeController({ deleteOne }).deleteOne(user, '5')).toEqual({ success: true });
expect(await makeController({ deleteOne }).deleteOne(user, '5')).toEqual({ success: true });
});
});
@@ -47,14 +47,20 @@ import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
import { NotificationsService } from '../../../src/nest/notifications/notifications.service';
import { makeNotificationsService, makeNotificationPreferencesService } from '../../helpers/notifications';
const notifications = makeNotificationsService(new DatabaseService(testDb));
const createNotification = notifications.createNotification.bind(notifications);
const createNotificationForRecipient = notifications.createNotificationForRecipient.bind(notifications);
const respondToBoolean = notifications.respond.bind(notifications);
// Built in beforeAll: the service now takes a UnitOfWork, which is async to build.
let notifications: NotificationsService;
// Arrow forwarders rather than `.bind(notifications)`: under `strictBindCallApply: false`
// a bound alias is typed `any`, which hides a missing `await` from tsc AND from the
// type-aware lint rules (recipe R4).
type Svc = NotificationsService;
const createNotification = (...a: Parameters<Svc['createNotification']>) => notifications.createNotification(...a);
const createNotificationForRecipient = (...a: Parameters<Svc['createNotificationForRecipient']>) => notifications.createNotificationForRecipient(...a);
const respondToBoolean = (...a: Parameters<Svc['respond']>) => notifications.respond(...a);
beforeAll(() => {
beforeAll(async () => {
createTables(testDb);
runMigrations(testDb);
notifications = await makeNotificationsService(new DatabaseService(testDb));
});
beforeEach(() => {
@@ -71,14 +77,14 @@ afterAll(() => {
// ─────────────────────────────────────────────────────────────────────────────
describe('createNotification — preference filtering', () => {
it('INOTIF-001 — notification without event_type is delivered to all recipients (backward compat)', () => {
it('INOTIF-001 — notification without event_type is delivered to all recipients (backward compat)', async () => {
const { user: admin } = createAdmin(testDb);
const { user: recipient } = createUser(testDb);
// The admin scope targets all admins — create a second admin as the sender
const { user: sender } = createAdmin(testDb);
// Send to a specific user (user scope) without event_type
const ids = createNotification({
const ids = await createNotification({
type: 'simple',
scope: 'user',
target: recipient.id,
@@ -94,7 +100,7 @@ describe('createNotification — preference filtering', () => {
// Also verify the admin who disabled all prefs still gets messages without event_type
disableNotificationPref(testDb, admin.id, 'trip_invite', 'inapp');
// admin still gets this since no event_type check
const adminIds = createNotification({
const adminIds = await createNotification({
type: 'simple',
scope: 'user',
target: admin.id,
@@ -105,7 +111,7 @@ describe('createNotification — preference filtering', () => {
expect(adminIds.length).toBe(1);
});
it('INOTIF-002 — notification with event_type skips recipients who have disabled that event on inapp', () => {
it('INOTIF-002 — notification with event_type skips recipients who have disabled that event on inapp', async () => {
const { user: sender } = createAdmin(testDb);
const { user: recipient1 } = createUser(testDb);
const { user: recipient2 } = createUser(testDb);
@@ -118,7 +124,7 @@ describe('createNotification — preference filtering', () => {
testDb.prepare('INSERT INTO trip_members (trip_id, user_id) VALUES (?, ?)').run(tripId, recipient1.id);
testDb.prepare('INSERT INTO trip_members (trip_id, user_id) VALUES (?, ?)').run(tripId, recipient2.id);
const ids = createNotification({
const ids = await createNotification({
type: 'simple',
scope: 'trip',
target: tripId,
@@ -136,12 +142,12 @@ describe('createNotification — preference filtering', () => {
expect(r2).toBeUndefined();
});
it('INOTIF-003 — notification with event_type delivers to recipients with no stored preferences', () => {
it('INOTIF-003 — notification with event_type delivers to recipients with no stored preferences', async () => {
const { user: sender } = createAdmin(testDb);
const { user: recipient } = createUser(testDb);
// No preferences stored for recipient — should default to enabled
const ids = createNotification({
const ids = await createNotification({
type: 'simple',
scope: 'user',
target: recipient.id,
@@ -156,11 +162,11 @@ describe('createNotification — preference filtering', () => {
expect(row).toBeDefined();
});
it('INOTIF-003b — createNotificationForRecipient inserts a single notification and broadcasts via WS', () => {
it('INOTIF-003b — createNotificationForRecipient inserts a single notification and broadcasts via WS', async () => {
const { user: sender } = createAdmin(testDb);
const { user: recipient } = createUser(testDb);
const id = createNotificationForRecipient(
const id = await createNotificationForRecipient(
{
type: 'navigate',
scope: 'user',
@@ -185,14 +191,14 @@ describe('createNotification — preference filtering', () => {
expect(broadcastMock.mock.calls[0][0]).toBe(recipient.id);
});
it('INOTIF-004 — admin-scope version_available only reaches admins with enabled pref', () => {
it('INOTIF-004 — admin-scope version_available only reaches admins with enabled pref', async () => {
const { user: admin1 } = createAdmin(testDb);
const { user: admin2 } = createAdmin(testDb);
// admin2 disables version_available inapp notifications
disableNotificationPref(testDb, admin2.id, 'version_available', 'inapp');
const ids = createNotification({
const ids = await createNotification({
type: 'navigate',
scope: 'admin',
target: 0,
@@ -381,10 +387,10 @@ describe('respondToBoolean', () => {
expect(broadcastPayload?.notification.created_at).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/);
});
it('INOTIF-014 — createNotification broadcast carries an ISO-UTC created_at (was the un-patched #1149 path)', () => {
it('INOTIF-014 — createNotification broadcast carries an ISO-UTC created_at (was the un-patched #1149 path)', async () => {
const { user } = createUser(testDb);
createNotification({
await createNotification({
type: 'simple',
scope: 'user',
target: user.id,
@@ -101,7 +101,8 @@ import { setPluginChannelSource } from '../../../src/nest/notifications/channel-
import type { ExternalChannel } from '../../../src/nest/notifications/notification-events';
import { makeNotificationsService, makeNotificationPreferencesService } from '../../helpers/notifications';
const notifications = makeNotificationsService(new DatabaseService(testDb));
// Built in beforeAll: the service now takes a UnitOfWork, which is async to build.
let notifications: NotificationsService;
const send = (payload: NotificationPayload) => notifications.send(payload);
// ── Helpers ────────────────────────────────────────────────────────────────
@@ -138,9 +139,10 @@ function countAllNotifications(): number {
// ── Setup ──────────────────────────────────────────────────────────────────
beforeAll(() => {
beforeAll(async () => {
createTables(testDb);
runMigrations(testDb);
notifications = await makeNotificationsService(new DatabaseService(testDb));
});
beforeEach(() => {
@@ -233,51 +233,51 @@ describe.each([
.run(Date.now() - ms, placeId);
}
it('PPC-009: a place with no photo stays remembered well past the old five-minute window', () => {
cache.markError('photo-less');
it('PPC-009: a place with no photo stays remembered well past the old five-minute window', async () => {
await cache.markError('photo-less');
ageError('photo-less', 30 * 60 * 1000);
expect(cache.getErrored('photo-less')).toBe(true);
expect(await cache.getErrored('photo-less')).toBe(true);
ageError('photo-less', 5 * 60 * 60 * 1000);
expect(cache.getErrored('photo-less')).toBe(true);
expect(await cache.getErrored('photo-less')).toBe(true);
});
it('PPC-010: the miss expires once it is a day old', () => {
cache.markError('stale-miss');
it('PPC-010: the miss expires once it is a day old', async () => {
await cache.markError('stale-miss');
ageError('stale-miss', 24 * 60 * 60 * 1000);
expect(cache.getErrored('stale-miss')).toBe(false);
expect(await cache.getErrored('stale-miss')).toBe(false);
});
// A failed provider call says nothing about the place, so it must not inherit the
// long window a real "this place has no photo" answer gets.
it('PPC-011: a failed provider call is forgotten after minutes and never persisted', () => {
it('PPC-011: a failed provider call is forgotten after minutes and never persisted', async () => {
vi.useFakeTimers();
try {
cache.markError('flaky', 'provider-error');
expect(cache.getErrored('flaky')).toBe(true);
await cache.markError('flaky', 'provider-error');
expect(await cache.getErrored('flaky')).toBe(true);
// Nothing on disk — a restart retries instead of inheriting someone's outage.
expect(testDb.prepare('SELECT 1 FROM google_place_photo_meta WHERE place_id = ?').get('flaky')).toBeUndefined();
vi.advanceTimersByTime(5 * 60 * 1000);
expect(cache.getErrored('flaky')).toBe(false);
expect(await cache.getErrored('flaky')).toBe(false);
// The long window belongs to the other case: same age, still remembered.
cache.markError('photo-less-too');
await cache.markError('photo-less-too');
ageError('photo-less-too', 5 * 60 * 1000);
expect(cache.getErrored('photo-less-too')).toBe(true);
expect(await cache.getErrored('photo-less-too')).toBe(true);
} finally {
vi.useRealTimers();
}
});
it('PPC-012: a cached photo clears an earlier failed attempt', async () => {
cache.markError('recovered', 'provider-error');
expect(cache.getErrored('recovered')).toBe(true);
await cache.markError('recovered', 'provider-error');
expect(await cache.getErrored('recovered')).toBe(true);
await cache.put('recovered', await makeJpeg(40, 40), null);
expect(cache.getErrored('recovered')).toBe(false);
expect(await cache.getErrored('recovered')).toBe(false);
});
});
});
@@ -88,26 +88,26 @@ beforeEach(() => {
});
describe('ReminderJobsService bootstrap', () => {
it('RJOB-001 — registers both 9 AM crons under their names', () => {
it('RJOB-001 — registers both 9 AM crons under their names', async () => {
const { svc, registered } = makeJobs();
svc.onApplicationBootstrap();
await svc.onApplicationBootstrap();
expect(registered.map(r => [r.name, r.expr])).toEqual([
['trip-reminders', '0 9 * * *'],
['todo-reminders', '0 9 * * *'],
]);
});
it('RJOB-002 — does nothing under the test gate (no crons, no banners)', () => {
it('RJOB-002 — does nothing under the test gate (no crons, no banners)', async () => {
const { svc, registered, registrar } = makeJobs();
registrar.isEnabled.mockReturnValue(false);
svc.onApplicationBootstrap();
await svc.onApplicationBootstrap();
expect(registered).toHaveLength(0);
expect(logMock.logInfo).not.toHaveBeenCalled();
});
it('RJOB-003 — logs the enabled banners by default and the disabled ones when toggled off', () => {
it('RJOB-003 — logs the enabled banners by default and the disabled ones when toggled off', async () => {
const { svc } = makeJobs();
svc.onApplicationBootstrap();
await svc.onApplicationBootstrap();
expect(logMock.logInfo).toHaveBeenCalledWith('Trip reminders: enabled via []');
expect(logMock.logInfo).toHaveBeenCalledWith('Todo due reminders: enabled (lead 3d)');
@@ -115,17 +115,17 @@ describe('ReminderJobsService bootstrap', () => {
setAppSetting(testDb, 'notify_trip_reminder', 'false');
setAppSetting(testDb, 'notify_todo_due', 'false');
const { svc: svc2 } = makeJobs();
svc2.onApplicationBootstrap();
await svc2.onApplicationBootstrap();
expect(logMock.logInfo).toHaveBeenCalledWith('Trip reminders: disabled in settings');
expect(logMock.logInfo).toHaveBeenCalledWith('Todo due reminders: disabled in settings');
});
it('RJOB-004 — the trip banner carries the active channels and the reminder-trip count', () => {
it('RJOB-004 — the trip banner carries the active channels and the reminder-trip count', async () => {
const { user } = createUser(testDb);
setNotificationChannels(testDb, 'email');
tripWithReminder(user.id, 5);
const { svc } = makeJobs();
svc.onApplicationBootstrap();
await svc.onApplicationBootstrap();
expect(logMock.logInfo).toHaveBeenCalledWith('Trip reminders: enabled via [email], 1 trip(s) with active reminders');
});
});