feat(core): add process facts to ordered account notifications (#539)

* feat(core): carry hook process status in notifications

`offline` alone cannot tell an external supervisor whether the QQ session dropped (log back in) or the process is gone (restart the client). Resolve the hook process behind a UIN at notify time and expose `status`, `pid` and `error` as template variables; a failing lookup degrades to empty values so delivery is never blocked.

The default webhook/email templates gain a process-status line; existing channels keep their stored template untouched.

* fix(core): preserve notification lifecycle ordering and simplify state

---------

Co-authored-by: zhngzhu <[email protected]>
Co-authored-by: 手瓜一十雪 <[email protected]>
This commit is contained in:
authored and GitHub committed 2026-10-18 11:13:58 +08:00
1 parent b6d86a586d
commit 8e24995fc3
19 files changed
+616 -387

No files matched your search

+4
View File
@@ -24,6 +24,10 @@
"types": "./src/env.ts", "types": "./src/env.ts",
"default": "./src/env.ts" "default": "./src/env.ts"
}, },
"./notification-templates": {
"types": "./src/notification-templates.ts",
"default": "./src/notification-templates.ts"
},
"./single-flight-cache": { "./single-flight-cache": {
"types": "./src/single-flight-cache.ts", "types": "./src/single-flight-cache.ts",
"default": "./src/single-flight-cache.ts" "default": "./src/single-flight-cache.ts"
@@ -0,0 +1,14 @@
export const DEFAULT_WEBHOOK_BODY = `{
"title": "账号状态通知:{event}",
"desp": "您的账号状态发生了改变。\\n\\n**昵称**:{nickname}\\n**QQ号**:{uin}\\n**当前状态**:{event}\\n**进程状态**:{status}\\n**时间**:{time}"
}`;
export const DEFAULT_EMAIL_SUBJECT = '账号{event}:{nickname} ({uin})';
export const DEFAULT_EMAIL_BODY = `账号状态发生了改变。
昵称:{nickname}
QQ号:{uin}
当前状态:{event}
进程状态:{status}
时间:{time}`;
+53 -169
View File
@@ -16,19 +16,19 @@ const log = createLogger('Bridge');
const runtimeLog = createLogger('Bridge.Runtime'); const runtimeLog = createLogger('Bridge.Runtime');
const VERBOSE_WARMUP = process.env.SNOWLUMA_VERBOSE_WARMUP === '1'; const VERBOSE_WARMUP = process.env.SNOWLUMA_VERBOSE_WARMUP === '1';
interface ProcessConnection {
pid: number;
client: PacketSender;
receiveHealthy: boolean;
}
export class Bridge implements BridgeInterface { export class Bridge implements BridgeInterface {
readonly identity: IdentityService; readonly identity: IdentityService;
private pids_ = new Set<number>(); /** Insertion order tracks login recency; the newest connection sends packets. */
private readonly receiveHealthByPid_ = new Map<number, boolean>(); private readonly connections = new Map<number, ProcessConnection>();
/** Packet senders keyed by their owning QQ process. Keeping the sender and
* PID together is what makes disconnect fallback deterministic: a sender
* can never outlive the PID that supplied it. */
private readonly packetClientsByPid_ = new Map<number, PacketSender>();
readonly events = new BridgeEventBus(); readonly events = new BridgeEventBus();
readonly apis: ApiHub; readonly apis: ApiHub;
private readonly pipeline: IncomingPacketPipeline; private readonly pipeline: IncomingPacketPipeline;
private packetClient_: PacketSender | null = null;
private packetClientPid_: number | null = null;
private static readonly UPLOADED_FILE_CACHE_MAX = 1024; private static readonly UPLOADED_FILE_CACHE_MAX = 1024;
private uploadedFileMeta_ = new Map<string, UploadedFileMeta>(); private uploadedFileMeta_ = new Map<string, UploadedFileMeta>();
private clientSeq_ = 100000000 + (Date.now() % 1000000000); private clientSeq_ = 100000000 + (Date.now() % 1000000000);
@@ -40,9 +40,10 @@ export class Bridge implements BridgeInterface {
private disposePromise_: Promise<void> | null = null; private disposePromise_: Promise<void> | null = null;
private readonly pendingPackets_ = new Set<Promise<void>>(); private readonly pendingPackets_ = new Set<Promise<void>>();
private rosterWarmupStarted_ = false; private rosterWarmupStarted_ = false;
private rosterWarmupSettled_ = false; private settleRosterWarmup!: (result: RosterWarmupResult) => void;
private rosterWarmupResult_: RosterWarmupResult | null = null; private readonly rosterWarmup = new Promise<RosterWarmupResult>((resolve) => {
private readonly rosterWarmupWaiters_: Array<(result: RosterWarmupResult) => void> = []; this.settleRosterWarmup = resolve;
});
constructor(identity: IdentityService) { constructor(identity: IdentityService) {
this.identity = identity; this.identity = identity;
@@ -151,11 +152,7 @@ export class Bridge implements BridgeInterface {
this.disposed_ = true; this.disposed_ = true;
this.settleRosterWarmup({ friendsLoaded: false, groupsLoaded: false }); this.settleRosterWarmup({ friendsLoaded: false, groupsLoaded: false });
this.pids_.clear(); this.connections.clear();
this.receiveHealthByPid_.clear();
this.packetClientsByPid_.clear();
this.packetClient_ = null;
this.packetClientPid_ = null;
this.onlineClients_ = null; this.onlineClients_ = null;
this.disposePromise_ = (async () => { this.disposePromise_ = (async () => {
try { try {
@@ -168,22 +165,6 @@ export class Bridge implements BridgeInterface {
return this.disposePromise_; return this.disposePromise_;
} }
/** Legacy two-step setter retained for external compatibility. It assigns
* the sender to the most recently attached PID when one exists. New
* BridgeManager code uses bindPid() for an atomic transition. */
setPacketClient(client: PacketSender): void {
this.packetClient_ = client;
const pids = [...this.pids_];
const pid = pids.length > 0 ? pids[pids.length - 1]! : null;
this.packetClientPid_ = pid;
if (pid !== null) {
this.packetClientsByPid_.set(pid, client);
}
this.maybeStartRosterWarmup();
}
registerCmd(cmd: string, parser: CmdParser): void { registerCmd(cmd: string, parser: CmdParser): void {
this.pipeline.registerCmd(cmd, parser); this.pipeline.registerCmd(cmd, parser);
} }
@@ -192,34 +173,18 @@ export class Bridge implements BridgeInterface {
return this.pipeline.handlesCmd(cmd); return this.pipeline.handlesCmd(cmd);
} }
/** Attach a process without a sender. Retained for compatibility; the
* manager uses bindPid() for the atomic PID+sender transition. Re-attaching
* deliberately refreshes recency. */
attachPid(pid: number): void {
this.pids_.delete(pid);
this.pids_.add(pid);
// A fresh/rebound login starts UNKNOWN-but-compatible. The receive
// watchdog only flips this false after observing QQ's own heartbeat and
// then missing the full stale + confirmation window.
this.receiveHealthByPid_.set(pid, true);
}
/** Atomically attach a process and make its sender the active sender.
* Set insertion order is the recency order used for fallback. */
bindPid(pid: number, client: PacketSender): void { bindPid(pid: number, client: PacketSender): void {
const previousPid = this.packetClientPid_; const previous = this.activeConnection;
const previousClient = this.packetClient_; this.connections.delete(pid);
this.attachPid(pid); // A new login stays healthy until the watchdog confirms a failure.
this.packetClientsByPid_.set(pid, client); this.connections.set(pid, { pid, client, receiveHealthy: true });
this.packetClient_ = client;
this.packetClientPid_ = pid;
if (previousPid !== pid || previousClient !== client) { if (previous?.pid !== pid || previous.client !== client) {
runtimeLog.trace( runtimeLog.trace(
'bridge_sender_fact event=selected uin=%j pid=%d previousPid=%j', 'bridge_sender_fact event=selected uin=%j pid=%d previousPid=%j',
this.identity.uin, this.identity.uin,
pid, pid,
previousPid, previous?.pid ?? null,
); );
} }
@@ -229,84 +194,59 @@ export class Bridge implements BridgeInterface {
/** @internal BridgeManager lookup used when an incoming packet is the first /** @internal BridgeManager lookup used when an incoming packet is the first
* observation that a live PID changed UIN. */ * observation that a live PID changed UIN. */
packetClientForPid(pid: number): PacketSender | null { packetClientForPid(pid: number): PacketSender | null {
return this.packetClientsByPid_.get(pid) ?? null; return this.connections.get(pid)?.client ?? null;
} }
detachPid(pid: number): void { detachPid(pid: number): void {
this.pids_.delete(pid); const wasActive = this.activePid === pid;
this.receiveHealthByPid_.delete(pid); this.connections.delete(pid);
this.packetClientsByPid_.delete(pid); const active = this.activeConnection;
if (this.packetClientPid_ !== pid) { if (wasActive && active) {
// An unscoped legacy sender cannot be associated with a particular PID. runtimeLog.trace(
// It is safe to retain while another PID exists, but never after the 'bridge_sender_fact event=fallback uin=%j detachedPid=%d fallbackPid=%d',
// Bridge becomes empty. this.identity.uin,
if (this.pids_.size === 0) { pid,
this.packetClient_ = null; active.pid,
this.packetClientPid_ = null; );
} log.debug(
'packet sender changed: UIN=%s PID=%d→%d',
return; this.identity.uin,
pid,
active.pid,
);
} }
this.selectFallbackPacketClient(pid);
} }
hasPid(pid: number): boolean { hasPid(pid: number): boolean {
return this.pids_.has(pid); return this.connections.has(pid);
} }
get empty(): boolean { get empty(): boolean {
return this.pids_.size === 0; return this.connections.size === 0;
}
private get activeConnection(): ProcessConnection | undefined {
return [...this.connections.values()].at(-1);
} }
get activePid(): number | null { get activePid(): number | null {
if (this.packetClientPid_ !== null && this.pids_.has(this.packetClientPid_)) { return this.activeConnection?.pid ?? null;
return this.packetClientPid_;
}
const pids = [...this.pids_];
return pids.length > 0 ? pids[pids.length - 1]! : null;
} }
get receiveHealthy(): boolean { get receiveHealthy(): boolean {
for (const pid of this.pids_) { return [...this.connections.values()].some((connection) => connection.receiveHealthy);
const healthy = this.receiveHealthByPid_.get(pid);
if (healthy === undefined) {
const message = `Bridge receive-health invariant violated: PID=${pid} has no health state`;
log.error(message);
throw new Error(message);
}
if (healthy) {
return true;
}
}
return false;
} }
setPidReceiveHealthy(pid: number, healthy: boolean): void { setPidReceiveHealthy(pid: number, healthy: boolean): void {
if (!this.pids_.has(pid)) { const connection = this.connections.get(pid);
if (!connection) {
throw new Error(`Bridge receive-health invariant violated: PID=${pid} is not attached`); throw new Error(`Bridge receive-health invariant violated: PID=${pid} is not attached`);
} }
this.receiveHealthByPid_.set(pid, healthy); connection.receiveHealthy = healthy;
} }
getOnlineClients(): readonly Readonly<OnlineDeviceInfo>[] | null { getOnlineClients(): readonly Readonly<OnlineDeviceInfo>[] | null {
return this.onlineClients_; return this.onlineClients_;
} }
whenRosterWarmupSettled(): Promise<RosterWarmupResult> { whenRosterWarmupSettled(): Promise<RosterWarmupResult> {
if (this.rosterWarmupSettled_ && this.rosterWarmupResult_) { return this.rosterWarmup;
return Promise.resolve(this.rosterWarmupResult_);
}
this.maybeStartRosterWarmup();
return new Promise((resolve) => {
if (this.rosterWarmupSettled_ && this.rosterWarmupResult_) {
resolve(this.rosterWarmupResult_);
return;
}
this.rosterWarmupWaiters_.push(resolve);
});
} }
onPacket(pkt: PacketInfo): Promise<void> { onPacket(pkt: PacketInfo): Promise<void> {
@@ -358,7 +298,9 @@ export class Bridge implements BridgeInterface {
body: Uint8Array, body: Uint8Array,
timeoutMs = packetTimeoutMs(), timeoutMs = packetTimeoutMs(),
): Promise<SendPacketResult> { ): Promise<SendPacketResult> {
if (!this.packetClient_) { const connection = this.activeConnection;
if (!connection) {
return runWithTraceRequest(() => { return runWithTraceRequest(() => {
const startedAt = Date.now(); const startedAt = Date.now();
runtimeLog.trace(() => [ runtimeLog.trace(() => [
@@ -391,11 +333,7 @@ export class Bridge implements BridgeInterface {
} }
const startedAt = Date.now(); const startedAt = Date.now();
const result = await this.packetClient_.sendPacket( const result = await connection.client.sendPacket(serviceCmd, Buffer.from(body), timeoutMs);
serviceCmd,
Buffer.from(body),
timeoutMs,
);
const elapsed = Date.now() - startedAt; const elapsed = Date.now() - startedAt;
const respLen = result.responseData ? result.responseData.length : 0; const respLen = result.responseData ? result.responseData.length : 0;
@@ -424,52 +362,12 @@ export class Bridge implements BridgeInterface {
return result; return result;
} }
private selectFallbackPacketClient(detachedPid: number): void {
const pids = [...this.pids_];
for (let index = pids.length - 1; index >= 0; index -= 1) {
const fallbackPid = pids[index]!;
const fallback = this.packetClientsByPid_.get(fallbackPid);
if (!fallback) {
continue;
}
this.packetClient_ = fallback;
this.packetClientPid_ = fallbackPid;
runtimeLog.trace(
'bridge_sender_fact event=fallback uin=%j detachedPid=%d fallbackPid=%d',
this.identity.uin,
detachedPid,
fallbackPid,
);
log.debug(
'packet sender fallback: UIN=%s detached PID=%d fallback PID=%d',
this.identity.uin,
detachedPid,
fallbackPid,
);
return;
}
this.packetClient_ = null;
this.packetClientPid_ = null;
if (this.pids_.size > 0) {
log.warn(
'packet sender unavailable after PID detach: UIN=%s detached PID=%d remaining PIDs=%d',
this.identity.uin,
detachedPid,
this.pids_.size,
);
}
}
async resolveUserUid(uin: number, groupId?: number): Promise<string> { async resolveUserUid(uin: number, groupId?: number): Promise<string> {
return this.identity.resolveUid(uin, groupId); return this.identity.resolveUid(uin, groupId);
} }
private maybeStartRosterWarmup(): void { private maybeStartRosterWarmup(): void {
if (this.disposed_ || this.rosterWarmupStarted_ || !this.packetClient_) { if (this.disposed_ || this.rosterWarmupStarted_ || this.empty) {
return; return;
} }
@@ -495,20 +393,6 @@ export class Bridge implements BridgeInterface {
); );
} }
private settleRosterWarmup(result: RosterWarmupResult): void {
if (this.rosterWarmupSettled_) {
return;
}
this.rosterWarmupSettled_ = true;
this.rosterWarmupResult_ = result;
const waiters = this.rosterWarmupWaiters_.splice(0);
for (const resolve of waiters) {
resolve(result);
}
}
private stillOpen(): boolean { private stillOpen(): boolean {
return !this.disposed_; return !this.disposed_;
} }
+6 -12
View File
@@ -6,7 +6,7 @@ import { IdentityService } from '@snowluma/protocol/identity-service';
import { Bridge } from './bridge'; import { Bridge } from './bridge';
export type SessionStartedCallback = (uin: string, bridge: Bridge) => void; export type SessionStartedCallback = (uin: string, bridge: Bridge) => void;
export type SessionClosedCallback = (uin: string, bridge: Bridge) => void; export type SessionClosedCallback = (uin: string, bridge: Bridge, pid: number) => void;
interface QQSession { interface QQSession {
bridge: Bridge; bridge: Bridge;
@@ -64,8 +64,8 @@ export class BridgeManager {
/** Additive subscription: every observer (OneBotManager, NotificationManager, /** Additive subscription: every observer (OneBotManager, NotificationManager,
* …) receives every session edge. (Was a single `set*Callback` setter — * …) receives every session edge. (Was a single `set*Callback` setter —
* converted to N listeners so a second observer can't clobber the first.) * 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 * The close edge carries the final detached PID and the bridge so observers
* nickname before it is disposed. */ * can identify the process and read its nickname before disposal. */
addSessionStartedListener(cb: SessionStartedCallback): void { addSessionStartedListener(cb: SessionStartedCallback): void {
this.sessionStartedListeners_.push(cb); this.sessionStartedListeners_.push(cb);
} }
@@ -86,10 +86,10 @@ export class BridgeManager {
} }
} }
private fireSessionClosed(uin: string, bridge: Bridge): void { private fireSessionClosed(uin: string, bridge: Bridge, pid: number): void {
for (const cb of this.sessionClosedListeners_) { for (const cb of this.sessionClosedListeners_) {
try { try {
cb(uin, bridge); cb(uin, bridge, pid);
} catch (err) { } catch (err) {
log.warn( log.warn(
'session-closed listener threw: %s', 'session-closed listener threw: %s',
@@ -397,12 +397,6 @@ export class BridgeManager {
throw new Error(message); throw new Error(message);
} }
if (!session.bridge.packetClientForPid(pid)) {
const message = `BridgeManager invariant violated: PID=${pid} is mapped to UIN=${uin}, but Bridge has no sender for the PID`;
log.error(message);
throw new Error(message);
}
// Validation is complete. Mutate both sides only after the ownership // Validation is complete. Mutate both sides only after the ownership
// invariant is known to hold, so a fail-fast error preserves the evidence. // invariant is known to hold, so a fail-fast error preserves the evidence.
this.pidToUin_.delete(pid); this.pidToUin_.delete(pid);
@@ -415,7 +409,7 @@ export class BridgeManager {
this.sessions_.delete(uin); this.sessions_.delete(uin);
log.debug('session closed: UIN=%s', uin); log.debug('session closed: UIN=%s', uin);
// Fire before dispose() so listeners can still read bridge.identity. // Fire before dispose() so listeners can still read bridge.identity.
this.fireSessionClosed(uin, session.bridge); this.fireSessionClosed(uin, session.bridge, pid);
this.closeSession(uin, session.bridge); this.closeSession(uin, session.bridge);
return true; return true;
} }
+8 -1
View File
@@ -91,7 +91,14 @@ async function main() {
// Global notification subsystem (account up/down → webhook). Bound AFTER // Global notification subsystem (account up/down → webhook). Bound AFTER
// OneBotManager so the nickname fallback is already populated when it observes. // OneBotManager so the nickname fallback is already populated when it observes.
const notificationManager = createNotificationManager(); // Lifecycle events identify their PID; an older process with the same UIN
// must not supply facts for a recovered account.
const notificationManager = createNotificationManager(async (uin, pid) => {
const found = (await hookManager.listProcesses()).find(
(p) => p.pid === pid && p.uin === uin,
);
return found ? { status: found.status, pid: found.pid, error: found.error } : undefined;
});
notificationManager.bind(bridgeManager); notificationManager.bind(bridgeManager);
let stopWebUI: (() => Promise<void>) | undefined; let stopWebUI: (() => Promise<void>) | undefined;
+10 -30
View File
@@ -1,14 +1,11 @@
// Global notification-channel store + the pure template renderer. // Global channels are selected per account by OneBotConfig.notifications.channelIds.
//
// Mirrors the conventions of `webui/ui-config.ts` (the plan calls for this
// explicitly): every `normalize*` is TOTAL — any unknown / corrupt input
// collapses to a safe default, numbers clamp, unknown keys are dropped — and
// persistence is an atomic write (tmp → rename) behind a module-level cache.
//
// Channels are GLOBAL (defined once here); each UIN opts into a subset via
// `OneBotConfig.notifications.channelIds` (see packages/onebot/src/config.ts).
import { boolOr, clampInt, isObject } from '@snowluma/common/coerce'; import { boolOr, clampInt, isObject } from '@snowluma/common/coerce';
import { createLogger } from '@snowluma/common/logger'; import { createLogger } from '@snowluma/common/logger';
import {
DEFAULT_WEBHOOK_BODY,
DEFAULT_EMAIL_BODY,
DEFAULT_EMAIL_SUBJECT,
} from '@snowluma/common/notification-templates';
import fs from 'fs'; import fs from 'fs';
import path from 'path'; import path from 'path';
import { extractAddress, parseRecipients } from './smtp'; import { extractAddress, parseRecipients } from './smtp';
@@ -79,23 +76,6 @@ export interface NotificationsConfig {
channels: NotificationChannel[]; channels: NotificationChannel[];
} }
/** Default body template — Server酱-style JSON ({title}/{desp}). The WebUI
* ships additional per-vendor presets (钉钉/Discord/…) as frontend constants
* the operator can drop in. */
export const DEFAULT_BODY_TEMPLATE = `{
"title": "账号状态通知:{event}",
"desp": "您的账号状态发生了改变。\\n\\n**昵称**:{nickname}\\n**QQ号**:{uin}\\n**当前状态**:{event}\\n**时间**:{time}"
}`;
export const DEFAULT_SUBJECT_TEMPLATE = '账号{event}:{nickname} ({uin})';
export const DEFAULT_EMAIL_BODY_TEMPLATE = `账号状态发生了改变。
昵称:{nickname}
QQ号:{uin}
当前状态:{event}
时间:{time}`;
const SMTP_HOST_MAX = 253; const SMTP_HOST_MAX = 253;
const SMTP_USER_MAX = 256; const SMTP_USER_MAX = 256;
const SMTP_PASS_MAX = 256; const SMTP_PASS_MAX = 256;
@@ -315,7 +295,7 @@ function normalizeEmailChannel(
name, name,
type: 'email', type: 'email',
url: '', url: '',
bodyTemplate: strOr(raw.bodyTemplate, DEFAULT_EMAIL_BODY_TEMPLATE, BODY_TEMPLATE_MAX), bodyTemplate: strOr(raw.bodyTemplate, DEFAULT_EMAIL_BODY, BODY_TEMPLATE_MAX),
enabled: boolOr(raw.enabled, true), enabled: boolOr(raw.enabled, true),
smtpHost, smtpHost,
smtpPort, smtpPort,
@@ -325,8 +305,8 @@ function normalizeEmailChannel(
from, from,
to, to,
subjectTemplate: subjectTemplate:
strOr(raw.subjectTemplate, DEFAULT_SUBJECT_TEMPLATE, SUBJECT_TEMPLATE_MAX) || strOr(raw.subjectTemplate, DEFAULT_EMAIL_SUBJECT, SUBJECT_TEMPLATE_MAX) ||
DEFAULT_SUBJECT_TEMPLATE, DEFAULT_EMAIL_SUBJECT,
}; };
} }
@@ -368,7 +348,7 @@ function normalizeChannel(raw: unknown): NotificationChannel | null {
name, name,
type: 'webhook', type: 'webhook',
url, url,
bodyTemplate: strOr(raw.bodyTemplate, DEFAULT_BODY_TEMPLATE, BODY_TEMPLATE_MAX), bodyTemplate: strOr(raw.bodyTemplate, DEFAULT_WEBHOOK_BODY, BODY_TEMPLATE_MAX),
enabled: boolOr(raw.enabled, true), enabled: boolOr(raw.enabled, true),
...(headers ? { headers } : {}), ...(headers ? { headers } : {}),
}; };
+17 -58
View File
@@ -1,14 +1,5 @@
// Per-UIN debounce state machine for online↔offline notifications. // Offline must survive the debounce window before it can emit a recovery pair.
// // The manager owns timers and delivery; this machine only decides transitions.
// 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'; import type { NotificationEvent } from './config';
export type DebounceDecision = export type DebounceDecision =
@@ -17,80 +8,48 @@ export type DebounceDecision =
| { kind: 'cancel' } | { kind: 'cancel' }
| { kind: 'emit'; event: NotificationEvent }; | { 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 { export class DebounceMachine {
private readonly states = new Map<string, UinState>(); private readonly states = new Map<string, 'pending' | 'offline'>();
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 /** Account went offline. `debounceSeconds` is read fresh from config so a
* reload takes effect on the next transition. */ * reload takes effect on the next transition. */
onOffline(uin: string, debounceSeconds: number): DebounceDecision { onOffline(uin: string, debounceSeconds: number): DebounceDecision {
const s = this.state(uin); if (this.states.has(uin)) {
if (s.firedOffline || s.pending) {
return { kind: 'none' }; 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) { if (!Number.isFinite(debounceSeconds) || debounceSeconds <= 0) {
s.firedOffline = true; this.states.set(uin, 'offline');
return { kind: 'emit', event: 'offline' }; return { kind: 'emit', event: 'offline' };
} }
s.pending = true; this.states.set(uin, 'pending');
return { kind: 'schedule', delayMs: debounceSeconds * 1000 }; return { kind: 'schedule', delayMs: debounceSeconds * 1000 };
} }
/** Account came online. */ /** Account came online. */
onOnline(uin: string): DebounceDecision { onOnline(uin: string): DebounceDecision {
const s = this.state(uin); const state = this.states.get(uin);
this.states.delete(uin);
if (s.pending) { if (state === 'pending') {
s.pending = false; return { kind: 'cancel' };
return { kind: 'cancel' }; // self-heal within the debounce window — nothing fired
} }
if (s.firedOffline) { if (state === 'offline') {
s.firedOffline = false; return { kind: 'emit', event: 'online' };
return { kind: 'emit', event: 'online' }; // recovery, paired with the fired offline
} }
return { kind: 'none' }; // cold online / already up return { kind: 'none' };
} }
/** The offline debounce window elapsed (the armed timer fired). */ /** The offline debounce window elapsed (the armed timer fired). */
onTimerElapsed(uin: string): DebounceDecision { onTimerElapsed(uin: string): DebounceDecision {
const s = this.state(uin); if (this.states.get(uin) !== 'pending') {
if (!s.pending) {
return { kind: 'none' }; return { kind: 'none' };
} // cancelled before firing }
s.pending = false; this.states.set(uin, 'offline');
s.firedOffline = true;
return { kind: 'emit', event: 'offline' }; return { kind: 'emit', event: 'offline' };
} }
/** Drop a UIN's state (e.g. on dispose). */
forget(uin: string): void {
this.states.delete(uin);
}
} }
+106 -47
View File
@@ -9,6 +9,7 @@
// SMTP send, the clock) are injected so the class is fully unit-testable; the // SMTP send, the clock) are injected so the class is fully unit-testable; the
// real wiring lives in `createNotificationManager()` at the bottom. // real wiring lives in `createNotificationManager()` at the bottom.
import { positiveIntEnv } from '@snowluma/common/env'; import { positiveIntEnv } from '@snowluma/common/env';
import type { HookProcessInfo } from '@snowluma/bridge/types';
import { createLogger } from '@snowluma/common/logger'; import { createLogger } from '@snowluma/common/logger';
import { loadOneBotConfig } from '@snowluma/onebot/config'; import { loadOneBotConfig } from '@snowluma/onebot/config';
import type { BridgeManager } from '../bridge/manager'; import type { BridgeManager } from '../bridge/manager';
@@ -27,9 +28,8 @@ const log = createLogger('Notifications');
const DEFAULT_HISTORY_LIMIT = 100; const DEFAULT_HISTORY_LIMIT = 100;
const DEFAULT_POST_TIMEOUT_MS = 10_000; const DEFAULT_POST_TIMEOUT_MS = 10_000;
const FALLBACK_DEBOUNCE_SECONDS = 30;
/** One delivery attempt; kept only in memory (the plan forbids persistence). */ /** One delivery attempt, retained in bounded in-memory history. */
export interface DeliveryRecord { export interface DeliveryRecord {
time: number; time: number;
uin: string; uin: string;
@@ -58,17 +58,39 @@ export interface MailPayload {
text: string; text: string;
} }
/**
* Optional hook process snapshot attached to a notification. Missing facts
* mean unknown, not proof that QQ exited. Hook status describes connectivity;
* it does not by itself identify the reason an account went offline.
* Undefined fields render empty in templates.
*/
export type NotificationProcessFacts = Partial<Pick<HookProcessInfo, 'status' | 'pid' | 'error'>>;
export interface NotificationManagerDeps { export interface NotificationManagerDeps {
/** Global channel store (channels + debounceSeconds). */ /** Global channel store (channels + debounceSeconds). */
loadConfig: () => NotificationsConfig; loadConfig: () => NotificationsConfig;
/** The channel ids a UIN has opted into. */ /** The channel ids a UIN has opted into. */
loadChannelIds: (uin: string) => string[]; loadChannelIds: (uin: string) => string[];
/** Webhook delivery — never throws; failures come back as `{ ok: false }`. */ /** Webhook delivery. Rejections are recorded as failed attempts. */
post: (url: string, body: string, headers?: Record<string, string>) => Promise<PostResult>; post: (url: string, body: string, headers?: Record<string, string>) => Promise<PostResult>;
/** SMTP delivery — optional so webhook-only tests stay lean. */ /** SMTP delivery — optional so webhook-only tests stay lean. */
sendMail?: (mail: MailPayload) => Promise<PostResult>; sendMail?: (mail: MailPayload) => Promise<PostResult>;
now: () => number; now: () => number;
historyLimit?: number; historyLimit?: number;
/**
* Optional: look up the lifecycle event's PID and UIN at dispatch time. Omitted
* (or resolving to `undefined`) means "process unknown" — the fact
* variables then render empty rather than leaving `{status}` in the body.
*/
resolveProcess?: (
uin: string,
pid: number | null,
) => Promise<NotificationProcessFacts | undefined>;
}
interface AccountNotificationContext {
nickname: string;
pid: number | null;
} }
function errMsg(err: unknown): string { function errMsg(err: unknown): string {
@@ -91,8 +113,9 @@ export class NotificationManager {
private readonly deps: NotificationManagerDeps; private readonly deps: NotificationManagerDeps;
private readonly machine = new DebounceMachine(); private readonly machine = new DebounceMachine();
private readonly timers = new Map<string, ReturnType<typeof setTimeout>>(); private readonly timers = new Map<string, ReturnType<typeof setTimeout>>();
private readonly nicknames = new Map<string, string>(); private readonly accounts = new Map<string, AccountNotificationContext>();
private readonly history: DeliveryRecord[] = []; private readonly history: DeliveryRecord[] = [];
private readonly deliveries = new Map<string, Promise<void>>();
private readonly historyLimit: number; private readonly historyLimit: number;
private disposed = false; private disposed = false;
@@ -105,76 +128,65 @@ export class NotificationManager {
* OneBotManager so the nickname fallback is already populated. */ * OneBotManager so the nickname fallback is already populated. */
bind(bridgeManager: BridgeManager): void { bind(bridgeManager: BridgeManager): void {
bridgeManager.addSessionStartedListener((uin, bridge) => bridgeManager.addSessionStartedListener((uin, bridge) =>
this.handleOnline(uin, bridge.identity.nickname), this.handleOnline(uin, bridge.identity.nickname, bridge.activePid),
); );
bridgeManager.addSessionClosedListener((uin, bridge) => bridgeManager.addSessionClosedListener((uin, bridge, pid) =>
this.handleOffline(uin, bridge.identity.nickname), this.handleOffline(uin, bridge.identity.nickname, pid),
); );
} }
handleOnline(uin: string, nickname?: string): void { handleOnline(uin: string, nickname?: string, pid: number | null = null): void {
if (this.disposed) { if (this.disposed) {
return; return;
} }
if (nickname) { this.accounts.set(uin, {
this.nicknames.set(uin, nickname); nickname: nickname || this.accounts.get(uin)?.nickname || uin,
} pid,
});
this.apply(uin, this.machine.onOnline(uin)); this.apply(uin, this.machine.onOnline(uin));
} }
handleOffline(uin: string, nickname?: string): void { handleOffline(uin: string, nickname?: string, pid: number | null = null): void {
if (this.disposed) { if (this.disposed) {
return; return;
} }
if (nickname) { let debounceSeconds: number;
this.nicknames.set(uin, nickname);
}
this.apply(uin, this.machine.onOffline(uin, this.debounceSeconds()));
}
private debounceSeconds(): number {
try { try {
return this.deps.loadConfig().debounceSeconds; debounceSeconds = this.deps.loadConfig().debounceSeconds;
} catch { } catch (err) {
return FALLBACK_DEBOUNCE_SECONDS; log.warn('offline(%s) skipped — config load failed: %s', uin, errMsg(err));
return;
} }
this.accounts.set(uin, {
nickname: nickname || this.accounts.get(uin)?.nickname || uin,
pid,
});
this.apply(uin, this.machine.onOffline(uin, debounceSeconds));
} }
private apply(uin: string, decision: DebounceDecision): void { private apply(uin: string, decision: DebounceDecision): void {
switch (decision.kind) { switch (decision.kind) {
case 'schedule': { case 'schedule': {
const existing = this.timers.get(uin);
if (existing) {
clearTimeout(existing);
}
const timer = setTimeout(() => { const timer = setTimeout(() => {
this.timers.delete(uin); this.timers.delete(uin);
this.apply(uin, this.machine.onTimerElapsed(uin)); this.apply(uin, this.machine.onTimerElapsed(uin));
}, decision.delayMs); }, decision.delayMs);
// Don't let a pending notification timer keep the process alive. // Don't let a pending notification timer keep the process alive.
if (typeof (timer as { unref?: () => void }).unref === 'function') { timer.unref();
(timer as { unref: () => void }).unref();
}
this.timers.set(uin, timer); this.timers.set(uin, timer);
break; break;
} }
case 'cancel': { case 'cancel': {
const timer = this.timers.get(uin); clearTimeout(this.timers.get(uin));
this.timers.delete(uin);
if (timer) {
clearTimeout(timer);
this.timers.delete(uin);
}
break; break;
} }
@@ -186,9 +198,36 @@ export class NotificationManager {
} }
} }
/** Render + deliver a transition to every opted-in, enabled channel and record /** Queue one transition; channel failures are recorded independently. */
* the outcome. Never throws (a bad channel can't break the others). */ notify(uin: string, event: NotificationEvent): Promise<void> {
async notify(uin: string, event: NotificationEvent): Promise<void> { if (this.disposed) {
return Promise.resolve();
}
const account = this.accounts.get(uin) ?? { nickname: uin, pid: null };
const previous = this.deliveries.get(uin) ?? Promise.resolve();
// Both enrichment and every channel delivery belong to this transition.
// A slow lookup/send must not let recovery overtake offline for one UIN.
const delivery = previous
.then(() => this.notifyNow(uin, event, account))
.finally(() => {
if (this.deliveries.get(uin) === delivery) {
this.deliveries.delete(uin);
}
});
this.deliveries.set(uin, delivery);
return delivery;
}
private async notifyNow(
uin: string,
event: NotificationEvent,
account: AccountNotificationContext,
): Promise<void> {
if (this.disposed) {
return;
}
let channels: NotificationChannel[]; let channels: NotificationChannel[];
try { try {
@@ -203,15 +242,29 @@ export class NotificationManager {
return; return;
} }
const nickname = this.nicknames.get(uin) || uin; let facts: NotificationProcessFacts | undefined;
try {
facts = await this.deps.resolveProcess?.(uin, account.pid);
} catch (err) {
log.warn('resolveProcess(%s, %s) failed: %s', uin, account.pid, errMsg(err));
}
const vars: Record<string, string> = { const vars: Record<string, string> = {
uin, uin,
nickname, nickname: account.nickname,
event, event,
time: new Date(this.deps.now()).toISOString(), time: new Date(this.deps.now()).toISOString(),
status: facts?.status ?? '',
pid: facts?.pid === undefined ? '' : String(facts.pid),
error: facts?.error ?? '',
}; };
for (const ch of channels) { for (const ch of channels) {
if (this.disposed) {
return;
}
const result = await this.deliver(ch, vars); const result = await this.deliver(ch, vars);
this.record({ this.record({
time: this.deps.now(), time: this.deps.now(),
@@ -265,7 +318,6 @@ export class NotificationManager {
return await this.deps.post(ch.url, renderTemplate(ch.bodyTemplate, vars), ch.headers); return await this.deps.post(ch.url, renderTemplate(ch.bodyTemplate, vars), ch.headers);
} catch (err) { } catch (err) {
// Injected collaborators are contracted not to throw, but guard anyway.
return { ok: false, error: errMsg(err) }; return { ok: false, error: errMsg(err) };
} }
} }
@@ -292,6 +344,9 @@ export class NotificationManager {
nickname: '测试账号', nickname: '测试账号',
event: 'offline' as const, event: 'offline' as const,
time: new Date(this.deps.now()).toISOString(), time: new Date(this.deps.now()).toISOString(),
status: 'disconnected',
pid: '1234',
error: '',
}; };
return { ...(await this.deliver(channel, vars)), found: true }; return { ...(await this.deliver(channel, vars)), found: true };
} }
@@ -378,13 +433,17 @@ export function createDefaultSendMail(
}; };
} }
/** The real, fully-wired singleton. */ /** The real, fully-wired singleton. `resolveProcess` is supplied by the
export function createNotificationManager(): NotificationManager { * runtime — this package deliberately knows nothing about HookManager. */
export function createNotificationManager(
resolveProcess?: NotificationManagerDeps['resolveProcess'],
): NotificationManager {
return new NotificationManager({ return new NotificationManager({
loadConfig: loadNotificationsConfig, loadConfig: loadNotificationsConfig,
loadChannelIds: (uin) => loadOneBotConfig(uin).notifications?.channelIds ?? [], loadChannelIds: (uin) => loadOneBotConfig(uin).notifications?.channelIds ?? [],
post: createDefaultPost(), post: createDefaultPost(),
sendMail: createDefaultSendMail(), sendMail: createDefaultSendMail(),
now: () => Date.now(), now: () => Date.now(),
resolveProcess,
}); });
} }
@@ -339,6 +339,7 @@ describe('BridgeManager PID ownership', () => {
manager.onPidDisconnected(101); manager.onPidDisconnected(101);
expect(manager.getSession('10001')).toBeNull(); expect(manager.getSession('10001')).toBeNull();
expect(closed).toHaveBeenCalledOnce(); expect(closed).toHaveBeenCalledOnce();
expect(closed).toHaveBeenCalledWith('10001', bridge, 101);
await expect( await expect(
bridge.sendRawPacket('Test.NoSender', new Uint8Array([3])), bridge.sendRawPacket('Test.NoSender', new Uint8Array([3])),
).resolves.toMatchObject({ ).resolves.toMatchObject({
@@ -512,7 +513,7 @@ describe('BridgeManager PID ownership', () => {
expect(started).toHaveBeenCalledTimes(2); expect(started).toHaveBeenCalledTimes(2);
expect(closed).toHaveBeenCalledOnce(); expect(closed).toHaveBeenCalledOnce();
expect(closed).toHaveBeenCalledWith('10001', expect.anything()); expect(closed).toHaveBeenCalledWith('10001', expect.anything(), 101);
expect(manager.getSession('10001')).toBeNull(); expect(manager.getSession('10001')).toBeNull();
expect(manager.getSession('20002')!.bridge).toBe(targetBridge); expect(manager.getSession('20002')!.bridge).toBe(targetBridge);
expect(targetBridge.activePid).toBe(101); expect(targetBridge.activePid).toBe(101);
@@ -561,9 +562,7 @@ describe('BridgeManager PID ownership', () => {
try { try {
manager.onHookLogin(101, '10001', sender.client); manager.onHookLogin(101, '10001', sender.client);
// Deliberately violate the private ownership invariant through Bridge's // Remove the connection without updating the manager's ownership index.
// compatibility surface: Manager still maps PID 101 to this UIN, while
// Bridge no longer owns either the PID or its sender.
manager.getSession('10001')!.bridge.detachPid(101); manager.getSession('10001')!.bridge.detachPid(101);
expect(() => manager.onPacket(packet(101, '10001'))).toThrowError( expect(() => manager.onPacket(packet(101, '10001'))).toThrowError(
@@ -68,6 +68,35 @@ function makeProfile(uin: number, uid: string, nickname: string): UserProfileInf
} }
describe('Bridge roster warmup', () => { describe('Bridge roster warmup', () => {
it('settles all callers, including callers waiting before the first connection', async () => {
const bridge = new Bridge(IdentityService.memory('10001'));
const fetchFriends = vi
.spyOn(bridge.apis.contacts, 'fetchFriendList')
.mockResolvedValue([makeFriend(10001, 'u_self', 'me')]);
vi.spyOn(bridge.apis.contacts, 'fetchGroupList').mockResolvedValue([]);
const beforeLogin = bridge.whenRosterWarmupSettled();
bridge.bindPid(7, sender);
const afterLogin = bridge.whenRosterWarmupSettled();
const expected = { friendsLoaded: true, groupsLoaded: true };
await expect(Promise.all([beforeLogin, afterLogin])).resolves.toEqual([expected, expected]);
await expect(bridge.whenRosterWarmupSettled()).resolves.toEqual(expected);
expect(fetchFriends).toHaveBeenCalledOnce();
await bridge.dispose();
await expect(bridge.whenRosterWarmupSettled()).resolves.toEqual(expected);
});
it('releases warmup waiters when disposed before the first connection', async () => {
const bridge = new Bridge(IdentityService.memory('10001'));
const waiting = bridge.whenRosterWarmupSettled();
await bridge.dispose();
await expect(waiting).resolves.toEqual({ friendsLoaded: false, groupsLoaded: false });
await expect(bridge.whenRosterWarmupSettled()).resolves.toEqual({
friendsLoaded: false,
groupsLoaded: false,
});
});
it('fetches friends and groups after the first sender and writes Identity', async () => { it('fetches friends and groups after the first sender and writes Identity', async () => {
const identity = IdentityService.memory('10001'); const identity = IdentityService.memory('10001');
const bridge = new Bridge(identity); const bridge = new Bridge(identity);
@@ -3,10 +3,12 @@ import fs from 'fs';
import os from 'os'; import os from 'os';
import path from 'path'; import path from 'path';
import { import {
DEFAULT_BODY_TEMPLATE, DEFAULT_WEBHOOK_BODY,
DEFAULT_EMAIL_BODY,
DEFAULT_EMAIL_SUBJECT,
} from '@snowluma/common/notification-templates';
import {
DEFAULT_DEBOUNCE_SECONDS, DEFAULT_DEBOUNCE_SECONDS,
DEFAULT_EMAIL_BODY_TEMPLATE,
DEFAULT_SUBJECT_TEMPLATE,
defaultNotificationsConfig, defaultNotificationsConfig,
normalizeNotificationsConfig, normalizeNotificationsConfig,
renderTemplate, renderTemplate,
@@ -145,7 +147,7 @@ describe('normalizeNotificationsConfig — total normalize', () => {
expect(channels[0].enabled).toBe(true); expect(channels[0].enabled).toBe(true);
expect(channels[0].name).toBe('c1'); expect(channels[0].name).toBe('c1');
expect(channels[0].type).toBe('webhook'); expect(channels[0].type).toBe('webhook');
expect(channels[0].bodyTemplate).toBe(DEFAULT_BODY_TEMPLATE); expect(channels[0].bodyTemplate).toBe(DEFAULT_WEBHOOK_BODY);
expect(channels[0].headers).toBeUndefined(); expect(channels[0].headers).toBeUndefined();
}); });
@@ -198,14 +200,14 @@ describe('normalizeNotificationsConfig — total normalize', () => {
name: 'ops-mail', name: 'ops-mail',
type: 'email', type: 'email',
url: '', url: '',
bodyTemplate: DEFAULT_EMAIL_BODY_TEMPLATE, bodyTemplate: DEFAULT_EMAIL_BODY,
enabled: true, enabled: true,
smtpHost: 'smtp.qq.com', smtpHost: 'smtp.qq.com',
smtpPort: 465, smtpPort: 465,
smtpSecure: true, smtpSecure: true,
from: 'SnowLuma <[email protected]>', from: 'SnowLuma <[email protected]>',
to: '[email protected], [email protected]', to: '[email protected], [email protected]',
subjectTemplate: DEFAULT_SUBJECT_TEMPLATE, subjectTemplate: DEFAULT_EMAIL_SUBJECT,
}, },
]); ]);
}); });
@@ -62,10 +62,14 @@ describe('DebounceMachine — online↔offline debounce (Uptime-Kuma semantics)'
expect(m.onOnline('a')).toEqual({ kind: 'emit', event: 'online' }); expect(m.onOnline('a')).toEqual({ kind: 'emit', event: 'online' });
}); });
it('forget() resets a UIN to baseline', () => { it('starts a new debounce cycle after recovery without retaining the old timer state', () => {
const m = new DebounceMachine(); const m = new DebounceMachine();
m.onOffline('u', 0); // fired offline m.onOffline('u', 30);
m.forget('u'); m.onTimerElapsed('u');
expect(m.onOnline('u')).toEqual({ kind: 'none' }); // state cleared → no recovery m.onOnline('u');
expect(m.onTimerElapsed('u')).toEqual({ kind: 'none' });
expect(m.onOffline('u', 60)).toEqual({ kind: 'schedule', delayMs: 60_000 });
expect(m.onOnline('u')).toEqual({ kind: 'cancel' });
expect(m.onOnline('u')).toEqual({ kind: 'none' });
}); });
}); });
@@ -0,0 +1,97 @@
import { IdentityService } from '@snowluma/protocol/identity-service';
import type { PacketSender } from '@snowluma/common/packet-sender';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { BridgeManager } from '../src/bridge/manager';
import { NotificationManager, type NotificationManagerDeps } from '../src/notifications/manager';
const sender: PacketSender = {
sendPacket: async () => ({
success: false,
gotResponse: false,
errorCode: -1,
errorMessage: 'test: no QQ connection',
responseData: null,
}),
};
describe('notification lifecycle PID', () => {
let bridges: BridgeManager;
let notifications: NotificationManager;
const posts: string[] = [];
const resolveProcess = vi.fn<NonNullable<NotificationManagerDeps['resolveProcess']>>(
async (_uin, pid) => (pid === null ? undefined : { pid }),
);
beforeEach(() => {
vi.useFakeTimers();
vi.spyOn(IdentityService, 'openForUin').mockImplementation((uin) =>
IdentityService.memory(uin),
);
posts.length = 0;
resolveProcess.mockClear();
bridges = new BridgeManager();
notifications = new NotificationManager({
loadConfig: () => ({
version: 1,
debounceSeconds: 30,
channels: [
{
id: 'c1',
name: 'C1',
type: 'webhook',
url: 'https://hook.example/c1',
enabled: true,
bodyTemplate: '{event}:{uin}:{pid}',
},
],
}),
loadChannelIds: () => ['c1'],
post: async (_url, body) => {
posts.push(body);
return { ok: true };
},
now: () => Date.now(),
resolveProcess,
});
notifications.bind(bridges);
});
afterEach(async () => {
notifications.dispose();
await bridges.dispose();
vi.restoreAllMocks();
vi.useRealTimers();
});
it('retains the final detached PID through debounce and uses the new PID on recovery', async () => {
bridges.onHookLogin(1001, '12345', sender);
bridges.onHookLogin(2002, '12345', sender);
bridges.onPidDisconnected(1001);
await vi.advanceTimersByTimeAsync(30_000);
expect(posts).toEqual([]);
bridges.onPidDisconnected(2002);
expect(bridges.getSession('12345')).toBeNull();
await vi.advanceTimersByTimeAsync(30_000);
expect(resolveProcess).toHaveBeenNthCalledWith(1, '12345', 2002);
bridges.onHookLogin(3003, '12345', sender);
await vi.advanceTimersByTimeAsync(0);
expect(resolveProcess).toHaveBeenNthCalledWith(2, '12345', 3003);
expect(posts).toEqual(['offline:12345:2002', 'online:12345:3003']);
});
it('keeps queued event context when the same UIN recovers on another PID', async () => {
bridges.onHookLogin(1001, '12345', sender);
bridges.onPidDisconnected(1001);
const offline = notifications.notify('12345', 'offline');
bridges.onHookLogin(2002, '12345', sender);
const online = notifications.notify('12345', 'online');
await Promise.all([offline, online]);
expect(resolveProcess.mock.calls).toEqual([
['12345', 1001],
['12345', 2002],
]);
expect(posts).toEqual(['offline:12345:1001', 'online:12345:2002']);
});
});
@@ -1,10 +1,12 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { subscribeLogs, type LogEntry } from '@snowluma/common/logger';
import { import {
NotificationManager, NotificationManager,
createDefaultPost, createDefaultPost,
selectChannels, selectChannels,
type MailPayload, type MailPayload,
type NotificationManagerDeps, type NotificationManagerDeps,
type NotificationProcessFacts,
type PostResult, type PostResult,
} from '../src/notifications/manager'; } from '../src/notifications/manager';
import type { NotificationChannel, NotificationsConfig } from '../src/notifications/config'; import type { NotificationChannel, NotificationsConfig } from '../src/notifications/config';
@@ -105,6 +107,48 @@ describe('NotificationManager — dispatch + history', () => {
expect(posts[0].body).toBe('offline:123:Alice'); expect(posts[0].body).toBe('offline:123:Alice');
}); });
it('carries process facts into the template so a supervisor can act on them', async () => {
const { posts, mgr } = setup({
loadConfig: () => ({
version: 1,
debounceSeconds: 30,
channels: [ch({ bodyTemplate: '{event}:{uin}:{status}:{pid}:{error}' })],
}),
resolveProcess: async () => ({ status: 'disconnected', pid: 4242, error: '' }),
});
await mgr.notify('123', 'offline');
expect(posts[0].body).toBe('offline:123:disconnected:4242:');
});
it('renders fact variables empty when no resolver is configured', async () => {
const { posts, mgr } = setup({
loadConfig: () => ({
version: 1,
debounceSeconds: 30,
channels: [ch({ bodyTemplate: '{event}:{status}:{pid}' })],
}),
});
await mgr.notify('123', 'offline');
// No resolver → empty, not the literal placeholders.
expect(posts[0].body).toBe('offline::');
});
it('still notifies when the resolver throws', async () => {
const { posts, mgr } = setup({
loadConfig: () => ({
version: 1,
debounceSeconds: 30,
channels: [ch({ bodyTemplate: '{event}:{status}' })],
}),
resolveProcess: async () => {
throw new Error('hook manager unavailable');
},
});
await mgr.notify('123', 'offline');
expect(posts).toHaveLength(1);
expect(posts[0].body).toBe('offline:');
});
it('records ok and failed deliveries, most-recent-first', async () => { it('records ok and failed deliveries, most-recent-first', async () => {
let n = 0; let n = 0;
const { mgr } = setup({ const { mgr } = setup({
@@ -119,6 +163,90 @@ describe('NotificationManager — dispatch + history', () => {
expect(recent[1]).toMatchObject({ event: 'offline', ok: true, status: 200 }); expect(recent[1]).toMatchObject({ event: 'offline', ok: true, status: 200 });
}); });
it('keeps offline before recovery when the offline process lookup is delayed', async () => {
let resolve!: (facts: NotificationProcessFacts) => void;
const delayed = new Promise<NotificationProcessFacts>((done) => {
resolve = done;
});
const resolveProcess = vi
.fn()
.mockReturnValueOnce(delayed)
.mockResolvedValue({ status: 'online', pid: 4242 });
const { posts, mgr } = setup({ resolveProcess });
const offline = mgr.notify('123', 'offline');
const online = mgr.notify('123', 'online');
await new Promise<void>((done) => setImmediate(done));
const whileResolving = [...posts];
resolve({ status: 'disconnected', pid: 4242 });
await Promise.all([offline, online]);
expect(whileResolving).toEqual([]);
expect(posts.map((post) => post.body)).toEqual(['offline:123:123', 'online:123:123']);
});
it('finishes every channel before sending the recovery, even when a delivery fails', async () => {
let reject!: (error: Error) => void;
const delayed = new Promise<PostResult>((_resolve, fail) => {
reject = fail;
});
const deliveries: string[] = [];
const { mgr } = setup({
loadConfig: () => ({
version: 1,
debounceSeconds: 0,
channels: [ch(), ch({ id: 'c2' })],
}),
loadChannelIds: () => ['c1', 'c2'],
post: async (_url, body) => {
deliveries.push(body);
return deliveries.length === 1 ? delayed : { ok: true };
},
});
const offline = mgr.notify('123', 'offline');
const online = mgr.notify('123', 'online');
await new Promise<void>((done) => setImmediate(done));
reject(new Error('delivery failed'));
await Promise.all([offline, online]);
expect(deliveries).toEqual([
'offline:123:123',
'offline:123:123',
'online:123:123',
'online:123:123',
]);
expect(mgr.getRecent().filter((record) => !record.ok)).toHaveLength(1);
});
it('does not block another account behind a slow process lookup', async () => {
let resolve!: (facts: undefined) => void;
const delayed = new Promise<undefined>((done) => {
resolve = done;
});
const { posts, mgr } = setup({
resolveProcess: (uin) => (uin === '123' ? delayed : Promise.resolve(undefined)),
});
const slow = mgr.notify('123', 'offline');
await mgr.notify('456', 'offline');
const whileResolving = [...posts];
resolve(undefined);
await slow;
expect(whileResolving.map((post) => post.body)).toEqual(['offline:456:456']);
expect(posts.map((post) => post.body)).toEqual(['offline:456:456', 'offline:123:123']);
});
it('drops queued notifications on disposal and does not deliver after a pending lookup', async () => {
let resolve!: (facts: undefined) => void;
const delayed = new Promise<undefined>((done) => {
resolve = done;
});
const { posts, mgr } = setup({ resolveProcess: () => delayed });
const offline = mgr.notify('123', 'offline');
const online = mgr.notify('123', 'online');
await new Promise<void>((done) => setImmediate(done));
mgr.dispose();
resolve(undefined);
await Promise.all([offline, online]);
expect(posts).toEqual([]);
});
it('skips channels the UIN did not opt into', async () => { it('skips channels the UIN did not opt into', async () => {
const { posts, mgr } = setup({ loadChannelIds: () => [] }); const { posts, mgr } = setup({ loadChannelIds: () => [] });
await mgr.notify('123', 'offline'); await mgr.notify('123', 'offline');
@@ -309,9 +437,7 @@ describe('NotificationManager — debounce integration (fake timers)', () => {
mgr.handleOffline('123', 'Bob'); // arm 30s timer mgr.handleOffline('123', 'Bob'); // arm 30s timer
await vi.advanceTimersByTimeAsync(10_000); await vi.advanceTimersByTimeAsync(10_000);
mgr.handleOnline('123', 'Bob'); // self-heal → cancel timer mgr.handleOnline('123', 'Bob'); // self-heal → cancel timer
// The machine's state guard alone would suppress the misfire; assert the expect(vi.getTimerCount()).toBe(0);
// 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); await vi.advanceTimersByTimeAsync(60_000);
expect(events).toEqual([]); expect(events).toEqual([]);
}); });
@@ -333,6 +459,50 @@ describe('NotificationManager — debounce integration (fake timers)', () => {
expect(events).toEqual(['offline']); expect(events).toEqual(['offline']);
}); });
it('reports config failure without inventing a debounce window or a recovery event', async () => {
const loadConfig = vi.fn<NotificationManagerDeps['loadConfig']>().mockImplementation(() => {
throw new Error('config unreadable');
});
const post = vi.fn<NotificationManagerDeps['post']>().mockResolvedValue({ ok: true });
const mgr = new NotificationManager({
loadConfig,
loadChannelIds: () => ['c1'],
post,
now: () => 1000,
});
const logs: LogEntry[] = [];
const unsubscribe = subscribeLogs((entry) => logs.push(entry));
try {
mgr.handleOffline('123', 'Bob');
expect(vi.getTimerCount()).toBe(0);
expect(logs).toContainEqual(
expect.objectContaining({
scope: 'Notifications',
level: 'warn',
message: 'offline(123) skipped — config load failed: config unreadable',
}),
);
loadConfig.mockReturnValue({ version: 1, debounceSeconds: 5, channels: [ch()] });
await vi.advanceTimersByTimeAsync(30_000);
mgr.handleOnline('123', 'Bob');
await vi.advanceTimersByTimeAsync(0);
expect(post).not.toHaveBeenCalled();
mgr.handleOffline('123', 'Bob');
await vi.advanceTimersByTimeAsync(5_000);
expect(post).toHaveBeenCalledExactlyOnceWith(
'https://hook.example/c1',
'offline:123:Bob',
undefined,
);
} finally {
unsubscribe();
mgr.dispose();
}
});
it('ignores online/offline after dispose so process exit is not a runtime drop', async () => { it('ignores online/offline after dispose so process exit is not a runtime drop', async () => {
const { events, mgr } = setup(0); const { events, mgr } = setup(0);
mgr.dispose(); mgr.dispose();
+15
View File
@@ -39,6 +39,21 @@ request headers. The backend still accepts `Authorization: Bearer <token>` for
existing clients when the dedicated header is absent. Both layers still require existing clients when the dedicated header is absent. Both layers still require
their own valid credentials. their own valid credentials.
## Account notification templates
Webhook bodies and email subjects/bodies support `{uin}`, `{nickname}`, `{event}`
(`offline` or `online`), `{time}`, `{status}` (Hook process state), `{pid}`, and
`{error}` (Hook process error). New webhook and email channels include process
status in their default body; existing saved templates are preserved.
Process facts are resolved when the notification is dispatched, after any offline
debounce. Each transition carries its process PID, including the final PID detached
when an account goes offline. Facts are looked up for that PID and UIN without
substituting another process. Missing facts render empty and mean unknown, not
proof that QQ exited. Hook status alone does not identify the cause of a QQ login
failure. Notifications for one account are delivered in transition order; a slow
account does not delay other accounts.
## Local development ## Local development
On Windows, the native API logs the process token and EXE integrity label once On Windows, the native API logs the process token and EXE integrity label once
@@ -3,6 +3,11 @@
// The channel id is the stable key per-account opt-ins reference, so it's // The channel id is the stable key per-account opt-ins reference, so it's
// editable only on create and locked on edit. // editable only on create and locked on edit.
import { useState } from 'react'; import { useState } from 'react';
import {
DEFAULT_WEBHOOK_BODY,
DEFAULT_EMAIL_BODY,
DEFAULT_EMAIL_SUBJECT,
} from '@snowluma/common/notification-templates';
import { Plus, Trash2 } from 'lucide-react'; import { Plus, Trash2 } from 'lucide-react';
import { Modal } from '@/components/interior/modal'; import { Modal } from '@/components/interior/modal';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
@@ -65,20 +70,6 @@ function hasRecipient(value: string): boolean {
return value.split(/[,;\n]+/).some((part) => looksLikeEmail(part)); return value.split(/[,;\n]+/).some((part) => looksLikeEmail(part));
} }
export const DEFAULT_WEBHOOK_BODY = `{
"title": "账号状态通知:{event}",
"desp": "您的账号状态发生了改变。\\n\\n**昵称**:{nickname}\\n**QQ号**:{uin}\\n**当前状态**:{event}\\n**时间**:{time}"
}`;
export const DEFAULT_EMAIL_BODY = `账号状态发生了改变。
昵称:{nickname}
QQ号:{uin}
当前状态:{event}
时间:{time}`;
export const DEFAULT_EMAIL_SUBJECT = '账号{event}:{nickname} ({uin})';
export function applyType( export function applyType(
draft: NotificationChannel, draft: NotificationChannel,
type: NotificationChannelType, type: NotificationChannelType,
@@ -227,11 +218,6 @@ export function NotificationChannelDialog(props: NotificationChannelDialogProps)
open={open} open={open}
onClose={() => onOpenChange(false)} onClose={() => onOpenChange(false)}
title={isEdit ? '编辑渠道' : '新建渠道'} title={isEdit ? '编辑渠道' : '新建渠道'}
description={
type === 'email'
? '账号上线 / 下线时向该邮箱发送一封渲染后的通知。'
: '账号上线 / 下线时向该 Webhook POST 一条渲染后的通知。'
}
closeLabel="关闭渠道编辑弹窗" closeLabel="关闭渠道编辑弹窗"
maxWidth={576} maxWidth={576}
maxHeight="min(86dvh, 780px)" maxHeight="min(86dvh, 780px)"
@@ -365,7 +351,7 @@ export function NotificationChannelDialog(props: NotificationChannelDialogProps)
))} ))}
</div> </div>
<p className="text-xs leading-relaxed text-muted-foreground"> <p className="text-xs leading-relaxed text-muted-foreground">
可选。用于飞书等需要鉴权头的 Webhook;默认仍带 JSON Content-Type。 可选,默认 Content-Type 为 application/json。
</p> </p>
</div> </div>
</> </>
@@ -442,7 +428,7 @@ export function NotificationChannelDialog(props: NotificationChannelDialogProps)
<div className="min-w-0"> <div className="min-w-0">
<Label className="text-sm">隐式 TLS</Label> <Label className="text-sm">隐式 TLS</Label>
<p className="mt-1 text-xs leading-relaxed text-muted-foreground"> <p className="mt-1 text-xs leading-relaxed text-muted-foreground">
465 通常开启;587 先明文再 STARTTLS,请关掉此项。 465 开启,587 关闭(STARTTLS)。
</p> </p>
</div> </div>
<ToggleSwitch <ToggleSwitch
@@ -492,8 +478,12 @@ export function NotificationChannelDialog(props: NotificationChannelDialogProps)
变量:<code className="font-mono">{'{uin}'}</code>{' '} 变量:<code className="font-mono">{'{uin}'}</code>{' '}
<code className="font-mono">{'{nickname}'}</code>{' '} <code className="font-mono">{'{nickname}'}</code>{' '}
<code className="font-mono">{'{event}'}</code>(offline/online){' '} <code className="font-mono">{'{event}'}</code>(offline/online){' '}
<code className="font-mono">{'{time}'}</code> <code className="font-mono">{'{time}'}</code>{' '}
{type === 'email' ? '。正文以 < 开头时按 HTML 发送。' : ''} <code className="font-mono">{'{status}'}</code>(Hook 状态){' '}
<code className="font-mono">{'{pid}'}</code>(进程 ID){' '}
<code className="font-mono">{'{error}'}</code>(进程错误)
。进程信息为空表示未知。
{type === 'email' ? '正文以 < 开头时按 HTML 发送。' : ''}
</p> </p>
</div> </div>
@@ -501,7 +491,7 @@ export function NotificationChannelDialog(props: NotificationChannelDialogProps)
<div className="min-w-0"> <div className="min-w-0">
<Label className="text-sm">启用</Label> <Label className="text-sm">启用</Label>
<p className="mt-1 text-xs leading-relaxed text-muted-foreground"> <p className="mt-1 text-xs leading-relaxed text-muted-foreground">
关闭后保留配置但不推送;账号侧对应开关会被锁定并关闭。 关闭后停止推送,保留配置。
</p> </p>
</div> </div>
<ToggleSwitch <ToggleSwitch
@@ -4,6 +4,7 @@
// like the per-account config page — no explicit save button. // like the per-account config page — no explicit save button.
import { useCallback, useEffect, useRef, useState } from 'react'; import { useCallback, useEffect, useRef, useState } from 'react';
import { motion } from 'motion/react'; import { motion } from 'motion/react';
import { DEFAULT_WEBHOOK_BODY } from '@snowluma/common/notification-templates';
import { Bell, Loader2, Pencil, Plus, Send, Trash2 } from 'lucide-react'; import { Bell, Loader2, Pencil, Plus, Send, Trash2 } from 'lucide-react';
import { Badge } from '@/components/ui/badge'; import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
@@ -21,7 +22,7 @@ import {
type NotificationChannel, type NotificationChannel,
type NotificationsConfig, type NotificationsConfig,
} from '@/types'; } from '@/types';
import { DEFAULT_WEBHOOK_BODY, NotificationChannelDialog } from './notification-channel-dialog'; import { NotificationChannelDialog } from './notification-channel-dialog';
/** A fresh channel with a non-colliding default id. */ /** A fresh channel with a non-colliding default id. */
function blankChannel(existing: NotificationChannel[]): NotificationChannel { function blankChannel(existing: NotificationChannel[]): NotificationChannel {
@@ -43,7 +44,6 @@ function blankChannel(existing: NotificationChannel[]): NotificationChannel {
} }
interface DialogState { interface DialogState {
open: boolean;
index: number | null; // null → create index: number | null; // null → create
seed: NotificationChannel; seed: NotificationChannel;
} }
@@ -53,11 +53,7 @@ export function NotificationsPanel() {
const { runAction } = useActionFeedback(); const { runAction } = useActionFeedback();
const [config, setConfig] = useState<NotificationsConfig | null>(null); const [config, setConfig] = useState<NotificationsConfig | null>(null);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [dialog, setDialog] = useState<DialogState>({ const [dialog, setDialog] = useState<DialogState | null>(null);
open: false,
index: null,
seed: blankChannel([]),
});
const [testing, setTesting] = useState<string | null>(null); const [testing, setTesting] = useState<string | null>(null);
const { msg, flash, setMsg } = useFlashMessage(); const { msg, flash, setMsg } = useFlashMessage();
const saveTimer = useRef<number | null>(null); const saveTimer = useRef<number | null>(null);
@@ -166,18 +162,18 @@ export function NotificationsPanel() {
const otherIds = (index: number | null) => const otherIds = (index: number | null) =>
channels.filter((_, i) => i !== index).map((c) => c.id); channels.filter((_, i) => i !== index).map((c) => c.id);
const openCreate = () => setDialog({ open: true, index: null, seed: blankChannel(channels) }); const openCreate = () => setDialog({ index: null, seed: blankChannel(channels) });
const openEdit = (i: number) => setDialog({ open: true, index: i, seed: channels[i] }); const openEdit = (i: number) => setDialog({ index: i, seed: channels[i] });
const submitChannel = (ch: NotificationChannel) => { const submitChannel = (ch: NotificationChannel, index: number | null) => {
if (dialog.index == null) { if (index === null) {
setChannels([...channels, ch], { setChannels([...channels, ch], {
title: '正在新增通知渠道', title: '正在新增通知渠道',
successTitle: '通知渠道已新增', successTitle: '通知渠道已新增',
}); });
} else { } else {
setChannels( setChannels(
channels.map((c, idx) => (idx === dialog.index ? ch : c)), channels.map((c, idx) => (idx === index ? ch : c)),
{ title: '正在更新通知渠道', successTitle: '通知渠道已更新' }, { title: '正在更新通知渠道', successTitle: '通知渠道已更新' },
); );
} }
@@ -234,10 +230,7 @@ export function NotificationsPanel() {
<div className="flex flex-col gap-4 rounded-xl border bg-card/40 p-4"> <div className="flex flex-col gap-4 rounded-xl border bg-card/40 p-4">
<div className="flex items-start gap-2 text-xs leading-relaxed text-muted-foreground"> <div className="flex items-start gap-2 text-xs leading-relaxed text-muted-foreground">
<Bell className="mt-0.5 size-3.5 shrink-0" /> <Bell className="mt-0.5 size-3.5 shrink-0" />
<p> <p>在此管理通知渠道,再到账号「配置」页选择启用。</p>
账号上线 / 下线时向启用的渠道发送通知(Webhook POST
或邮件,仅去抖防刷屏)。渠道在此全局定义,每个账号在其「配置」页勾选启用哪些。
</p>
</div> </div>
<div className="flex flex-col gap-1.5 border-t pt-3"> <div className="flex flex-col gap-1.5 border-t pt-3">
<Label>去抖窗口(秒)</Label> <Label>去抖窗口(秒)</Label>
@@ -258,8 +251,7 @@ export function NotificationsPanel() {
}} }}
/> />
<p className="text-xs leading-relaxed text-muted-foreground"> <p className="text-xs leading-relaxed text-muted-foreground">
下线后在该秒数内自愈则不发;超时才发「下线」,恢复时再发「上线」。 下线持续超过此时长才通知,恢复时再通知。0 表示立即通知。
<code className="font-mono">0</code> = 立即发、不去抖。
</p> </p>
</div> </div>
</div> </div>
@@ -329,14 +321,14 @@ export function NotificationsPanel() {
</p> </p>
)} )}
{dialog.open && ( {dialog && (
<NotificationChannelDialog <NotificationChannelDialog
open={dialog.open} open
onOpenChange={(open) => !open && setDialog((d) => ({ ...d, open: false }))} onOpenChange={(open) => !open && setDialog(null)}
isEdit={dialog.index != null} isEdit={dialog.index != null}
initial={dialog.seed} initial={dialog.seed}
otherIds={otherIds(dialog.index)} otherIds={otherIds(dialog.index)}
onSubmit={submitChannel} onSubmit={(channel) => submitChannel(channel, dialog.index)}
/> />
)} )}
</div> </div>
@@ -1,9 +1,10 @@
import { renderToStaticMarkup } from 'react-dom/server'; import { renderToStaticMarkup } from 'react-dom/server';
import { describe, expect, it, vi } from 'vitest'; import { describe, expect, it, vi } from 'vitest';
import { DEFAULT_EMAIL_BODY, DEFAULT_WEBHOOK_BODY } from '@snowluma/common/notification-templates';
import { import {
DEFAULT_EMAIL_BODY,
DEFAULT_WEBHOOK_BODY,
NotificationChannelDialog, NotificationChannelDialog,
applyType,
toChannel,
} from '../src/components/settings/notification-channel-dialog'; } from '../src/components/settings/notification-channel-dialog';
vi.mock('@/contexts/ThemeContext', () => ({ vi.mock('@/contexts/ThemeContext', () => ({
@@ -53,7 +54,9 @@ describe('NotificationChannelDialog', () => {
expect(markup).toContain('Webhook URL'); expect(markup).toContain('Webhook URL');
expect(markup).toContain('请求头'); expect(markup).toContain('请求头');
expect(markup).not.toContain('SMTP 主机'); expect(markup).not.toContain('SMTP 主机');
expect(markup).toContain('向该 Webhook POST'); expect(markup).toContain('{status}');
expect(markup).toContain('{pid}');
expect(markup).toContain('{error}');
}); });
it('shows SMTP fields for an email channel', () => { it('shows SMTP fields for an email channel', () => {
@@ -86,6 +89,34 @@ describe('NotificationChannelDialog', () => {
expect(markup).toContain('主题模板'); expect(markup).toContain('主题模板');
expect(markup).toContain('隐式 TLS'); expect(markup).toContain('隐式 TLS');
expect(markup).not.toContain('Webhook URL'); expect(markup).not.toContain('Webhook URL');
expect(markup).toContain('向该邮箱发送'); expect(markup).toContain('{status}');
expect(markup).toContain('{pid}');
expect(markup).toContain('{error}');
});
it('includes process status when saving a new webhook or switching it to email', () => {
const webhook = {
id: 'new-channel',
name: 'New',
type: 'webhook' as const,
url: 'https://example.com/webhook',
enabled: true,
bodyTemplate: DEFAULT_WEBHOOK_BODY,
};
expect(toChannel(webhook, []).bodyTemplate).toContain('{status}');
expect(toChannel(applyType(webhook, 'email'), []).bodyTemplate).toContain('{status}');
});
it('preserves an existing custom template', () => {
const existing = {
id: 'existing',
name: 'Existing',
type: 'webhook' as const,
url: 'https://example.com/webhook',
enabled: true,
bodyTemplate: '{event}:{uin}',
};
expect(toChannel(existing, []).bodyTemplate).toBe('{event}:{uin}');
expect(toChannel(applyType(existing, 'email'), []).bodyTemplate).toBe('{event}:{uin}');
}); });
}); });
@@ -1,11 +1,10 @@
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { import {
applyType,
DEFAULT_EMAIL_BODY, DEFAULT_EMAIL_BODY,
DEFAULT_EMAIL_SUBJECT, DEFAULT_EMAIL_SUBJECT,
DEFAULT_WEBHOOK_BODY, DEFAULT_WEBHOOK_BODY,
toChannel, } from '@snowluma/common/notification-templates';
} from '../src/components/settings/notification-channel-dialog'; import { applyType, toChannel } from '../src/components/settings/notification-channel-dialog';
import { notificationChannelType, type NotificationChannel } from '../src/types'; import { notificationChannelType, type NotificationChannel } from '../src/types';
function webhook(over: Partial<NotificationChannel> = {}): NotificationChannel { function webhook(over: Partial<NotificationChannel> = {}): NotificationChannel {