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:
19 files changed
+616
-387
No files matched your search
@@ -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,
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user