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:
7 files changed
+324
-158
No files matched your search
@@ -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 ?? ''}`;
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
// Base-level test for the reload state machine that `IOneBotNetworkAdapter`
|
||||
// now owns (the template method lifted out of all four concrete adapters).
|
||||
//
|
||||
// It imports `../src/network/adapter` DIRECTLY rather than the `../src/network`
|
||||
// barrel on purpose: the barrel re-exports the ws adapters, which pull in
|
||||
// `@snowluma/websocket`'s native addon — absent in a plain checkout. The base
|
||||
// class has no such dependency, so the state machine is testable in isolation.
|
||||
//
|
||||
// A `ProbeAdapter` deliberately does NOT override `reload()`: it exercises the
|
||||
// inherited template, with `open()`/`close()` reduced to call-counters so each
|
||||
// test can assert exactly which transition the template drove (and that the
|
||||
// returned `NetworkReloadType` — a test-only observability seam — matches).
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
IOneBotNetworkAdapter,
|
||||
NetworkReloadType,
|
||||
type AdapterStatus,
|
||||
type NetworkAdapterContext,
|
||||
} from '../src/network/adapter';
|
||||
import type { NetworkBase } from '../src/types';
|
||||
|
||||
interface ProbeConfig extends NetworkBase {
|
||||
/** The only field `bindingSignature` reads — lets a test flip the binding
|
||||
* independently of `enabled` / `url`. */
|
||||
sig?: string;
|
||||
/** Present only so the client-style `willEnable` override has something to
|
||||
* require. */
|
||||
url?: string;
|
||||
}
|
||||
|
||||
const CTX: NetworkAdapterContext = {
|
||||
uin: '10001',
|
||||
api: {} as never,
|
||||
buildLifecycleEvent: () => ({}),
|
||||
buildHeartbeatEvent: () => ({}),
|
||||
};
|
||||
|
||||
class ProbeAdapter extends IOneBotNetworkAdapter<ProbeConfig> {
|
||||
opens = 0;
|
||||
closes = 0;
|
||||
configReplaced = 0;
|
||||
|
||||
constructor(name: string, config: ProbeConfig, private readonly requireUrl = false) {
|
||||
super(name, config, CTX);
|
||||
}
|
||||
|
||||
open(): void {
|
||||
this.opens++;
|
||||
// Faithful to the real adapters: only actually enable when the config says
|
||||
// so. The template should only ever call open() when willEnable is true,
|
||||
// so this doubles as an invariant check.
|
||||
if (this.willEnable(this.config)) this.isEnabled = true;
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.closes++;
|
||||
this.isEnabled = false;
|
||||
}
|
||||
|
||||
onEvent(): void { /* unused here */ }
|
||||
|
||||
describeStatus(): AdapterStatus {
|
||||
return { name: this.name, kind: 'httpServer', status: this.isEnabled ? 'ok' : 'disabled', detail: '' };
|
||||
}
|
||||
|
||||
protected bindingSignature(config: ProbeConfig): string {
|
||||
return config.sig ?? 'fixed';
|
||||
}
|
||||
|
||||
// Mirrors the client adapters (ws-client / http-post): also requires a url.
|
||||
protected override willEnable(config: ProbeConfig): boolean {
|
||||
return config.enabled !== false && (!this.requireUrl || !!config.url);
|
||||
}
|
||||
|
||||
protected override onConfigReplaced(_next: ProbeConfig): void {
|
||||
this.configReplaced++;
|
||||
}
|
||||
}
|
||||
|
||||
function cfg(partial: Partial<ProbeConfig> = {}): ProbeConfig {
|
||||
return { name: 'probe', enabled: true, sig: 'A', messageFormat: 'array', reportSelfMessage: false, ...partial };
|
||||
}
|
||||
|
||||
/** Build a probe, optionally bring it to the enabled state, then zero the
|
||||
* counters so a test observes only reload-driven open/close calls. */
|
||||
function makeProbe(initial: Partial<ProbeConfig>, opts: { requireUrl?: boolean; open?: boolean } = {}): ProbeAdapter {
|
||||
const a = new ProbeAdapter('probe', cfg(initial), opts.requireUrl);
|
||||
if (opts.open) a.open();
|
||||
a.opens = 0;
|
||||
a.closes = 0;
|
||||
a.configReplaced = 0;
|
||||
return a;
|
||||
}
|
||||
|
||||
describe('IOneBotNetworkAdapter.reload — shared state machine', () => {
|
||||
it('stable enabled, signature unchanged → Normal (no open/close)', async () => {
|
||||
const a = makeProbe({ sig: 'A' }, { open: true });
|
||||
expect(a.isActive).toBe(true);
|
||||
|
||||
const t = await a.reload(cfg({ sig: 'A' }));
|
||||
|
||||
expect(t).toBe(NetworkReloadType.Normal);
|
||||
expect(a.opens).toBe(0);
|
||||
expect(a.closes).toBe(0);
|
||||
expect(a.isActive).toBe(true);
|
||||
});
|
||||
|
||||
it('stable disabled stays disabled → Normal (no open/close)', async () => {
|
||||
const a = makeProbe({ enabled: false, sig: 'A' }); // not opened → wasEnabled=false
|
||||
expect(a.isActive).toBe(false);
|
||||
|
||||
const t = await a.reload(cfg({ enabled: false, sig: 'A' }));
|
||||
|
||||
expect(t).toBe(NetworkReloadType.Normal);
|
||||
expect(a.opens).toBe(0);
|
||||
expect(a.closes).toBe(0);
|
||||
expect(a.isActive).toBe(false);
|
||||
});
|
||||
|
||||
it('disabled → enabled → Opened (open only)', async () => {
|
||||
const a = makeProbe({ enabled: false, sig: 'A' });
|
||||
|
||||
const t = await a.reload(cfg({ enabled: true, sig: 'A' }));
|
||||
|
||||
expect(t).toBe(NetworkReloadType.Opened);
|
||||
expect(a.opens).toBe(1);
|
||||
expect(a.closes).toBe(0);
|
||||
expect(a.isActive).toBe(true);
|
||||
});
|
||||
|
||||
it('disabled → enabled even with a changed signature → Opened, NOT Reopened', async () => {
|
||||
// Reopened requires wasEnabled; a signature change alone must not promote
|
||||
// an Opened into a Reopened.
|
||||
const a = makeProbe({ enabled: false, sig: 'A' });
|
||||
|
||||
const t = await a.reload(cfg({ enabled: true, sig: 'B' }));
|
||||
|
||||
expect(t).toBe(NetworkReloadType.Opened);
|
||||
expect(a.opens).toBe(1);
|
||||
expect(a.closes).toBe(0);
|
||||
});
|
||||
|
||||
it('enabled → disabled (enabled:false), signature unchanged → Closed (close only)', async () => {
|
||||
const a = makeProbe({ sig: 'A' }, { open: true });
|
||||
|
||||
const t = await a.reload(cfg({ enabled: false, sig: 'A' }));
|
||||
|
||||
expect(t).toBe(NetworkReloadType.Closed);
|
||||
expect(a.closes).toBe(1);
|
||||
expect(a.opens).toBe(0);
|
||||
expect(a.isActive).toBe(false);
|
||||
});
|
||||
|
||||
it('enabled, signature changed, still enabled → Reopened (close + open)', async () => {
|
||||
const a = makeProbe({ sig: 'A' }, { open: true });
|
||||
|
||||
const t = await a.reload(cfg({ sig: 'B' }));
|
||||
|
||||
expect(t).toBe(NetworkReloadType.Reopened);
|
||||
expect(a.closes).toBe(1);
|
||||
expect(a.opens).toBe(1);
|
||||
expect(a.isActive).toBe(true);
|
||||
});
|
||||
|
||||
it('enabled, signature changed, will disable → Closed (close only, no reopen)', async () => {
|
||||
const a = makeProbe({ sig: 'A' }, { open: true });
|
||||
|
||||
const t = await a.reload(cfg({ enabled: false, sig: 'B' }));
|
||||
|
||||
expect(t).toBe(NetworkReloadType.Closed);
|
||||
expect(a.closes).toBe(1);
|
||||
expect(a.opens).toBe(0);
|
||||
expect(a.isActive).toBe(false);
|
||||
});
|
||||
|
||||
it('onConfigReplaced runs on every reload, and config is swapped before the decision', async () => {
|
||||
const a = makeProbe({ sig: 'A' }, { open: true });
|
||||
|
||||
await a.reload(cfg({ sig: 'A' })); // Normal
|
||||
await a.reload(cfg({ sig: 'B' })); // Reopened
|
||||
await a.reload(cfg({ enabled: false, sig: 'B' })); // Closed
|
||||
|
||||
expect(a.configReplaced).toBe(3);
|
||||
expect(a.currentConfig.sig).toBe('B');
|
||||
expect(a.currentConfig.enabled).toBe(false);
|
||||
});
|
||||
|
||||
describe('willEnable override (client-style: requires url)', () => {
|
||||
it('enabled:true but no url → willEnable false → stays disabled → Normal', async () => {
|
||||
const a = makeProbe({ enabled: false, sig: 'A', url: undefined }, { requireUrl: true });
|
||||
|
||||
const t = await a.reload(cfg({ enabled: true, sig: 'A', url: undefined }));
|
||||
|
||||
expect(t).toBe(NetworkReloadType.Normal);
|
||||
expect(a.opens).toBe(0);
|
||||
expect(a.isActive).toBe(false);
|
||||
});
|
||||
|
||||
it('enabled:true with a url → Opened', async () => {
|
||||
const a = makeProbe({ enabled: false, sig: 'A' }, { requireUrl: true });
|
||||
|
||||
const t = await a.reload(cfg({ enabled: true, sig: 'A', url: 'ws://x' }));
|
||||
|
||||
expect(t).toBe(NetworkReloadType.Opened);
|
||||
expect(a.opens).toBe(1);
|
||||
expect(a.isActive).toBe(true);
|
||||
});
|
||||
|
||||
it('url removed while enabled (signature unchanged) → willEnable false → Closed', async () => {
|
||||
// Proves the `wasEnabled && !willEnable` branch fires from the predicate
|
||||
// alone, independent of any binding-signature change.
|
||||
const a = makeProbe({ sig: 'A', url: 'ws://x' }, { requireUrl: true, open: true });
|
||||
expect(a.isActive).toBe(true);
|
||||
|
||||
const t = await a.reload(cfg({ enabled: true, sig: 'A', url: undefined }));
|
||||
|
||||
expect(t).toBe(NetworkReloadType.Closed);
|
||||
expect(a.closes).toBe(1);
|
||||
expect(a.opens).toBe(0);
|
||||
expect(a.isActive).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -25,7 +25,9 @@ class FakeAdapter extends IOneBotNetworkAdapter<FakeNetworkConfig> {
|
||||
this.closes++;
|
||||
this.isEnabled = false;
|
||||
}
|
||||
reload(next: FakeNetworkConfig): NetworkReloadType {
|
||||
// Keeps its own reload — this is a manager test double, not a reload test;
|
||||
// base.reload became concrete so this is now a genuine override.
|
||||
override reload(next: FakeNetworkConfig): NetworkReloadType {
|
||||
this.reloads++;
|
||||
this.config = structuredClone(next);
|
||||
if (next.enabled === false && this.isEnabled) {
|
||||
@@ -38,6 +40,9 @@ class FakeAdapter extends IOneBotNetworkAdapter<FakeNetworkConfig> {
|
||||
}
|
||||
return NetworkReloadType.Normal;
|
||||
}
|
||||
protected bindingSignature(config: FakeNetworkConfig): string {
|
||||
return JSON.stringify(config);
|
||||
}
|
||||
onEvent(event: JsonObject, payload: DispatchPayload): void {
|
||||
this.events.push(event);
|
||||
this.lastPayloads.push(payload);
|
||||
|
||||
Reference in new issue
Block a user