feat(onebot): emit bot_status on account session edges
Give downstream bots a notice when an account comes up or goes down, so they can handle their own alerts. Operator notification channels are unchanged.
This commit is contained in:
9 files changed
+307
-10
No files matched your search
@@ -197,6 +197,12 @@ export class OneBotInstance {
|
||||
return this.networkReady;
|
||||
}
|
||||
|
||||
/** Bridge session edge → OneBot notice. Awaited so offline can leave
|
||||
* adapters before this generation is disposed. */
|
||||
emitBotStatus(subType: 'online' | 'offline'): Promise<void> {
|
||||
return this.dispatchEvent(makeBotStatusEvent(parseInt(this.uin, 10) || 0, subType));
|
||||
}
|
||||
|
||||
/** Begin observing request-list-only group invitations after adapters exist. */
|
||||
startGroupRequestPolling(): void {
|
||||
if (this.disposeRequested) return;
|
||||
@@ -355,11 +361,11 @@ export class OneBotInstance {
|
||||
return this.pids.size === 0;
|
||||
}
|
||||
|
||||
private dispatchEvent(
|
||||
private async dispatchEvent(
|
||||
event: JsonObject,
|
||||
source: 'bridge' | 'send' = 'bridge',
|
||||
startedAt = Date.now(),
|
||||
): void {
|
||||
): Promise<void> {
|
||||
if (source === 'bridge') {
|
||||
this.cacheMessageEvent(event);
|
||||
if (this.consumePendingSelfSentEcho(event)) {
|
||||
@@ -386,9 +392,11 @@ export class OneBotInstance {
|
||||
return;
|
||||
}
|
||||
this.traceEventHandoffTerminal(event, startedAt, 'reporting_started');
|
||||
void this.networkManager.emitEvent(event).catch((err) => {
|
||||
try {
|
||||
await this.networkManager.emitEvent(event);
|
||||
} catch (err) {
|
||||
this.log.warn('emitEvent failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private traceEventHandoffTerminal(
|
||||
@@ -654,6 +662,21 @@ export class OneBotInstance {
|
||||
}
|
||||
}
|
||||
|
||||
export function makeBotStatusEvent(
|
||||
selfId: number,
|
||||
subType: 'online' | 'offline',
|
||||
time = Math.floor(Date.now() / 1000),
|
||||
): JsonObject {
|
||||
return {
|
||||
time,
|
||||
self_id: selfId,
|
||||
post_type: 'notice',
|
||||
notice_type: 'bot_status',
|
||||
sub_type: subType,
|
||||
user_id: selfId,
|
||||
};
|
||||
}
|
||||
|
||||
function toInt(value: unknown): number {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
|
||||
if (typeof value === 'string' && value.trim()) {
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
createMessageStoreMigrationTask,
|
||||
estimateRemainingSeconds,
|
||||
} from './message-store-migration-task';
|
||||
import type { AdapterStatus, NetworkApplyError } from './network';
|
||||
import type { AdapterStatus, NetworkApplyError, NetworkShutdownResult } from './network';
|
||||
import type { OneBotConfig } from './types';
|
||||
|
||||
const log = createLogger('OneBot');
|
||||
@@ -351,10 +351,20 @@ export class OneBotManager {
|
||||
|
||||
this.instances.set(uin, instance);
|
||||
log.info('session started: UIN=%s', uin);
|
||||
this.trackLifecycle(`network startup UIN=${uin}`, instance.waitUntilNetworkReady().then((result) => {
|
||||
this.trackLifecycle(`network startup UIN=${uin}`, instance.waitUntilNetworkReady().then(async (result) => {
|
||||
if (result.applied) log.info('network startup applied: UIN=%s adapters=%d', uin, result.statuses.length);
|
||||
else log.warn('network startup degraded: UIN=%s failures=%d', uin, result.errors.length);
|
||||
instance.startGroupRequestPolling();
|
||||
if (this.disposed || this.instances.get(uin) !== instance) return;
|
||||
try {
|
||||
await instance.emitBotStatus('online');
|
||||
} catch (error) {
|
||||
log.warn(
|
||||
'bot_status online failed: UIN=%s: %s',
|
||||
uin,
|
||||
error instanceof Error ? (error.stack ?? error.message) : String(error),
|
||||
);
|
||||
}
|
||||
}));
|
||||
void this.armLoginHistorySync(uin, instance, bridge);
|
||||
}
|
||||
@@ -412,15 +422,27 @@ export class OneBotManager {
|
||||
this.retiringInstances.add(instance);
|
||||
this.trackLifecycle(
|
||||
`network shutdown UIN=${uin}`,
|
||||
instance.dispose().then((result) => {
|
||||
this.retirementSucceeded(instance);
|
||||
return result;
|
||||
}),
|
||||
this.emitOfflineThenDispose(instance),
|
||||
[instance],
|
||||
);
|
||||
log.info('session closed: UIN=%s', uin);
|
||||
}
|
||||
|
||||
private async emitOfflineThenDispose(instance: OneBotInstance): Promise<NetworkShutdownResult> {
|
||||
try {
|
||||
await instance.emitBotStatus('offline');
|
||||
} catch (error) {
|
||||
log.warn(
|
||||
'bot_status offline failed: UIN=%s: %s',
|
||||
instance.uin,
|
||||
error instanceof Error ? (error.stack ?? error.message) : String(error),
|
||||
);
|
||||
}
|
||||
const result = await instance.dispose();
|
||||
this.retirementSucceeded(instance);
|
||||
return result;
|
||||
}
|
||||
|
||||
private async finishRetiringBeforeStart(
|
||||
uin: string,
|
||||
pending: { bridge: BridgeInterface; cancelled: boolean },
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { convertEvent, type ConverterContext } from '../src/event-converter';
|
||||
import { makeBotStatusEvent } from '../src/instance';
|
||||
import type { QQEventVariant } from '@snowluma/protocol/events';
|
||||
|
||||
describe('makeBotStatusEvent', () => {
|
||||
it('emits a notice with online/offline sub_type and matching ids', () => {
|
||||
const online = makeBotStatusEvent(10000, 'online', 1_710_000_000);
|
||||
expect(online).toEqual({
|
||||
time: 1_710_000_000,
|
||||
self_id: 10000,
|
||||
post_type: 'notice',
|
||||
notice_type: 'bot_status',
|
||||
sub_type: 'online',
|
||||
user_id: 10000,
|
||||
});
|
||||
|
||||
const offline = makeBotStatusEvent(10000, 'offline', 1_710_000_001);
|
||||
expect(offline.post_type).toBe('notice');
|
||||
expect(offline.notice_type).toBe('bot_status');
|
||||
expect(offline.sub_type).toBe('offline');
|
||||
expect(offline.self_id).toBe(10000);
|
||||
expect(offline.user_id).toBe(10000);
|
||||
});
|
||||
});
|
||||
|
||||
describe('convertEvent — bot_offline (KickNT)', () => {
|
||||
it('keeps notice_type bot_offline with tag and message', async () => {
|
||||
const ctx: ConverterContext = {
|
||||
selfId: 10001,
|
||||
imageUrlResolver: null,
|
||||
mediaUrlResolver: null,
|
||||
messageIdResolver: null,
|
||||
mediaSegmentSink: null,
|
||||
};
|
||||
const out = await convertEvent(ctx, {
|
||||
kind: 'bot_offline',
|
||||
time: 1,
|
||||
selfUin: 10001,
|
||||
tag: '你已离线',
|
||||
message: '你的账号在其他设备登录',
|
||||
} as QQEventVariant);
|
||||
expect(out).toEqual({
|
||||
time: 1,
|
||||
self_id: 10001,
|
||||
post_type: 'notice',
|
||||
notice_type: 'bot_offline',
|
||||
user_id: 10001,
|
||||
tag: '你已离线',
|
||||
message: '你的账号在其他设备登录',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,151 @@
|
||||
import { mkdtempSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import type { OneBotInstance } from '../src/instance';
|
||||
import {
|
||||
OneBotManager,
|
||||
type DatabaseMigrationCallbacks,
|
||||
} from '../src/manager';
|
||||
|
||||
function fakeBridge() {
|
||||
return {
|
||||
activePid: null,
|
||||
identity: { nickname: 'test' },
|
||||
whenRosterWarmupSettled: () => Promise.resolve({ friendsLoaded: false, groupsLoaded: false }),
|
||||
};
|
||||
}
|
||||
|
||||
describe('OneBotManager bot_status', () => {
|
||||
async function withTempCwd(run: () => Promise<void>): Promise<void> {
|
||||
const originalCwd = process.cwd();
|
||||
const root = mkdtempSync(path.join(tmpdir(), 'snowluma-manager-bot-status-'));
|
||||
process.chdir(root);
|
||||
try {
|
||||
await run();
|
||||
} finally {
|
||||
process.chdir(originalCwd);
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
function preparingManager(instance: OneBotInstance) {
|
||||
let callbacks!: DatabaseMigrationCallbacks;
|
||||
const manager = new OneBotManager({
|
||||
createDatabaseMigrationTask: () => ({
|
||||
beginMigration: vi.fn(),
|
||||
cancel: vi.fn(),
|
||||
start: (next) => { callbacks = next; },
|
||||
}),
|
||||
createInstance: () => instance,
|
||||
});
|
||||
return {
|
||||
manager,
|
||||
ready: () => callbacks.onReady(),
|
||||
};
|
||||
}
|
||||
|
||||
it('emits online after the instance network is ready', async () => {
|
||||
await withTempCwd(async () => {
|
||||
let releaseNetwork!: (value: { applied: boolean; statuses: []; errors: [] }) => void;
|
||||
const networkReady = new Promise<{ applied: boolean; statuses: []; errors: [] }>((resolve) => {
|
||||
releaseNetwork = resolve;
|
||||
});
|
||||
const emitBotStatus = vi.fn(async () => undefined);
|
||||
const instance = {
|
||||
uin: '10001',
|
||||
nickname: 'test',
|
||||
quiesce: vi.fn(),
|
||||
dispose: vi.fn(async () => ({ closed: true, errors: [] })),
|
||||
emitBotStatus,
|
||||
waitUntilNetworkReady: vi.fn(() => networkReady),
|
||||
startGroupRequestPolling: vi.fn(),
|
||||
startLoginHistorySync: vi.fn(),
|
||||
getConnectionStatuses: () => [],
|
||||
} as unknown as OneBotInstance;
|
||||
const { manager, ready } = preparingManager(instance);
|
||||
try {
|
||||
(manager as unknown as { onSessionStarted(uin: string, bridge: never): void })
|
||||
.onSessionStarted('10001', fakeBridge() as never);
|
||||
ready();
|
||||
await Promise.resolve();
|
||||
expect(emitBotStatus).not.toHaveBeenCalled();
|
||||
releaseNetwork({ applied: true, statuses: [], errors: [] });
|
||||
await vi.waitFor(() => {
|
||||
expect(emitBotStatus).toHaveBeenCalledOnce();
|
||||
});
|
||||
expect(emitBotStatus).toHaveBeenCalledWith('online');
|
||||
expect(instance.startGroupRequestPolling).toHaveBeenCalledOnce();
|
||||
} finally {
|
||||
await manager.dispose();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('emits offline and awaits it before dispose', async () => {
|
||||
let finishOffline!: () => void;
|
||||
const offlineGate = new Promise<void>((resolve) => { finishOffline = resolve; });
|
||||
const order: string[] = [];
|
||||
const emitBotStatus = vi.fn(async (subType: 'online' | 'offline') => {
|
||||
if (subType === 'offline') {
|
||||
order.push('offline-start');
|
||||
await offlineGate;
|
||||
order.push('offline-done');
|
||||
}
|
||||
});
|
||||
const dispose = vi.fn(async () => {
|
||||
order.push('dispose');
|
||||
return { closed: true, errors: [] };
|
||||
});
|
||||
const instance = {
|
||||
uin: '10001',
|
||||
nickname: 'test',
|
||||
quiesce: vi.fn(),
|
||||
dispose,
|
||||
emitBotStatus,
|
||||
startGroupRequestPolling: vi.fn(),
|
||||
getConnectionStatuses: () => [],
|
||||
} as unknown as OneBotInstance;
|
||||
const manager = new OneBotManager();
|
||||
const internals = manager as unknown as {
|
||||
instances: Map<string, OneBotInstance>;
|
||||
onSessionClosed(uin: string): void;
|
||||
};
|
||||
internals.instances.set('10001', instance);
|
||||
|
||||
internals.onSessionClosed('10001');
|
||||
await Promise.resolve();
|
||||
expect(order).toEqual(['offline-start']);
|
||||
expect(dispose).not.toHaveBeenCalled();
|
||||
|
||||
finishOffline();
|
||||
await vi.waitFor(() => {
|
||||
expect(order).toEqual(['offline-start', 'offline-done', 'dispose']);
|
||||
});
|
||||
expect(emitBotStatus).toHaveBeenCalledWith('offline');
|
||||
await manager.dispose();
|
||||
});
|
||||
|
||||
it('does not emit offline when the process is disposing', async () => {
|
||||
const emitBotStatus = vi.fn(async () => undefined);
|
||||
const dispose = vi.fn(async () => ({ closed: true, errors: [] }));
|
||||
const instance = {
|
||||
uin: '10001',
|
||||
nickname: 'test',
|
||||
quiesce: vi.fn(),
|
||||
dispose,
|
||||
emitBotStatus,
|
||||
startGroupRequestPolling: vi.fn(),
|
||||
getConnectionStatuses: () => [],
|
||||
} as unknown as OneBotInstance;
|
||||
const manager = new OneBotManager();
|
||||
(manager as unknown as { instances: Map<string, OneBotInstance> }).instances.set('10001', instance);
|
||||
|
||||
await manager.dispose();
|
||||
expect(emitBotStatus).not.toHaveBeenCalled();
|
||||
expect(dispose).toHaveBeenCalledOnce();
|
||||
|
||||
(manager as unknown as { onSessionClosed(uin: string): void }).onSessionClosed('10001');
|
||||
expect(emitBotStatus).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -31,6 +31,7 @@ function fakeInstance(
|
||||
nickname: `retiring-${uin}`,
|
||||
quiesce,
|
||||
dispose,
|
||||
emitBotStatus: vi.fn(async () => undefined),
|
||||
startGroupRequestPolling: vi.fn(),
|
||||
getConnectionStatuses: () => statuses,
|
||||
} as unknown as OneBotInstance;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type {
|
||||
OneBotBotStatusEvent,
|
||||
OneBotGroupMessageEvent,
|
||||
OneBotMessageEvent,
|
||||
OneBotMetaEvent,
|
||||
@@ -26,6 +27,13 @@ export function isNoticeEvent(event: SnowLumaEvent): event is OneBotNoticeEvent
|
||||
return event.post_type === 'notice' && typeof event.notice_type === 'string';
|
||||
}
|
||||
|
||||
export function isBotStatusEvent(event: SnowLumaEvent): event is OneBotBotStatusEvent {
|
||||
return isNoticeEvent(event)
|
||||
&& event.notice_type === 'bot_status'
|
||||
&& (event.sub_type === 'online' || event.sub_type === 'offline')
|
||||
&& typeof event.user_id === 'number';
|
||||
}
|
||||
|
||||
export function isRequestEvent(event: SnowLumaEvent): event is OneBotRequestEvent {
|
||||
return event.post_type === 'request' && typeof event.request_type === 'string' && typeof event.flag === 'string';
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ export {
|
||||
} from './errors';
|
||||
export {
|
||||
createEventContext,
|
||||
isBotStatusEvent,
|
||||
isGroupMessageEvent,
|
||||
isMessageEvent,
|
||||
isMetaEvent,
|
||||
|
||||
@@ -50,6 +50,15 @@ export interface OneBotNoticeEvent extends OneBotBaseEvent {
|
||||
notice_type: string;
|
||||
}
|
||||
|
||||
export type BotStatusSubType = 'online' | 'offline';
|
||||
|
||||
/** Bridge session edge. Not KickNT `bot_offline`. */
|
||||
export interface OneBotBotStatusEvent extends OneBotNoticeEvent {
|
||||
notice_type: 'bot_status';
|
||||
sub_type: BotStatusSubType;
|
||||
user_id: number;
|
||||
}
|
||||
|
||||
export interface OneBotRequestEvent extends OneBotBaseEvent {
|
||||
post_type: 'request';
|
||||
request_type: string;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
isBotStatusEvent,
|
||||
isGroupMessageEvent,
|
||||
isMessageEvent,
|
||||
isMetaEvent,
|
||||
@@ -248,6 +249,34 @@ describe('isNoticeEvent', () => {
|
||||
expect(isNoticeEvent(nulled)).toBe(false);
|
||||
});
|
||||
|
||||
it('accepts bot_status notices and rejects incomplete ones', () => {
|
||||
expect(isBotStatusEvent({
|
||||
time: 19,
|
||||
self_id: 10000,
|
||||
post_type: 'notice',
|
||||
notice_type: 'bot_status',
|
||||
sub_type: 'online',
|
||||
user_id: 10000,
|
||||
})).toBe(true);
|
||||
expect(isBotStatusEvent({
|
||||
time: 20,
|
||||
self_id: 10000,
|
||||
post_type: 'notice',
|
||||
notice_type: 'bot_status',
|
||||
sub_type: 'offline',
|
||||
user_id: 10000,
|
||||
})).toBe(true);
|
||||
expect(isBotStatusEvent(NOTICE)).toBe(false);
|
||||
expect(isBotStatusEvent({
|
||||
time: 21,
|
||||
self_id: 10000,
|
||||
post_type: 'notice',
|
||||
notice_type: 'bot_status',
|
||||
sub_type: 'flap',
|
||||
user_id: 10000,
|
||||
})).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects other post types', () => {
|
||||
expect(isNoticeEvent(PRIVATE_MESSAGE)).toBe(false);
|
||||
expect(isNoticeEvent(REQUEST)).toBe(false);
|
||||
|
||||
Reference in new issue
Block a user