fix(onebot): continue storage updates after account startup

Start each account as soon as its message storage is ready, then continue older history updates without delaying normal account availability. Keep already started accounts online when maintenance needs to be retried.

Handle preparation failures, stale completions, early exits, logout, and shutdown consistently. Add lifecycle coverage for startup ordering, automatic retries, cancellation, and account availability.
This commit is contained in:
DrSmoothl committed 2026-07-30 09:57:18 +08:00
1 parent caed31ca20
commit 25e61ce5df
7 files changed
+800 -29

No files matched your search

+35 -21
View File
@@ -10,30 +10,37 @@ import {
import { OneBotManager } from '@snowluma/onebot/manager';
import { migrateGlobalSettings } from '@snowluma/onebot/global-config';
import { cleanupInvalidPerUinConfigs } from '@snowluma/onebot/config';
import {
isMessageStoreMigrationWorkerData,
runMessageStoreMigrationWorker,
} from '@snowluma/onebot/message-store-migration-worker';
import { workerData } from 'node:worker_threads';
import { BridgeManager } from './bridge/manager';
import { createNotificationManager } from './notifications/manager';
import { createStateWiring } from './webui/state-wiring';
const runtimeConfig = loadRuntimeConfig();
const log = createLogger('App');
// Last-resort process guards. This is a long-running daemon: a hooked QQ pipe
// can drop at any moment, and a stray rejection on a detached callback (or a
// throw that escapes one) must NOT take the whole process down — otherwise
// Docker restarts it (dropping every session) and a bare Windows run just dies
// ("connection pipe closed", bot offline). Log and keep serving; the bridge's
// own watcher reconnects the dropped pipe. Targeted handlers still cover the
// known paths (e.g. the hook-client send deferreds) — these only catch what
// slips through, and surface its stack so the real source can be fixed.
process.on('unhandledRejection', (reason) => {
log.error('unhandledRejection (kept alive): %s',
reason instanceof Error ? (reason.stack ?? reason.message) : String(reason));
});
process.on('uncaughtException', (error) => {
log.error('uncaughtException (kept alive): %s', error.stack ?? error.message);
});
function installProcessGuards(): void {
// Last-resort process guards. This is a long-running daemon: a hooked QQ pipe
// can drop at any moment, and a stray rejection on a detached callback (or a
// throw that escapes one) must NOT take the whole process down — otherwise
// Docker restarts it (dropping every session) and a bare Windows run just dies
// ("connection pipe closed", bot offline). Log and keep serving; the bridge's
// own watcher reconnects the dropped pipe. Targeted handlers still cover the
// known paths (e.g. the hook-client send deferreds) — these only catch what
// slips through, and surface its stack so the real source can be fixed.
process.on('unhandledRejection', (reason) => {
log.error('unhandledRejection (kept alive): %s',
reason instanceof Error ? (reason.stack ?? reason.message) : String(reason));
});
process.on('uncaughtException', (error) => {
log.error('uncaughtException (kept alive): %s', error.stack ?? error.message);
});
}
async function main() {
const runtimeConfig = loadRuntimeConfig();
await configureFileTransport({
maxTotalMb: runtimeConfig.logMaxTotalMb ?? DEFAULT_LOG_MAX_TOTAL_MB,
retainDays: runtimeConfig.logRetainDays ?? DEFAULT_LOG_RETAIN_DAYS,
@@ -134,8 +141,15 @@ function resolveAutoLoad(fromConfig: boolean | undefined): boolean {
return fromConfig === true;
}
main().catch(async (error) => {
log.error(error instanceof Error ? (error.stack ?? error.message) : String(error));
await closeLogger();
process.exit(1);
});
if (isMessageStoreMigrationWorkerData(workerData)) {
runMessageStoreMigrationWorker(workerData).catch(() => {
process.exitCode = 1;
});
} else {
installProcessGuards();
main().catch(async (error) => {
log.error(error instanceof Error ? (error.stack ?? error.message) : String(error));
await closeLogger();
process.exit(1);
});
}
+4
View File
@@ -60,6 +60,10 @@
"types": "./src/message-store.ts",
"default": "./src/message-store.ts"
},
"./message-store-migration-worker": {
"types": "./src/message-store-migration-worker.ts",
"default": "./src/message-store-migration-worker.ts"
},
"./media-store": {
"types": "./src/media-store.ts",
"default": "./src/media-store.ts"
+204 -7
View File
@@ -4,6 +4,11 @@ import type { BridgeManager } from '@snowluma/core/manager';
import { loadOneBotConfig } from './config';
import { loadGlobalSettings } from './global-config';
import { OneBotInstance } from './instance';
import type { MessageStoreMigrationStatus } from './message-store-migration';
import {
createMessageStoreMigrationTask,
estimateRemainingSeconds,
} from './message-store-migration-task';
import type { AdapterStatus, NetworkApplyError } from './network';
import type { OneBotConfig } from './types';
@@ -17,11 +22,44 @@ class InstanceLifecycleError extends Error {
}
}
export interface AccountDatabaseMigration {
phase: 'preparing' | 'migrating' | 'complete' | 'failed';
usable: boolean;
processed: number;
total: number | null;
progress: number | null;
estimatedRemainingSeconds: number | null;
error?: string;
}
export interface DatabaseMigrationCallbacks {
onReady(): void;
onProgress(status: MessageStoreMigrationStatus, elapsedMs: number): void;
onFailed(error: unknown): void;
}
export interface DatabaseMigrationTask {
start(callbacks: DatabaseMigrationCallbacks): void;
beginMigration(): void;
cancel(): void;
}
export interface OneBotManagerOptions {
createDatabaseMigrationTask?: (uin: string) => DatabaseMigrationTask;
createInstance?: (
uin: string,
bridge: BridgeInterface,
config: OneBotConfig,
globalSettings: ReturnType<typeof loadGlobalSettings>,
) => OneBotInstance;
}
/** Per-account OneBot connection health, surfaced to the WebUI dashboard. */
export interface AccountConnections {
uin: string;
nickname: string;
adapters: AdapterStatus[];
databaseMigration?: AccountDatabaseMigration;
}
export interface ConfigApplyResult {
@@ -41,9 +79,32 @@ export class OneBotManager {
instances?: Set<OneBotInstance>;
}> = [];
private readonly pendingStarts = new Map<string, { bridge: BridgeInterface; cancelled: boolean }>();
private readonly databaseMigrations = new Map<string, {
bridge: BridgeInterface;
task: DatabaseMigrationTask;
state: AccountDatabaseMigration;
ready: boolean;
cancelled: boolean;
rowsPerSecond: number | null;
retryTimer: NodeJS.Timeout | null;
}>();
private readonly createDatabaseMigrationTask: (uin: string) => DatabaseMigrationTask;
private readonly createInstance: NonNullable<OneBotManagerOptions['createInstance']>;
private disposePromise: Promise<void> | null = null;
private disposed = false;
constructor(options: OneBotManagerOptions = {}) {
this.createDatabaseMigrationTask = options.createDatabaseMigrationTask
?? createMessageStoreMigrationTask;
this.createInstance = options.createInstance
?? ((uin, bridge, config, globalSettings) => new OneBotInstance(
uin,
bridge,
config,
globalSettings,
));
}
bind(bridgeManager: BridgeManager): void {
bridgeManager.addSessionStartedListener((uin, bridge) => {
this.onSessionStarted(uin, bridge);
@@ -69,11 +130,25 @@ export class OneBotManager {
for (const instance of this.retiringInstances) {
if (!visible.includes(instance)) visible.push(instance);
}
return visible.map((i) => ({
uin: i.uin,
nickname: i.nickname,
adapters: i.getConnectionStatuses(),
const connections = visible.map((instance) => ({
uin: instance.uin,
nickname: instance.nickname,
adapters: instance.getConnectionStatuses(),
...(this.databaseMigrations.get(instance.uin)?.state
? { databaseMigration: this.databaseMigrations.get(instance.uin)?.state }
: {}),
}));
const activeUins = new Set(this.instances.keys());
for (const [uin, migration] of this.databaseMigrations) {
if (activeUins.has(uin)) continue;
connections.push({
uin,
nickname: migration.bridge.identity?.nickname || uin,
adapters: [],
databaseMigration: migration.state,
});
}
return connections;
}
async reloadConfig(uin: string, config: OneBotConfig): Promise<ConfigApplyResult> {
@@ -107,6 +182,12 @@ export class OneBotManager {
dispose(): Promise<void> {
if (this.disposePromise) return this.disposePromise;
this.disposed = true;
for (const migration of this.databaseMigrations.values()) {
migration.cancelled = true;
if (migration.retryTimer) clearTimeout(migration.retryTimer);
migration.task.cancel();
}
this.databaseMigrations.clear();
for (const instance of this.instances.values()) this.retiringInstances.add(instance);
// Quiesce every live generation before awaiting older startup/shutdown
// work. A deferred lifecycle operation must not leave Action ingress open
@@ -173,14 +254,95 @@ export class OneBotManager {
return;
}
this.startSession(uin, bridge);
this.prepareDatabase(uin, bridge);
}
private prepareDatabase(uin: string, bridge: BridgeInterface): void {
if (this.disposed || this.instances.has(uin) || this.databaseMigrations.has(uin)) return;
const migration = {
bridge,
task: this.createDatabaseMigrationTask(uin),
state: preparingMigrationState(),
ready: false,
cancelled: false,
rowsPerSecond: null as number | null,
retryTimer: null as NodeJS.Timeout | null,
};
this.databaseMigrations.set(uin, migration);
const startTask = (): void => {
const handleFailure = (): void => {
if (migration.cancelled || this.databaseMigrations.get(uin) !== migration) return;
migration.state = {
...migration.state,
phase: 'failed',
usable: migration.ready,
estimatedRemainingSeconds: null,
error: '数据库迁移失败,将自动重试',
};
log.error('database migration failed: UIN=%s', uin);
migration.task.cancel();
if (migration.retryTimer) return;
migration.retryTimer = setTimeout(() => {
migration.retryTimer = null;
if (migration.cancelled || this.databaseMigrations.get(uin) !== migration) return;
migration.task = this.createDatabaseMigrationTask(uin);
migration.state = migration.ready
? { ...migration.state, phase: 'migrating', usable: true, error: undefined }
: preparingMigrationState();
startTask();
}, 5_000);
migration.retryTimer.unref?.();
};
try {
migration.task.start({
onReady: () => {
if (migration.cancelled || this.databaseMigrations.get(uin) !== migration) return;
try {
this.startSession(uin, bridge);
} catch {
handleFailure();
return;
}
migration.ready = true;
migration.state = {
...migration.state,
phase: 'migrating',
usable: true,
error: undefined,
};
try {
migration.task.beginMigration();
} catch {
handleFailure();
}
},
onProgress: (status, elapsedMs) => {
if (migration.cancelled || this.databaseMigrations.get(uin) !== migration) return;
const previousProcessed = migration.state.processed;
const processedDelta = Math.max(0, status.processed - previousProcessed);
if (processedDelta > 0 && elapsedMs > 0) {
const observed = processedDelta / (elapsedMs / 1000);
migration.rowsPerSecond = migration.rowsPerSecond === null
? observed
: (migration.rowsPerSecond * 0.7) + (observed * 0.3);
}
migration.state = migrationPublicState(status, migration.rowsPerSecond);
if (status.phase === 'complete') migration.task.cancel();
},
onFailed: handleFailure,
});
} catch {
handleFailure();
}
};
startTask();
}
private startSession(uin: string, bridge: BridgeInterface): void {
if (this.disposed || this.instances.has(uin)) return;
const config = loadOneBotConfig(uin, { persistDefaults: true });
const instance = new OneBotInstance(uin, bridge, config, loadGlobalSettings());
const instance = this.createInstance(uin, bridge, config, loadGlobalSettings());
const activePid = bridge.activePid;
if (activePid !== null) {
@@ -219,6 +381,13 @@ export class OneBotManager {
}
private onSessionClosed(uin: string): void {
const migration = this.databaseMigrations.get(uin);
if (migration) {
migration.cancelled = true;
if (migration.retryTimer) clearTimeout(migration.retryTimer);
migration.task.cancel();
this.databaseMigrations.delete(uin);
}
const instance = this.instances.get(uin);
if (!instance) {
const pending = this.pendingStarts.get(uin);
@@ -261,7 +430,7 @@ export class OneBotManager {
if (this.pendingStarts.get(uin) !== pending) return;
this.pendingStarts.delete(uin);
if (pending.cancelled || this.disposed) return;
this.startSession(uin, pending.bridge);
this.prepareDatabase(uin, pending.bridge);
}
private trackLifecycle(
@@ -298,6 +467,34 @@ export class OneBotManager {
}
function preparingMigrationState(): AccountDatabaseMigration {
return {
phase: 'preparing',
usable: false,
processed: 0,
total: null,
progress: null,
estimatedRemainingSeconds: null,
};
}
function migrationPublicState(
status: MessageStoreMigrationStatus,
rowsPerSecond: number | null,
): AccountDatabaseMigration {
const progress = status.total === 0
? 1
: Math.min(1, status.processed / status.total);
return {
phase: status.phase,
usable: true,
processed: status.processed,
total: status.total,
progress,
estimatedRemainingSeconds: estimateRemainingSeconds(status, rowsPerSecond),
};
}
interface BridgeWarmupResult {
friendsLoaded: boolean;
groupsLoaded: boolean;
@@ -0,0 +1,103 @@
import { createRequire } from 'node:module';
import path from 'node:path';
import { Worker, type WorkerOptions } from 'node:worker_threads';
import type {
DatabaseMigrationCallbacks,
DatabaseMigrationTask,
} from './manager';
import type { MessageStoreMigrationStatus } from './message-store-migration';
import {
MESSAGE_STORE_WORKER_KIND,
type MessageStoreMigrationWorkerData,
type MessageStoreMigrationWorkerMessage,
} from './message-store-migration-worker';
export interface MessageStoreMigrationWorkerHandle {
on(event: 'message', listener: (message: MessageStoreMigrationWorkerMessage) => void): this;
once(event: 'error', listener: (error: Error) => void): this;
once(event: 'exit', listener: (code: number) => void): this;
postMessage(message: 'start' | 'cancel'): void;
unref(): void;
}
type CreateMigrationWorker = (
filename: string,
options: WorkerOptions,
) => MessageStoreMigrationWorkerHandle;
export function createMessageStoreMigrationTask(
uin: string,
createWorker: CreateMigrationWorker = (filename, options) => new Worker(filename, options),
): DatabaseMigrationTask {
let worker: MessageStoreMigrationWorkerHandle | null = null;
let cancelled = false;
let finished = false;
let failureReported = false;
return {
start(callbacks: DatabaseMigrationCallbacks): void {
const reportFailure = (error: Error): void => {
if (cancelled || failureReported) return;
failureReported = true;
callbacks.onFailed(error);
};
const data: MessageStoreMigrationWorkerData = {
kind: MESSAGE_STORE_WORKER_KIND,
dbPath: path.join('data', uin, 'messages.db'),
};
const entryPath = process.argv[1];
const sourceEntry = /\.(?:cts|mts|ts|tsx)$/.test(entryPath);
worker = createWorker(
sourceEntry ? sourceWorkerBootstrap(entryPath) : entryPath,
{
workerData: data,
eval: sourceEntry,
execArgv: sourceEntry ? [] : process.execArgv,
},
);
worker.on('message', (message: MessageStoreMigrationWorkerMessage) => {
if (cancelled) return;
if (message.kind === 'ready') {
callbacks.onReady();
} else if (message.kind === 'progress') {
callbacks.onProgress(message.status, message.elapsedMs);
if (message.status.phase === 'complete') finished = true;
} else {
reportFailure(new Error(message.message));
}
});
worker.once('error', reportFailure);
worker.once('exit', (code) => {
if (!cancelled && !finished) {
reportFailure(new Error(`database migration worker exited before completion with code ${code}`));
}
});
},
beginMigration(): void {
if (!cancelled) worker?.postMessage('start');
},
cancel(): void {
cancelled = true;
worker?.postMessage('cancel');
worker?.unref();
},
};
}
function sourceWorkerBootstrap(entryPath: string): string {
const require = createRequire(path.resolve(entryPath));
return [
`const { register } = require(${JSON.stringify(require.resolve('tsx/esm/api'))});`,
'register();',
`import(${JSON.stringify(path.resolve(entryPath))});`,
].join('\n');
}
export function estimateRemainingSeconds(
status: MessageStoreMigrationStatus,
recentRowsPerSecond: number | null,
): number | null {
if (status.phase === 'complete') return 0;
if (!recentRowsPerSecond || recentRowsPerSecond <= 0) return null;
return Math.max(0, Math.ceil((status.total - status.processed) / recentRowsPerSecond));
}
@@ -0,0 +1,85 @@
import { parentPort, workerData } from 'node:worker_threads';
import {
MessageStoreMigrator,
prepareMessageStoreDatabase,
type MessageStoreMigrationStatus,
} from './message-store-migration';
export const MESSAGE_STORE_WORKER_KIND = 'snowluma-message-store-migration';
const DEFAULT_BATCH_SIZE = 200;
const DEFAULT_BATCH_PAUSE_MS = 25;
export interface MessageStoreMigrationWorkerData {
kind: typeof MESSAGE_STORE_WORKER_KIND;
dbPath: string;
}
export type MessageStoreMigrationWorkerMessage =
| { kind: 'ready' }
| {
kind: 'progress';
status: MessageStoreMigrationStatus;
elapsedMs: number;
}
| { kind: 'failed'; message: string };
export function isMessageStoreMigrationWorkerData(
value: unknown = workerData,
): value is MessageStoreMigrationWorkerData {
if (value === null || typeof value !== 'object') return false;
const candidate = value as Partial<MessageStoreMigrationWorkerData>;
return candidate.kind === MESSAGE_STORE_WORKER_KIND && typeof candidate.dbPath === 'string';
}
export async function runMessageStoreMigrationWorker(
data: MessageStoreMigrationWorkerData,
port = parentPort,
): Promise<void> {
if (!port) throw new Error('database migration worker port is unavailable');
let migrator: MessageStoreMigrator | null = null;
let cancelled = false;
let releaseStart!: () => void;
const startRequested = new Promise<void>((resolve) => { releaseStart = resolve; });
const handleControlMessage = (message: unknown): void => {
if (message === 'cancel') cancelled = true;
if (message === 'start' || message === 'cancel') releaseStart();
};
port.on('message', handleControlMessage);
try {
prepareMessageStoreDatabase(data.dbPath);
port.postMessage({ kind: 'ready' } satisfies MessageStoreMigrationWorkerMessage);
await startRequested;
if (cancelled) return;
migrator = new MessageStoreMigrator(data.dbPath);
let lastProgressAt: number | null = null;
while (!cancelled) {
const status = migrator.runBatch(DEFAULT_BATCH_SIZE);
const progressAt = performance.now();
port.postMessage({
kind: 'progress',
status,
elapsedMs: lastProgressAt === null
? 0
: Math.max(0, progressAt - lastProgressAt),
} satisfies MessageStoreMigrationWorkerMessage);
lastProgressAt = progressAt;
if (status.phase === 'complete') return;
await pause(DEFAULT_BATCH_PAUSE_MS);
}
} catch (error) {
port.postMessage({
kind: 'failed',
message: error instanceof Error ? error.message : String(error),
} satisfies MessageStoreMigrationWorkerMessage);
} finally {
port.off('message', handleControlMessage);
migrator?.close();
}
}
function pause(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
+303 -1
View File
@@ -1,7 +1,15 @@
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 { AdapterStatus } from '../src/network';
import type { OneBotInstance } from '../src/instance';
import { OneBotManager } from '../src/manager';
import {
OneBotManager,
type DatabaseMigrationCallbacks,
type DatabaseMigrationTask,
} from '../src/manager';
import { estimateRemainingSeconds } from '../src/message-store-migration-task';
function fakeInstance(
uin: string,
@@ -18,6 +26,300 @@ function fakeInstance(
} as unknown as OneBotInstance;
}
describe('database migration estimates', () => {
it('waits for measured throughput and reaches zero on completion', () => {
expect(estimateRemainingSeconds(
{ phase: 'migrating', processed: 200, total: 1_000 },
null,
)).toBeNull();
expect(estimateRemainingSeconds(
{ phase: 'migrating', processed: 200, total: 1_000 },
125,
)).toBe(7);
expect(estimateRemainingSeconds(
{ phase: 'complete', processed: 1_000, total: 1_000 },
null,
)).toBe(0);
});
});
describe('OneBotManager database preparation', () => {
it('surfaces preparation as unavailable and ignores a stale completion after logout', async () => {
let callbacks!: DatabaseMigrationCallbacks;
const cancel = vi.fn();
const task: DatabaseMigrationTask = {
beginMigration: vi.fn(),
cancel,
start: vi.fn((next) => { callbacks = next; }),
};
const manager = new OneBotManager({
createDatabaseMigrationTask: () => task,
createInstance: () => { throw new Error('stale preparation started an account'); },
});
const internals = manager as unknown as {
onSessionStarted(uin: string, bridge: never): void;
onSessionClosed(uin: string): void;
};
internals.onSessionStarted('10001', {} as never);
expect(manager.getConnectionStatuses()).toEqual([{
uin: '10001',
nickname: '10001',
adapters: [],
databaseMigration: {
phase: 'preparing',
usable: false,
processed: 0,
total: null,
progress: null,
estimatedRemainingSeconds: null,
},
}]);
internals.onSessionClosed('10001');
callbacks.onReady();
await Promise.resolve();
expect(cancel).toHaveBeenCalledOnce();
expect(manager.getInstance('10001')).toBeNull();
expect(manager.getConnectionStatuses()).toEqual([]);
});
it('starts migration only after the account instance is available', async () => {
const originalCwd = process.cwd();
const root = mkdtempSync(path.join(tmpdir(), 'snowluma-manager-lifecycle-'));
process.chdir(root);
let callbacks!: DatabaseMigrationCallbacks;
let instanceCreated = false;
const beginMigration = vi.fn(() => {
expect(instanceCreated).toBe(true);
});
const instance = {
...fakeInstance('10001', async () => undefined),
waitUntilNetworkReady: vi.fn(async () => ({
applied: true,
statuses: [],
errors: [],
})),
startLoginHistorySync: vi.fn(),
} as unknown as OneBotInstance;
const manager = new OneBotManager({
createDatabaseMigrationTask: () => ({
beginMigration,
cancel: vi.fn(),
start: (next) => { callbacks = next; },
}),
createInstance: (_uin, _bridge, _config, _globalSettings) => {
instanceCreated = true;
return instance;
},
});
try {
const bridge = {
activePid: null,
identity: { nickname: 'test' },
fetchFriends: vi.fn(async () => undefined),
fetchGroups: vi.fn(async () => undefined),
};
(manager as unknown as { onSessionStarted(uin: string, bridge: never): void })
.onSessionStarted('10001', bridge as never);
callbacks.onReady();
expect(beginMigration).toHaveBeenCalledOnce();
expect(manager.getInstance('10001')).not.toBeNull();
} finally {
await manager.dispose();
process.chdir(originalCwd);
rmSync(root, { recursive: true, force: true });
}
});
it('retries when starting the database task fails synchronously', () => {
vi.useFakeTimers();
try {
const tasks: DatabaseMigrationTask[] = [];
const manager = new OneBotManager({
createDatabaseMigrationTask: () => {
const task: DatabaseMigrationTask = {
beginMigration: vi.fn(),
cancel: vi.fn(),
start: vi.fn(() => { throw new Error('private worker detail'); }),
};
tasks.push(task);
return task;
},
});
const internals = manager as unknown as {
onSessionStarted(uin: string, bridge: never): void;
onSessionClosed(uin: string): void;
};
const bridge = {
activePid: null,
identity: { nickname: 'test' },
};
expect(() => internals.onSessionStarted('10001', bridge as never)).not.toThrow();
expect(tasks[0].cancel).toHaveBeenCalledOnce();
expect(manager.getConnectionStatuses()[0].databaseMigration).toMatchObject({
phase: 'failed',
usable: false,
error: '数据库迁移失败,将自动重试',
});
vi.advanceTimersByTime(5_000);
expect(tasks).toHaveLength(2);
expect(tasks[1].start).toHaveBeenCalledOnce();
internals.onSessionClosed('10001');
} finally {
vi.useRealTimers();
}
});
it('keeps the account usable when beginning migration fails', () => {
vi.useFakeTimers();
try {
let callbacks!: DatabaseMigrationCallbacks;
const tasks: DatabaseMigrationTask[] = [];
const instance = {
...fakeInstance('10001', async () => undefined),
waitUntilNetworkReady: vi.fn(async () => ({
applied: true,
statuses: [],
errors: [],
})),
startLoginHistorySync: vi.fn(),
} as unknown as OneBotInstance;
const manager = new OneBotManager({
createDatabaseMigrationTask: () => {
const task: DatabaseMigrationTask = {
beginMigration: vi.fn(() => { throw new Error('private signal detail'); }),
cancel: vi.fn(),
start: vi.fn((next) => { callbacks = next; }),
};
tasks.push(task);
return task;
},
createInstance: () => instance,
});
const internals = manager as unknown as {
onSessionStarted(uin: string, bridge: never): void;
onSessionClosed(uin: string): void;
};
const bridge = {
activePid: null,
identity: { nickname: 'test' },
fetchFriends: vi.fn(async () => undefined),
fetchGroups: vi.fn(async () => undefined),
};
internals.onSessionStarted('10001', bridge as never);
expect(() => callbacks.onReady()).not.toThrow();
expect(tasks[0].cancel).toHaveBeenCalledOnce();
expect(manager.getInstance('10001')).toBe(instance);
expect(manager.getConnectionStatuses()[0].databaseMigration).toMatchObject({
phase: 'failed',
usable: true,
error: '数据库迁移失败,将自动重试',
});
vi.advanceTimersByTime(5_000);
expect(tasks).toHaveLength(2);
internals.onSessionClosed('10001');
} finally {
vi.useRealTimers();
}
});
it('retries when account startup fails after database preparation', () => {
vi.useFakeTimers();
try {
const callbacks: DatabaseMigrationCallbacks[] = [];
const tasks: DatabaseMigrationTask[] = [];
const manager = new OneBotManager({
createDatabaseMigrationTask: () => {
const task: DatabaseMigrationTask = {
beginMigration: vi.fn(),
cancel: vi.fn(),
start: vi.fn((next) => { callbacks.push(next); }),
};
tasks.push(task);
return task;
},
createInstance: () => { throw new Error('private startup detail'); },
});
const internals = manager as unknown as {
onSessionStarted(uin: string, bridge: never): void;
onSessionClosed(uin: string): void;
};
const bridge = {
activePid: null,
identity: { nickname: 'test' },
};
internals.onSessionStarted('10001', bridge as never);
expect(() => callbacks[0].onReady()).not.toThrow();
expect(tasks[0].cancel).toHaveBeenCalledOnce();
expect(tasks[0].beginMigration).not.toHaveBeenCalled();
expect(manager.getInstance('10001')).toBeNull();
expect(manager.getConnectionStatuses()[0].databaseMigration).toMatchObject({
phase: 'failed',
usable: false,
error: '数据库迁移失败,将自动重试',
});
vi.advanceTimersByTime(5_000);
expect(tasks).toHaveLength(2);
expect(tasks[1].start).toHaveBeenCalledOnce();
internals.onSessionClosed('10001');
} finally {
vi.useRealTimers();
}
});
it('retries a failed database task while the session remains present', async () => {
vi.useFakeTimers();
try {
const callbacks: DatabaseMigrationCallbacks[] = [];
const tasks: DatabaseMigrationTask[] = [];
const manager = new OneBotManager({
createDatabaseMigrationTask: () => {
const task: DatabaseMigrationTask = {
beginMigration: vi.fn(),
cancel: vi.fn(),
start: vi.fn((next) => { callbacks.push(next); }),
};
tasks.push(task);
return task;
},
});
const internals = manager as unknown as {
onSessionStarted(uin: string, bridge: never): void;
onSessionClosed(uin: string): void;
};
internals.onSessionStarted('10001', {} as never);
callbacks[0].onFailed(new Error('private detail'));
expect(manager.getConnectionStatuses()[0].databaseMigration).toMatchObject({
phase: 'failed',
usable: false,
error: '数据库迁移失败,将自动重试',
});
vi.advanceTimersByTime(5_000);
expect(tasks).toHaveLength(2);
expect(tasks[1].start).toHaveBeenCalledOnce();
internals.onSessionClosed('10001');
callbacks[1].onFailed(new Error('late failure'));
vi.advanceTimersByTime(5_000);
expect(tasks).toHaveLength(2);
} finally {
vi.useRealTimers();
}
});
});
describe('OneBotManager lifecycle failure accounting', () => {
it('quiesces active instances before waiting for pending lifecycle work', async () => {
const manager = new OneBotManager();
@@ -0,0 +1,66 @@
import { EventEmitter } from 'node:events';
import { describe, expect, it, vi } from 'vitest';
import type { DatabaseMigrationCallbacks } from '../src/manager';
import {
createMessageStoreMigrationTask,
type MessageStoreMigrationWorkerHandle,
} from '../src/message-store-migration-task';
function fakeWorker(): EventEmitter & MessageStoreMigrationWorkerHandle {
const worker = new EventEmitter() as EventEmitter & MessageStoreMigrationWorkerHandle;
worker.postMessage = vi.fn();
worker.unref = vi.fn();
return worker;
}
function callbacks(): DatabaseMigrationCallbacks {
return {
onReady: vi.fn(),
onProgress: vi.fn(),
onFailed: vi.fn(),
};
}
describe('message-store migration task lifecycle', () => {
it('reports an exit before completion even when its code is zero', () => {
const worker = fakeWorker();
const handlers = callbacks();
const task = createMessageStoreMigrationTask('10001', () => worker);
task.start(handlers);
worker.emit('exit', 0);
expect(handlers.onFailed).toHaveBeenCalledOnce();
});
it('accepts a normal exit after completion', () => {
const worker = fakeWorker();
const handlers = callbacks();
const task = createMessageStoreMigrationTask('10001', () => worker);
task.start(handlers);
worker.emit('message', {
kind: 'progress',
status: { phase: 'complete', processed: 8, total: 8 },
elapsedMs: 25,
});
worker.emit('exit', 0);
expect(handlers.onProgress).toHaveBeenCalledOnce();
expect(handlers.onFailed).not.toHaveBeenCalled();
});
it('ignores worker exit after cancellation', () => {
const worker = fakeWorker();
const handlers = callbacks();
const task = createMessageStoreMigrationTask('10001', () => worker);
task.start(handlers);
task.cancel();
worker.emit('exit', 1);
expect(worker.postMessage).toHaveBeenCalledWith('cancel');
expect(worker.unref).toHaveBeenCalledOnce();
expect(handlers.onFailed).not.toHaveBeenCalled();
});
});