feat(notifications): P2 manager — debounce state machine + render/POST + history
Global singleton observing every account's online/offline edge: - Pure per-UIN debounce state machine (debounce.ts): an offline surviving debounceSeconds fires "offline"; recovery fires the paired "online"; a self-heal within the window fires nothing; a cold online fires nothing. - NotificationManager (manager.ts): renders each opted-in + enabled channel's body template and POSTs it (single attempt + timeout, JSON), recording the outcome in a bounded in-memory history (lost on restart). Side effects (config/channelIds/post/clock) are injected for testability. - BridgeManager: single-callback setters → additive listeners so OneBotManager and NotificationManager observe independently; close edge now carries the bridge (read nickname before dispose); fire-all with per-listener try/catch. - Wired into the composition root, bound after OneBotManager. Tests: debounce machine (pure, all misfire sequences) + manager (selectChannels, dispatch, history cap, fake-timer self-heal/pairing). 23 green, typecheck clean. Adversarial review: 0 blockers / 0 should-fix (2 NITs applied).
This commit is contained in:
@@ -5,7 +5,7 @@ import { IdentityService } from '@snowluma/protocol/identity-service';
|
||||
import { Bridge } from './bridge';
|
||||
|
||||
export type SessionStartedCallback = (uin: string, bridge: Bridge) => void;
|
||||
export type SessionClosedCallback = (uin: string) => void;
|
||||
export type SessionClosedCallback = (uin: string, bridge: Bridge) => void;
|
||||
|
||||
interface QQSession {
|
||||
bridge: Bridge;
|
||||
@@ -18,11 +18,40 @@ export class BridgeManager {
|
||||
private pidToUin_ = new Map<number, string>();
|
||||
private pidPacketClients_ = new Map<number, PacketSender>();
|
||||
|
||||
private onSessionStarted_: SessionStartedCallback | null = null;
|
||||
private onSessionClosed_: SessionClosedCallback | null = null;
|
||||
private sessionStartedListeners_: SessionStartedCallback[] = [];
|
||||
private sessionClosedListeners_: SessionClosedCallback[] = [];
|
||||
|
||||
setSessionStartedCallback(cb: SessionStartedCallback): void { this.onSessionStarted_ = cb; }
|
||||
setSessionClosedCallback(cb: SessionClosedCallback): void { this.onSessionClosed_ = cb; }
|
||||
/** Additive subscription: every observer (OneBotManager, NotificationManager,
|
||||
* …) receives every session edge. (Was a single `set*Callback` setter —
|
||||
* converted to N listeners so a second observer can't clobber the first.)
|
||||
* The close edge now carries the bridge too, since callers read the last
|
||||
* nickname before it is disposed. */
|
||||
addSessionStartedListener(cb: SessionStartedCallback): void {
|
||||
this.sessionStartedListeners_.push(cb);
|
||||
}
|
||||
addSessionClosedListener(cb: SessionClosedCallback): void {
|
||||
this.sessionClosedListeners_.push(cb);
|
||||
}
|
||||
|
||||
private fireSessionStarted(uin: string, bridge: Bridge): void {
|
||||
for (const cb of this.sessionStartedListeners_) {
|
||||
try {
|
||||
cb(uin, bridge);
|
||||
} catch (err) {
|
||||
log.warn('session-started listener threw: %s', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fireSessionClosed(uin: string, bridge: Bridge): void {
|
||||
for (const cb of this.sessionClosedListeners_) {
|
||||
try {
|
||||
cb(uin, bridge);
|
||||
} catch (err) {
|
||||
log.warn('session-closed listener threw: %s', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
onPidDisconnected(pid: number): void {
|
||||
this.pidPacketClients_.delete(pid);
|
||||
@@ -37,7 +66,8 @@ export class BridgeManager {
|
||||
if (session.bridge.empty) {
|
||||
this.sessions_.delete(uin);
|
||||
log.debug('session closed: UIN=%s', uin);
|
||||
if (this.onSessionClosed_) this.onSessionClosed_(uin);
|
||||
// Fire before dispose() so listeners can still read bridge.identity.
|
||||
this.fireSessionClosed(uin, session.bridge);
|
||||
session.bridge.dispose();
|
||||
}
|
||||
}
|
||||
@@ -59,9 +89,7 @@ export class BridgeManager {
|
||||
|
||||
if (created) {
|
||||
log.debug('session started: UIN=%s', uin);
|
||||
if (this.onSessionStarted_) {
|
||||
this.onSessionStarted_(uin, session.bridge);
|
||||
}
|
||||
this.fireSessionStarted(uin, session.bridge);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,9 +112,7 @@ export class BridgeManager {
|
||||
// Notify session started on first real packet
|
||||
if (created) {
|
||||
log.debug('session started: UIN=%s', uin);
|
||||
if (this.onSessionStarted_) {
|
||||
this.onSessionStarted_(uin, session.bridge);
|
||||
}
|
||||
this.fireSessionStarted(uin, session.bridge);
|
||||
}
|
||||
|
||||
// Dispatch packet to bridge
|
||||
|
||||
@@ -3,6 +3,7 @@ import { closeLogger, createLogger } from '@snowluma/common/logger';
|
||||
import { loadRuntimeConfig } from '@snowluma/common/runtime';
|
||||
import { OneBotManager } from '@snowluma/onebot/manager';
|
||||
import { BridgeManager } from './bridge/manager';
|
||||
import { createNotificationManager } from './notifications/manager';
|
||||
|
||||
const runtimeConfig = loadRuntimeConfig();
|
||||
const log = createLogger('App');
|
||||
@@ -36,6 +37,11 @@ async function main() {
|
||||
|
||||
oneBotManager.bind(bridgeManager);
|
||||
|
||||
// Global notification subsystem (account up/down → webhook). Bound AFTER
|
||||
// OneBotManager so the nickname fallback is already populated when it observes.
|
||||
const notificationManager = createNotificationManager();
|
||||
notificationManager.bind(bridgeManager);
|
||||
|
||||
if (
|
||||
(typeof __BUILD_WEBUI__ !== 'undefined' && __BUILD_WEBUI__) ||
|
||||
process.env.SNOWLUMA_DEV_WEBUI === '1'
|
||||
@@ -53,6 +59,7 @@ async function main() {
|
||||
const shutdown = (signal: string) => async () => {
|
||||
log.warn(`Shutting down (${signal})...`);
|
||||
oneBotManager.dispose();
|
||||
notificationManager.dispose();
|
||||
hookManager.dispose();
|
||||
await closeLogger();
|
||||
process.exit(0);
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
// Per-UIN debounce state machine for online↔offline notifications.
|
||||
//
|
||||
// Uptime-Kuma semantics (grill-locked in the plan): an offline that SURVIVES
|
||||
// `debounceSeconds` fires an "offline" notification; its later recovery fires
|
||||
// the paired "online". An offline that self-heals within the window fires
|
||||
// NOTHING (the blip is suppressed). A cold online — one with no prior fired
|
||||
// offline — fires nothing (it is not a recovery).
|
||||
//
|
||||
// This module is PURE: no timers, no I/O, no clock. It only decides; the
|
||||
// manager owns the timer + the side effects. That keeps the debounce logic
|
||||
// fully unit-testable by driving a sequence of events.
|
||||
import type { NotificationEvent } from './config';
|
||||
|
||||
export type DebounceDecision =
|
||||
| { kind: 'none' }
|
||||
| { kind: 'schedule'; delayMs: number }
|
||||
| { kind: 'cancel' }
|
||||
| { kind: 'emit'; event: NotificationEvent };
|
||||
|
||||
interface UinState {
|
||||
/** An offline debounce timer is armed but has not yet fired. */
|
||||
pending: boolean;
|
||||
/** An "offline" notification has fired and is awaiting its recovery. */
|
||||
firedOffline: boolean;
|
||||
}
|
||||
|
||||
export class DebounceMachine {
|
||||
private readonly states = new Map<string, UinState>();
|
||||
|
||||
private state(uin: string): UinState {
|
||||
let s = this.states.get(uin);
|
||||
if (!s) {
|
||||
s = { pending: false, firedOffline: false };
|
||||
this.states.set(uin, s);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/** Account went offline. `debounceSeconds` is read fresh from config so a
|
||||
* reload takes effect on the next transition. */
|
||||
onOffline(uin: string, debounceSeconds: number): DebounceDecision {
|
||||
const s = this.state(uin);
|
||||
if (s.firedOffline || s.pending) return { kind: 'none' }; // already down / already counting
|
||||
// Non-finite / non-positive → no debounce, fire immediately. Stays total:
|
||||
// never schedule a setTimeout(NaN|Infinity). Production config always
|
||||
// clamps to a finite [0,3600]; this only hardens direct callers.
|
||||
if (!Number.isFinite(debounceSeconds) || debounceSeconds <= 0) {
|
||||
s.firedOffline = true;
|
||||
return { kind: 'emit', event: 'offline' };
|
||||
}
|
||||
s.pending = true;
|
||||
return { kind: 'schedule', delayMs: debounceSeconds * 1000 };
|
||||
}
|
||||
|
||||
/** Account came online. */
|
||||
onOnline(uin: string): DebounceDecision {
|
||||
const s = this.state(uin);
|
||||
if (s.pending) {
|
||||
s.pending = false;
|
||||
return { kind: 'cancel' }; // self-heal within the debounce window — nothing fired
|
||||
}
|
||||
if (s.firedOffline) {
|
||||
s.firedOffline = false;
|
||||
return { kind: 'emit', event: 'online' }; // recovery, paired with the fired offline
|
||||
}
|
||||
return { kind: 'none' }; // cold online / already up
|
||||
}
|
||||
|
||||
/** The offline debounce window elapsed (the armed timer fired). */
|
||||
onTimerElapsed(uin: string): DebounceDecision {
|
||||
const s = this.state(uin);
|
||||
if (!s.pending) return { kind: 'none' }; // cancelled before firing
|
||||
s.pending = false;
|
||||
s.firedOffline = true;
|
||||
return { kind: 'emit', event: 'offline' };
|
||||
}
|
||||
|
||||
/** Drop a UIN's state (e.g. on dispose). */
|
||||
forget(uin: string): void {
|
||||
this.states.delete(uin);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
// The global notification subsystem: one singleton watching ALL accounts.
|
||||
//
|
||||
// Subscribes to BridgeManager session online/offline edges, runs a per-UIN
|
||||
// debounce state machine (see debounce.ts), and on a fired transition renders
|
||||
// each opted-in + enabled channel's body template and POSTs it — recording the
|
||||
// outcome in a bounded in-memory history (lost on restart, by design).
|
||||
//
|
||||
// Side-effecting collaborators (config load, per-UIN channel ids, the outbound
|
||||
// POST, the clock) are injected so the class is fully unit-testable; the real
|
||||
// wiring lives in `createNotificationManager()` at the bottom.
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { loadOneBotConfig } from '@snowluma/onebot/config';
|
||||
import type { BridgeManager } from '../bridge/manager';
|
||||
import {
|
||||
loadNotificationsConfig,
|
||||
renderTemplate,
|
||||
type NotificationChannel,
|
||||
type NotificationEvent,
|
||||
type NotificationsConfig,
|
||||
} from './config';
|
||||
import { DebounceMachine, type DebounceDecision } from './debounce';
|
||||
|
||||
const log = createLogger('Notifications');
|
||||
|
||||
const DEFAULT_HISTORY_LIMIT = 100;
|
||||
const DEFAULT_POST_TIMEOUT_MS = 10_000;
|
||||
const FALLBACK_DEBOUNCE_SECONDS = 30;
|
||||
|
||||
/** One delivery attempt; kept only in memory (the plan forbids persistence). */
|
||||
export interface DeliveryRecord {
|
||||
time: number;
|
||||
uin: string;
|
||||
event: NotificationEvent;
|
||||
channelId: string;
|
||||
ok: boolean;
|
||||
status?: number;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface PostResult {
|
||||
ok: boolean;
|
||||
status?: number;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface NotificationManagerDeps {
|
||||
/** Global channel store (channels + debounceSeconds). */
|
||||
loadConfig: () => NotificationsConfig;
|
||||
/** The channel ids a UIN has opted into. */
|
||||
loadChannelIds: (uin: string) => string[];
|
||||
/** Outbound delivery — never throws; failures come back as `{ ok: false }`. */
|
||||
post: (url: string, body: string) => Promise<PostResult>;
|
||||
now: () => number;
|
||||
historyLimit?: number;
|
||||
}
|
||||
|
||||
function errMsg(err: unknown): string {
|
||||
return err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pure: the channels a UIN should be notified through — globally enabled AND
|
||||
* opted into by the UIN — preserving config order. Exported for unit tests.
|
||||
*/
|
||||
export function selectChannels(channels: NotificationChannel[], enabledIds: string[]): NotificationChannel[] {
|
||||
const wanted = new Set(enabledIds);
|
||||
return channels.filter((c) => c.enabled && wanted.has(c.id));
|
||||
}
|
||||
|
||||
export class NotificationManager {
|
||||
private readonly deps: NotificationManagerDeps;
|
||||
private readonly machine = new DebounceMachine();
|
||||
private readonly timers = new Map<string, ReturnType<typeof setTimeout>>();
|
||||
private readonly nicknames = new Map<string, string>();
|
||||
private readonly history: DeliveryRecord[] = [];
|
||||
private readonly historyLimit: number;
|
||||
|
||||
constructor(deps: NotificationManagerDeps) {
|
||||
this.deps = deps;
|
||||
this.historyLimit = deps.historyLimit ?? DEFAULT_HISTORY_LIMIT;
|
||||
}
|
||||
|
||||
/** Subscribe to the global session online/offline edges. Register AFTER
|
||||
* OneBotManager so the nickname fallback is already populated. */
|
||||
bind(bridgeManager: BridgeManager): void {
|
||||
bridgeManager.addSessionStartedListener((uin, bridge) => this.handleOnline(uin, bridge.identity.nickname));
|
||||
bridgeManager.addSessionClosedListener((uin, bridge) => this.handleOffline(uin, bridge.identity.nickname));
|
||||
}
|
||||
|
||||
handleOnline(uin: string, nickname?: string): void {
|
||||
if (nickname) this.nicknames.set(uin, nickname);
|
||||
this.apply(uin, this.machine.onOnline(uin));
|
||||
}
|
||||
|
||||
handleOffline(uin: string, nickname?: string): void {
|
||||
if (nickname) this.nicknames.set(uin, nickname);
|
||||
this.apply(uin, this.machine.onOffline(uin, this.debounceSeconds()));
|
||||
}
|
||||
|
||||
private debounceSeconds(): number {
|
||||
try {
|
||||
return this.deps.loadConfig().debounceSeconds;
|
||||
} catch {
|
||||
return FALLBACK_DEBOUNCE_SECONDS;
|
||||
}
|
||||
}
|
||||
|
||||
private apply(uin: string, decision: DebounceDecision): void {
|
||||
switch (decision.kind) {
|
||||
case 'schedule': {
|
||||
const existing = this.timers.get(uin);
|
||||
if (existing) clearTimeout(existing);
|
||||
const timer = setTimeout(() => {
|
||||
this.timers.delete(uin);
|
||||
this.apply(uin, this.machine.onTimerElapsed(uin));
|
||||
}, decision.delayMs);
|
||||
// Don't let a pending notification timer keep the process alive.
|
||||
if (typeof (timer as { unref?: () => void }).unref === 'function') {
|
||||
(timer as { unref: () => void }).unref();
|
||||
}
|
||||
this.timers.set(uin, timer);
|
||||
break;
|
||||
}
|
||||
case 'cancel': {
|
||||
const timer = this.timers.get(uin);
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
this.timers.delete(uin);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'emit':
|
||||
void this.notify(uin, decision.event);
|
||||
break;
|
||||
case 'none':
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/** Render + POST a transition to every opted-in, enabled channel and record
|
||||
* the outcome. Never throws (a bad channel can't break the others). */
|
||||
async notify(uin: string, event: NotificationEvent): Promise<void> {
|
||||
let channels: NotificationChannel[];
|
||||
try {
|
||||
const cfg = this.deps.loadConfig();
|
||||
channels = selectChannels(cfg.channels, this.deps.loadChannelIds(uin));
|
||||
} catch (err) {
|
||||
log.warn('notify(%s, %s) skipped — config load failed: %s', uin, event, errMsg(err));
|
||||
return;
|
||||
}
|
||||
if (channels.length === 0) return;
|
||||
|
||||
const nickname = this.nicknames.get(uin) || uin;
|
||||
const vars: Record<string, string> = {
|
||||
uin,
|
||||
nickname,
|
||||
event,
|
||||
time: new Date(this.deps.now()).toISOString(),
|
||||
};
|
||||
|
||||
for (const ch of channels) {
|
||||
const body = renderTemplate(ch.bodyTemplate, vars);
|
||||
let result: PostResult;
|
||||
try {
|
||||
result = await this.deps.post(ch.url, body);
|
||||
} catch (err) {
|
||||
// The injected post is contracted not to throw, but guard anyway.
|
||||
result = { ok: false, error: errMsg(err) };
|
||||
}
|
||||
this.record({
|
||||
time: this.deps.now(),
|
||||
uin,
|
||||
event,
|
||||
channelId: ch.id,
|
||||
ok: result.ok,
|
||||
status: result.status,
|
||||
error: result.ok ? undefined : (result.error ?? (result.status ? `HTTP ${result.status}` : 'delivery failed')),
|
||||
});
|
||||
if (!result.ok) {
|
||||
log.warn('notify %s→%s channel=%s failed: %s', uin, event, ch.id, result.error ?? `HTTP ${result.status ?? '?'}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private record(rec: DeliveryRecord): void {
|
||||
this.history.push(rec);
|
||||
if (this.history.length > this.historyLimit) {
|
||||
this.history.splice(0, this.history.length - this.historyLimit);
|
||||
}
|
||||
}
|
||||
|
||||
/** Most-recent-first delivery history (capped at the buffer size). */
|
||||
getRecent(limit = this.historyLimit): DeliveryRecord[] {
|
||||
const n = Math.max(0, Math.min(Math.trunc(limit) || 0, this.history.length));
|
||||
return this.history.slice(this.history.length - n).reverse();
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
for (const timer of this.timers.values()) clearTimeout(timer);
|
||||
this.timers.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/** Default outbound POST: a single attempt with a timeout, JSON content-type
|
||||
* (the common case for 钉钉/Discord/飞书). Never throws. */
|
||||
export function createDefaultPost(timeoutMs = DEFAULT_POST_TIMEOUT_MS): NotificationManagerDeps['post'] {
|
||||
return async (url, body) => {
|
||||
try {
|
||||
const res = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body,
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
});
|
||||
return { ok: res.ok, status: res.status, error: res.ok ? undefined : `HTTP ${res.status}` };
|
||||
} catch (err) {
|
||||
return { ok: false, error: errMsg(err) };
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** The real, fully-wired singleton. */
|
||||
export function createNotificationManager(): NotificationManager {
|
||||
return new NotificationManager({
|
||||
loadConfig: loadNotificationsConfig,
|
||||
loadChannelIds: (uin) => loadOneBotConfig(uin).notifications?.channelIds ?? [],
|
||||
post: createDefaultPost(),
|
||||
now: () => Date.now(),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { DebounceMachine } from '../src/notifications/debounce';
|
||||
|
||||
describe('DebounceMachine — online↔offline debounce (Uptime-Kuma semantics)', () => {
|
||||
it('a cold online (no prior offline) fires nothing', () => {
|
||||
const m = new DebounceMachine();
|
||||
expect(m.onOnline('u')).toEqual({ kind: 'none' });
|
||||
});
|
||||
|
||||
it('an offline that self-heals within the window fires nothing', () => {
|
||||
const m = new DebounceMachine();
|
||||
expect(m.onOffline('u', 30)).toEqual({ kind: 'schedule', delayMs: 30_000 });
|
||||
expect(m.onOnline('u')).toEqual({ kind: 'cancel' });
|
||||
// back to baseline — a later offline schedules fresh
|
||||
expect(m.onOffline('u', 30)).toEqual({ kind: 'schedule', delayMs: 30_000 });
|
||||
});
|
||||
|
||||
it('an offline that survives the window fires offline, then recovery fires online (paired)', () => {
|
||||
const m = new DebounceMachine();
|
||||
expect(m.onOffline('u', 30)).toEqual({ kind: 'schedule', delayMs: 30_000 });
|
||||
expect(m.onTimerElapsed('u')).toEqual({ kind: 'emit', event: 'offline' });
|
||||
expect(m.onOnline('u')).toEqual({ kind: 'emit', event: 'online' });
|
||||
// after recovery completes, the next online is cold again
|
||||
expect(m.onOnline('u')).toEqual({ kind: 'none' });
|
||||
});
|
||||
|
||||
it('debounceSeconds<=0 fires offline immediately', () => {
|
||||
const m = new DebounceMachine();
|
||||
expect(m.onOffline('u', 0)).toEqual({ kind: 'emit', event: 'offline' });
|
||||
expect(m.onOnline('u')).toEqual({ kind: 'emit', event: 'online' });
|
||||
});
|
||||
|
||||
it('treats a non-finite debounceSeconds as no-debounce (fires immediately)', () => {
|
||||
const m = new DebounceMachine();
|
||||
expect(m.onOffline('u', Number.NaN)).toEqual({ kind: 'emit', event: 'offline' });
|
||||
});
|
||||
|
||||
it('a second offline while pending is a no-op', () => {
|
||||
const m = new DebounceMachine();
|
||||
expect(m.onOffline('u', 30)).toEqual({ kind: 'schedule', delayMs: 30_000 });
|
||||
expect(m.onOffline('u', 30)).toEqual({ kind: 'none' });
|
||||
});
|
||||
|
||||
it('a second offline after one already fired is a no-op', () => {
|
||||
const m = new DebounceMachine();
|
||||
m.onOffline('u', 0); // fires offline
|
||||
expect(m.onOffline('u', 0)).toEqual({ kind: 'none' });
|
||||
});
|
||||
|
||||
it('a timer elapsing after a cancel is a no-op (stale timer)', () => {
|
||||
const m = new DebounceMachine();
|
||||
m.onOffline('u', 30); // schedule
|
||||
m.onOnline('u'); // cancel
|
||||
expect(m.onTimerElapsed('u')).toEqual({ kind: 'none' });
|
||||
});
|
||||
|
||||
it('tracks UINs independently', () => {
|
||||
const m = new DebounceMachine();
|
||||
expect(m.onOffline('a', 0)).toEqual({ kind: 'emit', event: 'offline' });
|
||||
expect(m.onOffline('b', 30)).toEqual({ kind: 'schedule', delayMs: 30_000 });
|
||||
expect(m.onOnline('b')).toEqual({ kind: 'cancel' });
|
||||
expect(m.onOnline('a')).toEqual({ kind: 'emit', event: 'online' });
|
||||
});
|
||||
|
||||
it('forget() resets a UIN to baseline', () => {
|
||||
const m = new DebounceMachine();
|
||||
m.onOffline('u', 0); // fired offline
|
||||
m.forget('u');
|
||||
expect(m.onOnline('u')).toEqual({ kind: 'none' }); // state cleared → no recovery
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,151 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
NotificationManager,
|
||||
selectChannels,
|
||||
type NotificationManagerDeps,
|
||||
type PostResult,
|
||||
} from '../src/notifications/manager';
|
||||
import type { NotificationChannel, NotificationsConfig } from '../src/notifications/config';
|
||||
|
||||
function ch(over: Partial<NotificationChannel> = {}): NotificationChannel {
|
||||
return {
|
||||
id: 'c1',
|
||||
name: 'C1',
|
||||
url: 'https://hook.example/c1',
|
||||
bodyTemplate: '{event}:{uin}:{nickname}',
|
||||
enabled: true,
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
describe('selectChannels (pure)', () => {
|
||||
it('keeps only enabled channels the UIN opted into, in config order', () => {
|
||||
const channels = [ch({ id: 'a' }), ch({ id: 'b', enabled: false }), ch({ id: 'c' })];
|
||||
expect(selectChannels(channels, ['c', 'a', 'b']).map((c) => c.id)).toEqual(['a', 'c']);
|
||||
});
|
||||
|
||||
it('is empty when the UIN opted into nothing', () => {
|
||||
expect(selectChannels([ch({ id: 'a' })], [])).toEqual([]);
|
||||
});
|
||||
|
||||
it('ignores opted-in ids with no matching channel', () => {
|
||||
expect(selectChannels([ch({ id: 'a' })], ['ghost'])).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('NotificationManager — dispatch + history', () => {
|
||||
function setup(over: Partial<NotificationManagerDeps> = {}) {
|
||||
const posts: { url: string; body: string }[] = [];
|
||||
const cfg: NotificationsConfig = { version: 1, debounceSeconds: 30, channels: [ch()] };
|
||||
const deps: NotificationManagerDeps = {
|
||||
loadConfig: () => cfg,
|
||||
loadChannelIds: () => ['c1'],
|
||||
post: async (url, body): Promise<PostResult> => {
|
||||
posts.push({ url, body });
|
||||
return { ok: true, status: 200 };
|
||||
},
|
||||
now: () => 1000,
|
||||
...over,
|
||||
};
|
||||
return { posts, mgr: new NotificationManager(deps) };
|
||||
}
|
||||
|
||||
it('renders {event}{uin}{nickname} and posts to opted-in channels', async () => {
|
||||
const { posts, mgr } = setup();
|
||||
await mgr.notify('123', 'offline');
|
||||
// nickname falls back to the uin when none was captured
|
||||
expect(posts).toEqual([{ url: 'https://hook.example/c1', body: 'offline:123:123' }]);
|
||||
});
|
||||
|
||||
it('uses the nickname captured on an online/offline edge', async () => {
|
||||
const { posts, mgr } = setup();
|
||||
mgr.handleOnline('123', 'Alice'); // caches nickname; cold online → no post
|
||||
expect(posts).toHaveLength(0);
|
||||
await mgr.notify('123', 'offline');
|
||||
expect(posts[0].body).toBe('offline:123:Alice');
|
||||
});
|
||||
|
||||
it('records ok and failed deliveries, most-recent-first', async () => {
|
||||
let n = 0;
|
||||
const { mgr } = setup({
|
||||
post: async (): Promise<PostResult> => (++n === 1 ? { ok: true, status: 200 } : { ok: false, status: 500 }),
|
||||
});
|
||||
await mgr.notify('123', 'offline');
|
||||
await mgr.notify('123', 'online');
|
||||
const recent = mgr.getRecent();
|
||||
expect(recent).toHaveLength(2);
|
||||
expect(recent[0]).toMatchObject({ event: 'online', ok: false, status: 500 });
|
||||
expect(recent[1]).toMatchObject({ event: 'offline', ok: true, status: 200 });
|
||||
});
|
||||
|
||||
it('skips channels the UIN did not opt into', async () => {
|
||||
const { posts, mgr } = setup({ loadChannelIds: () => [] });
|
||||
await mgr.notify('123', 'offline');
|
||||
expect(posts).toEqual([]);
|
||||
});
|
||||
|
||||
it('a post that throws is captured as a failed record, not propagated', async () => {
|
||||
const { mgr } = setup({
|
||||
post: async (): Promise<PostResult> => {
|
||||
throw new Error('boom');
|
||||
},
|
||||
});
|
||||
await expect(mgr.notify('123', 'offline')).resolves.toBeUndefined();
|
||||
expect(mgr.getRecent()[0]).toMatchObject({ ok: false, error: 'boom' });
|
||||
});
|
||||
|
||||
it('caps history at the configured limit (oldest dropped)', async () => {
|
||||
const { mgr } = setup({ historyLimit: 3 });
|
||||
for (let i = 0; i < 5; i++) await mgr.notify('123', 'offline');
|
||||
expect(mgr.getRecent(99)).toHaveLength(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe('NotificationManager — debounce integration (fake timers)', () => {
|
||||
beforeEach(() => vi.useFakeTimers());
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
function setup(debounceSeconds: number) {
|
||||
const events: string[] = [];
|
||||
const deps: NotificationManagerDeps = {
|
||||
loadConfig: () => ({ version: 1, debounceSeconds, channels: [ch()] }),
|
||||
loadChannelIds: () => ['c1'],
|
||||
post: async (_url, body) => {
|
||||
events.push(body.split(':')[0]);
|
||||
return { ok: true, status: 200 };
|
||||
},
|
||||
now: () => 1000,
|
||||
};
|
||||
return { events, mgr: new NotificationManager(deps) };
|
||||
}
|
||||
|
||||
it('suppresses an offline that self-heals within the window', async () => {
|
||||
const { events, mgr } = setup(30);
|
||||
mgr.handleOnline('123', 'Bob'); // cold online
|
||||
mgr.handleOffline('123', 'Bob'); // arm 30s timer
|
||||
await vi.advanceTimersByTimeAsync(10_000);
|
||||
mgr.handleOnline('123', 'Bob'); // self-heal → cancel timer
|
||||
// The machine's state guard alone would suppress the misfire; assert the
|
||||
// manager ALSO cleared the timer (defense-in-depth a pure test can't see).
|
||||
expect((mgr as unknown as { timers: Map<string, unknown> }).timers.size).toBe(0);
|
||||
await vi.advanceTimersByTimeAsync(60_000);
|
||||
expect(events).toEqual([]);
|
||||
});
|
||||
|
||||
it('fires offline after the window, then online on recovery (paired)', async () => {
|
||||
const { events, mgr } = setup(30);
|
||||
mgr.handleOffline('123', 'Bob'); // arm
|
||||
await vi.advanceTimersByTimeAsync(30_000); // window elapses → offline fires
|
||||
expect(events).toEqual(['offline']);
|
||||
mgr.handleOnline('123', 'Bob'); // recovery
|
||||
await vi.advanceTimersByTimeAsync(0); // flush the dispatch microtasks
|
||||
expect(events).toEqual(['offline', 'online']);
|
||||
});
|
||||
|
||||
it('with debounce 0, offline fires immediately', async () => {
|
||||
const { events, mgr } = setup(0);
|
||||
mgr.handleOffline('123', 'Bob');
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(events).toEqual(['offline']);
|
||||
});
|
||||
});
|
||||
@@ -19,11 +19,11 @@ export class OneBotManager {
|
||||
private readonly instances = new Map<string, OneBotInstance>();
|
||||
|
||||
bind(bridgeManager: BridgeManager): void {
|
||||
bridgeManager.setSessionStartedCallback((uin, bridge) => {
|
||||
bridgeManager.addSessionStartedListener((uin, bridge) => {
|
||||
this.onSessionStarted(uin, bridge);
|
||||
});
|
||||
|
||||
bridgeManager.setSessionClosedCallback((uin) => {
|
||||
bridgeManager.addSessionClosedListener((uin) => {
|
||||
this.onSessionClosed(uin);
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user