mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-01 08:53:13 +00:00
feat(server): replica_failure admin notifications — events bridge, hourly debounce, channel registration
This commit is contained in:
@@ -39,6 +39,7 @@ export type NotifEventType =
|
||||
| 'collab_message'
|
||||
| 'packing_tagged'
|
||||
| 'version_available'
|
||||
| 'replica_failure'
|
||||
| 'synology_session_cleared'
|
||||
| 'plugin_notification';
|
||||
|
||||
@@ -55,12 +56,13 @@ export const ALL_EVENT_TYPES: NotifEventType[] = [
|
||||
'collab_message',
|
||||
'packing_tagged',
|
||||
'version_available',
|
||||
'replica_failure',
|
||||
'synology_session_cleared',
|
||||
'plugin_notification',
|
||||
];
|
||||
|
||||
/** Events that target admins only (shown in admin panel, not in user settings). */
|
||||
export const ADMIN_SCOPED_EVENTS = new Set<NotifEventType>(['version_available']);
|
||||
export const ADMIN_SCOPED_EVENTS = new Set<NotifEventType>(['version_available', 'replica_failure']);
|
||||
|
||||
// Compile-time guard: shared NotificationEventKey and server NotifEventType must
|
||||
// stay in sync. It sits next to the union it guards — it used to live in the
|
||||
|
||||
@@ -4,23 +4,36 @@ import { NotificationsMcp } from './notifications.mcp';
|
||||
import { NotificationsService } from './notifications.service';
|
||||
import { NotificationPreferencesService } from './notification-preferences.service';
|
||||
import { ReminderJobsService } from './reminder-jobs.service';
|
||||
import { StorageHealthNotifierService } from './storage-health-notifier.service';
|
||||
import { NtfyService } from './transports/ntfy.service';
|
||||
import { WebhookService } from './transports/webhook.service';
|
||||
import { MailerModule } from './mailer/mailer.module';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { SchedulingModule } from '../scheduling/scheduling.module';
|
||||
import { StorageModule } from '../storage/storage.module';
|
||||
|
||||
/** Notifications domain (L6 leaf module). Registered in AppModule.
|
||||
* AuthModule feeds NotificationsMcp's demo gate; MailerModule carries SMTP,
|
||||
* which lives outside this module so AuthService can send the password-reset
|
||||
* mail without AuthModule and NotificationsModule importing each other.
|
||||
* StorageModule feeds StorageHealthNotifierService, which bridges replica
|
||||
* failures into admin notifications — this direction has no cycle (Storage
|
||||
* imports only AppConfig+Audit+Scheduling).
|
||||
* NotificationsService and NotificationPreferencesService are exported for
|
||||
* in-container consumers (AdminController's dev test send and preferences tab,
|
||||
* the plugin RPC surface, HostSurfaceRpc). */
|
||||
@Module({
|
||||
imports: [AuthModule, MailerModule, SchedulingModule],
|
||||
imports: [AuthModule, MailerModule, SchedulingModule, StorageModule],
|
||||
controllers: [NotificationsController, AdminNotificationPreferencesController],
|
||||
providers: [NotificationsService, NotificationPreferencesService, WebhookService, NtfyService, NotificationsMcp, ReminderJobsService],
|
||||
providers: [
|
||||
NotificationsService,
|
||||
NotificationPreferencesService,
|
||||
WebhookService,
|
||||
NtfyService,
|
||||
NotificationsMcp,
|
||||
ReminderJobsService,
|
||||
StorageHealthNotifierService,
|
||||
],
|
||||
exports: [NotificationsService, NotificationPreferencesService],
|
||||
})
|
||||
export class NotificationsModule {}
|
||||
|
||||
@@ -210,6 +210,13 @@ const EVENT_NOTIFICATION_CONFIG: Record<string, EventNotifConfig> = {
|
||||
navigateTextKey: 'notif.action.view_admin',
|
||||
navigateTarget: () => '/admin',
|
||||
},
|
||||
replica_failure: {
|
||||
inAppType: 'navigate',
|
||||
titleKey: 'notif.replica_failure.title',
|
||||
textKey: 'notif.replica_failure.text',
|
||||
navigateTextKey: 'notif.action.view',
|
||||
navigateTarget: () => '/admin?tab=storage',
|
||||
},
|
||||
synology_session_cleared: {
|
||||
inAppType: 'simple',
|
||||
titleKey: 'notifications.synologySessionCleared.title',
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* Lazy per-backend debounce (backfill/stats/notifications spec): the first
|
||||
* failure notifies immediately; later failures accumulate and the next one
|
||||
* past the window rides out as a summary carrying the suppressed count. No
|
||||
* timers — the summary is sent on the next failure, which is the only moment
|
||||
* anyone would care. Process-local, like the health ring itself.
|
||||
*/
|
||||
export class ReplicaFailureDebouncer {
|
||||
private readonly windows = new Map<string, { windowStart: number; suppressed: number }>();
|
||||
|
||||
constructor(
|
||||
private readonly windowMs: number,
|
||||
private readonly now: () => number = Date.now,
|
||||
) {}
|
||||
|
||||
/** null = suppress; otherwise the suppressed-count to report with this send. */
|
||||
admit(backend: string): number | null {
|
||||
const now = this.now();
|
||||
const window = this.windows.get(backend);
|
||||
if (!window || now - window.windowStart > this.windowMs) {
|
||||
const suppressed = window?.suppressed ?? 0;
|
||||
this.windows.set(backend, { windowStart: now, suppressed: 0 });
|
||||
return suppressed;
|
||||
}
|
||||
window.suppressed += 1;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { Injectable, Logger, OnApplicationBootstrap } from '@nestjs/common';
|
||||
import { StorageEventsService } from '../storage/storage-events.service';
|
||||
import { NotificationsService } from './notifications.service';
|
||||
import { ReplicaFailureDebouncer } from './replica-failure-debouncer';
|
||||
|
||||
const DEBOUNCE_WINDOW_MS = 60 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* Bridges storage replica failures into the admin notification channels.
|
||||
* Lives HERE (not in StorageModule) because NotificationsModule → AuthModule
|
||||
* → StorageModule — the reverse import would cycle. Subscribes at bootstrap;
|
||||
* the debouncer keeps an outage from becoming a notification storm.
|
||||
*/
|
||||
@Injectable()
|
||||
export class StorageHealthNotifierService implements OnApplicationBootstrap {
|
||||
private readonly logger = new Logger(StorageHealthNotifierService.name);
|
||||
private readonly debouncer = new ReplicaFailureDebouncer(DEBOUNCE_WINDOW_MS);
|
||||
|
||||
constructor(
|
||||
private readonly events: StorageEventsService,
|
||||
private readonly notifications: NotificationsService,
|
||||
) {}
|
||||
|
||||
onApplicationBootstrap(): void {
|
||||
this.events.onReplicaFailure((failure) => {
|
||||
const suppressed = this.debouncer.admit(failure.backend);
|
||||
if (suppressed === null) return;
|
||||
void this.notifications
|
||||
.send({
|
||||
event: 'replica_failure',
|
||||
actorId: null,
|
||||
scope: 'admin',
|
||||
targetId: 0,
|
||||
params: {
|
||||
backend: failure.backend,
|
||||
key: failure.key,
|
||||
op: failure.op,
|
||||
error: failure.error,
|
||||
suppressed: String(suppressed),
|
||||
},
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
this.logger.error(
|
||||
`replica_failure notification failed: ${err instanceof Error ? err.message : String(err)}`,
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,7 @@ const NTFY_EVENT_META: Partial<Record<NotifEventType, { priority: 1 | 2 | 3 | 4
|
||||
collab_message: { priority: 3, tags: ['speech_balloon'] },
|
||||
packing_tagged: { priority: 3, tags: ['luggage'] },
|
||||
version_available: { priority: 4, tags: ['package'] },
|
||||
replica_failure: { priority: 5, tags: ['warning', 'floppy_disk'] },
|
||||
synology_session_cleared: { priority: 3, tags: ['warning'] },
|
||||
};
|
||||
const NTFY_DEFAULT_META = { priority: 3 as const, tags: [] as string[] };
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { ReplicaFailureDebouncer } from '../../../../src/nest/notifications/replica-failure-debouncer';
|
||||
|
||||
const HOUR = 60 * 60 * 1000;
|
||||
|
||||
describe('ReplicaFailureDebouncer', () => {
|
||||
it('DEB-001 first failure per backend is admitted with suppressed=0', () => {
|
||||
let now = 1_000_000;
|
||||
const debouncer = new ReplicaFailureDebouncer(HOUR, () => now);
|
||||
expect(debouncer.admit('s3-bkp')).toBe(0);
|
||||
});
|
||||
|
||||
it('DEB-002 failures inside the window are suppressed; the next one after it carries the count', () => {
|
||||
let now = 1_000_000;
|
||||
const debouncer = new ReplicaFailureDebouncer(HOUR, () => now);
|
||||
expect(debouncer.admit('s3-bkp')).toBe(0);
|
||||
now += 1000;
|
||||
expect(debouncer.admit('s3-bkp')).toBeNull();
|
||||
expect(debouncer.admit('s3-bkp')).toBeNull();
|
||||
now += HOUR;
|
||||
expect(debouncer.admit('s3-bkp')).toBe(2); // the two suppressed ones ride the summary
|
||||
now += 1000;
|
||||
expect(debouncer.admit('s3-bkp')).toBeNull(); // window reset
|
||||
});
|
||||
|
||||
it('DEB-003 backends debounce independently', () => {
|
||||
let now = 1_000_000;
|
||||
const debouncer = new ReplicaFailureDebouncer(HOUR, () => now);
|
||||
expect(debouncer.admit('a')).toBe(0);
|
||||
expect(debouncer.admit('b')).toBe(0);
|
||||
expect(debouncer.admit('a')).toBeNull();
|
||||
expect(debouncer.admit('b')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { StorageEventsService } from '../../../../src/nest/storage/storage-events.service';
|
||||
import { StorageHealthNotifierService } from '../../../../src/nest/notifications/storage-health-notifier.service';
|
||||
import type { NotificationsService } from '../../../../src/nest/notifications/notifications.service';
|
||||
|
||||
describe('StorageHealthNotifierService', () => {
|
||||
it('NOTIF-001 subscribes on bootstrap and sends an admin-scoped replica_failure with params', () => {
|
||||
const events = new StorageEventsService();
|
||||
const send = vi.fn().mockResolvedValue(undefined);
|
||||
const notifier = new StorageHealthNotifierService(events, { send } as unknown as NotificationsService);
|
||||
notifier.onApplicationBootstrap();
|
||||
events.emitReplicaFailure({ backend: 's3-bkp', key: 'backups/db.zip', op: 'put', error: 'timeout', at: 1 });
|
||||
expect(send).toHaveBeenCalledWith({
|
||||
event: 'replica_failure',
|
||||
actorId: null,
|
||||
scope: 'admin',
|
||||
targetId: 0,
|
||||
params: { backend: 's3-bkp', key: 'backups/db.zip', op: 'put', error: 'timeout', suppressed: '0' },
|
||||
});
|
||||
// Second failure inside the window: suppressed, no second send.
|
||||
events.emitReplicaFailure({ backend: 's3-bkp', key: 'backups/x.zip', op: 'put', error: 'timeout', at: 2 });
|
||||
expect(send).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('NOTIF-002 a rejected send never throws into the emitter (write path stays safe)', () => {
|
||||
const events = new StorageEventsService();
|
||||
const send = vi.fn().mockRejectedValue(new Error('smtp down'));
|
||||
const notifier = new StorageHealthNotifierService(events, { send } as unknown as NotificationsService);
|
||||
notifier.onApplicationBootstrap();
|
||||
expect(() =>
|
||||
events.emitReplicaFailure({ backend: 'b', key: 'k', op: 'delete', error: 'e', at: 3 }),
|
||||
).not.toThrow();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user