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 <215231231+zhngzhu@users.noreply.github.com> Co-authored-by: 手瓜一十雪 <nanaeonn@outlook.com>
This commit is contained in:
@@ -24,6 +24,10 @@
|
||||
"types": "./src/env.ts",
|
||||
"default": "./src/env.ts"
|
||||
},
|
||||
"./notification-templates": {
|
||||
"types": "./src/notification-templates.ts",
|
||||
"default": "./src/notification-templates.ts"
|
||||
},
|
||||
"./single-flight-cache": {
|
||||
"types": "./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}`;
|
||||
@@ -16,19 +16,19 @@ const log = createLogger('Bridge');
|
||||
const runtimeLog = createLogger('Bridge.Runtime');
|
||||
const VERBOSE_WARMUP = process.env.SNOWLUMA_VERBOSE_WARMUP === '1';
|
||||
|
||||
interface ProcessConnection {
|
||||
pid: number;
|
||||
client: PacketSender;
|
||||
receiveHealthy: boolean;
|
||||
}
|
||||
|
||||
export class Bridge implements BridgeInterface {
|
||||
readonly identity: IdentityService;
|
||||
private pids_ = new Set<number>();
|
||||
private readonly receiveHealthByPid_ = new Map<number, boolean>();
|
||||
/** 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>();
|
||||
/** Insertion order tracks login recency; the newest connection sends packets. */
|
||||
private readonly connections = new Map<number, ProcessConnection>();
|
||||
readonly events = new BridgeEventBus();
|
||||
readonly apis: ApiHub;
|
||||
private readonly pipeline: IncomingPacketPipeline;
|
||||
private packetClient_: PacketSender | null = null;
|
||||
private packetClientPid_: number | null = null;
|
||||
private static readonly UPLOADED_FILE_CACHE_MAX = 1024;
|
||||
private uploadedFileMeta_ = new Map<string, UploadedFileMeta>();
|
||||
private clientSeq_ = 100000000 + (Date.now() % 1000000000);
|
||||
@@ -40,9 +40,10 @@ export class Bridge implements BridgeInterface {
|
||||
private disposePromise_: Promise<void> | null = null;
|
||||
private readonly pendingPackets_ = new Set<Promise<void>>();
|
||||
private rosterWarmupStarted_ = false;
|
||||
private rosterWarmupSettled_ = false;
|
||||
private rosterWarmupResult_: RosterWarmupResult | null = null;
|
||||
private readonly rosterWarmupWaiters_: Array<(result: RosterWarmupResult) => void> = [];
|
||||
private settleRosterWarmup!: (result: RosterWarmupResult) => void;
|
||||
private readonly rosterWarmup = new Promise<RosterWarmupResult>((resolve) => {
|
||||
this.settleRosterWarmup = resolve;
|
||||
});
|
||||
|
||||
constructor(identity: IdentityService) {
|
||||
this.identity = identity;
|
||||
@@ -151,11 +152,7 @@ export class Bridge implements BridgeInterface {
|
||||
|
||||
this.disposed_ = true;
|
||||
this.settleRosterWarmup({ friendsLoaded: false, groupsLoaded: false });
|
||||
this.pids_.clear();
|
||||
this.receiveHealthByPid_.clear();
|
||||
this.packetClientsByPid_.clear();
|
||||
this.packetClient_ = null;
|
||||
this.packetClientPid_ = null;
|
||||
this.connections.clear();
|
||||
this.onlineClients_ = null;
|
||||
this.disposePromise_ = (async () => {
|
||||
try {
|
||||
@@ -168,22 +165,6 @@ export class Bridge implements BridgeInterface {
|
||||
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 {
|
||||
this.pipeline.registerCmd(cmd, parser);
|
||||
}
|
||||
@@ -192,34 +173,18 @@ export class Bridge implements BridgeInterface {
|
||||
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 {
|
||||
const previousPid = this.packetClientPid_;
|
||||
const previousClient = this.packetClient_;
|
||||
this.attachPid(pid);
|
||||
this.packetClientsByPid_.set(pid, client);
|
||||
this.packetClient_ = client;
|
||||
this.packetClientPid_ = pid;
|
||||
const previous = this.activeConnection;
|
||||
this.connections.delete(pid);
|
||||
// A new login stays healthy until the watchdog confirms a failure.
|
||||
this.connections.set(pid, { pid, client, receiveHealthy: true });
|
||||
|
||||
if (previousPid !== pid || previousClient !== client) {
|
||||
if (previous?.pid !== pid || previous.client !== client) {
|
||||
runtimeLog.trace(
|
||||
'bridge_sender_fact event=selected uin=%j pid=%d previousPid=%j',
|
||||
this.identity.uin,
|
||||
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
|
||||
* observation that a live PID changed UIN. */
|
||||
packetClientForPid(pid: number): PacketSender | null {
|
||||
return this.packetClientsByPid_.get(pid) ?? null;
|
||||
return this.connections.get(pid)?.client ?? null;
|
||||
}
|
||||
|
||||
detachPid(pid: number): void {
|
||||
this.pids_.delete(pid);
|
||||
this.receiveHealthByPid_.delete(pid);
|
||||
this.packetClientsByPid_.delete(pid);
|
||||
const wasActive = this.activePid === pid;
|
||||
this.connections.delete(pid);
|
||||
const active = this.activeConnection;
|
||||
|
||||
if (this.packetClientPid_ !== pid) {
|
||||
// An unscoped legacy sender cannot be associated with a particular PID.
|
||||
// It is safe to retain while another PID exists, but never after the
|
||||
// Bridge becomes empty.
|
||||
if (this.pids_.size === 0) {
|
||||
this.packetClient_ = null;
|
||||
this.packetClientPid_ = null;
|
||||
}
|
||||
|
||||
return;
|
||||
if (wasActive && active) {
|
||||
runtimeLog.trace(
|
||||
'bridge_sender_fact event=fallback uin=%j detachedPid=%d fallbackPid=%d',
|
||||
this.identity.uin,
|
||||
pid,
|
||||
active.pid,
|
||||
);
|
||||
log.debug(
|
||||
'packet sender changed: UIN=%s PID=%d→%d',
|
||||
this.identity.uin,
|
||||
pid,
|
||||
active.pid,
|
||||
);
|
||||
}
|
||||
|
||||
this.selectFallbackPacketClient(pid);
|
||||
}
|
||||
hasPid(pid: number): boolean {
|
||||
return this.pids_.has(pid);
|
||||
return this.connections.has(pid);
|
||||
}
|
||||
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 {
|
||||
if (this.packetClientPid_ !== null && this.pids_.has(this.packetClientPid_)) {
|
||||
return this.packetClientPid_;
|
||||
}
|
||||
|
||||
const pids = [...this.pids_];
|
||||
return pids.length > 0 ? pids[pids.length - 1]! : null;
|
||||
return this.activeConnection?.pid ?? null;
|
||||
}
|
||||
get receiveHealthy(): boolean {
|
||||
for (const pid of this.pids_) {
|
||||
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;
|
||||
return [...this.connections.values()].some((connection) => connection.receiveHealthy);
|
||||
}
|
||||
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`);
|
||||
}
|
||||
|
||||
this.receiveHealthByPid_.set(pid, healthy);
|
||||
connection.receiveHealthy = healthy;
|
||||
}
|
||||
getOnlineClients(): readonly Readonly<OnlineDeviceInfo>[] | null {
|
||||
return this.onlineClients_;
|
||||
}
|
||||
|
||||
whenRosterWarmupSettled(): Promise<RosterWarmupResult> {
|
||||
if (this.rosterWarmupSettled_ && this.rosterWarmupResult_) {
|
||||
return Promise.resolve(this.rosterWarmupResult_);
|
||||
}
|
||||
|
||||
this.maybeStartRosterWarmup();
|
||||
return new Promise((resolve) => {
|
||||
if (this.rosterWarmupSettled_ && this.rosterWarmupResult_) {
|
||||
resolve(this.rosterWarmupResult_);
|
||||
return;
|
||||
}
|
||||
|
||||
this.rosterWarmupWaiters_.push(resolve);
|
||||
});
|
||||
return this.rosterWarmup;
|
||||
}
|
||||
|
||||
onPacket(pkt: PacketInfo): Promise<void> {
|
||||
@@ -358,7 +298,9 @@ export class Bridge implements BridgeInterface {
|
||||
body: Uint8Array,
|
||||
timeoutMs = packetTimeoutMs(),
|
||||
): Promise<SendPacketResult> {
|
||||
if (!this.packetClient_) {
|
||||
const connection = this.activeConnection;
|
||||
|
||||
if (!connection) {
|
||||
return runWithTraceRequest(() => {
|
||||
const startedAt = Date.now();
|
||||
runtimeLog.trace(() => [
|
||||
@@ -391,11 +333,7 @@ export class Bridge implements BridgeInterface {
|
||||
}
|
||||
|
||||
const startedAt = Date.now();
|
||||
const result = await this.packetClient_.sendPacket(
|
||||
serviceCmd,
|
||||
Buffer.from(body),
|
||||
timeoutMs,
|
||||
);
|
||||
const result = await connection.client.sendPacket(serviceCmd, Buffer.from(body), timeoutMs);
|
||||
const elapsed = Date.now() - startedAt;
|
||||
const respLen = result.responseData ? result.responseData.length : 0;
|
||||
|
||||
@@ -424,52 +362,12 @@ export class Bridge implements BridgeInterface {
|
||||
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> {
|
||||
return this.identity.resolveUid(uin, groupId);
|
||||
}
|
||||
|
||||
private maybeStartRosterWarmup(): void {
|
||||
if (this.disposed_ || this.rosterWarmupStarted_ || !this.packetClient_) {
|
||||
if (this.disposed_ || this.rosterWarmupStarted_ || this.empty) {
|
||||
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 {
|
||||
return !this.disposed_;
|
||||
}
|
||||
|
||||
@@ -6,7 +6,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, bridge: Bridge) => void;
|
||||
export type SessionClosedCallback = (uin: string, bridge: Bridge, pid: number) => void;
|
||||
|
||||
interface QQSession {
|
||||
bridge: Bridge;
|
||||
@@ -64,8 +64,8 @@ export class BridgeManager {
|
||||
/** 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. */
|
||||
* The close edge carries the final detached PID and the bridge so observers
|
||||
* can identify the process and read its nickname before disposal. */
|
||||
addSessionStartedListener(cb: SessionStartedCallback): void {
|
||||
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_) {
|
||||
try {
|
||||
cb(uin, bridge);
|
||||
cb(uin, bridge, pid);
|
||||
} catch (err) {
|
||||
log.warn(
|
||||
'session-closed listener threw: %s',
|
||||
@@ -397,12 +397,6 @@ export class BridgeManager {
|
||||
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
|
||||
// invariant is known to hold, so a fail-fast error preserves the evidence.
|
||||
this.pidToUin_.delete(pid);
|
||||
@@ -415,7 +409,7 @@ export class BridgeManager {
|
||||
this.sessions_.delete(uin);
|
||||
log.debug('session closed: UIN=%s', uin);
|
||||
// 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);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -91,7 +91,14 @@ async function main() {
|
||||
|
||||
// Global notification subsystem (account up/down → webhook). Bound AFTER
|
||||
// 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);
|
||||
|
||||
let stopWebUI: (() => Promise<void>) | undefined;
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
// Global notification-channel store + the pure template renderer.
|
||||
//
|
||||
// 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).
|
||||
// Global channels are selected per account by OneBotConfig.notifications.channelIds.
|
||||
import { boolOr, clampInt, isObject } from '@snowluma/common/coerce';
|
||||
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 path from 'path';
|
||||
import { extractAddress, parseRecipients } from './smtp';
|
||||
@@ -79,23 +76,6 @@ export interface NotificationsConfig {
|
||||
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_USER_MAX = 256;
|
||||
const SMTP_PASS_MAX = 256;
|
||||
@@ -315,7 +295,7 @@ function normalizeEmailChannel(
|
||||
name,
|
||||
type: 'email',
|
||||
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),
|
||||
smtpHost,
|
||||
smtpPort,
|
||||
@@ -325,8 +305,8 @@ function normalizeEmailChannel(
|
||||
from,
|
||||
to,
|
||||
subjectTemplate:
|
||||
strOr(raw.subjectTemplate, DEFAULT_SUBJECT_TEMPLATE, SUBJECT_TEMPLATE_MAX) ||
|
||||
DEFAULT_SUBJECT_TEMPLATE,
|
||||
strOr(raw.subjectTemplate, DEFAULT_EMAIL_SUBJECT, SUBJECT_TEMPLATE_MAX) ||
|
||||
DEFAULT_EMAIL_SUBJECT,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -368,7 +348,7 @@ function normalizeChannel(raw: unknown): NotificationChannel | null {
|
||||
name,
|
||||
type: 'webhook',
|
||||
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),
|
||||
...(headers ? { headers } : {}),
|
||||
};
|
||||
|
||||
@@ -1,14 +1,5 @@
|
||||
// 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.
|
||||
// Offline must survive the debounce window before it can emit a recovery pair.
|
||||
// The manager owns timers and delivery; this machine only decides transitions.
|
||||
import type { NotificationEvent } from './config';
|
||||
|
||||
export type DebounceDecision =
|
||||
@@ -17,80 +8,48 @@ export type DebounceDecision =
|
||||
| { 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;
|
||||
}
|
||||
private readonly states = new Map<string, 'pending' | 'offline'>();
|
||||
|
||||
/** 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) {
|
||||
if (this.states.has(uin)) {
|
||||
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;
|
||||
this.states.set(uin, 'offline');
|
||||
return { kind: 'emit', event: 'offline' };
|
||||
}
|
||||
|
||||
s.pending = true;
|
||||
this.states.set(uin, 'pending');
|
||||
return { kind: 'schedule', delayMs: debounceSeconds * 1000 };
|
||||
}
|
||||
|
||||
/** Account came online. */
|
||||
onOnline(uin: string): DebounceDecision {
|
||||
const s = this.state(uin);
|
||||
const state = this.states.get(uin);
|
||||
this.states.delete(uin);
|
||||
|
||||
if (s.pending) {
|
||||
s.pending = false;
|
||||
return { kind: 'cancel' }; // self-heal within the debounce window — nothing fired
|
||||
if (state === 'pending') {
|
||||
return { kind: 'cancel' };
|
||||
}
|
||||
|
||||
if (s.firedOffline) {
|
||||
s.firedOffline = false;
|
||||
return { kind: 'emit', event: 'online' }; // recovery, paired with the fired offline
|
||||
if (state === 'offline') {
|
||||
return { kind: 'emit', event: 'online' };
|
||||
}
|
||||
|
||||
return { kind: 'none' }; // cold online / already up
|
||||
return { kind: 'none' };
|
||||
}
|
||||
|
||||
/** The offline debounce window elapsed (the armed timer fired). */
|
||||
onTimerElapsed(uin: string): DebounceDecision {
|
||||
const s = this.state(uin);
|
||||
|
||||
if (!s.pending) {
|
||||
if (this.states.get(uin) !== 'pending') {
|
||||
return { kind: 'none' };
|
||||
} // cancelled before firing
|
||||
}
|
||||
|
||||
s.pending = false;
|
||||
s.firedOffline = true;
|
||||
this.states.set(uin, 'offline');
|
||||
return { kind: 'emit', event: 'offline' };
|
||||
}
|
||||
|
||||
/** Drop a UIN's state (e.g. on dispose). */
|
||||
forget(uin: string): void {
|
||||
this.states.delete(uin);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
// SMTP send, the clock) are injected so the class is fully unit-testable; the
|
||||
// real wiring lives in `createNotificationManager()` at the bottom.
|
||||
import { positiveIntEnv } from '@snowluma/common/env';
|
||||
import type { HookProcessInfo } from '@snowluma/bridge/types';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { loadOneBotConfig } from '@snowluma/onebot/config';
|
||||
import type { BridgeManager } from '../bridge/manager';
|
||||
@@ -27,9 +28,8 @@ 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). */
|
||||
/** One delivery attempt, retained in bounded in-memory history. */
|
||||
export interface DeliveryRecord {
|
||||
time: number;
|
||||
uin: string;
|
||||
@@ -58,17 +58,39 @@ export interface MailPayload {
|
||||
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 {
|
||||
/** Global channel store (channels + debounceSeconds). */
|
||||
loadConfig: () => NotificationsConfig;
|
||||
/** The channel ids a UIN has opted into. */
|
||||
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>;
|
||||
/** SMTP delivery — optional so webhook-only tests stay lean. */
|
||||
sendMail?: (mail: MailPayload) => Promise<PostResult>;
|
||||
now: () => 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 {
|
||||
@@ -91,8 +113,9 @@ 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 accounts = new Map<string, AccountNotificationContext>();
|
||||
private readonly history: DeliveryRecord[] = [];
|
||||
private readonly deliveries = new Map<string, Promise<void>>();
|
||||
private readonly historyLimit: number;
|
||||
private disposed = false;
|
||||
|
||||
@@ -105,76 +128,65 @@ export class NotificationManager {
|
||||
* OneBotManager so the nickname fallback is already populated. */
|
||||
bind(bridgeManager: BridgeManager): void {
|
||||
bridgeManager.addSessionStartedListener((uin, bridge) =>
|
||||
this.handleOnline(uin, bridge.identity.nickname),
|
||||
this.handleOnline(uin, bridge.identity.nickname, bridge.activePid),
|
||||
);
|
||||
bridgeManager.addSessionClosedListener((uin, bridge) =>
|
||||
this.handleOffline(uin, bridge.identity.nickname),
|
||||
bridgeManager.addSessionClosedListener((uin, bridge, pid) =>
|
||||
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) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (nickname) {
|
||||
this.nicknames.set(uin, nickname);
|
||||
}
|
||||
this.accounts.set(uin, {
|
||||
nickname: nickname || this.accounts.get(uin)?.nickname || uin,
|
||||
pid,
|
||||
});
|
||||
|
||||
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) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (nickname) {
|
||||
this.nicknames.set(uin, nickname);
|
||||
}
|
||||
let debounceSeconds: number;
|
||||
|
||||
this.apply(uin, this.machine.onOffline(uin, this.debounceSeconds()));
|
||||
}
|
||||
|
||||
private debounceSeconds(): number {
|
||||
try {
|
||||
return this.deps.loadConfig().debounceSeconds;
|
||||
} catch {
|
||||
return FALLBACK_DEBOUNCE_SECONDS;
|
||||
debounceSeconds = this.deps.loadConfig().debounceSeconds;
|
||||
} catch (err) {
|
||||
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 {
|
||||
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();
|
||||
}
|
||||
|
||||
timer.unref();
|
||||
this.timers.set(uin, timer);
|
||||
break;
|
||||
}
|
||||
|
||||
case 'cancel': {
|
||||
const timer = this.timers.get(uin);
|
||||
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
this.timers.delete(uin);
|
||||
}
|
||||
|
||||
clearTimeout(this.timers.get(uin));
|
||||
this.timers.delete(uin);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -186,9 +198,36 @@ export class NotificationManager {
|
||||
}
|
||||
}
|
||||
|
||||
/** Render + deliver 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> {
|
||||
/** Queue one transition; channel failures are recorded independently. */
|
||||
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[];
|
||||
|
||||
try {
|
||||
@@ -203,15 +242,29 @@ export class NotificationManager {
|
||||
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> = {
|
||||
uin,
|
||||
nickname,
|
||||
nickname: account.nickname,
|
||||
event,
|
||||
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) {
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await this.deliver(ch, vars);
|
||||
this.record({
|
||||
time: this.deps.now(),
|
||||
@@ -265,7 +318,6 @@ export class NotificationManager {
|
||||
|
||||
return await this.deps.post(ch.url, renderTemplate(ch.bodyTemplate, vars), ch.headers);
|
||||
} catch (err) {
|
||||
// Injected collaborators are contracted not to throw, but guard anyway.
|
||||
return { ok: false, error: errMsg(err) };
|
||||
}
|
||||
}
|
||||
@@ -292,6 +344,9 @@ export class NotificationManager {
|
||||
nickname: '测试账号',
|
||||
event: 'offline' as const,
|
||||
time: new Date(this.deps.now()).toISOString(),
|
||||
status: 'disconnected',
|
||||
pid: '1234',
|
||||
error: '',
|
||||
};
|
||||
return { ...(await this.deliver(channel, vars)), found: true };
|
||||
}
|
||||
@@ -378,13 +433,17 @@ export function createDefaultSendMail(
|
||||
};
|
||||
}
|
||||
|
||||
/** The real, fully-wired singleton. */
|
||||
export function createNotificationManager(): NotificationManager {
|
||||
/** The real, fully-wired singleton. `resolveProcess` is supplied by the
|
||||
* runtime — this package deliberately knows nothing about HookManager. */
|
||||
export function createNotificationManager(
|
||||
resolveProcess?: NotificationManagerDeps['resolveProcess'],
|
||||
): NotificationManager {
|
||||
return new NotificationManager({
|
||||
loadConfig: loadNotificationsConfig,
|
||||
loadChannelIds: (uin) => loadOneBotConfig(uin).notifications?.channelIds ?? [],
|
||||
post: createDefaultPost(),
|
||||
sendMail: createDefaultSendMail(),
|
||||
now: () => Date.now(),
|
||||
resolveProcess,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -339,6 +339,7 @@ describe('BridgeManager PID ownership', () => {
|
||||
manager.onPidDisconnected(101);
|
||||
expect(manager.getSession('10001')).toBeNull();
|
||||
expect(closed).toHaveBeenCalledOnce();
|
||||
expect(closed).toHaveBeenCalledWith('10001', bridge, 101);
|
||||
await expect(
|
||||
bridge.sendRawPacket('Test.NoSender', new Uint8Array([3])),
|
||||
).resolves.toMatchObject({
|
||||
@@ -512,7 +513,7 @@ describe('BridgeManager PID ownership', () => {
|
||||
|
||||
expect(started).toHaveBeenCalledTimes(2);
|
||||
expect(closed).toHaveBeenCalledOnce();
|
||||
expect(closed).toHaveBeenCalledWith('10001', expect.anything());
|
||||
expect(closed).toHaveBeenCalledWith('10001', expect.anything(), 101);
|
||||
expect(manager.getSession('10001')).toBeNull();
|
||||
expect(manager.getSession('20002')!.bridge).toBe(targetBridge);
|
||||
expect(targetBridge.activePid).toBe(101);
|
||||
@@ -561,9 +562,7 @@ describe('BridgeManager PID ownership', () => {
|
||||
try {
|
||||
manager.onHookLogin(101, '10001', sender.client);
|
||||
|
||||
// Deliberately violate the private ownership invariant through Bridge's
|
||||
// compatibility surface: Manager still maps PID 101 to this UIN, while
|
||||
// Bridge no longer owns either the PID or its sender.
|
||||
// Remove the connection without updating the manager's ownership index.
|
||||
manager.getSession('10001')!.bridge.detachPid(101);
|
||||
|
||||
expect(() => manager.onPacket(packet(101, '10001'))).toThrowError(
|
||||
|
||||
@@ -68,6 +68,35 @@ function makeProfile(uin: number, uid: string, nickname: string): UserProfileInf
|
||||
}
|
||||
|
||||
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 () => {
|
||||
const identity = IdentityService.memory('10001');
|
||||
const bridge = new Bridge(identity);
|
||||
|
||||
@@ -3,10 +3,12 @@ import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import {
|
||||
DEFAULT_BODY_TEMPLATE,
|
||||
DEFAULT_WEBHOOK_BODY,
|
||||
DEFAULT_EMAIL_BODY,
|
||||
DEFAULT_EMAIL_SUBJECT,
|
||||
} from '@snowluma/common/notification-templates';
|
||||
import {
|
||||
DEFAULT_DEBOUNCE_SECONDS,
|
||||
DEFAULT_EMAIL_BODY_TEMPLATE,
|
||||
DEFAULT_SUBJECT_TEMPLATE,
|
||||
defaultNotificationsConfig,
|
||||
normalizeNotificationsConfig,
|
||||
renderTemplate,
|
||||
@@ -145,7 +147,7 @@ describe('normalizeNotificationsConfig — total normalize', () => {
|
||||
expect(channels[0].enabled).toBe(true);
|
||||
expect(channels[0].name).toBe('c1');
|
||||
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();
|
||||
});
|
||||
|
||||
@@ -198,14 +200,14 @@ describe('normalizeNotificationsConfig — total normalize', () => {
|
||||
name: 'ops-mail',
|
||||
type: 'email',
|
||||
url: '',
|
||||
bodyTemplate: DEFAULT_EMAIL_BODY_TEMPLATE,
|
||||
bodyTemplate: DEFAULT_EMAIL_BODY,
|
||||
enabled: true,
|
||||
smtpHost: 'smtp.qq.com',
|
||||
smtpPort: 465,
|
||||
smtpSecure: true,
|
||||
from: 'SnowLuma <bot@qq.com>',
|
||||
to: 'a@example.com, b@example.com',
|
||||
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' });
|
||||
});
|
||||
|
||||
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();
|
||||
m.onOffline('u', 0); // fired offline
|
||||
m.forget('u');
|
||||
expect(m.onOnline('u')).toEqual({ kind: 'none' }); // state cleared → no recovery
|
||||
m.onOffline('u', 30);
|
||||
m.onTimerElapsed('u');
|
||||
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 { subscribeLogs, type LogEntry } from '@snowluma/common/logger';
|
||||
import {
|
||||
NotificationManager,
|
||||
createDefaultPost,
|
||||
selectChannels,
|
||||
type MailPayload,
|
||||
type NotificationManagerDeps,
|
||||
type NotificationProcessFacts,
|
||||
type PostResult,
|
||||
} from '../src/notifications/manager';
|
||||
import type { NotificationChannel, NotificationsConfig } from '../src/notifications/config';
|
||||
@@ -105,6 +107,48 @@ describe('NotificationManager — dispatch + history', () => {
|
||||
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 () => {
|
||||
let n = 0;
|
||||
const { mgr } = setup({
|
||||
@@ -119,6 +163,90 @@ describe('NotificationManager — dispatch + history', () => {
|
||||
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 () => {
|
||||
const { posts, mgr } = setup({ loadChannelIds: () => [] });
|
||||
await mgr.notify('123', 'offline');
|
||||
@@ -309,9 +437,7 @@ describe('NotificationManager — debounce integration (fake timers)', () => {
|
||||
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);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
await vi.advanceTimersByTimeAsync(60_000);
|
||||
expect(events).toEqual([]);
|
||||
});
|
||||
@@ -333,6 +459,50 @@ describe('NotificationManager — debounce integration (fake timers)', () => {
|
||||
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 () => {
|
||||
const { events, mgr } = setup(0);
|
||||
mgr.dispose();
|
||||
|
||||
@@ -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
|
||||
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
|
||||
|
||||
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
|
||||
// editable only on create and locked on edit.
|
||||
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 { Modal } from '@/components/interior/modal';
|
||||
import { Button } from '@/components/ui/button';
|
||||
@@ -65,20 +70,6 @@ function hasRecipient(value: string): boolean {
|
||||
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(
|
||||
draft: NotificationChannel,
|
||||
type: NotificationChannelType,
|
||||
@@ -227,11 +218,6 @@ export function NotificationChannelDialog(props: NotificationChannelDialogProps)
|
||||
open={open}
|
||||
onClose={() => onOpenChange(false)}
|
||||
title={isEdit ? '编辑渠道' : '新建渠道'}
|
||||
description={
|
||||
type === 'email'
|
||||
? '账号上线 / 下线时向该邮箱发送一封渲染后的通知。'
|
||||
: '账号上线 / 下线时向该 Webhook POST 一条渲染后的通知。'
|
||||
}
|
||||
closeLabel="关闭渠道编辑弹窗"
|
||||
maxWidth={576}
|
||||
maxHeight="min(86dvh, 780px)"
|
||||
@@ -365,7 +351,7 @@ export function NotificationChannelDialog(props: NotificationChannelDialogProps)
|
||||
))}
|
||||
</div>
|
||||
<p className="text-xs leading-relaxed text-muted-foreground">
|
||||
可选。用于飞书等需要鉴权头的 Webhook;默认仍带 JSON Content-Type。
|
||||
可选,默认 Content-Type 为 application/json。
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
@@ -442,7 +428,7 @@ export function NotificationChannelDialog(props: NotificationChannelDialogProps)
|
||||
<div className="min-w-0">
|
||||
<Label className="text-sm">隐式 TLS</Label>
|
||||
<p className="mt-1 text-xs leading-relaxed text-muted-foreground">
|
||||
465 通常开启;587 先明文再 STARTTLS,请关掉此项。
|
||||
465 开启,587 关闭(STARTTLS)。
|
||||
</p>
|
||||
</div>
|
||||
<ToggleSwitch
|
||||
@@ -492,8 +478,12 @@ export function NotificationChannelDialog(props: NotificationChannelDialogProps)
|
||||
变量:<code className="font-mono">{'{uin}'}</code>{' '}
|
||||
<code className="font-mono">{'{nickname}'}</code>{' '}
|
||||
<code className="font-mono">{'{event}'}</code>(offline/online){' '}
|
||||
<code className="font-mono">{'{time}'}</code>
|
||||
{type === 'email' ? '。正文以 < 开头时按 HTML 发送。' : ''}
|
||||
<code className="font-mono">{'{time}'}</code>{' '}
|
||||
<code className="font-mono">{'{status}'}</code>(Hook 状态){' '}
|
||||
<code className="font-mono">{'{pid}'}</code>(进程 ID){' '}
|
||||
<code className="font-mono">{'{error}'}</code>(进程错误)
|
||||
。进程信息为空表示未知。
|
||||
{type === 'email' ? '正文以 < 开头时按 HTML 发送。' : ''}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -501,7 +491,7 @@ export function NotificationChannelDialog(props: NotificationChannelDialogProps)
|
||||
<div className="min-w-0">
|
||||
<Label className="text-sm">启用</Label>
|
||||
<p className="mt-1 text-xs leading-relaxed text-muted-foreground">
|
||||
关闭后保留配置但不推送;账号侧对应开关会被锁定并关闭。
|
||||
关闭后停止推送,保留配置。
|
||||
</p>
|
||||
</div>
|
||||
<ToggleSwitch
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// like the per-account config page — no explicit save button.
|
||||
import { useCallback, useEffect, useRef, useState } from '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 { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
@@ -21,7 +22,7 @@ import {
|
||||
type NotificationChannel,
|
||||
type NotificationsConfig,
|
||||
} 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. */
|
||||
function blankChannel(existing: NotificationChannel[]): NotificationChannel {
|
||||
@@ -43,7 +44,6 @@ function blankChannel(existing: NotificationChannel[]): NotificationChannel {
|
||||
}
|
||||
|
||||
interface DialogState {
|
||||
open: boolean;
|
||||
index: number | null; // null → create
|
||||
seed: NotificationChannel;
|
||||
}
|
||||
@@ -53,11 +53,7 @@ export function NotificationsPanel() {
|
||||
const { runAction } = useActionFeedback();
|
||||
const [config, setConfig] = useState<NotificationsConfig | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [dialog, setDialog] = useState<DialogState>({
|
||||
open: false,
|
||||
index: null,
|
||||
seed: blankChannel([]),
|
||||
});
|
||||
const [dialog, setDialog] = useState<DialogState | null>(null);
|
||||
const [testing, setTesting] = useState<string | null>(null);
|
||||
const { msg, flash, setMsg } = useFlashMessage();
|
||||
const saveTimer = useRef<number | null>(null);
|
||||
@@ -166,18 +162,18 @@ export function NotificationsPanel() {
|
||||
const otherIds = (index: number | null) =>
|
||||
channels.filter((_, i) => i !== index).map((c) => c.id);
|
||||
|
||||
const openCreate = () => setDialog({ open: true, index: null, seed: blankChannel(channels) });
|
||||
const openEdit = (i: number) => setDialog({ open: true, index: i, seed: channels[i] });
|
||||
const openCreate = () => setDialog({ index: null, seed: blankChannel(channels) });
|
||||
const openEdit = (i: number) => setDialog({ index: i, seed: channels[i] });
|
||||
|
||||
const submitChannel = (ch: NotificationChannel) => {
|
||||
if (dialog.index == null) {
|
||||
const submitChannel = (ch: NotificationChannel, index: number | null) => {
|
||||
if (index === null) {
|
||||
setChannels([...channels, ch], {
|
||||
title: '正在新增通知渠道',
|
||||
successTitle: '通知渠道已新增',
|
||||
});
|
||||
} else {
|
||||
setChannels(
|
||||
channels.map((c, idx) => (idx === dialog.index ? ch : c)),
|
||||
channels.map((c, idx) => (idx === index ? ch : c)),
|
||||
{ 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 items-start gap-2 text-xs leading-relaxed text-muted-foreground">
|
||||
<Bell className="mt-0.5 size-3.5 shrink-0" />
|
||||
<p>
|
||||
账号上线 / 下线时向启用的渠道发送通知(Webhook POST
|
||||
或邮件,仅去抖防刷屏)。渠道在此全局定义,每个账号在其「配置」页勾选启用哪些。
|
||||
</p>
|
||||
<p>在此管理通知渠道,再到账号「配置」页选择启用。</p>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5 border-t pt-3">
|
||||
<Label>去抖窗口(秒)</Label>
|
||||
@@ -258,8 +251,7 @@ export function NotificationsPanel() {
|
||||
}}
|
||||
/>
|
||||
<p className="text-xs leading-relaxed text-muted-foreground">
|
||||
下线后在该秒数内自愈则不发;超时才发「下线」,恢复时再发「上线」。
|
||||
<code className="font-mono">0</code> = 立即发、不去抖。
|
||||
下线持续超过此时长才通知,恢复时再通知。0 表示立即通知。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -329,14 +321,14 @@ export function NotificationsPanel() {
|
||||
</p>
|
||||
)}
|
||||
|
||||
{dialog.open && (
|
||||
{dialog && (
|
||||
<NotificationChannelDialog
|
||||
open={dialog.open}
|
||||
onOpenChange={(open) => !open && setDialog((d) => ({ ...d, open: false }))}
|
||||
open
|
||||
onOpenChange={(open) => !open && setDialog(null)}
|
||||
isEdit={dialog.index != null}
|
||||
initial={dialog.seed}
|
||||
otherIds={otherIds(dialog.index)}
|
||||
onSubmit={submitChannel}
|
||||
onSubmit={(channel) => submitChannel(channel, dialog.index)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { DEFAULT_EMAIL_BODY, DEFAULT_WEBHOOK_BODY } from '@snowluma/common/notification-templates';
|
||||
import {
|
||||
DEFAULT_EMAIL_BODY,
|
||||
DEFAULT_WEBHOOK_BODY,
|
||||
NotificationChannelDialog,
|
||||
applyType,
|
||||
toChannel,
|
||||
} from '../src/components/settings/notification-channel-dialog';
|
||||
|
||||
vi.mock('@/contexts/ThemeContext', () => ({
|
||||
@@ -53,7 +54,9 @@ describe('NotificationChannelDialog', () => {
|
||||
expect(markup).toContain('Webhook URL');
|
||||
expect(markup).toContain('请求头');
|
||||
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', () => {
|
||||
@@ -86,6 +89,34 @@ describe('NotificationChannelDialog', () => {
|
||||
expect(markup).toContain('主题模板');
|
||||
expect(markup).toContain('隐式 TLS');
|
||||
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 {
|
||||
applyType,
|
||||
DEFAULT_EMAIL_BODY,
|
||||
DEFAULT_EMAIL_SUBJECT,
|
||||
DEFAULT_WEBHOOK_BODY,
|
||||
toChannel,
|
||||
} from '../src/components/settings/notification-channel-dialog';
|
||||
} from '@snowluma/common/notification-templates';
|
||||
import { applyType, toChannel } from '../src/components/settings/notification-channel-dialog';
|
||||
import { notificationChannelType, type NotificationChannel } from '../src/types';
|
||||
|
||||
function webhook(over: Partial<NotificationChannel> = {}): NotificationChannel {
|
||||
|
||||
Reference in New Issue
Block a user