refactor(bridge): start roster warmup when the session can send
Friend, group, and member lists load as soon as a Bridge can send packets, instead of waiting for OneBot database preparation. Login history sync still waits until the instance is usable and both lists have loaded.
This commit is contained in:
5 files changed
+419
-144
No files matched your search
+30
-117
@@ -13,7 +13,6 @@ import type { AdapterStatus, NetworkApplyError } from './network';
|
||||
import type { OneBotConfig } from './types';
|
||||
|
||||
const log = createLogger('OneBot');
|
||||
const VERBOSE_WARMUP = process.env.SNOWLUMA_VERBOSE_WARMUP === '1';
|
||||
|
||||
class InstanceLifecycleError extends Error {
|
||||
constructor(readonly instance: OneBotInstance, readonly rootCause: unknown) {
|
||||
@@ -357,27 +356,36 @@ export class OneBotManager {
|
||||
else log.warn('network startup degraded: UIN=%s failures=%d', uin, result.errors.length);
|
||||
instance.startGroupRequestPolling();
|
||||
}));
|
||||
void warmUpBridgeState(uin, bridge).then(
|
||||
(warmup) => {
|
||||
if (warmup.friendsLoaded && warmup.groupsLoaded) {
|
||||
instance.startLoginHistorySync();
|
||||
return;
|
||||
}
|
||||
log.warn(
|
||||
'login history sync skipped because roster warmup was incomplete: '
|
||||
+ 'UIN=%s friendsLoaded=%s groupsLoaded=%s',
|
||||
uin,
|
||||
String(warmup.friendsLoaded),
|
||||
String(warmup.groupsLoaded),
|
||||
);
|
||||
},
|
||||
(err) => {
|
||||
log.warn(
|
||||
'warmup error for UIN %s: %s',
|
||||
uin,
|
||||
err instanceof Error ? (err.stack ?? err.message) : String(err),
|
||||
);
|
||||
},
|
||||
void this.armLoginHistorySync(uin, instance, bridge);
|
||||
}
|
||||
|
||||
private async armLoginHistorySync(
|
||||
uin: string,
|
||||
instance: OneBotInstance,
|
||||
bridge: BridgeInterface,
|
||||
): Promise<void> {
|
||||
let warmup;
|
||||
try {
|
||||
warmup = await bridge.whenRosterWarmupSettled();
|
||||
} catch (err) {
|
||||
log.warn(
|
||||
'warmup error for UIN %s: %s',
|
||||
uin,
|
||||
err instanceof Error ? (err.stack ?? err.message) : String(err),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (this.disposed || this.instances.get(uin) !== instance) return;
|
||||
if (warmup.friendsLoaded && warmup.groupsLoaded) {
|
||||
instance.startLoginHistorySync();
|
||||
return;
|
||||
}
|
||||
log.warn(
|
||||
'login history sync skipped because roster warmup was incomplete: '
|
||||
+ 'UIN=%s friendsLoaded=%s groupsLoaded=%s',
|
||||
uin,
|
||||
String(warmup.friendsLoaded),
|
||||
String(warmup.groupsLoaded),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -497,99 +505,4 @@ function migrationPublicState(
|
||||
};
|
||||
}
|
||||
|
||||
interface BridgeWarmupResult {
|
||||
friendsLoaded: boolean;
|
||||
groupsLoaded: boolean;
|
||||
}
|
||||
|
||||
async function warmUpBridgeState(
|
||||
uin: string,
|
||||
bridge: BridgeInterface,
|
||||
): Promise<BridgeWarmupResult> {
|
||||
const selfUin = parseInt(uin, 10) || 0;
|
||||
let selfResolved = false;
|
||||
let friendsLoaded = false;
|
||||
|
||||
// Step 1: Fetch friend list + derive self profile when QQ happens to
|
||||
// include self in the response. Some accounts / versions omit self,
|
||||
// which used to leave identity.nickname empty — see step 1b for the
|
||||
// explicit fallback.
|
||||
try {
|
||||
const friends = await bridge.apis.contacts.fetchFriendList();
|
||||
friendsLoaded = true;
|
||||
log.info('friends loaded: UIN=%s count=%d', uin, friends.length);
|
||||
|
||||
for (const f of friends) {
|
||||
if (f.uin === selfUin) {
|
||||
bridge.identity.setSelfProfile({
|
||||
uin: f.uin, uid: f.uid,
|
||||
nickname: f.nickname || uin,
|
||||
remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '', level: 0,
|
||||
qidianMasterFlag: 0, qidianCrewFlag: 0, qidianCrewFlag2: 0,
|
||||
});
|
||||
bridge.identity.nickname = f.nickname || uin;
|
||||
log.debug('self info: UIN=%s uid=%s nickname=%s', uin, f.uid, f.nickname ?? '');
|
||||
selfResolved = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
log.warn('failed to load friends for UIN %s: %s', uin, e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
|
||||
// Step 1b: friend-list path didn't resolve self → fetch user profile
|
||||
// directly via OIDB 0xFE1_2 so multi-account WebUI shows a nickname
|
||||
// for every injected session, not just the ones where QQ echoed self
|
||||
// back in the friend list.
|
||||
if (!selfResolved && selfUin > 0) {
|
||||
try {
|
||||
const profile = await bridge.apis.contacts.fetchUserProfile(selfUin);
|
||||
bridge.identity.setSelfProfile(profile);
|
||||
bridge.identity.nickname = profile.nickname || uin;
|
||||
log.debug('self info via profile: UIN=%s uid=%s nickname=%s',
|
||||
uin, profile.uid, profile.nickname);
|
||||
} catch (e) {
|
||||
log.warn('failed to load self profile for UIN %s: %s',
|
||||
uin, e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
}
|
||||
|
||||
// Step 2: Fetch group list
|
||||
let groups: { groupId: number }[] = [];
|
||||
let groupsLoaded = false;
|
||||
try {
|
||||
groups = await bridge.apis.contacts.fetchGroupList();
|
||||
groupsLoaded = true;
|
||||
log.info('groups loaded: UIN=%s count=%d', uin, groups.length);
|
||||
} catch (e) {
|
||||
log.warn('failed to load groups for UIN %s: %s', uin, e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
|
||||
// Step 3: Fetch members for each group
|
||||
let loadedGroupCount = 0;
|
||||
let loadedMemberCount = 0;
|
||||
let failedGroupCount = 0;
|
||||
for (const g of groups) {
|
||||
try {
|
||||
const members = await bridge.apis.contacts.fetchGroupMemberList(g.groupId);
|
||||
loadedGroupCount += 1;
|
||||
loadedMemberCount += members.length;
|
||||
if (VERBOSE_WARMUP) {
|
||||
log.debug('members loaded: group=%d count=%d', g.groupId, members.length);
|
||||
}
|
||||
} catch (e) {
|
||||
failedGroupCount += 1;
|
||||
log.warn('failed to load members for group %d: %s', g.groupId, e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
}
|
||||
|
||||
log.info(
|
||||
'member warmup completed: UIN=%s groups=%d/%d members=%d failed=%d',
|
||||
uin,
|
||||
loadedGroupCount,
|
||||
groups.length,
|
||||
loadedMemberCount,
|
||||
failedGroupCount,
|
||||
);
|
||||
return { friendsLoaded, groupsLoaded };
|
||||
}
|
||||
@@ -12,6 +12,14 @@ import {
|
||||
} from '../src/manager';
|
||||
import { estimateRemainingSeconds } from '../src/message-store-migration-task';
|
||||
|
||||
function fakeBridge(warmup?: Promise<{ friendsLoaded: boolean; groupsLoaded: boolean }>) {
|
||||
return {
|
||||
activePid: null,
|
||||
identity: { nickname: 'test' },
|
||||
whenRosterWarmupSettled: () => warmup ?? Promise.resolve({ friendsLoaded: false, groupsLoaded: false }),
|
||||
};
|
||||
}
|
||||
|
||||
function fakeInstance(
|
||||
uin: string,
|
||||
dispose: () => Promise<unknown>,
|
||||
@@ -77,12 +85,7 @@ describe('OneBotManager database preparation', () => {
|
||||
addSessionStartedListener: (listener) => { startListener = listener; },
|
||||
addSessionClosedListener: vi.fn(),
|
||||
} as never);
|
||||
const bridge = {
|
||||
activePid: null,
|
||||
identity: { nickname: 'test' },
|
||||
fetchFriends: vi.fn(() => new Promise(() => undefined)),
|
||||
fetchGroups: vi.fn(() => new Promise(() => undefined)),
|
||||
};
|
||||
const bridge = fakeBridge(new Promise(() => undefined));
|
||||
|
||||
runWithRequestId(5201, () => startListener('10001', bridge as never));
|
||||
callbacks.onReady();
|
||||
@@ -162,12 +165,7 @@ describe('OneBotManager database preparation', () => {
|
||||
});
|
||||
|
||||
try {
|
||||
const bridge = {
|
||||
activePid: null,
|
||||
identity: { nickname: 'test' },
|
||||
fetchFriends: vi.fn(async () => undefined),
|
||||
fetchGroups: vi.fn(async () => undefined),
|
||||
};
|
||||
const bridge = fakeBridge();
|
||||
(manager as unknown as { onSessionStarted(uin: string, bridge: never): void })
|
||||
.onSessionStarted('10001', bridge as never);
|
||||
callbacks.onReady();
|
||||
@@ -203,10 +201,7 @@ describe('OneBotManager database preparation', () => {
|
||||
onSessionStarted(uin: string, bridge: never): void;
|
||||
onSessionClosed(uin: string): void;
|
||||
};
|
||||
const bridge = {
|
||||
activePid: null,
|
||||
identity: { nickname: 'test' },
|
||||
};
|
||||
const bridge = fakeBridge();
|
||||
|
||||
expect(() => internals.onSessionStarted('10001', bridge as never)).not.toThrow();
|
||||
expect(tasks[0].cancel).toHaveBeenCalledOnce();
|
||||
@@ -255,12 +250,7 @@ describe('OneBotManager database preparation', () => {
|
||||
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),
|
||||
};
|
||||
const bridge = fakeBridge();
|
||||
|
||||
internals.onSessionStarted('10001', bridge as never);
|
||||
expect(() => callbacks.onReady()).not.toThrow();
|
||||
@@ -301,10 +291,7 @@ describe('OneBotManager database preparation', () => {
|
||||
onSessionStarted(uin: string, bridge: never): void;
|
||||
onSessionClosed(uin: string): void;
|
||||
};
|
||||
const bridge = {
|
||||
activePid: null,
|
||||
identity: { nickname: 'test' },
|
||||
};
|
||||
const bridge = fakeBridge();
|
||||
|
||||
internals.onSessionStarted('10001', bridge as never);
|
||||
expect(() => callbacks[0].onReady()).not.toThrow();
|
||||
@@ -369,6 +356,110 @@ describe('OneBotManager database preparation', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('OneBotManager login history sync', () => {
|
||||
async function withTempCwd(run: () => Promise<void>): Promise<void> {
|
||||
const originalCwd = process.cwd();
|
||||
const root = mkdtempSync(path.join(tmpdir(), 'snowluma-manager-history-'));
|
||||
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('does not start history sync when roster warmup is incomplete', async () => {
|
||||
await withTempCwd(async () => {
|
||||
const instance = {
|
||||
...fakeInstance('10001', async () => undefined),
|
||||
waitUntilNetworkReady: vi.fn(async () => ({ applied: true, statuses: [], errors: [] })),
|
||||
startLoginHistorySync: vi.fn(),
|
||||
} 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();
|
||||
await Promise.resolve();
|
||||
expect(instance.startLoginHistorySync).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
await manager.dispose();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('starts history sync only after the instance is usable and warmup has both lists', async () => {
|
||||
await withTempCwd(async () => {
|
||||
let settleWarmup!: (result: { friendsLoaded: boolean; groupsLoaded: boolean }) => void;
|
||||
const warmup = new Promise<{ friendsLoaded: boolean; groupsLoaded: boolean }>((resolve) => {
|
||||
settleWarmup = resolve;
|
||||
});
|
||||
const instance = {
|
||||
...fakeInstance('10001', async () => undefined),
|
||||
waitUntilNetworkReady: vi.fn(async () => ({ applied: true, statuses: [], errors: [] })),
|
||||
startLoginHistorySync: vi.fn(),
|
||||
} as unknown as OneBotInstance;
|
||||
const { manager, ready } = preparingManager(instance);
|
||||
try {
|
||||
(manager as unknown as { onSessionStarted(uin: string, bridge: never): void })
|
||||
.onSessionStarted('10001', fakeBridge(warmup) as never);
|
||||
ready();
|
||||
await Promise.resolve();
|
||||
expect(instance.startLoginHistorySync).not.toHaveBeenCalled();
|
||||
settleWarmup({ friendsLoaded: true, groupsLoaded: true });
|
||||
await vi.waitFor(() => {
|
||||
expect(instance.startLoginHistorySync).toHaveBeenCalledOnce();
|
||||
});
|
||||
} finally {
|
||||
await manager.dispose();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('starts history sync when warmup finished before the instance became usable', async () => {
|
||||
await withTempCwd(async () => {
|
||||
const instance = {
|
||||
...fakeInstance('10001', async () => undefined),
|
||||
waitUntilNetworkReady: vi.fn(async () => ({ applied: true, statuses: [], errors: [] })),
|
||||
startLoginHistorySync: vi.fn(),
|
||||
} as unknown as OneBotInstance;
|
||||
const { manager, ready } = preparingManager(instance);
|
||||
try {
|
||||
(manager as unknown as { onSessionStarted(uin: string, bridge: never): void })
|
||||
.onSessionStarted('10001', fakeBridge(Promise.resolve({
|
||||
friendsLoaded: true,
|
||||
groupsLoaded: true,
|
||||
})) as never);
|
||||
expect(instance.startLoginHistorySync).not.toHaveBeenCalled();
|
||||
ready();
|
||||
await vi.waitFor(() => {
|
||||
expect(instance.startLoginHistorySync).toHaveBeenCalledOnce();
|
||||
});
|
||||
} finally {
|
||||
await manager.dispose();
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('OneBotManager lifecycle failure accounting', () => {
|
||||
it('quiesces active instances before waiting for pending lifecycle work', async () => {
|
||||
const manager = new OneBotManager();
|
||||
|
||||
Reference in new issue
Block a user