fix(onebot): bring an account back when shutdown stalls

If the previous OneBot session does not finish closing, the account now
comes back online instead of staying disconnected until QQ is restarted.

Fixes #509
This commit is contained in:
DrSmoothl committed 2026-10-06 00:11:44 +08:00
1 parent e0801ff9eb
commit 940b823571
11 files changed
+273 -8

No files matched your search

+14
View File
@@ -273,6 +273,20 @@ export class OneBotInstance {
this.ctx.musicSignUrl = globalSettings.musicSignUrl;
}
/** Drop listeners and sockets without waiting for shutdown to finish.
* Used when dispose() does not settle and a replacement session must bind. */
forceRelease(): void {
try {
this.quiesce();
} catch (error) {
this.log.warn(
'quiesce during forced release failed: %s',
error instanceof Error ? error.message : String(error),
);
}
this.networkManager.forceRelease();
}
/** Synchronously stop every ingress seam for this instance generation.
*
* This operation is sticky and idempotent. It is intentionally separate
+56 -8
View File
@@ -43,7 +43,13 @@ export interface DatabaseMigrationTask {
cancel(): void;
}
/** A peer that never finishes a close handshake must not keep the next
* account session offline. Ten seconds covers a normal drain. */
const SESSION_RELEASE_DEADLINE_MS = 10_000;
export interface OneBotManagerOptions {
/** How long a retiring instance may block the replacement session. */
sessionReleaseDeadlineMs?: number;
createDatabaseMigrationTask?: (uin: string) => DatabaseMigrationTask;
createInstance?: (
uin: string,
@@ -91,8 +97,12 @@ export class OneBotManager {
private readonly createInstance: NonNullable<OneBotManagerOptions['createInstance']>;
private disposePromise: Promise<void> | null = null;
private disposed = false;
private readonly sessionReleaseDeadlineMs: number;
constructor(options: OneBotManagerOptions = {}) {
this.sessionReleaseDeadlineMs = options.sessionReleaseDeadlineMs && options.sessionReleaseDeadlineMs > 0
? options.sessionReleaseDeadlineMs
: SESSION_RELEASE_DEADLINE_MS;
this.createDatabaseMigrationTask = options.createDatabaseMigrationTask
?? createMessageStoreMigrationTask;
this.createInstance = options.createInstance
@@ -447,20 +457,58 @@ export class OneBotManager {
return result;
}
private async releaseRetiringInstance(
uin: string,
pending: { bridge: BridgeInterface; cancelled: boolean },
instance: OneBotInstance,
): Promise<void> {
let timer: NodeJS.Timeout | undefined;
const timeout = new Promise<'timeout'>((resolve) => {
timer = setTimeout(() => resolve('timeout'), this.sessionReleaseDeadlineMs);
timer.unref?.();
});
// Map rejection here so a dispose() that fails after the deadline still
// has a handler. The race may already have moved on.
const releasing = instance.dispose().then(
() => 'released' as const,
(error: unknown) => ({ failed: error }),
);
try {
const outcome = await Promise.race([releasing, timeout]);
if (outcome === 'timeout') {
log.error(
'session release timed out; forcing adapters closed and starting the replacement: UIN=%s',
uin,
);
try {
instance.forceRelease?.();
} catch (error) {
log.error(
'forced session release failed: UIN=%s: %s',
uin,
error instanceof Error ? error.message : String(error),
);
}
return;
}
if (typeof outcome === 'object') {
// Do not leave this UIN permanently guarded by a failed handoff. A
// later session-start observation may retry the still-visible retire.
if (this.pendingStarts.get(uin) === pending) this.pendingStarts.delete(uin);
throw new InstanceLifecycleError(instance, outcome.failed);
}
} finally {
if (timer) clearTimeout(timer);
}
}
private async finishRetiringBeforeStart(
uin: string,
pending: { bridge: BridgeInterface; cancelled: boolean },
retiring: OneBotInstance[],
): Promise<void> {
for (const instance of retiring) {
try {
await instance.dispose();
} catch (error) {
// Do not leave this UIN permanently guarded by a failed handoff. A
// later session-start observation may retry the still-visible retire.
if (this.pendingStarts.get(uin) === pending) this.pendingStarts.delete(uin);
throw new InstanceLifecycleError(instance, error);
}
await this.releaseRetiringInstance(uin, pending, instance);
this.retirementSucceeded(instance);
}
if (this.pendingStarts.get(uin) !== pending) return;
+5
View File
@@ -61,6 +61,11 @@ export abstract class IOneBotNetworkAdapter<C extends NetworkBase> {
abstract open(): void | Promise<void>;
abstract close(): void | Promise<void>;
/** Drop sockets and listeners without waiting for a peer handshake.
* Graceful `close()` can sit forever on a half-open connection; shutdown
* uses this so the next account session can bind the same ports. */
forceClose(): void { /* adapters that own a listener override this */ }
abstract onEvent(event: JsonObject, payload: DispatchPayload): void | Promise<void>;
/** Report live connection health for the WebUI dashboard. */
@@ -25,6 +25,7 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
private server: Server | null = null;
private webSocketServer: WebSocketServer | null = null;
private listening = false;
private releaseForced = false;
private closePromise: Promise<void> | null = null;
private acceptingActions = false;
private readonly inFlightActions = new Set<Promise<void>>();
@@ -113,6 +114,7 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
try {
await attempt;
} catch (error) {
if (this.releaseForced) return;
if (!httpReleased && server?.listening === true) {
// A failed HTTP close callback cannot prove the listener was released.
// The upgrade handler is still attached, so the old ingress can accept
@@ -128,6 +130,26 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
}
}
override forceClose(): void {
this.releaseForced = true;
this.acceptingActions = false;
this.webSocketConnections.stopAccepting();
this.isEnabled = false;
this.listening = false;
this.webSocketConnections.terminateAll();
const webSocketServer = this.webSocketServer;
this.webSocketServer = null;
const server = this.server;
this.server = null;
if (webSocketServer) {
try { webSocketServer.destroy(); } catch { /* already dropping */ }
}
if (server) {
try { server.closeAllConnections(); } catch { /* already closed */ }
try { server.close(() => undefined); } catch { /* already closed */ }
}
}
override describeStatus(): AdapterStatus {
if (!this.isEnabled) return { name: this.name, kind: 'httpServer', status: 'disabled', detail: '未启用' };
if (!this.listening) return { name: this.name, kind: 'httpServer', status: 'down', detail: '未监听(端口被占用?)' };
@@ -228,6 +228,20 @@ export class OneBotNetworkManager {
return this.shutdown();
}
/** Best-effort immediate release. Does not wait for the operation queue,
* in-flight dispatches, or peer close handshakes. */
forceRelease(): void {
this.acceptingReconciles = false;
this.acceptingEvents = false;
for (const { adapter } of this.adapters.values()) {
try {
adapter.forceClose();
} catch (error) {
log.error('forced adapter release failed: %s', errMessage(error));
}
}
}
emitEvent(event: JsonObject): Promise<void> {
if (!this.acceptingEvents) {
return Promise.reject(new Error('network manager is shutting down; event dispatch rejected'));
@@ -60,6 +60,21 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
}
}
override forceClose(): void {
this.explicitlyClosed = true;
this.acceptingActions = false;
this.isEnabled = false;
this.connected = false;
this.cancelReconnect();
this.heartbeatStop?.();
this.heartbeatStop = null;
const socket = this.socket;
this.socket = null;
if (socket) {
try { socket.terminate(); } catch { /* already gone */ }
}
}
async close(): Promise<void> {
this.explicitlyClosed = true;
this.acceptingActions = false;
@@ -15,6 +15,7 @@ const moduleLog = createLogger('OneBot.WS-Server');
export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
private wss: WebSocketServer | null = null;
private listening = false;
private releaseForced = false;
private closePromise: Promise<void> | null = null;
private readonly connections: WsServerConnections;
@@ -66,6 +67,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
await attempt;
if (wss && this.wss === wss) this.wss = null;
} catch (error) {
if (this.releaseForced) return;
// A failed close callback leaves release ambiguous. Retain the server
// reference and active binding state so a later shutdown can retry.
this.isEnabled = wasEnabled;
@@ -77,6 +79,19 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
}
}
override forceClose(): void {
this.releaseForced = true;
this.isEnabled = false;
this.listening = false;
this.connections.stopAccepting();
this.connections.terminateAll();
const wss = this.wss;
this.wss = null;
if (wss) {
try { wss.destroy(); } catch { /* already dropping */ }
}
}
override describeStatus(): AdapterStatus {
if (!this.isEnabled) return { name: this.name, kind: 'wsServer', status: 'disabled', detail: '未启用' };
if (!this.listening) return { name: this.name, kind: 'wsServer', status: 'down', detail: '未监听(端口被占用?)' };
@@ -212,6 +212,17 @@ export class WsServerConnections {
this.connections.clear();
}
/** Destroy sockets immediately. A graceful close frame can leave the
* listener waiting on a peer that will never answer. */
terminateAll(): void {
this.stopAccepting();
for (const connection of this.connections.values()) {
connection.stopHeartbeat();
try { connection.socket.terminate(); } catch { /* already gone */ }
}
this.connections.clear();
}
private async handleApiMessage(socket: WebSocket, role: WsRole, raw: Buffer | string): Promise<void> {
const text = rawDataToString(raw);
if (!text) {