feat(onebot): reconcile and drain network adapters

Serialize desired network plans, isolate per-adapter apply failures, restore prior bindings when possible, and report saved versus applied state. Quiesce Action and event ingress, await in-flight dispatches and transport closes, retain failed generations for retry, and propagate shutdown failures.
This commit is contained in:
DrSmoothl committed 2026-07-10 13:49:17 +08:00
1 parent 01688c7567
commit 852004291b
29 files changed
+2700 -305

No files matched your search

+60 -13
View File
@@ -17,7 +17,7 @@ export enum NetworkReloadType {
Opened = 3,
}
export type AdapterStatusLevel = 'ok' | 'warn' | 'down' | 'disabled';
export type AdapterStatusLevel = 'ok' | 'warn' | 'down' | 'disabled' | 'degraded';
/** Live runtime status of a single network adapter, surfaced to the WebUI
* dashboard (and the per-node config cards) so the gateway's own
@@ -28,6 +28,11 @@ export interface AdapterStatus {
kind: 'httpServer' | 'httpClient' | 'wsServer' | 'wsClient';
status: AdapterStatusLevel;
detail: string;
/** Present when the desired config could not be applied or the bound
* transport later failed. The adapter may still be serving its restored
* previous config; `degraded` describes reconciliation, not only liveness. */
lastError?: string;
lastErrorAt?: number;
}
export abstract class IOneBotNetworkAdapter<C extends NetworkBase> {
@@ -36,6 +41,7 @@ export abstract class IOneBotNetworkAdapter<C extends NetworkBase> {
protected readonly ctx: NetworkAdapterContext;
protected readonly log: Logger;
protected isEnabled = false;
private applyFailure: { message: string; at: number } | null = null;
constructor(name: string, config: C, ctx: NetworkAdapterContext, moduleLog?: Logger) {
this.name = name;
@@ -50,6 +56,8 @@ export abstract class IOneBotNetworkAdapter<C extends NetworkBase> {
get currentConfig(): Readonly<C> { return this.config; }
get hasApplyFailure(): boolean { return this.applyFailure !== null; }
abstract open(): void | Promise<void>;
abstract close(): void | Promise<void>;
@@ -58,6 +66,35 @@ export abstract class IOneBotNetworkAdapter<C extends NetworkBase> {
/** Report live connection health for the WebUI dashboard. */
abstract describeStatus(): AdapterStatus;
/** Status with the manager-owned desired/live mismatch overlaid. Concrete
* adapters continue to describe transport health; reconciliation failures
* are kept here so a successfully restored old binding is still visible. */
describeManagedStatus(): AdapterStatus {
const status = this.describeStatus();
if (!this.applyFailure) return status;
return {
...status,
status: 'degraded',
detail: `应用失败:${this.applyFailure.message}`,
lastError: this.applyFailure.message,
lastErrorAt: this.applyFailure.at,
};
}
/** NetworkManager lifecycle seam. A failure is cleared only after a later
* reconciliation reaches the desired state. */
markApplyFailure(error: unknown, at = Date.now()): void {
this.applyFailure = { message: errorMessage(error), at };
}
clearApplyFailure(): void {
this.applyFailure = null;
}
protected recordTransportFailure(error: unknown, at = Date.now()): void {
this.markApplyFailure(error, at);
}
// ── meta-event framing: shared by the connection-oriented adapters ─────
//
// Lifecycle (connect/enable/disable) and heartbeat meta events don't flow
@@ -99,9 +136,10 @@ export abstract class IOneBotNetworkAdapter<C extends NetworkBase> {
// three things that genuinely differ per adapter are the hooks below.
//
// NOTE: the returned `NetworkReloadType` is a *test-observability* seam.
// The sole production caller (`instance.applyConfigDiff`) discards it —
// it exists so tests can assert "which transition did this config cause"
// without poking private state. Behaviour, not the label, is the contract.
// OneBotNetworkManager awaits the transition but derives apply truth from
// success/failure rather than this label. Tests use it to assert "which
// transition did this config cause" without poking private state.
// Behaviour, not the label, is the contract.
/** Stable string identity of the bound resource (host:port / url / token …).
* A change here means the live binding must be torn down and re-opened. */
@@ -121,27 +159,36 @@ export abstract class IOneBotNetworkAdapter<C extends NetworkBase> {
const prevSig = this.bindingSignature(this.config);
const wasEnabled = this.isEnabled;
const willEnable = this.willEnable(next);
this.config = structuredClone(next);
this.onConfigReplaced(next);
const sigChanged = prevSig !== this.bindingSignature(next);
if (sigChanged && wasEnabled) {
// Keep currentConfig truthful while the old live resource is being
// released. Only publish the desired config after close succeeds; an
// opening adapter necessarily sees the new config, while a close failure
// leaves the previous config intact for recovery and diagnostics.
if (wasEnabled && (sigChanged || !willEnable)) {
await this.close();
this.replaceConfig(next);
if (willEnable) {
await this.open();
return NetworkReloadType.Reopened;
}
return NetworkReloadType.Closed;
}
this.replaceConfig(next);
if (!wasEnabled && willEnable) {
await this.open();
return NetworkReloadType.Opened;
}
if (wasEnabled && !willEnable) {
await this.close();
return NetworkReloadType.Closed;
}
return NetworkReloadType.Normal;
}
private replaceConfig(next: C): void {
this.config = structuredClone(next);
this.onConfigReplaced(next);
}
}
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
@@ -52,16 +52,22 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
this.options = resolveReportOptions(next);
}
onEvent(event: JsonObject, payload: DispatchPayload): void {
async onEvent(event: JsonObject, payload: DispatchPayload): Promise<void> {
if (!this.isEnabled) return;
const json = pickDispatchJson(payload, this.options);
if (json === null) return;
void this.postEvent(json, event).catch((err) => {
this.log.warn('[%s] postEvent threw: %s', this.name, err instanceof Error ? (err.stack ?? err.message) : String(err));
});
// A reconcile may replace this.config while HMAC computation or fetch is
// awaiting. Keep one event on one immutable config epoch so an old token
// can never sign a request sent to a new URL (or vice versa).
const config = structuredClone(this.config);
await this.postEvent(json, event, config);
}
private async postEvent(payload: string, event: JsonObject): Promise<void> {
private async postEvent(
payload: string,
event: JsonObject,
config: HttpClientNetwork,
): Promise<void> {
if (!this.isEnabled) return;
const headers: Record<string, string> = {
@@ -69,13 +75,13 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
'User-Agent': 'OneBot',
'X-Self-ID': this.ctx.uin,
};
if (this.config.accessToken) {
headers['X-Signature'] = await computeHmacSha1(this.config.accessToken, payload);
if (config.accessToken) {
headers['X-Signature'] = await computeHmacSha1(config.accessToken, payload);
}
const timeoutMs = this.config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
try {
const response = await fetch(this.config.url, {
const response = await fetch(config.url, {
method: 'POST',
headers,
body: payload,
@@ -92,13 +98,11 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
}
} else {
this.lastDelivery = { at: Date.now(), ok: false };
this.log.warn('[%s] POST %s returned %d', this.name, this.config.url, response.status);
this.log.warn('[%s] POST %s returned %d', this.name, config.url, response.status);
}
} catch (error) {
this.lastDelivery = { at: Date.now(), ok: false };
if (this.isEnabled) {
this.log.warn('[%s] POST %s failed: %s', this.name, this.config.url, error instanceof Error ? error.message : String(error));
}
this.log.warn('[%s] POST %s failed: %s', this.name, config.url, error instanceof Error ? error.message : String(error));
}
}
@@ -17,24 +17,56 @@ const moduleLog = createLogger('OneBot.HTTP');
export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork> {
private server: Server | null = null;
private listening = false;
private closePromise: Promise<void> | null = null;
private acceptingActions = false;
private readonly inFlightActions = new Set<Promise<void>>();
constructor(name: string, config: HttpServerNetwork, ctx: NetworkAdapterContext) {
super(name, config, ctx, moduleLog);
}
open(): void {
if (this.isEnabled) return;
async open(): Promise<void> {
if (this.isEnabled && this.listening) return;
if (this.config.enabled === false) return;
this.startServer();
if (this.server) throw new Error(`HTTP adapter [${this.name}] still owns a previous server`);
await this.startServer();
this.isEnabled = true;
this.clearApplyFailure();
}
close(): void {
if (!this.isEnabled && !this.server) return;
async close(): Promise<void> {
if (this.closePromise) return this.closePromise;
if (!this.isEnabled && !this.server && this.inFlightActions.size === 0) return;
const wasEnabled = this.isEnabled;
const wasListening = this.listening;
const wasAcceptingActions = this.acceptingActions;
this.acceptingActions = false;
this.isEnabled = false;
this.listening = false;
this.server?.close();
this.server = null;
const server = this.server;
const release = server
? new Promise<void>((resolve, reject) => {
server.close((error) => {
if (error && !isAlreadyClosedError(error)) reject(error);
else resolve();
});
})
: Promise.resolve();
const attempt = Promise.all([release, Promise.all(this.inFlightActions)]).then(() => undefined);
this.closePromise = attempt;
try {
await attempt;
if (this.server === server) this.server = null;
} catch (error) {
// A failed close callback cannot prove the listener was released. Keep
// ownership and live-state truth so shutdown/reconcile can retry it.
this.isEnabled = wasEnabled;
this.listening = wasListening;
this.acceptingActions = wasAcceptingActions;
throw error;
} finally {
this.closePromise = null;
}
}
override describeStatus(): AdapterStatus {
@@ -49,28 +81,57 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
onEvent(_event: JsonObject, _payload: DispatchPayload): void { /* no-op */ }
private startServer(): void {
const server = createServer((req, res) => {
void this.handleRequest(req, res);
});
this.server = server;
private startServer(): Promise<void> {
return new Promise((resolve, reject) => {
const server = createServer((req, res) => {
this.trackInboundAction(req, res);
});
this.server = server;
let opening = true;
server.on('listening', () => {
this.listening = true;
this.log.success(
'[%s] listening %s:%d%s',
this.name,
this.config.host ?? '0.0.0.0',
this.config.port,
normalizePath(this.config.path ?? '/'),
);
});
server.on('error', (err) => {
this.listening = false;
this.log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err));
});
server.once('listening', () => {
opening = false;
if (this.server !== server || this.closePromise) {
server.close();
reject(new Error(`HTTP adapter [${this.name}] was closed while binding`));
return;
}
this.listening = true;
this.isEnabled = true;
this.acceptingActions = true;
this.log.success(
'[%s] listening %s:%d%s',
this.name,
this.config.host ?? '0.0.0.0',
this.config.port,
normalizePath(this.config.path ?? '/'),
);
resolve();
});
server.on('error', (error) => {
if (this.server === server) {
this.listening = false;
this.isEnabled = false;
this.acceptingActions = false;
this.recordTransportFailure(error);
if (opening) this.server = null;
}
this.log.error('[%s] server error: %s', this.name, error instanceof Error ? error.message : String(error));
if (opening) {
opening = false;
reject(error);
}
});
server.listen(this.config.port, this.config.host ?? '0.0.0.0');
try {
server.listen(this.config.port, this.config.host ?? '0.0.0.0');
} catch (error) {
opening = false;
if (this.server === server) this.server = null;
this.recordTransportFailure(error);
reject(error);
}
});
}
private async handleRequest(req: IncomingMessage, res: ServerResponse): Promise<void> {
@@ -200,6 +261,33 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
writeJson(res, 500, { status: 'failed', retcode: 1200, data: null, wording });
}
}
private trackInboundAction(req: IncomingMessage, res: ServerResponse): void {
if (!this.acceptingActions || this.ctx.api.isAcceptingActions === false) {
writeJson(res, 503, { status: 'failed', retcode: 1200, data: null, wording: 'server closing' });
return;
}
let action: Promise<void>;
try {
action = this.handleRequest(req, res);
} catch (error) {
this.log.error('[%s] inbound action start failed: %s', this.name, error instanceof Error ? (error.stack ?? error.message) : String(error));
writeJson(res, 500, { status: 'failed', retcode: 1200, data: null, wording: 'internal error' });
return;
}
const tracked = action.then(
() => undefined,
(error) => {
this.log.error('[%s] inbound action failed: %s', this.name, error instanceof Error ? (error.stack ?? error.message) : String(error));
},
);
this.inFlightActions.add(tracked);
void tracked.then(() => { this.inFlightActions.delete(tracked); });
}
}
function isAlreadyClosedError(error: Error): boolean {
return (error as NodeJS.ErrnoException).code === 'ERR_SERVER_NOT_RUNNING';
}
function readRequestBody(req: IncomingMessage, maxBytes = 2 * 1024 * 1024): Promise<string> {
@@ -223,7 +311,7 @@ function readRequestBody(req: IncomingMessage, maxBytes = 2 * 1024 * 1024): Prom
function writeJson(res: ServerResponse, statusCode: number, data: unknown): void {
// A streaming response may already have flushed headers (and even ended); a
// late error must not double-send and trip ERR_HTTP_HEADERS_SENT.
if (res.headersSent || res.writableEnded) return;
if (res.headersSent || res.writableEnded || res.destroyed) return;
res.statusCode = statusCode;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.end(JSON.stringify(data));
+10 -2
View File
@@ -7,8 +7,16 @@ export {
} from './adapter';
export { HttpPostAdapter } from './http-post-adapter';
export { HttpServerAdapter } from './http-server-adapter';
export { OneBotNetworkManager } from './network-manager';
export {
OneBotNetworkManager,
type DesiredNetworkAdapter,
type NetworkAdapterFactory,
type NetworkAdapterKind,
type NetworkApplyError,
type NetworkApplyPhase,
type NetworkReconcileResult,
type NetworkShutdownResult,
} from './network-manager';
export { executeQuickOperation } from './quick-operation';
export { WsClientAdapter } from './ws-client-adapter';
export { WsServerAdapter } from './ws-server-adapter';
+408 -53
View File
@@ -1,113 +1,468 @@
import { createLogger } from '@snowluma/common/logger';
import { assertValidOneBotConfig } from '../config';
import { buildDispatchPayload } from '../event-filter';
import type { JsonObject, NetworkBase } from '../types';
import type {
HttpClientNetwork,
HttpServerNetwork,
JsonObject,
NetworkBase,
OneBotConfig,
WsClientNetwork,
WsServerNetwork,
} from '../types';
import { IOneBotNetworkAdapter, type AdapterStatus } from './adapter';
const log = createLogger('OneBot.Network');
type AnyAdapter = IOneBotNetworkAdapter<NetworkBase>;
export type NetworkAdapterKind = AdapterStatus['kind'];
export type DesiredNetworkAdapter =
| { name: string; kind: 'httpServer'; config: HttpServerNetwork }
| { name: string; kind: 'httpClient'; config: HttpClientNetwork }
| { name: string; kind: 'wsServer'; config: WsServerNetwork }
| { name: string; kind: 'wsClient'; config: WsClientNetwork };
export type NetworkApplyPhase = 'open' | 'reload' | 'close' | 'replace' | 'restore' | 'shutdown';
export interface NetworkApplyError {
name: string;
kind: NetworkAdapterKind;
phase: NetworkApplyPhase;
message: string;
at: number;
/** True when the previous live adapter/config was restored. The desired
* config remains unapplied and the adapter stays visibly degraded. */
restored?: boolean;
}
export interface NetworkReconcileResult {
applied: boolean;
errors: NetworkApplyError[];
statuses: AdapterStatus[];
}
export interface NetworkShutdownResult {
closed: boolean;
errors: NetworkApplyError[];
}
export type NetworkAdapterFactory = (desired: DesiredNetworkAdapter) => AnyAdapter;
interface ManagedAdapter {
kind: NetworkAdapterKind;
adapter: AnyAdapter;
}
/**
* Single owner of the configured network topology.
*
* Configs are first compiled into a globally-name-unique desired plan. Every
* startup/reload/shutdown operation then runs through one FIFO, so a reload can
* never race another reload or teardown. Runtime failures are isolated per
* adapter and returned as data; deterministic plan errors throw before the
* operation is queued.
*/
export class OneBotNetworkManager {
private readonly adapters = new Map<string, AnyAdapter>();
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 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. */
private readonly debugSubscribers = new Set<(event: JsonObject) => void>();
constructor(factory?: NetworkAdapterFactory) {
this.factory = factory ?? null;
}
subscribeDebug(cb: (event: JsonObject) => void): () => void {
this.debugSubscribers.add(cb);
return () => { this.debugSubscribers.delete(cb); };
}
/** 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 {
const existing = this.adapters.get(adapter.name);
if (existing) {
log.info('replacing adapter [%s]', adapter.name);
Promise.resolve(existing.close()).catch(() => {
/* best-effort */
// 应该该打个日志以便排查问题,但不应当让调用者感知到这个失败。
});
if (!this.acceptingReconciles) {
throw new Error('network manager is shutting down');
}
this.adapters.set(adapter.name, adapter as AnyAdapter);
if (this.adapters.has(adapter.name)) {
throw new Error(`network adapter name already registered: ${adapter.name}`);
}
const kind = adapter.describeStatus().kind;
this.adapters.set(adapter.name, { kind, adapter: adapter as AnyAdapter });
}
has(name: string): boolean { return this.adapters.has(name); }
get(name: string): AnyAdapter | null {
return this.adapters.get(name) ?? null;
return this.adapters.get(name)?.adapter ?? null;
}
list(): AnyAdapter[] { return [...this.adapters.values()]; }
list(): AnyAdapter[] { return [...this.adapters.values()].map((entry) => entry.adapter); }
/** Live status of every registered adapter, for the WebUI dashboard. */
/** Live status of every registered adapter, including desired/live apply
* failures even when an older binding was restored and remains active. */
describeStatuses(): AdapterStatus[] {
return this.list().map((a) => a.describeStatus());
return this.list().map((adapter) => adapter.describeManagedStatus());
}
hasActiveAdapters(): boolean {
for (const a of this.adapters.values()) if (a.isActive) return true;
for (const { adapter } of this.adapters.values()) if (adapter.isActive) return true;
return false;
}
async openAll(): Promise<void> {
const tasks = this.list().map(async (a) => {
try {
await a.open();
} catch (err) {
log.error('adapter [%s] open failed: %s', a.name, errMessage(err));
}
});
await Promise.all(tasks);
/** Compile and validate outside the queue: deterministic errors never wait
* behind network I/O and can be rejected before a WebUI save. */
compileDesiredPlan(config: OneBotConfig): DesiredNetworkAdapter[] {
assertValidOneBotConfig(config);
return [
...config.networks.httpServers.map((network) => ({
name: network.name,
kind: 'httpServer' as const,
config: structuredClone(network),
})),
...config.networks.httpClients.map((network) => ({
name: network.name,
kind: 'httpClient' as const,
config: structuredClone(network),
})),
...config.networks.wsServers.map((network) => ({
name: network.name,
kind: 'wsServer' as const,
config: structuredClone(network),
})),
...config.networks.wsClients.map((network) => ({
name: network.name,
kind: 'wsClient' as const,
config: structuredClone(network),
})),
];
}
async closeAll(): Promise<void> {
const tasks = this.list().map(async (a) => {
try {
await a.close();
} catch (err) {
log.warn('adapter [%s] close failed: %s', a.name, errMessage(err));
}
});
await Promise.all(tasks);
this.adapters.clear();
}
async closeOne(name: string): Promise<void> {
const adapter = this.adapters.get(name);
if (!adapter) return;
this.adapters.delete(name);
try {
await adapter.close();
} catch (err) {
log.warn('adapter [%s] close failed: %s', adapter.name, errMessage(err));
reconcile(config: OneBotConfig): Promise<NetworkReconcileResult> {
const desired = this.compileDesiredPlan(config);
if (!this.acceptingReconciles) {
return Promise.reject(new Error('network manager is shutting down'));
}
return this.enqueue(() => this.reconcileNow(desired));
}
async emitEvent(event: JsonObject): Promise<void> {
/** Compatibility seam for tests/pre-built adapters. Opens sequentially and
* reports each failure instead of hiding it in a detached Promise. */
openAll(): Promise<NetworkReconcileResult> {
if (!this.acceptingReconciles) return Promise.reject(new Error('network manager is shutting down'));
return this.enqueue(async () => {
const errors: NetworkApplyError[] = [];
for (const entry of this.adapters.values()) {
try {
await entry.adapter.open();
entry.adapter.clearApplyFailure();
} catch (error) {
entry.adapter.markApplyFailure(error);
errors.push(this.report(entry.adapter.name, entry.kind, 'open', error));
}
}
return this.result(errors);
});
}
closeOne(name: string): Promise<void> {
if (!this.acceptingReconciles) return Promise.reject(new Error('network manager is shutting down'));
return this.enqueue(async () => {
const entry = this.adapters.get(name);
if (!entry) return;
await entry.adapter.close();
this.adapters.delete(name);
});
}
/** 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;
const attempt = this.enqueue(async () => {
const errors: NetworkApplyError[] = [];
const dispatches = await Promise.allSettled([...this.inFlightEmits]);
for (const dispatch of dispatches) {
if (dispatch.status === 'rejected') {
log.error('in-flight event dispatch failed during shutdown: %s', errMessage(dispatch.reason));
}
}
const entries = [...this.adapters.entries()].reverse();
for (const [name, entry] of entries) {
try {
await entry.adapter.close();
this.adapters.delete(name);
} catch (error) {
entry.adapter.markApplyFailure(error);
errors.push(this.report(name, entry.kind, 'shutdown', error));
}
}
this.debugSubscribers.clear();
return { closed: errors.length === 0, errors };
});
this.shutdownPromise = attempt;
void attempt.then(
(result) => {
this.shutdownResult = result.closed ? result : null;
this.shutdownPromise = null;
},
() => {
this.shutdownPromise = null;
},
);
return attempt;
}
closeAll(): Promise<NetworkShutdownResult> {
return this.shutdown();
}
emitEvent(event: JsonObject): Promise<void> {
if (!this.acceptingEvents) {
return Promise.reject(new Error('network manager is shutting down; event dispatch rejected'));
}
const operation = this.emitEventNow(event);
this.inFlightEmits.add(operation);
void operation.then(
() => { this.inFlightEmits.delete(operation); },
() => { this.inFlightEmits.delete(operation); },
);
return operation;
}
private async emitEventNow(event: JsonObject): Promise<void> {
// Notify debug taps first — before the adapter check — so the debug stream
// sees every event even when no adapter is connected. Never let a tap throw
// into the dispatch path.
// sees every event even when no adapter is connected. A diagnostic tap is
// isolated, but its failure is always logged with the root message.
if (this.debugSubscribers.size) {
for (const cb of this.debugSubscribers) {
try { cb(event); } catch (err) { log.warn('debug subscriber error: %s', errMessage(err)); }
try { cb(event); } catch (error) { log.warn('debug subscriber error: %s', errMessage(error)); }
}
}
if (!this.hasActiveAdapters()) return;
const payload = buildDispatchPayload(event);
const tasks: Promise<unknown>[] = [];
for (const adapter of this.adapters.values()) {
for (const { adapter } of this.adapters.values()) {
if (!adapter.isActive) continue;
tasks.push(
Promise.resolve()
.then(() => adapter.onEvent(event, payload))
.catch((err) => {
log.warn('adapter [%s] onEvent error: %s', adapter.name, errMessage(err));
.catch((error) => {
log.warn('adapter [%s] onEvent error: %s', adapter.name, errMessage(error));
}),
);
}
await Promise.allSettled(tasks);
}
private async reconcileNow(desired: DesiredNetworkAdapter[]): Promise<NetworkReconcileResult> {
const errors: NetworkApplyError[] = [];
const desiredByName = new Map(desired.map((entry) => [entry.name, entry]));
// Retire removed adapters first so their ports/resources are available to
// newly added entries in the same plan. Close is deliberately sequential.
for (const [name, live] of [...this.adapters]) {
if (desiredByName.has(name)) continue;
try {
await live.adapter.close();
this.adapters.delete(name);
} catch (error) {
live.adapter.markApplyFailure(error);
errors.push(this.report(name, live.kind, 'close', error));
}
}
for (const next of desired) {
const live = this.adapters.get(next.name);
if (!live) {
await this.createAndOpen(next, errors);
} else if (live.kind === next.kind) {
await this.reloadSameKind(live, next, errors);
} else {
await this.replaceKind(live, next, errors);
}
}
return this.result(errors);
}
private async createAndOpen(next: DesiredNetworkAdapter, errors: NetworkApplyError[]): Promise<void> {
let adapter: AnyAdapter;
try {
adapter = this.create(next);
} catch (error) {
errors.push(this.report(next.name, next.kind, 'open', error));
return;
}
this.adapters.set(next.name, { kind: next.kind, adapter });
try {
await adapter.open();
adapter.clearApplyFailure();
} catch (error) {
adapter.markApplyFailure(error);
errors.push(this.report(next.name, next.kind, 'open', error));
}
}
private async reloadSameKind(
live: ManagedAdapter,
next: DesiredNetworkAdapter,
errors: NetworkApplyError[],
): Promise<void> {
const previous = structuredClone(live.adapter.currentConfig);
try {
// A degraded adapter may still own a failed/ambiguous transport even if
// the desired binding signature is unchanged. Force a real release and
// reopen instead of letting reload() return Normal and clearing the
// evidence without recovery.
if (live.adapter.hasApplyFailure) await live.adapter.close();
await live.adapter.reload(next.config);
live.adapter.clearApplyFailure();
} catch (error) {
let restored = false;
try {
await live.adapter.reload(previous);
restored = true;
} catch (restoreError) {
errors.push(this.report(next.name, live.kind, 'restore', restoreError));
}
live.adapter.markApplyFailure(error);
errors.push(this.report(next.name, next.kind, 'reload', error, restored));
}
}
private async replaceKind(
live: ManagedAdapter,
next: DesiredNetworkAdapter,
errors: NetworkApplyError[],
): Promise<void> {
try {
await live.adapter.close();
} catch (error) {
live.adapter.markApplyFailure(error);
errors.push(this.report(next.name, live.kind, 'replace', error));
return;
}
let replacement: AnyAdapter;
try {
replacement = this.create(next);
} catch (error) {
let restored = false;
try {
await live.adapter.open();
restored = true;
} catch (restoreError) {
errors.push(this.report(next.name, live.kind, 'restore', restoreError));
}
// Whether restoration succeeds or not, the desired kind was not
// applied. Preserve that root failure on the still-managed old adapter.
live.adapter.markApplyFailure(error);
errors.push(this.report(next.name, next.kind, 'replace', error, restored));
return;
}
this.adapters.set(next.name, { kind: next.kind, adapter: replacement });
try {
await replacement.open();
replacement.clearApplyFailure();
return;
} catch (error) {
// The desired kind failed after the old resource was released. Clean up
// the partial replacement, then make a best-effort restoration of the
// previous live adapter. The original apply error remains the primary
// degraded reason even when restoration succeeds.
try {
await replacement.close();
} catch (cleanupError) {
// The replacement may still own a bound resource. Keep it in the map
// and do not start the old adapter: overwriting this reference would
// orphan a potentially-live transport and could double-bind a port.
replacement.markApplyFailure(error);
errors.push(this.report(next.name, next.kind, 'close', cleanupError));
errors.push(this.report(next.name, next.kind, 'replace', error, false));
return;
}
let restored = false;
try {
await live.adapter.open();
live.adapter.markApplyFailure(error);
this.adapters.set(next.name, live);
restored = true;
} catch (restoreError) {
replacement.markApplyFailure(error);
errors.push(this.report(next.name, live.kind, 'restore', restoreError));
}
errors.push(this.report(next.name, next.kind, 'replace', error, restored));
}
}
private create(next: DesiredNetworkAdapter): AnyAdapter {
if (!this.factory) throw new Error(`no network adapter factory configured for ${next.name}`);
const adapter = this.factory(next);
if (adapter.name !== next.name) {
throw new Error(`network adapter factory returned name ${adapter.name} for desired ${next.name}`);
}
return adapter;
}
private result(errors: NetworkApplyError[]): NetworkReconcileResult {
return {
applied: errors.length === 0,
errors,
statuses: this.describeStatuses(),
};
}
private report(
name: string,
kind: NetworkAdapterKind,
phase: NetworkApplyPhase,
error: unknown,
restored?: boolean,
): NetworkApplyError {
const detail: NetworkApplyError = {
name,
kind,
phase,
message: errMessage(error),
at: Date.now(),
...(restored === undefined ? {} : { restored }),
};
log.error(
'adapter [%s] kind=%s phase=%s failed%s: %s',
name,
kind,
phase,
restored === undefined ? '' : ` restored=${String(restored)}`,
detail.message,
);
return detail;
}
private enqueue<T>(operation: () => Promise<T>): Promise<T> {
const result = this.operationTail.then(operation);
// Keep the FIFO usable after a rejected invariant/programming error. The
// returned promise still rejects, so no error is hidden from its caller.
this.operationTail = result.then(
() => undefined,
() => undefined,
);
return result;
}
}
function errMessage(err: unknown): string {
return err instanceof Error ? err.message : String(err);
function errMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
@@ -27,6 +27,8 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
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
// closure in connect() still owns the #97 stale-socket case; this is idempotent
@@ -45,11 +47,22 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
if (!this.config.url) return;
this.explicitlyClosed = false;
this.isEnabled = true;
this.connect();
try {
this.connect();
this.acceptingActions = true;
this.clearApplyFailure();
} catch (error) {
this.isEnabled = false;
this.explicitlyClosed = true;
this.acceptingActions = false;
this.recordTransportFailure(error);
throw error;
}
}
close(): void {
async close(): Promise<void> {
this.explicitlyClosed = true;
this.acceptingActions = false;
this.isEnabled = false;
this.connected = false;
this.cancelReconnect();
@@ -59,6 +72,7 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
safeClose(this.socket);
this.socket = null;
}
await Promise.all(this.inFlightActions);
}
override describeStatus(): AdapterStatus {
@@ -131,9 +145,11 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
});
socket.on('message', (raw: Buffer) => {
void this.handleApiMessage(socket, raw).catch((err) => {
this.log.warn('[%s] handleApiMessage threw: %s', this.name, err instanceof Error ? (err.stack ?? err.message) : String(err));
});
if (this.socket !== socket) {
this.log.warn('[%s] rejected inbound action from stale socket', this.name);
return;
}
this.trackInboundAction(() => this.handleApiMessage(socket, raw));
});
socket.on('close', () => {
@@ -193,9 +209,30 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
);
}
private trackInboundAction(start: () => Promise<void>): void {
if (!this.acceptingActions || this.ctx.api.isAcceptingActions === false) {
this.log.warn('[%s] rejected inbound action while adapter is closing', this.name);
return;
}
let action: Promise<void>;
try {
action = start();
} catch (error) {
this.log.error('[%s] inbound action start failed: %s', this.name, error instanceof Error ? (error.stack ?? error.message) : String(error));
return;
}
const tracked = action.then(
() => undefined,
(error) => {
this.log.error('[%s] inbound action failed: %s', this.name, error instanceof Error ? (error.stack ?? error.message) : String(error));
},
);
this.inFlightActions.add(tracked);
void tracked.then(() => { this.inFlightActions.delete(tracked); });
}
private sendBootstrapMetaEvents(socket: WebSocket): void {
if (this.role !== 'Event' && this.role !== 'Universal') return;
for (const frame of this.bootstrapMetaFrames(this.options)) safeSend(socket, frame);
}
}
+122 -32
View File
@@ -30,6 +30,9 @@ interface ForwardConn {
export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
private wss: WebSocketServer | null = null;
private listening = false;
private closePromise: Promise<void> | null = null;
private acceptingActions = false;
private readonly inFlightActions = new Set<Promise<void>>();
private connections = new Map<WebSocket, ForwardConn>();
private options: EventReportOptions;
@@ -38,15 +41,22 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
this.options = resolveReportOptions(config);
}
open(): void {
if (this.isEnabled) return;
async open(): Promise<void> {
if (this.isEnabled && this.listening) return;
if (this.config.enabled === false) return;
this.startServer();
if (this.wss) throw new Error(`WebSocket adapter [${this.name}] still owns a previous server`);
await this.startServer();
this.isEnabled = true;
this.clearApplyFailure();
}
close(): void {
if (!this.isEnabled && this.connections.size === 0 && !this.wss) return;
async close(): Promise<void> {
if (this.closePromise) return this.closePromise;
if (!this.isEnabled && this.connections.size === 0 && !this.wss && this.inFlightActions.size === 0) return;
const wasEnabled = this.isEnabled;
const wasListening = this.listening;
const wasAcceptingActions = this.acceptingActions;
this.acceptingActions = false;
// Final lifecycle broadcast before tearing down so attached event clients
// see the disable transition.
const lifecycle = this.ctx.buildLifecycleEvent('disable');
@@ -63,8 +73,31 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
safeClose(conn.socket);
}
this.connections.clear();
this.wss?.close();
this.wss = null;
const wss = this.wss;
const releaseResult: Promise<{ error?: Error }> = wss
? new Promise<{ error?: Error }>((resolve) => {
wss.close((error) => resolve(error && !isAlreadyClosedError(error) ? { error } : {}));
})
: Promise.resolve({});
const attempt = (async () => {
await Promise.all(this.inFlightActions);
const release = await releaseResult;
if (release.error) throw release.error;
})();
this.closePromise = attempt;
try {
await attempt;
if (wss && this.wss === wss) this.wss = null;
} catch (error) {
// A failed close callback leaves release ambiguous. Retain the server
// reference and active binding state so a later shutdown can retry.
this.isEnabled = wasEnabled;
this.listening = wasListening;
this.acceptingActions = wasAcceptingActions;
throw error;
} finally {
this.closePromise = null;
}
}
override describeStatus(): AdapterStatus {
@@ -92,34 +125,67 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
}
}
private startServer(): void {
const wss = new WebSocketServer({
host: this.config.host ?? '0.0.0.0',
port: this.config.port,
path: this.config.path ?? '/',
});
this.wss = wss;
private startServer(): Promise<void> {
return new Promise((resolve, reject) => {
let wss: WebSocketServer;
try {
wss = new WebSocketServer({
host: this.config.host ?? '0.0.0.0',
port: this.config.port,
path: normalizePath(this.config.path),
});
} catch (error) {
this.recordTransportFailure(error);
reject(error);
return;
}
this.wss = wss;
let opening = true;
wss.on('listening', () => {
this.listening = true;
this.log.success(
'[%s] listening %s:%d%s',
this.name,
this.config.host ?? '0.0.0.0',
this.config.port,
this.config.path ?? '/',
);
});
wss.once('listening', () => {
opening = false;
if (this.wss !== wss || this.closePromise) {
wss.close();
reject(new Error(`WebSocket adapter [${this.name}] was closed while binding`));
return;
}
this.listening = true;
this.isEnabled = true;
this.acceptingActions = true;
this.log.success(
'[%s] listening %s:%d%s',
this.name,
this.config.host ?? '0.0.0.0',
this.config.port,
this.config.path ?? '/',
);
resolve();
});
wss.on('error', (err: Error) => {
this.listening = false;
this.log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err));
});
wss.on('error', (error: Error) => {
if (this.wss === wss) {
this.listening = false;
this.isEnabled = false;
this.acceptingActions = false;
this.recordTransportFailure(error);
if (opening) this.wss = null;
}
this.log.error('[%s] server error: %s', this.name, error instanceof Error ? error.message : String(error));
if (opening) {
opening = false;
reject(error);
}
});
wss.on('connection', (socket: WebSocket, request: IncomingMessage) => this.onConnection(socket, request));
wss.on('connection', (socket: WebSocket, request: IncomingMessage) => this.onConnection(socket, request));
});
}
private onConnection(socket: WebSocket, request: IncomingMessage): void {
if (!this.acceptingActions || this.ctx.api.isAcceptingActions === false) {
safeClose(socket, 1012, 'server closing');
return;
}
if (!isAuthorized(request, this.config.accessToken ?? '')) {
safeClose(socket, 1008, 'invalid access token');
return;
@@ -138,9 +204,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
this.connections.set(socket, conn);
socket.on('message', (raw: Buffer) => {
void this.handleApiMessage(socket, role, raw).catch((err) => {
this.log.warn('[%s] handleApiMessage threw: %s', this.name, err instanceof Error ? (err.stack ?? err.message) : String(err));
});
this.trackInboundAction(() => this.handleApiMessage(socket, role, raw));
});
socket.on('close', () => {
stopHeartbeat();
@@ -170,11 +234,37 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
);
}
private trackInboundAction(start: () => Promise<void>): void {
if (!this.acceptingActions || this.ctx.api.isAcceptingActions === false) {
this.log.warn('[%s] rejected inbound action while adapter is closing', this.name);
return;
}
let action: Promise<void>;
try {
action = start();
} catch (error) {
this.log.error('[%s] inbound action start failed: %s', this.name, error instanceof Error ? (error.stack ?? error.message) : String(error));
return;
}
const tracked = action.then(
() => undefined,
(error) => {
this.log.error('[%s] inbound action failed: %s', this.name, error instanceof Error ? (error.stack ?? error.message) : String(error));
},
);
this.inFlightActions.add(tracked);
void tracked.then(() => { this.inFlightActions.delete(tracked); });
}
private sendBootstrapMetaEvents(socket: WebSocket): void {
for (const frame of this.bootstrapMetaFrames(this.options)) safeSend(socket, frame);
}
}
function isAlreadyClosedError(error: Error): boolean {
return (error as NodeJS.ErrnoException).code === 'ERR_SERVER_NOT_RUNNING';
}
function classifyForwardRole(request: IncomingMessage): WsRole {
const path = parseRequestPath(request.url ?? '/');
if (path.endsWith('/api')) return 'Api';