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

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

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

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

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

---------

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

No files matched your search

@@ -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 <[email protected]>',
to: '[email protected], [email protected]',
subjectTemplate: DEFAULT_SUBJECT_TEMPLATE,
subjectTemplate: DEFAULT_EMAIL_SUBJECT,
},
]);
});
@@ -62,10 +62,14 @@ describe('DebounceMachine — online↔offline debounce (Uptime-Kuma semantics)'
expect(m.onOnline('a')).toEqual({ kind: 'emit', event: 'online' });
});
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();