refactor: use native async discovery and simplify shared state

This commit is contained in:
手瓜一十雪 committed 2026-10-18 12:57:18 +08:00
1 parent 5032cbb8c0
commit 4e2b6b1200
87 files changed
+2063 -2002

No files matched your search

+3 -17
View File
@@ -1,3 +1,4 @@
import { fromHex, toHex } from '@snowluma/common/hex';
import { mapWithConcurrency } from '@snowluma/common/concurrency';
import { positiveIntEnv } from '@snowluma/common/env';
import { readFile } from 'node:fs/promises';
@@ -3275,7 +3276,7 @@ export const actions = [
);
}
const body = hexToBytes(p.data);
const body = fromHex(p.data);
const result = await ctx.bridge.sendRawPacket(p.cmd, body);
if (!result.success) {
@@ -3286,7 +3287,7 @@ export const actions = [
return okResponse(null);
}
const respHex = result.responseData ? bytesToHex(result.responseData) : '';
const respHex = result.responseData ? toHex(result.responseData) : '';
return okResponse(respHex);
},
}),
@@ -3577,21 +3578,6 @@ async function fetchFilteredGroupRequests(ctx: ApiActionContext) {
return ctx.bridge.apis.contacts.fetchGroupRequests(true);
}
function hexToBytes(hex: string): Uint8Array {
const out = new Uint8Array(hex.length / 2);
for (let i = 0; i < out.length; i++) {
out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
}
return out;
}
function bytesToHex(buf: Buffer | Uint8Array): string {
const arr = buf instanceof Buffer ? buf : Buffer.from(buf);
return arr.toString('hex');
}
function parseDownloadHeaders(headers: unknown): Record<string, string> {
const result: Record<string, string> = {};
+1 -4
View File
@@ -1,3 +1,4 @@
import { errorMessage } from '@snowluma/common/errors';
// Stream API file actions (#163) — NapCat-compatible chunked file transfer.
//
// upload_file_stream: a client (possibly on another machine) pushes a file to
@@ -531,7 +532,3 @@ export const __test = {
MAX_CONCURRENT_STREAMS,
MAX_CHUNKS,
};
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
+1 -1
View File
@@ -287,7 +287,7 @@ export class GroupRequestPoller {
this.timer = null;
this.scheduledTask = this.runScheduledPoll();
}, this.intervalMs);
this.timer.unref?.();
this.timer.unref();
}
}
}
+1 -1
View File
@@ -534,7 +534,7 @@ function abortableSleep(ms: number, signal: AbortSignal): Promise<void> {
signal.removeEventListener('abort', onAbort);
resolve();
}, ms);
timer.unref?.();
timer.unref();
const onAbort = () => {
clearTimeout(timer);
+23 -57
View File
@@ -8,9 +8,6 @@ const log = createLogger('OneBot');
interface CachedRKey {
value: string;
type: number;
createTime: number;
ttlSeconds: number;
expiresAt: number;
}
@@ -61,72 +58,50 @@ export class RKeyCache {
);
}
async resolveImageUrl(
resolveImageUrl(
bridge: BridgeInterface,
element: MessageElement,
isGroup: boolean,
): Promise<string> {
const url = element.imageUrl ?? '';
if (!urlNeedsRKey(url)) {
return url;
}
// The rkey scene must follow the IMAGE's own upload context, not the
// message currently carrying it. A c2c image forwarded into a group
// keeps its original c2c fileid/appid (1406); signing it with the
// group rkey just because the forward node looks like a group message
// yields `invalid rkey` on download. So derive the scene from the
// appid baked into the URL, and only fall back to `isGroup` when the
// URL carries no recognised appid (legacy gchat / unknown shapes).
// Mirrors NapCat's getImageUrlFromParsedUrl (appid 1406 → private,
// 1407 → group).
const primaryType =
// Forwarded images retain their upload scene, encoded by appid in the URL.
const type =
imageRKeyTypeFromUrl(url) ??
(isGroup ? GROUP_IMAGE_RKEY_TYPE : PRIVATE_IMAGE_RKEY_TYPE);
const rkey = await this.findRKeyForType(bridge, primaryType);
if (!rkey) {
return url;
}
const cleanRKey = stripRKeyPrefix(rkey);
const separator = url.includes('?') ? '&rkey=' : '?rkey=';
return url + separator + encodeURIComponent(cleanRKey);
return this.resolveUrl(bridge, url, type);
}
async resolveMediaUrl(
resolveMediaUrl(
bridge: BridgeInterface,
element: MessageElement,
isGroup: boolean,
): Promise<string> {
const url = element.url ?? '';
let type: number;
if (!url || !urlNeedsRKey(url)) {
if (element.type === 'video') {
type = isGroup ? GROUP_VIDEO_RKEY_TYPE : PRIVATE_VIDEO_RKEY_TYPE;
} else if (element.type === 'record') {
type = isGroup ? GROUP_PTT_RKEY_TYPE : PRIVATE_PTT_RKEY_TYPE;
} else {
type = isGroup ? GROUP_IMAGE_RKEY_TYPE : PRIVATE_IMAGE_RKEY_TYPE;
}
return this.resolveUrl(bridge, element.url ?? '', type);
}
private async resolveUrl(bridge: BridgeInterface, url: string, type: number): Promise<string> {
if (!urlNeedsRKey(url)) {
return url;
}
const mediaType = element.type;
let primaryType: number;
if (mediaType === 'video') {
primaryType = isGroup ? GROUP_VIDEO_RKEY_TYPE : PRIVATE_VIDEO_RKEY_TYPE;
} else if (mediaType === 'record') {
primaryType = isGroup ? GROUP_PTT_RKEY_TYPE : PRIVATE_PTT_RKEY_TYPE;
} else {
// For file types, try image rkeys as a fallback (file URLs typically use image rkeys)
primaryType = isGroup ? GROUP_IMAGE_RKEY_TYPE : PRIVATE_IMAGE_RKEY_TYPE;
}
const rkey = await this.findRKeyForType(bridge, primaryType);
const rkey = await this.findRKeyForType(bridge, type);
if (!rkey) {
return url;
}
const cleanRKey = stripRKeyPrefix(rkey);
const separator = url.includes('?') ? '&rkey=' : '?rkey=';
return url + separator + encodeURIComponent(cleanRKey);
return url + separator + encodeURIComponent(stripRKeyPrefix(rkey));
}
private updateCache(rkeys: DownloadRKeyInfo[]): void {
@@ -141,9 +116,6 @@ export class RKeyCache {
const ttl = rk.ttlSeconds || 3600;
this.cache.set(rk.type, {
value: rk.rkey,
type: rk.type,
createTime: rk.createTime,
ttlSeconds: rk.ttlSeconds,
expiresAt: baseTime + ttl,
});
}
@@ -224,10 +196,6 @@ export class RKeyCache {
const inflight = this.refreshInflight;
if (!inflight) {
return;
}
let timer: ReturnType<typeof setTimeout> | undefined;
const timeout = new Promise<void>((resolve) => {
timer = setTimeout(resolve, RKEY_REFRESH_TIMEOUT_MS);
@@ -236,9 +204,7 @@ export class RKeyCache {
try {
await Promise.race([inflight, timeout]);
} finally {
if (timer) {
clearTimeout(timer);
}
clearTimeout(timer);
}
}
@@ -295,7 +261,7 @@ export class RKeyCache {
}
private setFallbackRkey(type: number, value: string, expiresAt: number): void {
this.cache.set(type, { value, type, createTime: 0, ttlSeconds: 0, expiresAt });
this.cache.set(type, { value, expiresAt });
}
}
+1 -1
View File
@@ -855,7 +855,7 @@ export class OneBotInstance {
this.heartbeatTimer = setInterval(() => {
this.dispatchEvent(this.makeHeartbeatEvent());
}, OneBotInstance.HEARTBEAT_INTERVAL);
this.heartbeatTimer.unref?.();
this.heartbeatTimer.unref();
}
private makeHeartbeatEvent(): JsonObject {
+53 -63
View File
@@ -1,6 +1,5 @@
import { createLogger, runWithoutRequestContext } from '@snowluma/common/logger';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import type { BridgeManager } from '@snowluma/core/manager';
import type { BridgeInterface, BridgeSessionSource } from '@snowluma/core/bridge-interface';
import { loadOneBotConfig, OneBotConfigValidationError } from './config';
import { loadGlobalSettings } from './global-config';
import { OneBotInstance } from './instance';
@@ -134,10 +133,7 @@ export class OneBotManager {
instances?: Set<OneBotInstance>;
}> = [];
private readonly pendingStarts = new Map<
string,
{ bridge: BridgeInterface; cancelled: boolean }
>();
private readonly pendingStarts = new Map<string, { bridge: BridgeInterface }>();
private readonly databaseMigrations = new Map<
string,
@@ -145,8 +141,6 @@ export class OneBotManager {
bridge: BridgeInterface;
task: DatabaseMigrationTask;
state: AccountDatabaseMigration;
ready: boolean;
cancelled: boolean;
rowsPerSecond: number | null;
retryTimer: NodeJS.Timeout | null;
}
@@ -157,6 +151,7 @@ export class OneBotManager {
private disposePromise: Promise<void> | null = null;
private disposed = false;
private unsubscribeSessions: (() => void) | null = null;
private readonly sessionReleaseDeadlineMs: number;
constructor(options: OneBotManagerOptions = {}) {
@@ -187,13 +182,17 @@ export class OneBotManager {
new OneBotInstance(uin, bridge, config, globalSettings));
}
bind(bridgeManager: BridgeManager): void {
bridgeManager.addSessionStartedListener((uin, bridge) => {
runWithoutRequestContext(() => this.onSessionStarted(uin, bridge));
});
bind(bridgeManager: BridgeSessionSource): void {
if (this.disposed) {
return;
}
bridgeManager.addSessionClosedListener((uin) => {
this.onSessionClosed(uin);
this.unsubscribeSessions?.();
this.unsubscribeSessions = bridgeManager.subscribeSessions({
started: (uin, bridge) => {
runWithoutRequestContext(() => this.onSessionStarted(uin, bridge));
},
closed: (uin) => this.onSessionClosed(uin),
});
}
@@ -208,22 +207,16 @@ export class OneBotManager {
/** Live OneBot adapter status for active accounts plus failed retiring
* generations. A zombie that still owns a port must remain observable. */
getConnectionStatuses(): AccountConnections[] {
const visible = [...this.instances.values()];
for (const instance of this.retiringInstances) {
if (!visible.includes(instance)) {
visible.push(instance);
}
}
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 visible = new Set([...this.instances.values(), ...this.retiringInstances]);
const connections = [...visible].map((instance) => {
const migration = this.databaseMigrations.get(instance.uin);
return {
uin: instance.uin,
nickname: instance.nickname,
adapters: instance.getConnectionStatuses(),
...(migration ? { databaseMigration: migration.state } : {}),
};
});
const activeUins = new Set(this.instances.keys());
@@ -288,10 +281,13 @@ export class OneBotManager {
}
this.disposed = true;
this.unsubscribeSessions?.();
this.unsubscribeSessions = null;
for (const migration of this.databaseMigrations.values()) {
migration.cancelled = true;
const migrations = [...this.databaseMigrations.values()];
this.databaseMigrations.clear();
for (const migration of migrations) {
if (migration.retryTimer) {
clearTimeout(migration.retryTimer);
}
@@ -299,8 +295,6 @@ export class OneBotManager {
migration.task.cancel();
}
this.databaseMigrations.clear();
for (const instance of this.instances.values()) {
this.retiringInstances.add(instance);
}
@@ -389,7 +383,7 @@ export class OneBotManager {
const retiring = [...this.retiringInstances].filter((instance) => instance.uin === uin);
if (retiring.length > 0) {
const pending = { bridge, cancelled: false };
const pending = { bridge };
this.pendingStarts.set(uin, pending);
this.trackLifecycle(
`session handoff UIN=${uin}`,
@@ -410,16 +404,21 @@ export class OneBotManager {
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 task = migration.task;
const isCurrent = () =>
this.databaseMigrations.get(uin) === migration &&
migration.task === task &&
migration.state.phase !== 'failed' &&
migration.state.phase !== 'complete';
const handleFailure = (error: unknown, stage = 'database migration'): void => {
if (migration.cancelled || this.databaseMigrations.get(uin) !== migration) {
if (!isCurrent()) {
return;
}
@@ -429,7 +428,6 @@ export class OneBotManager {
migration.state = {
...migration.state,
phase: 'failed',
usable: migration.ready,
estimatedRemainingSeconds: null,
error: `${label}:${detail}${retryable ? ';将自动重试' : ';请修正配置后重启'}`,
};
@@ -441,7 +439,7 @@ export class OneBotManager {
error instanceof Error ? (error.stack ?? error.message) : String(error),
);
migration.task.cancel();
task.cancel();
if (!retryable || migration.retryTimer) {
return;
@@ -450,23 +448,23 @@ export class OneBotManager {
migration.retryTimer = setTimeout(() => {
migration.retryTimer = null;
if (migration.cancelled || this.databaseMigrations.get(uin) !== migration) {
if (this.databaseMigrations.get(uin) !== migration) {
return;
}
migration.task = this.createDatabaseMigrationTask(uin);
migration.state = migration.ready
migration.state = migration.state.usable
? { ...migration.state, phase: 'migrating', usable: true, error: undefined }
: preparingMigrationState();
startTask();
}, 5_000);
migration.retryTimer.unref?.();
migration.retryTimer.unref();
};
try {
migration.task.start({
task.start({
onReady: () => {
if (migration.cancelled || this.databaseMigrations.get(uin) !== migration) {
if (!isCurrent()) {
return;
}
@@ -477,7 +475,6 @@ export class OneBotManager {
return;
}
migration.ready = true;
migration.state = {
...migration.state,
phase: 'migrating',
@@ -486,14 +483,14 @@ export class OneBotManager {
};
try {
migration.task.beginMigration();
task.beginMigration();
} catch (error) {
handleFailure(error);
}
},
onProgress: (status, elapsedMs) => {
if (migration.cancelled || this.databaseMigrations.get(uin) !== migration) {
if (!isCurrent()) {
return;
}
@@ -511,7 +508,7 @@ export class OneBotManager {
migration.state = migrationPublicState(status, migration.rowsPerSecond);
if (status.phase === 'complete') {
migration.task.cancel();
task.cancel();
}
},
@@ -628,26 +625,19 @@ export class OneBotManager {
const migration = this.databaseMigrations.get(uin);
if (migration) {
migration.cancelled = true;
this.databaseMigrations.delete(uin);
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);
if (pending) {
pending.cancelled = true;
this.pendingStarts.delete(uin);
}
this.pendingStarts.delete(uin);
return;
}
@@ -678,13 +668,13 @@ export class OneBotManager {
private async releaseRetiringInstance(
uin: string,
pending: { bridge: BridgeInterface; cancelled: boolean },
pending: { bridge: BridgeInterface },
instance: OneBotInstance,
): Promise<void> {
let timer: NodeJS.Timeout | undefined;
const timeout = new Promise<'timeout'>((resolve) => {
timer = setTimeout(() => resolve('timeout'), this.sessionReleaseDeadlineMs);
timer.unref?.();
timer.unref();
});
// Map rejection here so a dispose() that fails after the deadline still
@@ -704,7 +694,7 @@ export class OneBotManager {
);
try {
instance.forceRelease?.();
instance.forceRelease();
} catch (error) {
log.error(
'forced session release failed: UIN=%s: %s',
@@ -734,7 +724,7 @@ export class OneBotManager {
private async finishRetiringBeforeStart(
uin: string,
pending: { bridge: BridgeInterface; cancelled: boolean },
pending: { bridge: BridgeInterface },
retiring: OneBotInstance[],
): Promise<void> {
for (const instance of retiring) {
@@ -748,7 +738,7 @@ export class OneBotManager {
this.pendingStarts.delete(uin);
if (pending.cancelled || this.disposed) {
if (this.disposed) {
return;
}
@@ -37,7 +37,7 @@ export function waitPttTransText(key: string, timeoutMs: number): Promise<string
reject(new Error('语音转文字超时(未收到结果推送)'));
}, timeoutMs);
timer.unref?.();
timer.unref();
pending.set(key, { resolve, reject, timer });
});
}
+1 -4
View File
@@ -1,3 +1,4 @@
import { errorMessage } from '@snowluma/common/errors';
import { createLogger, type Logger } from '@snowluma/common/logger';
import type { ApiHandler } from '../api-handler';
import {
@@ -220,7 +221,3 @@ export abstract class IOneBotNetworkAdapter<C extends NetworkBase> {
this.onConfigReplaced(next);
}
}
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
+18 -33
View File
@@ -1,4 +1,5 @@
import { createLogger } from '@snowluma/common/logger';
import { errorMessage } from '@snowluma/common/errors';
import { assertValidOneBotConfig } from '../config';
import { buildDispatchPayload } from '../event-filter';
import type {
@@ -67,11 +68,9 @@ export class OneBotNetworkManager {
private readonly adapters = new Map<string, ManagedAdapter>();
private readonly factory: NetworkAdapterFactory | null;
private operationTail: Promise<void> = Promise.resolve();
private acceptingReconciles = true;
private acceptingEvents = true;
private accepting = true;
private readonly inFlightEmits = new Set<Promise<void>>();
private shutdownPromise: Promise<NetworkShutdownResult> | null = null;
private shutdownResult: NetworkShutdownResult | null = null;
/** Debug-stream taps — notified for every emitted event regardless of adapter
* state. Attached on-demand (ref-counted) by the WebUI debug stream. */
@@ -92,7 +91,7 @@ export class OneBotNetworkManager {
/** Test/embedding seam for pre-built adapters. Production topology changes
* go through reconcile(), which refuses duplicate names. */
register<C extends NetworkBase>(adapter: IOneBotNetworkAdapter<C>): void {
if (!this.acceptingReconciles) {
if (!this.accepting) {
throw new Error('network manager is shutting down');
}
@@ -163,17 +162,16 @@ export class OneBotNetworkManager {
reconcile(config: OneBotConfig): Promise<NetworkReconcileResult> {
const desired = this.compileDesiredPlan(config);
if (!this.acceptingReconciles) {
if (!this.accepting) {
return Promise.reject(new Error('network manager is shutting down'));
}
return this.enqueue(() => this.reconcileNow(desired));
}
/** Compatibility seam for tests/pre-built adapters. Opens sequentially and
* reports each failure instead of hiding it in a detached Promise. */
/** Open registered adapters in order and report each failure. */
openAll(): Promise<NetworkReconcileResult> {
if (!this.acceptingReconciles) {
if (!this.accepting) {
return Promise.reject(new Error('network manager is shutting down'));
}
@@ -195,7 +193,7 @@ export class OneBotNetworkManager {
}
closeOne(name: string): Promise<void> {
if (!this.acceptingReconciles) {
if (!this.accepting) {
return Promise.reject(new Error('network manager is shutting down'));
}
@@ -214,16 +212,11 @@ export class OneBotNetworkManager {
/** Ordered, idempotent shutdown. Reconcile calls made before shutdown finish
* first; calls made after shutdown is requested fail immediately. */
shutdown(): Promise<NetworkShutdownResult> {
if (this.shutdownResult?.closed) {
return Promise.resolve(this.shutdownResult);
}
if (this.shutdownPromise) {
return this.shutdownPromise;
}
this.acceptingReconciles = false;
this.acceptingEvents = false;
this.accepting = false;
const attempt = this.enqueue(async () => {
const errors: NetworkApplyError[] = [];
const dispatches = await Promise.allSettled([...this.inFlightEmits]);
@@ -232,7 +225,7 @@ export class OneBotNetworkManager {
if (dispatch.status === 'rejected') {
log.error(
'in-flight event dispatch failed during shutdown: %s',
errMessage(dispatch.reason),
errorMessage(dispatch.reason),
);
}
}
@@ -255,8 +248,9 @@ export class OneBotNetworkManager {
this.shutdownPromise = attempt;
void attempt.then(
(result) => {
this.shutdownResult = result.closed ? result : null;
this.shutdownPromise = null;
if (!result.closed) {
this.shutdownPromise = null;
}
},
() => {
this.shutdownPromise = null;
@@ -265,27 +259,22 @@ export class OneBotNetworkManager {
return attempt;
}
closeAll(): Promise<NetworkShutdownResult> {
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;
this.accepting = false;
for (const { adapter } of this.adapters.values()) {
try {
adapter.forceClose();
} catch (error) {
log.error('forced adapter release failed: %s', errMessage(error));
log.error('forced adapter release failed: %s', errorMessage(error));
}
}
}
emitEvent(event: JsonObject): Promise<void> {
if (!this.acceptingEvents) {
if (!this.accepting) {
return Promise.reject(
new Error('network manager is shutting down; event dispatch rejected'),
);
@@ -313,7 +302,7 @@ export class OneBotNetworkManager {
try {
cb(event);
} catch (error) {
log.warn('debug subscriber error: %s', errMessage(error));
log.warn('debug subscriber error: %s', errorMessage(error));
}
}
}
@@ -337,7 +326,7 @@ export class OneBotNetworkManager {
Promise.resolve()
.then(() => adapter.onEvent(event, payload))
.catch((error) => {
log.warn('adapter [%s] onEvent error: %s', adapter.name, errMessage(error));
log.warn('adapter [%s] onEvent error: %s', adapter.name, errorMessage(error));
log.trace(() => [
'report_target_failed target=%s error=%s',
adapter.name,
@@ -549,7 +538,7 @@ export class OneBotNetworkManager {
name,
kind,
phase,
message: errMessage(error),
message: errorMessage(error),
at: Date.now(),
...(restored === undefined ? {} : { restored }),
};
@@ -575,7 +564,3 @@ export class OneBotNetworkManager {
return result;
}
}
function errMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
+4 -8
View File
@@ -46,11 +46,7 @@ export function rawDataToString(
return Buffer.from(new Uint8Array(raw)).toString('utf8');
}
if (ArrayBuffer.isView(raw)) {
return Buffer.from(raw.buffer, raw.byteOffset, raw.byteLength).toString('utf8');
}
return '';
return Buffer.from(raw.buffer, raw.byteOffset, raw.byteLength).toString('utf8');
}
export function safeSend(socket: WebSocket, payload: string, onError?: (err: Error) => void): void {
@@ -156,7 +152,7 @@ export function startHeartbeat(
onDead();
}
}, opts.intervalMs);
timer.unref?.();
timer.unref();
function stop(): void {
if (stopped) {
@@ -165,8 +161,8 @@ export function startHeartbeat(
stopped = true;
clearInterval(timer);
socket.off?.('pong', onActivity);
socket.off?.('message', onActivity);
socket.off('pong', onActivity);
socket.off('message', onActivity);
}
return stop;
@@ -26,8 +26,6 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
private reconnectTimer: NodeJS.Timeout | null = null;
private options: EventReportOptions;
private role: WsRole;
private explicitlyClosed = false;
private acceptingActions = false;
private readonly inFlightActions = new Set<Promise<void>>();
// Stop fn for the CURRENT socket's keepalive, so close()/reload can halt it
// immediately instead of waiting for the deferred 'close' event. The per-socket
@@ -42,37 +40,23 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
}
open(): void {
if (this.isEnabled) {
if (this.isEnabled || !this.willEnable(this.config)) {
return;
}
if (this.config.enabled === false) {
return;
}
if (!this.config.url) {
return;
}
this.explicitlyClosed = false;
this.isEnabled = true;
try {
this.connect();
this.acceptingActions = true;
this.clearApplyFailure();
} catch (error) {
this.isEnabled = false;
this.explicitlyClosed = true;
this.acceptingActions = false;
this.recordTransportFailure(error);
throw error;
}
}
override forceClose(): void {
this.explicitlyClosed = true;
this.acceptingActions = false;
this.isEnabled = false;
this.connected = false;
this.cancelReconnect();
@@ -91,8 +75,6 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
}
async close(): Promise<void> {
this.explicitlyClosed = true;
this.acceptingActions = false;
this.isEnabled = false;
this.connected = false;
this.cancelReconnect();
@@ -156,7 +138,7 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
}
private connect(): void {
if (this.explicitlyClosed) {
if (!this.isEnabled) {
return;
}
@@ -200,7 +182,7 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
socket,
{ intervalMs: HEARTBEAT_INTERVAL_MS, maxMissed: HEARTBEAT_MAX_MISSED },
() => {
if (this.explicitlyClosed || !this.isEnabled) {
if (!this.isEnabled) {
return;
}
@@ -265,7 +247,7 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
this.socket = null;
this.connected = false;
if (this.explicitlyClosed || !this.isEnabled) {
if (!this.isEnabled) {
return;
}
@@ -287,7 +269,7 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
return;
}
if (this.explicitlyClosed) {
if (!this.isEnabled) {
return;
}
@@ -298,13 +280,13 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
const timer = setTimeout(() => {
this.reconnectTimer = null;
if (this.explicitlyClosed || !this.isEnabled) {
if (!this.isEnabled) {
return;
}
this.connect();
}, interval);
timer.unref?.();
timer.unref();
this.reconnectTimer = timer;
}
@@ -338,7 +320,7 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
}
private trackInboundAction(start: () => Promise<void>): void {
if (!this.acceptingActions || this.ctx.api.isAcceptingActions === false) {
if (!this.isEnabled || this.ctx.api.isAcceptingActions === false) {
this.log.warn('[%s] rejected inbound action while adapter is closing', this.name);
return;
}
+1 -4
View File
@@ -1,3 +1,4 @@
import { errorMessage } from '@snowluma/common/errors';
import { createLogger } from '@snowluma/common/logger';
import fs from 'node:fs';
import os from 'node:os';
@@ -254,10 +255,6 @@ function isMissing(error: unknown): boolean {
return error instanceof Error && 'code' in error && error.code === 'ENOENT';
}
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function assertManagedDirectory(directory: string, stat: fs.Stats): void {
if (stat.isSymbolicLink()) {
throw new Error(`managed stream directory must not be a symbolic link: ${directory}`);