refactor: use native async discovery and simplify shared state
This commit is contained in:
1 parent
5032cbb8c0
commit
4e2b6b1200
87 files changed
+2063
-2002
No files matched your search
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user