refactor(onebot): lift the network adapter reload state machine into the base class

The four NetworkAdapters each carried a byte-identical reload() state machine (sigChanged/wasEnabled -> Reopened/Closed/Opened/Normal). Lift it into IOneBotNetworkAdapter as a template method; per-adapter variation is now expressed via three hooks: bindingSignature(), willEnable() (default enabled!==false; clients add && !!url), and onConfigReplaced() (post-swap side effects).

Also delete four redundant 'override get isActive()' (identical to the base getter), lift the duplicated uin-logger setup into the base ctor, and drop http-post's now-redundant signature_ cache.

NetworkReloadType is a test-observability seam -- the sole production caller (instance.applyConfigDiff) discards it -- so a new base-level test exercises all transitions directly. Behaviour-preserving: +94/-157 in src, full workspace typecheck clean, 332 onebot tests pass.
This commit is contained in:
DrSmoothl committed 2026-06-03 20:53:36 +08:00
1 parent d3092a1806
commit 18f7d847ac
7 files changed
+324 -158

No files matched your search

+60 -2
View File
@@ -1,3 +1,4 @@
import { createLogger, type Logger } from '@snowluma/common/logger';
import type { ApiHandler } from '../api-handler';
import type { DispatchPayload } from '../event-filter';
import type { JsonObject, NetworkBase } from '../types';
@@ -33,12 +34,16 @@ export abstract class IOneBotNetworkAdapter<C extends NetworkBase> {
readonly name: string;
protected config: C;
protected readonly ctx: NetworkAdapterContext;
protected readonly log: Logger;
protected isEnabled = false;
constructor(name: string, config: C, ctx: NetworkAdapterContext) {
constructor(name: string, config: C, ctx: NetworkAdapterContext, moduleLog?: Logger) {
this.name = name;
this.config = structuredClone(config);
this.ctx = ctx;
const base = moduleLog ?? createLogger('OneBot.Network');
const uinNum = Number.parseInt(ctx.uin, 10);
this.log = Number.isFinite(uinNum) && uinNum > 0 ? base.child({ uin: uinNum }) : base;
}
get isActive(): boolean { return this.isEnabled; }
@@ -47,10 +52,63 @@ export abstract class IOneBotNetworkAdapter<C extends NetworkBase> {
abstract open(): void | Promise<void>;
abstract close(): void | Promise<void>;
abstract reload(config: C): NetworkReloadType | Promise<NetworkReloadType>;
abstract onEvent(event: JsonObject, payload: DispatchPayload): void | Promise<void>;
/** Report live connection health for the WebUI dashboard. */
abstract describeStatus(): AdapterStatus;
// ── reload: shared hot-reload state machine (template method) ──────────
//
// All four adapters reconcile a live config swap identically: decide
// whether the binding changed, whether the adapter should be enabled, and
// then open/close to reach the target state. The skeleton lives here; the
// 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.
/** 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. */
protected abstract bindingSignature(config: C): string;
/** Whether `config` should result in an enabled adapter. Defaults to the
* `enabled` flag; client adapters also require a target `url`. */
protected willEnable(config: C): boolean {
return config.enabled !== false;
}
/** Refresh derived state after `this.config` has been replaced (report
* options, role, propagation to live connections). Default: nothing. */
protected onConfigReplaced(_next: C): void { /* no-op */ }
async reload(next: C): Promise<NetworkReloadType> {
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) {
await this.close();
if (willEnable) {
await this.open();
return NetworkReloadType.Reopened;
}
return NetworkReloadType.Closed;
}
if (!wasEnabled && willEnable) {
await this.open();
return NetworkReloadType.Opened;
}
if (wasEnabled && !willEnable) {
await this.close();
return NetworkReloadType.Closed;
}
return NetworkReloadType.Normal;
}
}
@@ -1,4 +1,4 @@
import { createLogger, type Logger } from '@snowluma/common/logger';
import { createLogger } from '@snowluma/common/logger';
import {
pickDispatchJson,
resolveReportOptions,
@@ -6,7 +6,7 @@ import {
type EventReportOptions,
} from '../event-filter';
import type { HttpClientNetwork, JsonObject } from '../types';
import { IOneBotNetworkAdapter, NetworkReloadType, type AdapterStatus, type NetworkAdapterContext } from './adapter';
import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter';
import { executeQuickOperation } from './quick-operation';
const moduleLog = createLogger('OneBot.POST');
@@ -14,20 +14,11 @@ const DEFAULT_TIMEOUT_MS = 5000;
export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
private options: EventReportOptions;
private signature_: string;
private lastDelivery: { at: number; ok: boolean } | null = null;
private readonly log: Logger;
constructor(name: string, config: HttpClientNetwork, ctx: NetworkAdapterContext) {
super(name, config, ctx);
super(name, config, ctx, moduleLog);
this.options = resolveReportOptions(config);
this.signature_ = bindingSignature(config);
const uinNum = Number.parseInt(ctx.uin, 10);
this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
}
override get isActive(): boolean {
return this.isEnabled;
}
open(): void {
@@ -49,33 +40,16 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
: { name: this.name, kind: 'httpClient', status: 'warn', detail: `上次推送失败 ${at}` };
}
async reload(next: HttpClientNetwork): Promise<NetworkReloadType> {
const wasEnabled = this.isEnabled;
const willEnable = next.enabled !== false && !!next.url;
protected override bindingSignature(config: HttpClientNetwork): string {
return `${config.url}#${config.accessToken ?? ''}#${config.timeoutMs ?? DEFAULT_TIMEOUT_MS}`;
}
this.config = structuredClone(next);
protected override willEnable(config: HttpClientNetwork): boolean {
return config.enabled !== false && !!config.url;
}
protected override onConfigReplaced(next: HttpClientNetwork): void {
this.options = resolveReportOptions(next);
const newSig = bindingSignature(next);
const sigChanged = newSig !== this.signature_;
this.signature_ = newSig;
if (sigChanged && wasEnabled) {
this.close();
if (willEnable) {
this.open();
return NetworkReloadType.Reopened;
}
return NetworkReloadType.Closed;
}
if (!wasEnabled && willEnable) {
this.open();
return NetworkReloadType.Opened;
}
if (wasEnabled && !willEnable) {
this.close();
return NetworkReloadType.Closed;
}
return NetworkReloadType.Normal;
}
onEvent(event: JsonObject, payload: DispatchPayload): void {
@@ -139,10 +113,6 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
}
}
function bindingSignature(net: HttpClientNetwork): string {
return `${net.url}#${net.accessToken ?? ''}#${net.timeoutMs ?? DEFAULT_TIMEOUT_MS}`;
}
async function computeHmacSha1(secret: string, payload: string): Promise<string> {
const { createHmac } = await import('crypto');
return 'sha1=' + createHmac('sha1', secret).update(payload).digest('hex');
@@ -1,4 +1,4 @@
import { createLogger, type Logger } from '@snowluma/common/logger';
import { createLogger } from '@snowluma/common/logger';
import {
createServer,
type IncomingMessage,
@@ -7,7 +7,7 @@ import {
} from 'http';
import type { DispatchPayload } from '../event-filter';
import type { HttpServerNetwork, JsonObject, JsonValue } from '../types';
import { IOneBotNetworkAdapter, NetworkReloadType, type AdapterStatus, type NetworkAdapterContext } from './adapter';
import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter';
import { isAuthorized, normalizePath } from './utils';
const moduleLog = createLogger('OneBot.HTTP');
@@ -15,16 +15,9 @@ const moduleLog = createLogger('OneBot.HTTP');
export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork> {
private server: Server | null = null;
private listening = false;
private readonly log: Logger;
constructor(name: string, config: HttpServerNetwork, ctx: NetworkAdapterContext) {
super(name, config, ctx);
const uinNum = Number.parseInt(ctx.uin, 10);
this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
}
override get isActive(): boolean {
return this.isEnabled;
super(name, config, ctx, moduleLog);
}
open(): void {
@@ -48,31 +41,8 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
return { name: this.name, kind: 'httpServer', status: 'ok', detail: '监听中' };
}
async reload(next: HttpServerNetwork): Promise<NetworkReloadType> {
const prevSig = bindingSignature(this.config);
const wasEnabled = this.isEnabled;
const willEnable = next.enabled !== false;
this.config = structuredClone(next);
const sigChanged = prevSig !== bindingSignature(next);
if (sigChanged && wasEnabled) {
this.close();
if (willEnable) {
this.open();
return NetworkReloadType.Reopened;
}
return NetworkReloadType.Closed;
}
if (!wasEnabled && willEnable) {
this.open();
return NetworkReloadType.Opened;
}
if (wasEnabled && !willEnable) {
this.close();
return NetworkReloadType.Closed;
}
return NetworkReloadType.Normal;
protected override bindingSignature(config: HttpServerNetwork): string {
return `${config.host ?? '0.0.0.0'}:${config.port}${normalizePath(config.path ?? '/')}`;
}
onEvent(_event: JsonObject, _payload: DispatchPayload): void { /* no-op */ }
@@ -223,10 +193,6 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
}
}
function bindingSignature(net: HttpServerNetwork): string {
return `${net.host ?? '0.0.0.0'}:${net.port}${normalizePath(net.path ?? '/')}`;
}
function readRequestBody(req: IncomingMessage, maxBytes = 2 * 1024 * 1024): Promise<string> {
return new Promise((resolve, reject) => {
const chunks: Buffer[] = [];
@@ -1,5 +1,5 @@
import { WebSocket } from '@snowluma/websocket';
import { createLogger, type Logger } from '@snowluma/common/logger';
import { createLogger } from '@snowluma/common/logger';
import {
pickDispatchJson,
resolveReportOptions,
@@ -8,7 +8,7 @@ import {
type EventReportOptions,
} from '../event-filter';
import type { JsonObject, WsClientNetwork, WsRole } from '../types';
import { IOneBotNetworkAdapter, NetworkReloadType, type AdapterStatus, type NetworkAdapterContext } from './adapter';
import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter';
import { rawDataToString, safeClose, safeSend } from './utils';
const moduleLog = createLogger('OneBot.WS-Client');
@@ -21,18 +21,11 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
private options: EventReportOptions;
private role: WsRole;
private explicitlyClosed = false;
private readonly log: Logger;
constructor(name: string, config: WsClientNetwork, ctx: NetworkAdapterContext) {
super(name, config, ctx);
super(name, config, ctx, moduleLog);
this.options = resolveReportOptions(config);
this.role = config.role ?? 'Universal';
const uinNum = Number.parseInt(ctx.uin, 10);
this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
}
override get isActive(): boolean {
return this.isEnabled;
}
open(): void {
@@ -61,33 +54,17 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
return { name: this.name, kind: 'wsClient', status: 'warn', detail: this.reconnectTimer ? '重连中' : '连接中' };
}
async reload(next: WsClientNetwork): Promise<NetworkReloadType> {
const prevSig = bindingSignature(this.config);
const wasEnabled = this.isEnabled;
const willEnable = next.enabled !== false && !!next.url;
protected override bindingSignature(config: WsClientNetwork): string {
return `${config.url}#${config.role ?? 'Universal'}#${Math.max(1000, config.reconnectIntervalMs ?? DEFAULT_RECONNECT_INTERVAL_MS)}#${config.accessToken ?? ''}`;
}
this.config = structuredClone(next);
protected override willEnable(config: WsClientNetwork): boolean {
return config.enabled !== false && !!config.url;
}
protected override onConfigReplaced(next: WsClientNetwork): void {
this.options = resolveReportOptions(next);
this.role = next.role ?? 'Universal';
const sigChanged = prevSig !== bindingSignature(next);
if (sigChanged && wasEnabled) {
this.close();
if (willEnable) {
this.open();
return NetworkReloadType.Reopened;
}
return NetworkReloadType.Closed;
}
if (!wasEnabled && willEnable) {
this.open();
return NetworkReloadType.Opened;
}
if (wasEnabled && !willEnable) {
this.close();
return NetworkReloadType.Closed;
}
return NetworkReloadType.Normal;
}
onEvent(_event: JsonObject, payload: DispatchPayload): void {
@@ -181,6 +158,3 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
}
}
function bindingSignature(net: WsClientNetwork): string {
return `${net.url}#${net.role ?? 'Universal'}#${Math.max(1000, net.reconnectIntervalMs ?? DEFAULT_RECONNECT_INTERVAL_MS)}#${net.accessToken ?? ''}`;
}
@@ -1,6 +1,6 @@
import { WebSocket, WebSocketServer } from '@snowluma/websocket';
import type { IncomingMessage } from 'http';
import { createLogger, type Logger } from '@snowluma/common/logger';
import { createLogger } from '@snowluma/common/logger';
import {
pickDispatchJson,
resolveReportOptions,
@@ -9,7 +9,7 @@ import {
type EventReportOptions,
} from '../event-filter';
import type { JsonObject, WsRole, WsServerNetwork } from '../types';
import { IOneBotNetworkAdapter, NetworkReloadType, type AdapterStatus, type NetworkAdapterContext } from './adapter';
import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter';
import { isAuthorized, normalizePath, parseRequestPath, rawDataToString, safeClose, safeSend } from './utils';
const moduleLog = createLogger('OneBot.WS-Server');
@@ -25,17 +25,10 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
private listening = false;
private connections = new Map<WebSocket, ForwardConn>();
private options: EventReportOptions;
private readonly log: Logger;
constructor(name: string, config: WsServerNetwork, ctx: NetworkAdapterContext) {
super(name, config, ctx);
super(name, config, ctx, moduleLog);
this.options = resolveReportOptions(config);
const uinNum = Number.parseInt(ctx.uin, 10);
this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
}
override get isActive(): boolean {
return this.isEnabled;
}
open(): void {
@@ -71,33 +64,13 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
return { name: this.name, kind: 'wsServer', status: 'ok', detail: `${this.connections.size} 个客户端` };
}
async reload(next: WsServerNetwork): Promise<NetworkReloadType> {
const prevSig = bindingSignature(this.config);
const wasEnabled = this.isEnabled;
const willEnable = next.enabled !== false;
protected override bindingSignature(config: WsServerNetwork): string {
return `${config.host ?? '0.0.0.0'}:${config.port}${normalizePath(config.path)}#${config.role ?? 'auto'}#${config.accessToken ?? ''}`;
}
this.config = structuredClone(next);
protected override onConfigReplaced(next: WsServerNetwork): void {
this.options = resolveReportOptions(next);
for (const conn of this.connections.values()) conn.options = this.options;
const sigChanged = prevSig !== bindingSignature(next);
if (sigChanged && wasEnabled) {
this.close();
if (willEnable) {
this.open();
return NetworkReloadType.Reopened;
}
return NetworkReloadType.Closed;
}
if (!wasEnabled && willEnable) {
this.open();
return NetworkReloadType.Opened;
}
if (wasEnabled && !willEnable) {
this.close();
return NetworkReloadType.Closed;
}
return NetworkReloadType.Normal;
}
onEvent(_event: JsonObject, payload: DispatchPayload): void {
@@ -188,7 +161,3 @@ function classifyForwardRole(request: IncomingMessage): WsRole {
if (path.endsWith('/event')) return 'Event';
return 'Universal';
}
function bindingSignature(net: WsServerNetwork): string {
return `${net.host ?? '0.0.0.0'}:${net.port}${normalizePath(net.path)}#${net.role ?? 'auto'}#${net.accessToken ?? ''}`;
}