refactor(plugins): async DB-touching methods; transactions through UnitOfWork

This commit is contained in:
jubnl
2026-09-22 00:00:53 +02:00
parent e413308227
commit e28dc6de28
68 changed files with 743 additions and 706 deletions
@@ -88,17 +88,17 @@ function sanitizePluginChannels(raw: readonly ExternalChannel[]): ExternalChanne
// setPluginEventSink() in plugin-runtime.service.ts: the runtime pushes a getter
// in at onModuleInit, and we pull from it on every read so a plugin that is
// disabled or uninstalled simply stops appearing.
let pluginChannelSource: (() => ExternalChannel[]) | null = null;
let pluginChannelSource: (() => ExternalChannel[] | Promise<ExternalChannel[]>) | null = null;
export function setPluginChannelSource(source: (() => ExternalChannel[]) | null): void {
export function setPluginChannelSource(source: (() => ExternalChannel[] | Promise<ExternalChannel[]>) | null): void {
pluginChannelSource = source;
}
/** Every channel that currently exists: built-ins plus live, sanitized plugin channels. */
export function listChannels(): ExternalChannel[] {
const plugins = (() => {
export async function listChannels(): Promise<ExternalChannel[]> {
const plugins = await (async () => {
try {
return pluginChannelSource?.() ?? [];
return (await pluginChannelSource?.()) ?? [];
} catch {
// A broken plugin runtime must never take notifications down with it.
return [];
@@ -109,8 +109,8 @@ export function listChannels(): ExternalChannel[] {
return [...builtins.values(), ...sanitizePluginChannels(plugins)];
}
export function getChannel(id: string): ExternalChannel | undefined {
if (isPluginChannelId(id)) return listChannels().find((c) => c.id === id);
export async function getChannel(id: string): Promise<ExternalChannel | undefined> {
if (isPluginChannelId(id)) return (await listChannels()).find((c) => c.id === id);
return builtins.get(id);
}
@@ -135,7 +135,7 @@ export interface ExternalChannel {
*/
isInstanceConfigured?(): boolean;
/** Does this recipient have credentials for this channel? */
isConfiguredFor(userId: number): boolean;
isConfiguredFor(userId: number): boolean | Promise<boolean>;
sendToUser(userId: number, msg: ChannelMessage): Promise<unknown>;
sendGlobal?(msg: ChannelMessage): Promise<unknown>;
test?(userId: number, override?: Record<string, unknown>): Promise<{ success: boolean; error?: string }>;
@@ -45,13 +45,13 @@ export class NotificationPreferencesService {
* Channels implemented for an event. In-app takes everything; external channels
* decide for themselves (today: everything except `synology_session_cleared`).
*/
combosFor(event: NotifEventType): NotifChannel[] {
return [INAPP_CHANNEL, ...listChannels().filter(c => c.supportsEvent(event)).map(c => c.id)];
async combosFor(event: NotifEventType): Promise<NotifChannel[]> {
return [INAPP_CHANNEL, ...(await listChannels()).filter(c => c.supportsEvent(event)).map(c => c.id)];
}
private allCombos(): Record<string, NotifChannel[]> {
private async allCombos(): Promise<Record<string, NotifChannel[]>> {
const out: Record<string, NotifChannel[]> = {};
for (const event of ALL_EVENT_TYPES) out[event] = this.combosFor(event);
for (const event of ALL_EVENT_TYPES) out[event] = await this.combosFor(event);
return out;
}
@@ -68,16 +68,16 @@ export class NotificationPreferencesService {
* into this CSV, and the admin toggle rebuilds it from the three built-in booleans, which
* would silently drop any that were).
*/
getActiveChannels(): NotifChannel[] {
async getActiveChannels(): Promise<NotifChannel[]> {
const raw = this.getAppSetting('notification_channels') || this.getAppSetting('notification_channel') || 'none';
if (raw === 'none') return [];
const builtins = new Set(listChannels().filter(c => c.source === 'builtin').map(c => c.id));
const builtins = new Set((await listChannels()).filter(c => c.source === 'builtin').map(c => c.id));
return raw.split(',').map(c => c.trim()).filter(c => builtins.has(c));
}
/** Is this channel switched on? Plugin channels are on by virtue of being live. */
isChannelActive(channel: ExternalChannel): boolean {
return channel.source === 'plugin' || this.getActiveChannels().includes(channel.id);
async isChannelActive(channel: ExternalChannel): Promise<boolean> {
return channel.source === 'plugin' || (await this.getActiveChannels()).includes(channel.id);
}
// ── Per-user preference checks ─────────────────────────────────────────────
@@ -112,7 +112,7 @@ export class NotificationPreferencesService {
* scope='user' — a column per channel the admin turned on in `notification_channels`.
* scope='admin' — a column per channel that has admin-global credentials.
*/
private describeChannels(userId: number, scope: 'user' | 'admin'): ChannelDescriptor[] {
private async describeChannels(userId: number, scope: 'user' | 'admin'): Promise<ChannelDescriptor[]> {
const out: ChannelDescriptor[] = [this.inAppDescriptor()];
if (scope === 'admin') {
@@ -122,7 +122,7 @@ export class NotificationPreferencesService {
const hasAdminWebhook = !!this.getAppSetting('admin_webhook_url');
const hasAdminNtfy = !!this.getAppSetting('admin_ntfy_topic');
const adminActive: Record<string, boolean> = { email: hasSmtp, webhook: hasAdminWebhook, ntfy: hasAdminNtfy };
for (const channel of listChannels()) {
for (const channel of await listChannels()) {
// Plugin channels are user-scoped only — they never carry admin-global events.
if (channel.source !== 'builtin') continue;
const active = adminActive[channel.id] ?? false;
@@ -138,7 +138,7 @@ export class NotificationPreferencesService {
return out;
}
for (const channel of listChannels()) {
for (const channel of await listChannels()) {
out.push({
id: channel.id,
source: channel.source,
@@ -147,8 +147,8 @@ export class NotificationPreferencesService {
settingsPath: channel.settingsPath,
// A live plugin channel is always a column. `configured` tells the user whether
// they still need to enter credentials — it does not hide the channel from them.
active: this.isChannelActive(channel),
configured: channel.isConfiguredFor(userId),
active: await this.isChannelActive(channel),
configured: await channel.isConfiguredFor(userId),
});
}
return out;
@@ -159,7 +159,7 @@ export class NotificationPreferencesService {
* scope='user' — excludes admin-scoped events (for user settings page)
* scope='admin' — returns only admin-scoped events (for admin notifications tab)
*/
getPreferencesMatrix(userId: number, userRole: string, scope: 'user' | 'admin' = 'user'): PreferencesMatrix {
async getPreferencesMatrix(userId: number, userRole: string, scope: 'user' | 'admin' = 'user'): Promise<PreferencesMatrix> {
const rows = this.db.all<{ event_type: string; channel: string; enabled: number }>(
'SELECT event_type, channel, enabled FROM notification_channel_preferences WHERE user_id = ?', userId,
);
@@ -171,7 +171,7 @@ export class NotificationPreferencesService {
stored[row.event_type]![row.channel] = row.enabled === 1;
}
const implemented_combos = this.allCombos();
const implemented_combos = await this.allCombos();
// Build the full matrix with defaults (true when no row exists)
const preferences: Partial<Record<NotifEventType, Partial<Record<NotifChannel, boolean>>>> = {};
@@ -195,7 +195,7 @@ export class NotificationPreferencesService {
return {
preferences,
channels: this.describeChannels(userId, scope),
channels: await this.describeChannels(userId, scope),
event_types,
implemented_combos,
...(scope === 'user' && { defaults: { ntfyServer: this.getAppSetting('admin_ntfy_server') || null } }),
@@ -304,7 +304,7 @@ export class NotificationPreferencesService {
return this.mailer.isSmtpConfigured();
}
isWebhookConfigured(): boolean {
return this.getActiveChannels().includes('webhook');
async isWebhookConfigured(): Promise<boolean> {
return (await this.getActiveChannels()).includes('webhook');
}
}
@@ -264,13 +264,13 @@ export interface NotificationPayload {
* - 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.
*/
function shouldSendToUser(
async function shouldSendToUser(
channel: ExternalChannel,
event: NotifEventType,
recipientId: number,
activeChannels: string[],
prefs: NotificationPreferencesService,
): boolean {
): Promise<boolean> {
if (!channel.supportsEvent(event)) return false;
if (channel.isInstanceConfigured && !channel.isInstanceConfigured()) return false;
@@ -285,7 +285,7 @@ function shouldSendToUser(
if (!prefs.isEnabledForEvent(recipientId, event, channel.id)) return false;
}
return channel.isConfiguredFor(recipientId);
return await channel.isConfiguredFor(recipientId);
}
/**
@@ -324,16 +324,16 @@ export class NotificationsService {
registerBuiltinChannels({ mailer, webhook, ntfy });
}
getPreferences(userId: number, role: string): PreferencesMatrix {
return this.prefs.getPreferencesMatrix(userId, role, 'user');
async getPreferences(userId: number, role: string): Promise<PreferencesMatrix> {
return await this.prefs.getPreferencesMatrix(userId, role, 'user');
}
/** Send a test notification over any registered channel (built-in or plugin). */
async testChannel(userId: number, channelId: string): Promise<ChannelTestResult> {
const channel = getChannel(channelId);
const channel = await getChannel(channelId);
if (!channel) return { success: false, error: 'Unknown channel' };
if (!channel.test) return { success: false, error: 'This channel does not support test sends' };
if (!channel.isConfiguredFor(userId)) return { success: false, error: 'Channel is not configured for this user' };
if (!(await channel.isConfiguredFor(userId))) return { success: false, error: 'Channel is not configured for this user' };
try {
return await channel.test(userId);
} catch (e) {
@@ -702,8 +702,8 @@ export class NotificationsService {
}
}
const config = configEntry ?? FALLBACK_EVENT_CONFIG;
const activeChannels = this.prefs.getActiveChannels();
const channels = listChannels();
const activeChannels = await this.prefs.getActiveChannels();
const channels = await listChannels();
const appUrl = getAppUrl();
// Build navigate target (used by email/webhook CTA and in-app navigate)
@@ -783,7 +783,12 @@ export class NotificationsService {
// One loop over the registry. The message is rendered once per recipient, in
// their language, and handed to every channel that wants it — so a plugin
// channel never touches i18n.
const deliverable = channels.filter(ch => shouldSendToUser(ch, event, recipientId, activeChannels, this.prefs));
// R1.4: `filter` cannot await, and the credential check behind shouldSendToUser
// is now async (a plugin channel reads the recipient's stored settings).
const deliverable: ExternalChannel[] = [];
for (const ch of channels) {
if (await shouldSendToUser(ch, event, recipientId, activeChannels, this.prefs)) deliverable.push(ch);
}
if (deliverable.length > 0) {
const lang = this.mailer.getUserLanguage(recipientId);
const { title, body } = getEventText(lang, event, params);