This commit is contained in:
DrSmoothl committed 2026-10-12 15:43:34 +08:00
1 parent effeb66554
commit 7c0519f75f
977 files changed
+198426 -158324

No files matched your search

+197 -170
View File
@@ -1,20 +1,24 @@
import { createLogger, type Logger } from '@snowluma/common/logger';
import type { ApiHandler } from '../api-handler';
import { shapeEventForAdapter, type DispatchPayload, type EventReportOptions } from '../event-filter';
import {
shapeEventForAdapter,
type DispatchPayload,
type EventReportOptions,
} from '../event-filter';
import type { JsonObject, NetworkBase } from '../types';
export interface NetworkAdapterContext {
uin: string;
api: ApiHandler;
buildLifecycleEvent(subType: 'connect' | 'enable' | 'disable'): JsonObject;
buildHeartbeatEvent(): JsonObject;
uin: string;
api: ApiHandler;
buildLifecycleEvent(subType: 'connect' | 'enable' | 'disable'): JsonObject;
buildHeartbeatEvent(): JsonObject;
}
export enum NetworkReloadType {
Normal = 0,
Reopened = 1,
Closed = 2,
Opened = 3,
Normal = 0,
Reopened = 1,
Closed = 2,
Opened = 3,
}
export type AdapterStatusLevel = 'ok' | 'warn' | 'down' | 'disabled' | 'degraded';
@@ -24,176 +28,199 @@ export type AdapterStatusLevel = 'ok' | 'warn' | 'down' | 'disabled' | 'degraded
* connection health is visible. `detail` is a short human string, e.g.
* "3 个客户端" / "重连中" / "上次推送失败 14:53:01". */
export interface AdapterStatus {
name: string;
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;
name: string;
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> {
readonly name: string;
protected config: C;
protected readonly ctx: NetworkAdapterContext;
protected readonly log: Logger;
protected isEnabled = false;
private applyFailure: { message: string; at: number } | null = null;
readonly name: string;
protected config: C;
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;
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; }
get currentConfig(): Readonly<C> { return this.config; }
get hasApplyFailure(): boolean { return this.applyFailure !== null; }
abstract open(): void | Promise<void>;
abstract close(): void | Promise<void>;
/** Drop sockets and listeners without waiting for a peer handshake.
* Graceful `close()` can sit forever on a half-open connection; shutdown
* uses this so the next account session can bind the same ports. */
forceClose(): void { /* adapters that own a listener override this */ }
abstract onEvent(event: JsonObject, payload: DispatchPayload): void | Promise<void>;
/** 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
// through `OneBotNetworkManager.emitEvent` (no pre-serialized DispatchPayload),
// so each connection-oriented adapter shapes them per its report options and
// serializes on the spot. The shape+serialize policy lives here once; the
// adapters only own the transport (which socket(s) to `safeSend` to).
/** Shape one meta event for `options` and serialize it to a wire frame, or
* `null` when the shaper drops it (e.g. a self-message under
* `reportSelfMessage:false`). */
protected metaFrame(event: JsonObject, options: EventReportOptions): string | null {
const shaped = shapeEventForAdapter(event, options);
return shaped === null ? null : JSON.stringify(shaped);
}
/** The bootstrap meta frames an event client receives on (re)connect:
* `connect`, `enable`, then a `heartbeat`, shaped for `options`. Frames the
* shaper drops are omitted. */
protected bootstrapMetaFrames(options: EventReportOptions): string[] {
const events = [
this.ctx.buildLifecycleEvent('connect'),
this.ctx.buildLifecycleEvent('enable'),
this.ctx.buildHeartbeatEvent(),
];
const frames: string[] = [];
for (const event of events) {
const frame = this.metaFrame(event, options);
if (frame !== null) frames.push(frame);
}
return frames;
}
// ── 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.
// 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. */
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);
const sigChanged = prevSig !== this.bindingSignature(next);
// 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;
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;
}
this.replaceConfig(next);
if (!wasEnabled && willEnable) {
await this.open();
return NetworkReloadType.Opened;
get isActive(): boolean {
return this.isEnabled;
}
return NetworkReloadType.Normal;
}
private replaceConfig(next: C): void {
this.config = structuredClone(next);
this.onConfigReplaced(next);
}
get currentConfig(): Readonly<C> {
return this.config;
}
get hasApplyFailure(): boolean {
return this.applyFailure !== null;
}
abstract open(): void | Promise<void>;
abstract close(): void | Promise<void>;
/** Drop sockets and listeners without waiting for a peer handshake.
* Graceful `close()` can sit forever on a half-open connection; shutdown
* uses this so the next account session can bind the same ports. */
forceClose(): void {
/* adapters that own a listener override this */
}
abstract onEvent(event: JsonObject, payload: DispatchPayload): void | Promise<void>;
/** 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
// through `OneBotNetworkManager.emitEvent` (no pre-serialized DispatchPayload),
// so each connection-oriented adapter shapes them per its report options and
// serializes on the spot. The shape+serialize policy lives here once; the
// adapters only own the transport (which socket(s) to `safeSend` to).
/** Shape one meta event for `options` and serialize it to a wire frame, or
* `null` when the shaper drops it (e.g. a self-message under
* `reportSelfMessage:false`). */
protected metaFrame(event: JsonObject, options: EventReportOptions): string | null {
const shaped = shapeEventForAdapter(event, options);
return shaped === null ? null : JSON.stringify(shaped);
}
/** The bootstrap meta frames an event client receives on (re)connect:
* `connect`, `enable`, then a `heartbeat`, shaped for `options`. Frames the
* shaper drops are omitted. */
protected bootstrapMetaFrames(options: EventReportOptions): string[] {
const events = [
this.ctx.buildLifecycleEvent('connect'),
this.ctx.buildLifecycleEvent('enable'),
this.ctx.buildHeartbeatEvent(),
];
const frames: string[] = [];
for (const event of events) {
const frame = this.metaFrame(event, options);
if (frame !== null) {
frames.push(frame);
}
}
return frames;
}
// ── 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.
// 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. */
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);
const sigChanged = prevSig !== this.bindingSignature(next);
// 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;
}
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);
return error instanceof Error ? error.message : String(error);
}
+170 -127
View File
@@ -1,9 +1,9 @@
import { createLogger } from '@snowluma/common/logger';
import {
pickDispatchJson,
resolveReportOptions,
type DispatchPayload,
type EventReportOptions,
pickDispatchJson,
resolveReportOptions,
type DispatchPayload,
type EventReportOptions,
} from '../event-filter';
import type { HttpClientNetwork, JsonObject } from '../types';
import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter';
@@ -13,139 +13,182 @@ const moduleLog = createLogger('OneBot.POST');
const DEFAULT_TIMEOUT_MS = 5000;
export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
private options: EventReportOptions;
private lastDelivery: { at: number; ok: boolean } | null = null;
private options: EventReportOptions;
private lastDelivery: { at: number; ok: boolean } | null = null;
constructor(name: string, config: HttpClientNetwork, ctx: NetworkAdapterContext) {
super(name, config, ctx, moduleLog);
this.options = resolveReportOptions(config);
}
open(): void {
if (this.config.enabled === false) return;
if (!this.config.url) return;
this.isEnabled = true;
}
close(): void {
this.isEnabled = false;
}
override describeStatus(): AdapterStatus {
if (!this.isEnabled) return { name: this.name, kind: 'httpClient', status: 'disabled', detail: '未启用' };
if (!this.lastDelivery) return { name: this.name, kind: 'httpClient', status: 'ok', detail: '已启用' };
const at = new Date(this.lastDelivery.at).toTimeString().slice(0, 8);
return this.lastDelivery.ok
? { name: this.name, kind: 'httpClient', status: 'ok', detail: `上次推送成功 ${at}` }
: { name: this.name, kind: 'httpClient', status: 'warn', detail: `上次推送失败 ${at}` };
}
protected override bindingSignature(config: HttpClientNetwork): string {
return `${config.url}#${config.accessToken ?? ''}#${config.timeoutMs ?? DEFAULT_TIMEOUT_MS}`;
}
protected override willEnable(config: HttpClientNetwork): boolean {
return config.enabled !== false && !!config.url;
}
protected override onConfigReplaced(next: HttpClientNetwork): void {
this.options = resolveReportOptions(next);
}
async onEvent(event: JsonObject, payload: DispatchPayload): Promise<void> {
if (!this.isEnabled) return;
const json = pickDispatchJson(payload, this.options);
if (json === null) return;
// 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,
config: HttpClientNetwork,
): Promise<void> {
if (!this.isEnabled) return;
const headers: Record<string, string> = {
'Content-Type': 'application/json',
'User-Agent': 'OneBot',
'X-Self-ID': this.ctx.uin,
};
if (config.accessToken) {
headers['X-Signature'] = await computeHmacSha1(config.accessToken, payload);
constructor(name: string, config: HttpClientNetwork, ctx: NetworkAdapterContext) {
super(name, config, ctx, moduleLog);
this.options = resolveReportOptions(config);
}
const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
const startedAt = Date.now();
let response: Response;
try {
response = await fetch(config.url, {
method: 'POST',
headers,
body: payload,
signal: AbortSignal.timeout(timeoutMs),
});
} catch (error) {
this.lastDelivery = { at: Date.now(), ok: false };
this.log.warn('[%s] POST %s failed: %s', this.name, config.url, error instanceof Error ? error.message : String(error));
this.log.trace(() => [
'http_report_terminal target=%s outcome=transport_failed ms=%d error=%s',
this.name,
Date.now() - startedAt,
error instanceof Error ? (error.stack ?? error.message) : String(error),
]);
return;
open(): void {
if (this.config.enabled === false) {
return;
}
if (!this.config.url) {
return;
}
this.isEnabled = true;
}
if (!response.ok) {
this.lastDelivery = { at: Date.now(), ok: false };
this.log.warn('[%s] POST %s returned %d', this.name, config.url, response.status);
this.log.trace(
'http_report_terminal target=%s outcome=rejected status=%d ms=%d',
this.name,
response.status,
Date.now() - startedAt,
);
return;
close(): void {
this.isEnabled = false;
}
this.lastDelivery = { at: Date.now(), ok: true };
this.log.trace(
'http_report_terminal target=%s outcome=accepted status=%d ms=%d',
this.name,
response.status,
Date.now() - startedAt,
);
const contentType = response.headers.get('content-type') ?? '';
if (!contentType.includes('application/json')) return;
try {
const body = await response.text();
if (body.trim()) await this.handleQuickOperation(event, body);
} catch (error) {
this.log.warn(
'[%s] quick operation response read failed: %s',
this.name,
error instanceof Error ? error.message : String(error),
);
}
}
override describeStatus(): AdapterStatus {
if (!this.isEnabled) {
return { name: this.name, kind: 'httpClient', status: 'disabled', detail: '未启用' };
}
private async handleQuickOperation(event: JsonObject, responseBody: string): Promise<void> {
try {
const operation = JSON.parse(responseBody) as Record<string, unknown>;
if (!operation || typeof operation !== 'object') return;
await executeQuickOperation(event, operation, this.ctx.api);
} catch (error) {
this.log.warn('[%s] quick operation failed: %s', this.name, error instanceof Error ? error.message : String(error));
if (!this.lastDelivery) {
return { name: this.name, kind: 'httpClient', status: 'ok', detail: '已启用' };
}
const at = new Date(this.lastDelivery.at).toTimeString().slice(0, 8);
return this.lastDelivery.ok
? { name: this.name, kind: 'httpClient', status: 'ok', detail: `上次推送成功 ${at}` }
: { name: this.name, kind: 'httpClient', status: 'warn', detail: `上次推送失败 ${at}` };
}
protected override bindingSignature(config: HttpClientNetwork): string {
return `${config.url}#${config.accessToken ?? ''}#${config.timeoutMs ?? DEFAULT_TIMEOUT_MS}`;
}
protected override willEnable(config: HttpClientNetwork): boolean {
return config.enabled !== false && !!config.url;
}
protected override onConfigReplaced(next: HttpClientNetwork): void {
this.options = resolveReportOptions(next);
}
async onEvent(event: JsonObject, payload: DispatchPayload): Promise<void> {
if (!this.isEnabled) {
return;
}
const json = pickDispatchJson(payload, this.options);
if (json === null) {
return;
}
// 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,
config: HttpClientNetwork,
): Promise<void> {
if (!this.isEnabled) {
return;
}
const headers: Record<string, string> = {
'Content-Type': 'application/json',
'User-Agent': 'OneBot',
'X-Self-ID': this.ctx.uin,
};
if (config.accessToken) {
headers['X-Signature'] = await computeHmacSha1(config.accessToken, payload);
}
const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
const startedAt = Date.now();
let response: Response;
try {
response = await fetch(config.url, {
method: 'POST',
headers,
body: payload,
signal: AbortSignal.timeout(timeoutMs),
});
} catch (error) {
this.lastDelivery = { at: Date.now(), ok: false };
this.log.warn(
'[%s] POST %s failed: %s',
this.name,
config.url,
error instanceof Error ? error.message : String(error),
);
this.log.trace(() => [
'http_report_terminal target=%s outcome=transport_failed ms=%d error=%s',
this.name,
Date.now() - startedAt,
error instanceof Error ? (error.stack ?? error.message) : String(error),
]);
return;
}
if (!response.ok) {
this.lastDelivery = { at: Date.now(), ok: false };
this.log.warn('[%s] POST %s returned %d', this.name, config.url, response.status);
this.log.trace(
'http_report_terminal target=%s outcome=rejected status=%d ms=%d',
this.name,
response.status,
Date.now() - startedAt,
);
return;
}
this.lastDelivery = { at: Date.now(), ok: true };
this.log.trace(
'http_report_terminal target=%s outcome=accepted status=%d ms=%d',
this.name,
response.status,
Date.now() - startedAt,
);
const contentType = response.headers.get('content-type') ?? '';
if (!contentType.includes('application/json')) {
return;
}
try {
const body = await response.text();
if (body.trim()) {
await this.handleQuickOperation(event, body);
}
} catch (error) {
this.log.warn(
'[%s] quick operation response read failed: %s',
this.name,
error instanceof Error ? error.message : String(error),
);
}
}
private async handleQuickOperation(event: JsonObject, responseBody: string): Promise<void> {
try {
const operation = JSON.parse(responseBody) as Record<string, unknown>;
if (!operation || typeof operation !== 'object') {
return;
}
await executeQuickOperation(event, operation, this.ctx.api);
} catch (error) {
this.log.warn(
'[%s] quick operation failed: %s',
this.name,
error instanceof Error ? error.message : String(error),
);
}
}
}
}
async function computeHmacSha1(secret: string, payload: string): Promise<string> {
const { createHmac } = await import('crypto');
return 'sha1=' + createHmac('sha1', secret).update(payload).digest('hex');
const { createHmac } = await import('crypto');
return 'sha1=' + createHmac('sha1', secret).update(payload).digest('hex');
}
File diff suppressed because it is too large. Load diff
+13 -13
View File
@@ -1,21 +1,21 @@
export {
IOneBotNetworkAdapter,
NetworkReloadType,
type AdapterStatus,
type AdapterStatusLevel,
type NetworkAdapterContext,
IOneBotNetworkAdapter,
NetworkReloadType,
type AdapterStatus,
type AdapterStatusLevel,
type NetworkAdapterContext,
} from './adapter';
export { HttpPostAdapter } from './http-post-adapter';
export { HttpServerAdapter } from './http-server-adapter';
export {
OneBotNetworkManager,
type DesiredNetworkAdapter,
type NetworkAdapterFactory,
type NetworkAdapterKind,
type NetworkApplyError,
type NetworkApplyPhase,
type NetworkReconcileResult,
type NetworkShutdownResult,
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';
+501 -416
View File
@@ -2,13 +2,13 @@ import { createLogger } from '@snowluma/common/logger';
import { assertValidOneBotConfig } from '../config';
import { buildDispatchPayload } from '../event-filter';
import type {
HttpClientNetwork,
HttpServerNetwork,
JsonObject,
NetworkBase,
OneBotConfig,
WsClientNetwork,
WsServerNetwork,
HttpClientNetwork,
HttpServerNetwork,
JsonObject,
NetworkBase,
OneBotConfig,
WsClientNetwork,
WsServerNetwork,
} from '../types';
import { IOneBotNetworkAdapter, type AdapterStatus } from './adapter';
@@ -18,40 +18,40 @@ 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 };
| { 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;
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[];
applied: boolean;
errors: NetworkApplyError[];
statuses: AdapterStatus[];
}
export interface NetworkShutdownResult {
closed: boolean;
errors: NetworkApplyError[];
closed: boolean;
errors: NetworkApplyError[];
}
export type NetworkAdapterFactory = (desired: DesiredNetworkAdapter) => AnyAdapter;
interface ManagedAdapter {
kind: NetworkAdapterKind;
adapter: AnyAdapter;
kind: NetworkAdapterKind;
adapter: AnyAdapter;
}
/**
@@ -64,433 +64,518 @@ interface ManagedAdapter {
* operation is queued.
*/
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 readonly inFlightEmits = new Set<Promise<void>>();
private shutdownPromise: Promise<NetworkShutdownResult> | null = null;
private shutdownResult: NetworkShutdownResult | null = null;
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>();
/** 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 {
if (!this.acceptingReconciles) {
throw new Error('network manager is shutting down');
constructor(factory?: NetworkAdapterFactory) {
this.factory = factory ?? null;
}
if (this.adapters.has(adapter.name)) {
throw new Error(`network adapter name already registered: ${adapter.name}`);
subscribeDebug(cb: (event: JsonObject) => void): () => void {
this.debugSubscribers.add(cb);
return () => {
this.debugSubscribers.delete(cb);
};
}
const kind = adapter.describeStatus().kind;
this.adapters.set(adapter.name, { kind, adapter: adapter as AnyAdapter });
}
has(name: string): boolean { return this.adapters.has(name); }
/** 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) {
throw new Error('network manager is shutting down');
}
get(name: string): AnyAdapter | null {
return this.adapters.get(name)?.adapter ?? null;
}
if (this.adapters.has(adapter.name)) {
throw new Error(`network adapter name already registered: ${adapter.name}`);
}
list(): AnyAdapter[] { return [...this.adapters.values()].map((entry) => entry.adapter); }
/** 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((adapter) => adapter.describeManagedStatus());
}
hasActiveAdapters(): boolean {
for (const { adapter } of this.adapters.values()) if (adapter.isActive) return true;
return false;
}
/** 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),
})),
];
}
reconcile(config: OneBotConfig): Promise<NetworkReconcileResult> {
const desired = this.compileDesiredPlan(config);
if (!this.acceptingReconciles) {
return Promise.reject(new Error('network manager is shutting down'));
const kind = adapter.describeStatus().kind;
this.adapters.set(adapter.name, { kind, adapter: adapter as AnyAdapter });
}
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. */
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()) {
has(name: string): boolean {
return this.adapters.has(name);
}
get(name: string): AnyAdapter | null {
return this.adapters.get(name)?.adapter ?? null;
}
list(): AnyAdapter[] {
return [...this.adapters.values()].map((entry) => entry.adapter);
}
/** 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((adapter) => adapter.describeManagedStatus());
}
hasActiveAdapters(): boolean {
for (const { adapter } of this.adapters.values()) {
if (adapter.isActive) {
return true;
}
}
return false;
}
/** 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),
})),
];
}
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));
}
/** 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();
}
/** 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;
for (const { adapter } of this.adapters.values()) {
try {
adapter.forceClose();
} catch (error) {
log.error('forced adapter release failed: %s', errMessage(error));
}
}
}
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. 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 (error) {
log.warn('debug subscriber error: %s', errMessage(error));
}
}
}
const active = [...this.adapters.values()]
.map(({ adapter }) => adapter)
.filter((adapter) => adapter.isActive);
if (active.length === 0) {
log.trace('report_terminal outcome=no_active_targets');
return;
}
log.trace(() => [
'report_targets targets=%s',
JSON.stringify(active.map((adapter) => adapter.name)),
]);
const payload = buildDispatchPayload(event);
const tasks = active.map((adapter) =>
Promise.resolve()
.then(() => adapter.onEvent(event, payload))
.catch((error) => {
log.warn('adapter [%s] onEvent error: %s', adapter.name, errMessage(error));
log.trace(() => [
'report_target_failed target=%s error=%s',
adapter.name,
error instanceof Error ? (error.stack ?? error.message) : String(error),
]);
}),
);
await Promise.allSettled(tasks);
log.trace('report_terminal outcome=settled');
}
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 {
await entry.adapter.open();
entry.adapter.clearApplyFailure();
adapter = this.create(next);
} catch (error) {
entry.adapter.markApplyFailure(error);
errors.push(this.report(entry.adapter.name, entry.kind, 'open', error));
errors.push(this.report(next.name, next.kind, 'open', error));
return;
}
}
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);
});
}
this.adapters.set(next.name, { kind: next.kind, adapter });
/** 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);
await adapter.open();
adapter.clearApplyFailure();
} catch (error) {
entry.adapter.markApplyFailure(error);
errors.push(this.report(name, entry.kind, 'shutdown', error));
adapter.markApplyFailure(error);
errors.push(this.report(next.name, next.kind, 'open', 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();
}
/** 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;
for (const { adapter } of this.adapters.values()) {
try {
adapter.forceClose();
} catch (error) {
log.error('forced adapter release failed: %s', errMessage(error));
}
}
}
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. 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 (error) { log.warn('debug subscriber error: %s', errMessage(error)); }
}
}
const active = [...this.adapters.values()]
.map(({ adapter }) => adapter)
.filter((adapter) => adapter.isActive);
if (active.length === 0) {
log.trace('report_terminal outcome=no_active_targets');
return;
}
log.trace(() => [
'report_targets targets=%s',
JSON.stringify(active.map((adapter) => adapter.name)),
]);
private async reloadSameKind(
live: ManagedAdapter,
next: DesiredNetworkAdapter,
errors: NetworkApplyError[],
): Promise<void> {
const previous = structuredClone(live.adapter.currentConfig);
const payload = buildDispatchPayload(event);
const tasks = active.map((adapter) => (
Promise.resolve()
.then(() => adapter.onEvent(event, payload))
.catch((error) => {
log.warn('adapter [%s] onEvent error: %s', adapter.name, errMessage(error));
log.trace(() => [
'report_target_failed target=%s error=%s',
adapter.name,
error instanceof Error ? (error.stack ?? error.message) : String(error),
]);
})
));
await Promise.allSettled(tasks);
log.trace('report_terminal outcome=settled');
}
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();
}
private async reconcileNow(desired: DesiredNetworkAdapter[]): Promise<NetworkReconcileResult> {
const errors: NetworkApplyError[] = [];
const desiredByName = new Map(desired.map((entry) => [entry.name, entry]));
await live.adapter.reload(next.config);
live.adapter.clearApplyFailure();
} catch (error) {
let restored = false;
// 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));
}
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));
}
}
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);
}
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));
}
}
return this.result(errors);
}
private create(next: DesiredNetworkAdapter): AnyAdapter {
if (!this.factory) {
throw new Error(`no network adapter factory configured for ${next.name}`);
}
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));
}
}
const adapter = this.factory(next);
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));
}
}
if (adapter.name !== next.name) {
throw new Error(
`network adapter factory returned name ${adapter.name} for desired ${next.name}`,
);
}
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;
return adapter;
}
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;
private result(errors: NetworkApplyError[]): NetworkReconcileResult {
return {
applied: errors.length === 0,
errors,
statuses: this.describeStatuses(),
};
}
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 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 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}`);
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;
}
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(error: unknown): string {
return error instanceof Error ? error.message : String(error);
return error instanceof Error ? error.message : String(error);
}
+80 -69
View File
@@ -2,81 +2,92 @@ import type { ApiHandler } from '../api-handler';
import type { JsonObject, JsonValue } from '../types';
export async function executeQuickOperation(
event: JsonObject,
operation: Record<string, unknown>,
api: ApiHandler,
event: JsonObject,
operation: Record<string, unknown>,
api: ApiHandler,
): Promise<void> {
const postType = event.post_type as string;
const postType = event.post_type as string;
if (postType === 'message') {
if (operation.reply !== undefined && operation.reply !== null && operation.reply !== '') {
const messageType = event.message_type as string;
const autoEscape = !!operation.auto_escape;
if (postType === 'message') {
if (operation.reply !== undefined && operation.reply !== null && operation.reply !== '') {
const messageType = event.message_type as string;
const autoEscape = !!operation.auto_escape;
if (messageType === 'group') {
const params: JsonObject = {
group_id: event.group_id as number,
message: operation.reply as JsonValue,
auto_escape: autoEscape,
};
if (operation.at_sender !== false && event.user_id) {
const atSegment = { type: 'at', data: { qq: String(event.user_id) } };
if (typeof operation.reply === 'string') {
params.message = [atSegment, { type: 'text', data: { text: operation.reply as string } }] as JsonValue;
params.auto_escape = false;
} else if (Array.isArray(operation.reply)) {
params.message = [atSegment, ...(operation.reply as unknown[])] as JsonValue;
}
if (messageType === 'group') {
const params: JsonObject = {
group_id: event.group_id as number,
message: operation.reply as JsonValue,
auto_escape: autoEscape,
};
if (operation.at_sender !== false && event.user_id) {
const atSegment = { type: 'at', data: { qq: String(event.user_id) } };
if (typeof operation.reply === 'string') {
params.message = [
atSegment,
{ type: 'text', data: { text: operation.reply as string } },
] as JsonValue;
params.auto_escape = false;
} else if (Array.isArray(operation.reply)) {
params.message = [
atSegment,
...(operation.reply as unknown[]),
] as JsonValue;
}
}
await api.handle('send_group_msg', params);
} else if (messageType === 'private') {
await api.handle('send_private_msg', {
user_id: event.user_id as number,
message: operation.reply as JsonValue,
auto_escape: autoEscape,
});
}
}
if (operation.delete) {
await api.handle('delete_msg', { message_id: event.message_id as number });
}
if (operation.ban && event.message_type === 'group') {
const duration =
typeof operation.ban_duration === 'number' ? operation.ban_duration : 1800;
await api.handle('set_group_ban', {
group_id: event.group_id as number,
user_id: event.user_id as number,
duration: duration as JsonValue,
});
}
if (operation.kick && event.message_type === 'group') {
await api.handle('set_group_kick', {
group_id: event.group_id as number,
user_id: event.user_id as number,
reject_add_request: !!operation.reject_add_request,
});
}
await api.handle('send_group_msg', params);
} else if (messageType === 'private') {
await api.handle('send_private_msg', {
user_id: event.user_id as number,
message: operation.reply as JsonValue,
auto_escape: autoEscape,
});
}
}
if (operation.delete) {
await api.handle('delete_msg', { message_id: event.message_id as number });
}
if (postType === 'request') {
if (operation.approve !== undefined) {
const requestType = event.request_type as string;
if (operation.ban && event.message_type === 'group') {
const duration = typeof operation.ban_duration === 'number' ? operation.ban_duration : 1800;
await api.handle('set_group_ban', {
group_id: event.group_id as number,
user_id: event.user_id as number,
duration: duration as JsonValue,
});
if (requestType === 'friend') {
await api.handle('set_friend_add_request', {
flag: event.flag as string,
approve: operation.approve as JsonValue,
remark: (operation.remark ?? '') as JsonValue,
});
} else if (requestType === 'group') {
await api.handle('set_group_add_request', {
flag: event.flag as string,
sub_type: event.sub_type as string,
approve: operation.approve as JsonValue,
reason: (operation.reason ?? '') as JsonValue,
});
}
}
}
if (operation.kick && event.message_type === 'group') {
await api.handle('set_group_kick', {
group_id: event.group_id as number,
user_id: event.user_id as number,
reject_add_request: !!operation.reject_add_request,
});
}
}
if (postType === 'request') {
if (operation.approve !== undefined) {
const requestType = event.request_type as string;
if (requestType === 'friend') {
await api.handle('set_friend_add_request', {
flag: event.flag as string,
approve: operation.approve as JsonValue,
remark: (operation.remark ?? '') as JsonValue,
});
} else if (requestType === 'group') {
await api.handle('set_group_add_request', {
flag: event.flag as string,
sub_type: event.sub_type as string,
approve: operation.approve as JsonValue,
reason: (operation.reason ?? '') as JsonValue,
});
}
}
}
}
+131 -79
View File
@@ -3,33 +3,66 @@ import type { WebSocket } from '@snowluma/websocket';
import type { IncomingMessage } from 'http';
export function isAuthorized(request: IncomingMessage, token: string): boolean {
if (!token) return true;
const auth = request.headers.authorization ?? '';
if (auth === `Bearer ${token}`) return true;
try {
const url = new URL(request.url ?? '/', 'http://127.0.0.1');
if (url.searchParams.get('access_token') === token) return true;
} catch { /* ignore malformed URLs */ }
return false;
if (!token) {
return true;
}
const auth = request.headers.authorization ?? '';
if (auth === `Bearer ${token}`) {
return true;
}
try {
const url = new URL(request.url ?? '/', 'http://127.0.0.1');
if (url.searchParams.get('access_token') === token) {
return true;
}
} catch {
/* ignore malformed URLs */
}
return false;
}
/** Convert anything ws can hand us into a UTF-8 string. */
export function rawDataToString(raw: Buffer | string | ArrayBuffer | ArrayBufferView | Buffer[]): string {
if (typeof raw === 'string') return raw;
if (Buffer.isBuffer(raw)) return raw.toString('utf8');
if (Array.isArray(raw)) return Buffer.concat(raw).toString('utf8');
if (raw instanceof ArrayBuffer) return Buffer.from(new Uint8Array(raw)).toString('utf8');
if (ArrayBuffer.isView(raw)) {
return Buffer.from(raw.buffer, raw.byteOffset, raw.byteLength).toString('utf8');
}
return '';
export function rawDataToString(
raw: Buffer | string | ArrayBuffer | ArrayBufferView | Buffer[],
): string {
if (typeof raw === 'string') {
return raw;
}
if (Buffer.isBuffer(raw)) {
return raw.toString('utf8');
}
if (Array.isArray(raw)) {
return Buffer.concat(raw).toString('utf8');
}
if (raw instanceof ArrayBuffer) {
return Buffer.from(new Uint8Array(raw)).toString('utf8');
}
if (ArrayBuffer.isView(raw)) {
return Buffer.from(raw.buffer, raw.byteOffset, raw.byteLength).toString('utf8');
}
return '';
}
export function safeSend(socket: WebSocket, payload: string, onError?: (err: Error) => void): void {
if (socket.readyState !== 1 /* WebSocket.OPEN */) return;
socket.send(payload, (error?: Error | null) => {
if (error && onError) onError(error);
});
if (socket.readyState !== 1 /* WebSocket.OPEN */) {
return;
}
socket.send(payload, (error?: Error | null) => {
if (error && onError) {
onError(error);
}
});
}
/** Backpressure-aware send: resolves only once `ws` has flushed `payload` to
@@ -38,28 +71,33 @@ export function safeSend(socket: WebSocket, payload: string, onError?: (err: Err
* A closed socket or failed write rejects with the shared transport sentinel,
* allowing the action boundary to classify an in-progress stream cancellation. */
export function safeSendAsync(socket: WebSocket, payload: string): Promise<void> {
return new Promise((resolve, reject) => {
if (socket.readyState !== 1 /* WebSocket.OPEN */) {
reject(new StreamTransportClosedError('stream client disconnected'));
return;
}
try {
socket.send(payload, (error?: Error | null) => {
if (error) {
reject(new StreamTransportClosedError('stream client disconnected'));
return;
return new Promise((resolve, reject) => {
if (socket.readyState !== 1 /* WebSocket.OPEN */) {
reject(new StreamTransportClosedError('stream client disconnected'));
return;
}
resolve();
});
} catch {
reject(new StreamTransportClosedError('stream client disconnected'));
}
});
try {
socket.send(payload, (error?: Error | null) => {
if (error) {
reject(new StreamTransportClosedError('stream client disconnected'));
return;
}
resolve();
});
} catch {
reject(new StreamTransportClosedError('stream client disconnected'));
}
});
}
export function safeClose(socket: WebSocket, code = 1000, reason = 'normal'): void {
if (socket.readyState === 3 /* CLOSED */ || socket.readyState === 2 /* CLOSING */) return;
socket.close(code, reason);
if (socket.readyState === 3 /* CLOSED */ || socket.readyState === 2 /* CLOSING */) {
return;
}
socket.close(code, reason);
}
/** RFC6455 transport-level keepalive for a reverse-WS connection.
@@ -84,53 +122,67 @@ export function safeClose(socket: WebSocket, code = 1000, reason = 'normal'): vo
* Returns an idempotent stop function; the timer is `unref`'d so it never keeps
* the process alive. */
export function startHeartbeat(
socket: WebSocket,
opts: { intervalMs: number; maxMissed: number },
onDead: () => void,
socket: WebSocket,
opts: { intervalMs: number; maxMissed: number },
onDead: () => void,
): () => void {
let missed = 0;
let stopped = false;
const onActivity = (): void => { missed = 0; };
socket.on('pong', onActivity);
socket.on('message', onActivity);
let missed = 0;
let stopped = false;
const timer = setInterval(() => {
if (missed >= opts.maxMissed) {
// `maxMissed` consecutive intervals with zero inbound traffic — the read
// direction is dead. Stop first so onDead()'s terminate→close→reconnect
// can't re-enter this tick.
stop();
onDead();
return;
}
missed += 1;
try {
socket.ping();
} catch {
// Ping on an already-dead socket — treat as dead immediately.
stop();
onDead();
}
}, opts.intervalMs);
timer.unref?.();
const onActivity = (): void => {
missed = 0;
};
function stop(): void {
if (stopped) return;
stopped = true;
clearInterval(timer);
socket.off?.('pong', onActivity);
socket.off?.('message', onActivity);
}
return stop;
socket.on('pong', onActivity);
socket.on('message', onActivity);
const timer = setInterval(() => {
if (missed >= opts.maxMissed) {
// `maxMissed` consecutive intervals with zero inbound traffic — the read
// direction is dead. Stop first so onDead()'s terminate→close→reconnect
// can't re-enter this tick.
stop();
onDead();
return;
}
missed += 1;
try {
socket.ping();
} catch {
// Ping on an already-dead socket — treat as dead immediately.
stop();
onDead();
}
}, opts.intervalMs);
timer.unref?.();
function stop(): void {
if (stopped) {
return;
}
stopped = true;
clearInterval(timer);
socket.off?.('pong', onActivity);
socket.off?.('message', onActivity);
}
return stop;
}
export function normalizePath(pathValue: string | undefined): string {
const path = (pathValue ?? '/').trim() || '/';
if (path === '/') return '/';
return path.endsWith('/') ? path.slice(0, -1) : path;
const path = (pathValue ?? '/').trim() || '/';
if (path === '/') {
return '/';
}
return path.endsWith('/') ? path.slice(0, -1) : path;
}
export function parseRequestPath(urlValue: string): string {
const queryIndex = urlValue.indexOf('?');
return queryIndex === -1 ? urlValue : urlValue.slice(0, queryIndex);
const queryIndex = urlValue.indexOf('?');
return queryIndex === -1 ? urlValue : urlValue.slice(0, queryIndex);
}
+354 -234
View File
@@ -1,10 +1,10 @@
import { WebSocket } from '@snowluma/websocket';
import { createLogger } from '@snowluma/common/logger';
import {
pickDispatchJson,
resolveReportOptions,
type DispatchPayload,
type EventReportOptions,
pickDispatchJson,
resolveReportOptions,
type DispatchPayload,
type EventReportOptions,
} from '../event-filter';
import type { JsonObject, WsClientNetwork, WsRole } from '../types';
import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter';
@@ -21,244 +21,364 @@ const HEARTBEAT_MAX_MISSED = 2;
const HEARTBEAT_DEAD_AFTER_S = (HEARTBEAT_INTERVAL_MS * (HEARTBEAT_MAX_MISSED + 1)) / 1000;
export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
private socket: WebSocket | null = null;
private connected = false;
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
// closure in connect() still owns the #97 stale-socket case; this is idempotent
// with it (both call the same stop).
private heartbeatStop: (() => void) | null = null;
private socket: WebSocket | null = null;
private connected = false;
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
// closure in connect() still owns the #97 stale-socket case; this is idempotent
// with it (both call the same stop).
private heartbeatStop: (() => void) | null = null;
constructor(name: string, config: WsClientNetwork, ctx: NetworkAdapterContext) {
super(name, config, ctx, moduleLog);
this.options = resolveReportOptions(config);
this.role = config.role ?? 'Universal';
}
open(): void {
if (this.isEnabled) 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();
this.heartbeatStop?.();
this.heartbeatStop = null;
const socket = this.socket;
this.socket = null;
if (socket) {
try { socket.terminate(); } catch { /* already gone */ }
}
}
async close(): Promise<void> {
this.explicitlyClosed = true;
this.acceptingActions = false;
this.isEnabled = false;
this.connected = false;
this.cancelReconnect();
this.heartbeatStop?.();
this.heartbeatStop = null;
if (this.socket) {
safeClose(this.socket);
this.socket = null;
}
await Promise.all(this.inFlightActions);
}
override describeStatus(): AdapterStatus {
if (!this.isEnabled) return { name: this.name, kind: 'wsClient', status: 'disabled', detail: '未启用' };
if (this.connected) return { name: this.name, kind: 'wsClient', status: 'ok', detail: '已连接' };
return { name: this.name, kind: 'wsClient', status: 'warn', detail: this.reconnectTimer ? '重连中' : '连接中' };
}
protected override bindingSignature(config: WsClientNetwork): string {
return `${config.url}#${config.role ?? 'Universal'}#${Math.max(1000, config.reconnectIntervalMs ?? DEFAULT_RECONNECT_INTERVAL_MS)}#${config.accessToken ?? ''}`;
}
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';
}
onEvent(_event: JsonObject, payload: DispatchPayload): void {
if (!this.isEnabled || !this.socket) return;
if (this.role !== 'Event' && this.role !== 'Universal') return;
const json = pickDispatchJson(payload, this.options);
if (json === null) return;
safeSend(this.socket, json);
}
private connect(): void {
if (this.explicitlyClosed) return;
if (!this.config.url) return;
if (this.socket) return;
const headers: Record<string, string> = {
'User-Agent': 'OneBot/11',
'X-Self-ID': this.ctx.uin,
'X-Client-Role': this.role,
};
if (this.config.accessToken) {
headers.Authorization = `Bearer ${this.config.accessToken}`;
constructor(name: string, config: WsClientNetwork, ctx: NetworkAdapterContext) {
super(name, config, ctx, moduleLog);
this.options = resolveReportOptions(config);
this.role = config.role ?? 'Universal';
}
const socket = new WebSocket(this.config.url, { headers });
this.socket = socket;
// Per-socket so a hot-reload overlap (old close firing after the new socket
// is assigned, see #97) can only ever stop its own keepalive.
let stopHeartbeat: (() => void) | null = null;
socket.on('open', () => {
// Symmetric with the 'close' guard (#97): if this socket was already
// replaced, a late 'open' must not flip `connected` or install a stale
// heartbeat onto the current connection's slot.
if (this.socket !== socket) return;
this.connected = true;
this.log.info('[%s] connected %s', this.name, this.config.url);
this.sendBootstrapMetaEvents(socket);
// Only meaningful once OPEN — ping() no-ops before the handshake completes.
stopHeartbeat = startHeartbeat(
socket,
{ intervalMs: HEARTBEAT_INTERVAL_MS, maxMissed: HEARTBEAT_MAX_MISSED },
() => {
if (this.explicitlyClosed || !this.isEnabled) return;
this.log.warn('[%s] no inbound response for ~%ds, reconnecting half-open connection %s', this.name, HEARTBEAT_DEAD_AFTER_S, this.config.url);
// terminate → 'close' → scheduleReconnect, reusing the normal path.
socket.terminate();
},
);
this.heartbeatStop = stopHeartbeat;
});
socket.on('message', (raw: Buffer) => {
if (this.socket !== socket) {
this.log.warn('[%s] rejected inbound action from stale socket', this.name);
return;
}
if (this.ctx.api.isAcceptingActions === false) {
this.log.warn('[%s] rejected inbound action after instance quiesce', this.name);
if (this.role === 'Api' || this.role === 'Universal') {
const text = rawDataToString(raw);
if (text) this.ctx.api.traceQuiescedStreamRequest(text);
open(): void {
if (this.isEnabled) {
return;
}
return;
}
this.trackInboundAction(() => this.handleApiMessage(socket, raw));
});
socket.on('close', () => {
stopHeartbeat?.();
// Drop the instance handle only if it still points at THIS socket's stop
// (a newer socket may already own it after a hot-reload overlap).
if (this.heartbeatStop === stopHeartbeat) this.heartbeatStop = null;
stopHeartbeat = null;
// Ignore close events from a socket that is no longer the current
// connection. A hot reload (signature change) calls close() then open()
// back-to-back; the old socket's `'close'` event fires AFTER the new
// one is already assigned to `this.socket`, and without this guard it
// would null out `this.socket`, drop `connected`, and schedule an
// unwanted reconnect — observable as a reconnect storm against a
// single-connection backend that kicks duplicates. See issue #97.
if (this.socket !== socket) return;
this.socket = null;
this.connected = false;
if (this.explicitlyClosed || !this.isEnabled) return;
this.scheduleReconnect();
});
if (this.config.enabled === false) {
return;
}
socket.on('error', (err: Error) => {
this.log.warn('[%s] error %s: %s', this.name, this.config.url, err instanceof Error ? err.message : String(err));
});
}
if (!this.config.url) {
return;
}
private scheduleReconnect(): void {
if (this.reconnectTimer) return;
if (this.explicitlyClosed) return;
const interval = Math.max(1000, this.config.reconnectIntervalMs ?? DEFAULT_RECONNECT_INTERVAL_MS);
const timer = setTimeout(() => {
this.reconnectTimer = null;
if (this.explicitlyClosed || !this.isEnabled) return;
this.connect();
}, interval);
timer.unref?.();
this.reconnectTimer = timer;
}
this.explicitlyClosed = false;
this.isEnabled = true;
private cancelReconnect(): void {
if (!this.reconnectTimer) return;
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
private async handleApiMessage(socket: WebSocket, raw: Buffer | string): Promise<void> {
if (this.role !== 'Api' && this.role !== 'Universal') return;
const text = rawDataToString(raw);
if (!text) return;
// Stream API (#163): one frame for a normal action, N for a streaming one.
// Async send = backpressure; liveness check aborts on disconnect.
await this.ctx.api.processStreamRequest(
text,
(frame) => safeSendAsync(socket, frame),
() => socket.readyState === 1,
);
}
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;
try {
this.connect();
this.acceptingActions = true;
this.clearApplyFailure();
} catch (error) {
this.isEnabled = false;
this.explicitlyClosed = true;
this.acceptingActions = false;
this.recordTransportFailure(error);
throw error;
}
}
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);
}
override forceClose(): void {
this.explicitlyClosed = true;
this.acceptingActions = false;
this.isEnabled = false;
this.connected = false;
this.cancelReconnect();
this.heartbeatStop?.();
this.heartbeatStop = null;
const socket = this.socket;
this.socket = null;
if (socket) {
try {
socket.terminate();
} catch {
/* already gone */
}
}
}
async close(): Promise<void> {
this.explicitlyClosed = true;
this.acceptingActions = false;
this.isEnabled = false;
this.connected = false;
this.cancelReconnect();
this.heartbeatStop?.();
this.heartbeatStop = null;
if (this.socket) {
safeClose(this.socket);
this.socket = null;
}
await Promise.all(this.inFlightActions);
}
override describeStatus(): AdapterStatus {
if (!this.isEnabled) {
return { name: this.name, kind: 'wsClient', status: 'disabled', detail: '未启用' };
}
if (this.connected) {
return { name: this.name, kind: 'wsClient', status: 'ok', detail: '已连接' };
}
return {
name: this.name,
kind: 'wsClient',
status: 'warn',
detail: this.reconnectTimer ? '重连中' : '连接中',
};
}
protected override bindingSignature(config: WsClientNetwork): string {
return `${config.url}#${config.role ?? 'Universal'}#${Math.max(1000, config.reconnectIntervalMs ?? DEFAULT_RECONNECT_INTERVAL_MS)}#${config.accessToken ?? ''}`;
}
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';
}
onEvent(_event: JsonObject, payload: DispatchPayload): void {
if (!this.isEnabled || !this.socket) {
return;
}
if (this.role !== 'Event' && this.role !== 'Universal') {
return;
}
const json = pickDispatchJson(payload, this.options);
if (json === null) {
return;
}
safeSend(this.socket, json);
}
private connect(): void {
if (this.explicitlyClosed) {
return;
}
if (!this.config.url) {
return;
}
if (this.socket) {
return;
}
const headers: Record<string, string> = {
'User-Agent': 'OneBot/11',
'X-Self-ID': this.ctx.uin,
'X-Client-Role': this.role,
};
if (this.config.accessToken) {
headers.Authorization = `Bearer ${this.config.accessToken}`;
}
const socket = new WebSocket(this.config.url, { headers });
this.socket = socket;
// Per-socket so a hot-reload overlap (old close firing after the new socket
// is assigned, see #97) can only ever stop its own keepalive.
let stopHeartbeat: (() => void) | null = null;
socket.on('open', () => {
// Symmetric with the 'close' guard (#97): if this socket was already
// replaced, a late 'open' must not flip `connected` or install a stale
// heartbeat onto the current connection's slot.
if (this.socket !== socket) {
return;
}
this.connected = true;
this.log.info('[%s] connected %s', this.name, this.config.url);
this.sendBootstrapMetaEvents(socket);
// Only meaningful once OPEN — ping() no-ops before the handshake completes.
stopHeartbeat = startHeartbeat(
socket,
{ intervalMs: HEARTBEAT_INTERVAL_MS, maxMissed: HEARTBEAT_MAX_MISSED },
() => {
if (this.explicitlyClosed || !this.isEnabled) {
return;
}
this.log.warn(
'[%s] no inbound response for ~%ds, reconnecting half-open connection %s',
this.name,
HEARTBEAT_DEAD_AFTER_S,
this.config.url,
);
// terminate → 'close' → scheduleReconnect, reusing the normal path.
socket.terminate();
},
);
this.heartbeatStop = stopHeartbeat;
});
socket.on('message', (raw: Buffer) => {
if (this.socket !== socket) {
this.log.warn('[%s] rejected inbound action from stale socket', this.name);
return;
}
if (this.ctx.api.isAcceptingActions === false) {
this.log.warn('[%s] rejected inbound action after instance quiesce', this.name);
if (this.role === 'Api' || this.role === 'Universal') {
const text = rawDataToString(raw);
if (text) {
this.ctx.api.traceQuiescedStreamRequest(text);
}
}
return;
}
this.trackInboundAction(() => this.handleApiMessage(socket, raw));
});
socket.on('close', () => {
stopHeartbeat?.();
// Drop the instance handle only if it still points at THIS socket's stop
// (a newer socket may already own it after a hot-reload overlap).
if (this.heartbeatStop === stopHeartbeat) {
this.heartbeatStop = null;
}
stopHeartbeat = null;
// Ignore close events from a socket that is no longer the current
// connection. A hot reload (signature change) calls close() then open()
// back-to-back; the old socket's `'close'` event fires AFTER the new
// one is already assigned to `this.socket`, and without this guard it
// would null out `this.socket`, drop `connected`, and schedule an
// unwanted reconnect — observable as a reconnect storm against a
// single-connection backend that kicks duplicates. See issue #97.
if (this.socket !== socket) {
return;
}
this.socket = null;
this.connected = false;
if (this.explicitlyClosed || !this.isEnabled) {
return;
}
this.scheduleReconnect();
});
socket.on('error', (err: Error) => {
this.log.warn(
'[%s] error %s: %s',
this.name,
this.config.url,
err instanceof Error ? err.message : String(err),
);
});
}
private scheduleReconnect(): void {
if (this.reconnectTimer) {
return;
}
if (this.explicitlyClosed) {
return;
}
const interval = Math.max(
1000,
this.config.reconnectIntervalMs ?? DEFAULT_RECONNECT_INTERVAL_MS,
);
const timer = setTimeout(() => {
this.reconnectTimer = null;
if (this.explicitlyClosed || !this.isEnabled) {
return;
}
this.connect();
}, interval);
timer.unref?.();
this.reconnectTimer = timer;
}
private cancelReconnect(): void {
if (!this.reconnectTimer) {
return;
}
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
private async handleApiMessage(socket: WebSocket, raw: Buffer | string): Promise<void> {
if (this.role !== 'Api' && this.role !== 'Universal') {
return;
}
const text = rawDataToString(raw);
if (!text) {
return;
}
// Stream API (#163): one frame for a normal action, N for a streaming one.
// Async send = backpressure; liveness check aborts on disconnect.
await this.ctx.api.processStreamRequest(
text,
(frame) => safeSendAsync(socket, frame),
() => socket.readyState === 1,
);
}
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);
}
}
}
+254 -181
View File
@@ -5,203 +5,276 @@ import type { DispatchPayload } from '../event-filter';
import type { JsonObject, WsServerNetwork } from '../types';
import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter';
import { normalizePath, parseRequestPath } from './utils';
import {
WsServerConnections,
type WsServerConnectionConfig,
} from './ws-server-connections';
import { WsServerConnections, type WsServerConnectionConfig } from './ws-server-connections';
const moduleLog = createLogger('OneBot.WS-Server');
export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
private wss: WebSocketServer | null = null;
private listening = false;
private releaseForced = false;
private closePromise: Promise<void> | null = null;
private readonly connections: WsServerConnections;
private wss: WebSocketServer | null = null;
private listening = false;
private releaseForced = false;
private closePromise: Promise<void> | null = null;
private readonly connections: WsServerConnections;
constructor(name: string, config: WsServerNetwork, ctx: NetworkAdapterContext) {
super(name, config, ctx, moduleLog);
this.connections = new WsServerConnections(name, standaloneConnectionConfig(config), ctx, this.log, {
frame: (event, options) => this.metaFrame(event, options),
bootstrap: (options) => this.bootstrapMetaFrames(options),
});
}
async open(): Promise<void> {
if (this.isEnabled && this.listening) return;
if (this.config.enabled === false) return;
if (this.wss) throw new Error(`WebSocket adapter [${this.name}] still owns a previous server`);
await this.startServer();
this.isEnabled = true;
this.clearApplyFailure();
}
async close(): Promise<void> {
if (this.closePromise) return this.closePromise;
if (
!this.isEnabled &&
this.connections.connectionCount === 0 &&
!this.wss &&
!this.connections.hasInFlightActions
) return;
const wasEnabled = this.isEnabled;
const wasListening = this.listening;
const wasAcceptingActions = this.connections.isAcceptingActions;
this.isEnabled = false;
this.listening = false;
const connectionDrain = this.connections.closeConnections();
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 connectionDrain;
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) {
if (this.releaseForced) return;
// 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;
if (wasAcceptingActions) this.connections.startAccepting();
throw error;
} finally {
this.closePromise = null;
}
}
override forceClose(): void {
this.releaseForced = true;
this.isEnabled = false;
this.listening = false;
this.connections.stopAccepting();
this.connections.terminateAll();
const wss = this.wss;
this.wss = null;
if (wss) {
try { wss.destroy(); } catch { /* already dropping */ }
}
}
override describeStatus(): AdapterStatus {
if (!this.isEnabled) return { name: this.name, kind: 'wsServer', status: 'disabled', detail: '未启用' };
if (!this.listening) return { name: this.name, kind: 'wsServer', status: 'down', detail: '未监听(端口被占用?)' };
return {
name: this.name,
kind: 'wsServer',
status: 'ok',
detail: `${this.connections.connectionCount} 个客户端`,
};
}
protected override bindingSignature(config: WsServerNetwork): string {
return `${config.host ?? '0.0.0.0'}:${config.port}${normalizePath(config.path)}#${config.role ?? 'auto'}#${config.accessToken ?? ''}`;
}
protected override onConfigReplaced(next: WsServerNetwork): void {
this.connections.updateConfig(standaloneConnectionConfig(next));
}
onEvent(_event: JsonObject, payload: DispatchPayload): void {
if (!this.isEnabled) return;
this.connections.onEvent(payload);
}
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,
verifyClient: (
{ req }: { req: IncomingMessage },
done: (allow: boolean, code?: number, message?: string) => void,
) => {
const requestPath = parseRequestPath(req.url ?? '/');
if (!this.connections.acceptsUpgradePath(requestPath)) {
this.log.debug('[%s] rejected unknown WebSocket path %s', this.name, requestPath);
done(false, 400, 'Bad path for WebSocket');
return;
}
if (!this.connections.authorizeUpgrade(req)) {
done(false, 401, 'Unauthorized');
return;
}
done(true);
},
});
} catch (error) {
this.recordTransportFailure(error);
reject(error);
return;
}
this.wss = wss;
let opening = true;
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.connections.startAccepting();
this.log.success(
'[%s] listening %s:%d%s',
this.name,
this.config.host ?? '0.0.0.0',
this.config.port,
this.config.path ?? '/',
constructor(name: string, config: WsServerNetwork, ctx: NetworkAdapterContext) {
super(name, config, ctx, moduleLog);
this.connections = new WsServerConnections(
name,
standaloneConnectionConfig(config),
ctx,
this.log,
{
frame: (event, options) => this.metaFrame(event, options),
bootstrap: (options) => this.bootstrapMetaFrames(options),
},
);
resolve();
});
}
wss.on('error', (error: Error) => {
if (this.wss === wss) {
this.listening = false;
this.isEnabled = false;
this.connections.stopAccepting();
this.recordTransportFailure(error);
if (opening) this.wss = null;
async open(): Promise<void> {
if (this.isEnabled && this.listening) {
return;
}
this.log.error('[%s] server error: %s', this.name, error instanceof Error ? error.message : String(error));
if (opening) {
opening = false;
reject(error);
if (this.config.enabled === false) {
return;
}
});
wss.on('connection', (socket, request) => this.connections.accept(socket, request));
});
}
if (this.wss) {
throw new Error(`WebSocket adapter [${this.name}] still owns a previous server`);
}
/** Kept as the adapter-level lifecycle test seam. */
protected get acceptingActions(): boolean {
return this.connections.isAcceptingActions;
}
await this.startServer();
this.isEnabled = true;
this.clearApplyFailure();
}
/** Kept as the adapter-level lifecycle test seam. */
protected trackInboundAction(start: () => Promise<void>): void {
this.connections.trackInboundAction(start);
}
async close(): Promise<void> {
if (this.closePromise) {
return this.closePromise;
}
if (
!this.isEnabled &&
this.connections.connectionCount === 0 &&
!this.wss &&
!this.connections.hasInFlightActions
) {
return;
}
const wasEnabled = this.isEnabled;
const wasListening = this.listening;
const wasAcceptingActions = this.connections.isAcceptingActions;
this.isEnabled = false;
this.listening = false;
const connectionDrain = this.connections.closeConnections();
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 connectionDrain;
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) {
if (this.releaseForced) {
return;
}
// 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;
if (wasAcceptingActions) {
this.connections.startAccepting();
}
throw error;
} finally {
this.closePromise = null;
}
}
override forceClose(): void {
this.releaseForced = true;
this.isEnabled = false;
this.listening = false;
this.connections.stopAccepting();
this.connections.terminateAll();
const wss = this.wss;
this.wss = null;
if (wss) {
try {
wss.destroy();
} catch {
/* already dropping */
}
}
}
override describeStatus(): AdapterStatus {
if (!this.isEnabled) {
return { name: this.name, kind: 'wsServer', status: 'disabled', detail: '未启用' };
}
if (!this.listening) {
return {
name: this.name,
kind: 'wsServer',
status: 'down',
detail: '未监听(端口被占用?)',
};
}
return {
name: this.name,
kind: 'wsServer',
status: 'ok',
detail: `${this.connections.connectionCount} 个客户端`,
};
}
protected override bindingSignature(config: WsServerNetwork): string {
return `${config.host ?? '0.0.0.0'}:${config.port}${normalizePath(config.path)}#${config.role ?? 'auto'}#${config.accessToken ?? ''}`;
}
protected override onConfigReplaced(next: WsServerNetwork): void {
this.connections.updateConfig(standaloneConnectionConfig(next));
}
onEvent(_event: JsonObject, payload: DispatchPayload): void {
if (!this.isEnabled) {
return;
}
this.connections.onEvent(payload);
}
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,
verifyClient: (
{ req }: { req: IncomingMessage },
done: (allow: boolean, code?: number, message?: string) => void,
) => {
const requestPath = parseRequestPath(req.url ?? '/');
if (!this.connections.acceptsUpgradePath(requestPath)) {
this.log.debug(
'[%s] rejected unknown WebSocket path %s',
this.name,
requestPath,
);
done(false, 400, 'Bad path for WebSocket');
return;
}
if (!this.connections.authorizeUpgrade(req)) {
done(false, 401, 'Unauthorized');
return;
}
done(true);
},
});
} catch (error) {
this.recordTransportFailure(error);
reject(error);
return;
}
this.wss = wss;
let opening = true;
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.connections.startAccepting();
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', (error: Error) => {
if (this.wss === wss) {
this.listening = false;
this.isEnabled = false;
this.connections.stopAccepting();
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, request) => this.connections.accept(socket, request));
});
}
/** Kept as the adapter-level lifecycle test seam. */
protected get acceptingActions(): boolean {
return this.connections.isAcceptingActions;
}
/** Kept as the adapter-level lifecycle test seam. */
protected trackInboundAction(start: () => Promise<void>): void {
this.connections.trackInboundAction(start);
}
}
function isAlreadyClosedError(error: Error): boolean {
return (error as NodeJS.ErrnoException).code === 'ERR_SERVER_NOT_RUNNING';
return (error as NodeJS.ErrnoException).code === 'ERR_SERVER_NOT_RUNNING';
}
function standaloneConnectionConfig(config: WsServerNetwork): WsServerConnectionConfig {
return { ...config, role: config.role ?? 'Universal' };
return { ...config, role: config.role ?? 'Universal' };
}
@@ -2,22 +2,22 @@ import type { Logger } from '@snowluma/common/logger';
import type { WebSocket } from '@snowluma/websocket';
import type { IncomingMessage } from 'node:http';
import {
pickDispatchJson,
resolveReportOptions,
type DispatchPayload,
type EventReportOptions,
pickDispatchJson,
resolveReportOptions,
type DispatchPayload,
type EventReportOptions,
} from '../event-filter';
import type { JsonObject, NetworkBase, WsRole } from '../types';
import type { NetworkAdapterContext } from './adapter';
import {
isAuthorized,
normalizePath,
parseRequestPath,
rawDataToString,
safeClose,
safeSend,
safeSendAsync,
startHeartbeat,
isAuthorized,
normalizePath,
parseRequestPath,
rawDataToString,
safeClose,
safeSend,
safeSendAsync,
startHeartbeat,
} from './utils';
// Transport keepalive for each attached client, symmetric with the ws-client
@@ -31,15 +31,15 @@ const HEARTBEAT_DEAD_AFTER_S = (HEARTBEAT_INTERVAL_MS * (HEARTBEAT_MAX_MISSED +
export type WsServerConnectionConfig = NetworkBase & { path?: string; role?: WsRole };
interface ForwardConnection {
socket: WebSocket;
role: WsRole;
options: EventReportOptions;
stopHeartbeat: () => void;
socket: WebSocket;
role: WsRole;
options: EventReportOptions;
stopHeartbeat: () => void;
}
interface MetaFrames {
frame(event: JsonObject, options: EventReportOptions): string | null;
bootstrap(options: EventReportOptions): string[];
frame(event: JsonObject, options: EventReportOptions): string | null;
bootstrap(options: EventReportOptions): string[];
}
/**
@@ -52,247 +52,329 @@ interface MetaFrames {
* auth, role, event, heartbeat, stream, and shutdown semantics.
*/
export class WsServerConnections {
private acceptingActions = false;
private readonly inFlightActions = new Set<Promise<void>>();
private readonly connections = new Map<WebSocket, ForwardConnection>();
private config: WsServerConnectionConfig;
private options: EventReportOptions;
private acceptingActions = false;
private readonly inFlightActions = new Set<Promise<void>>();
private readonly connections = new Map<WebSocket, ForwardConnection>();
private config: WsServerConnectionConfig;
private options: EventReportOptions;
constructor(
private readonly name: string,
config: WsServerConnectionConfig,
private readonly ctx: NetworkAdapterContext,
private readonly log: Logger,
private readonly meta: MetaFrames,
) {
this.config = structuredClone(config);
this.options = resolveReportOptions(config);
}
get connectionCount(): number {
return this.connections.size;
}
get isAcceptingActions(): boolean {
return this.acceptingActions;
}
get hasInFlightActions(): boolean {
return this.inFlightActions.size > 0;
}
startAccepting(): void {
this.acceptingActions = true;
}
stopAccepting(): void {
this.acceptingActions = false;
}
updateConfig(next: WsServerConnectionConfig): void {
const tokenChanged = (this.config.accessToken ?? '') !== (next.accessToken ?? '');
this.config = structuredClone(next);
this.options = resolveReportOptions(next);
for (const connection of this.connections.values()) connection.options = this.options;
// An already-authorized socket must not retain access after token
// rotation. Drop it immediately; the client can reconnect with the new
// credential without forcing the shared HTTP listener to rebind.
if (tokenChanged) this.disconnectAll(1008, 'access token changed');
}
acceptsUpgradePath(requestPath: string): boolean {
return resolveForwardRole(requestPath, this.config) !== null;
}
onEvent(payload: DispatchPayload): void {
if (!this.acceptingActions || this.connections.size === 0) return;
for (const connection of this.connections.values()) {
if (connection.role !== 'Event' && connection.role !== 'Universal') continue;
const json = pickDispatchJson(payload, connection.options);
if (json === null) continue;
safeSend(connection.socket, json);
}
}
/** Authenticate the HTTP upgrade before a WebSocket object is allocated. */
authorizeUpgrade(request: IncomingMessage): boolean {
const authorized = isAuthorized(request, this.config.accessToken ?? '');
if (!authorized) this.log.debug('[%s] rejected unauthorized WebSocket upgrade', this.name);
return authorized;
}
accept(socket: WebSocket, request: IncomingMessage): void {
if (!this.acceptingActions || this.ctx.api.isAcceptingActions === false) {
safeClose(socket, 1012, 'server closing');
return;
}
// Defence in depth for custom/future listeners that bypass verifyClient.
if (!this.authorizeUpgrade(request)) {
safeClose(socket, 1008, 'invalid access token');
return;
}
const requestPath = parseRequestPath(request.url ?? '/');
const role = resolveForwardRole(requestPath, this.config);
if (role === null) {
this.log.warn('[%s] rejected WebSocket path after upgrade', this.name);
safeClose(socket, 1008, 'invalid path');
return;
}
const stopHeartbeat = startHeartbeat(
socket,
{ intervalMs: HEARTBEAT_INTERVAL_MS, maxMissed: HEARTBEAT_MAX_MISSED },
() => {
this.log.warn(
'[%s] client silent for ~%ds, terminating half-open connection',
this.name,
HEARTBEAT_DEAD_AFTER_S,
);
socket.terminate();
},
);
const connection: ForwardConnection = {
socket,
role,
options: this.options,
stopHeartbeat,
};
this.connections.set(socket, connection);
socket.on('message', (raw: Buffer) => {
// Token rotation removes the connection synchronously, before the close
// handshake necessarily reaches the peer. Ignore any frame arriving in
// that interval so old credentials cannot start another Action.
if (!this.connections.has(socket)) return;
if (this.ctx.api.isAcceptingActions === false) {
this.log.warn('[%s] rejected inbound action after instance quiesce', this.name);
if (role === 'Api' || role === 'Universal') {
const text = rawDataToString(raw);
if (text) this.ctx.api.traceQuiescedStreamRequest(text);
}
return;
}
this.trackInboundAction(() => this.handleApiMessage(socket, role, raw));
});
socket.on('close', () => {
stopHeartbeat();
this.connections.delete(socket);
});
socket.on('error', (error: Error) => {
this.log.warn(
'[%s] socket error: %s',
this.name,
error instanceof Error ? error.message : String(error),
);
});
if (role === 'Event' || role === 'Universal') {
for (const frame of this.meta.bootstrap(this.options)) safeSend(socket, frame);
}
}
async closeConnections(): Promise<void> {
this.stopAccepting();
const lifecycle = this.ctx.buildLifecycleEvent('disable');
for (const connection of this.connections.values()) {
if (connection.role === 'Api') continue;
const frame = this.meta.frame(lifecycle, connection.options);
if (frame) safeSend(connection.socket, frame);
}
this.disconnectAll();
await Promise.all(this.inFlightActions);
}
private disconnectAll(code = 1000, reason = 'normal'): void {
for (const connection of this.connections.values()) {
connection.stopHeartbeat();
safeClose(connection.socket, code, reason);
}
this.connections.clear();
}
/** Destroy sockets immediately. A graceful close frame can leave the
* listener waiting on a peer that will never answer. */
terminateAll(): void {
this.stopAccepting();
for (const connection of this.connections.values()) {
connection.stopHeartbeat();
try { connection.socket.terminate(); } catch { /* already gone */ }
}
this.connections.clear();
}
private async handleApiMessage(socket: WebSocket, role: WsRole, raw: Buffer | string): Promise<void> {
const text = rawDataToString(raw);
if (!text) {
this.log.debug('[%s] ignored empty WebSocket frame', this.name);
return;
}
if (role !== 'Api' && role !== 'Universal') {
this.log.warn('[%s] rejected Action frame from Event-only connection', this.name);
return;
}
await this.ctx.api.processStreamRequest(
text,
(frame) => safeSendAsync(socket, frame),
() => socket.readyState === 1 && this.connections.has(socket),
);
}
trackInboundAction(start: () => Promise<void>): void {
if (
!this.acceptingActions
|| this.ctx.api.isAcceptingActions === false
constructor(
private readonly name: string,
config: WsServerConnectionConfig,
private readonly ctx: NetworkAdapterContext,
private readonly log: Logger,
private readonly meta: MetaFrames,
) {
this.log.warn('[%s] rejected inbound action while adapter is closing', this.name);
return;
this.config = structuredClone(config);
this.options = resolveReportOptions(config);
}
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;
get connectionCount(): number {
return this.connections.size;
}
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),
get isAcceptingActions(): boolean {
return this.acceptingActions;
}
get hasInFlightActions(): boolean {
return this.inFlightActions.size > 0;
}
startAccepting(): void {
this.acceptingActions = true;
}
stopAccepting(): void {
this.acceptingActions = false;
}
updateConfig(next: WsServerConnectionConfig): void {
const tokenChanged = (this.config.accessToken ?? '') !== (next.accessToken ?? '');
this.config = structuredClone(next);
this.options = resolveReportOptions(next);
for (const connection of this.connections.values()) {
connection.options = this.options;
}
// An already-authorized socket must not retain access after token
// rotation. Drop it immediately; the client can reconnect with the new
// credential without forcing the shared HTTP listener to rebind.
if (tokenChanged) {
this.disconnectAll(1008, 'access token changed');
}
}
acceptsUpgradePath(requestPath: string): boolean {
return resolveForwardRole(requestPath, this.config) !== null;
}
onEvent(payload: DispatchPayload): void {
if (!this.acceptingActions || this.connections.size === 0) {
return;
}
for (const connection of this.connections.values()) {
if (connection.role !== 'Event' && connection.role !== 'Universal') {
continue;
}
const json = pickDispatchJson(payload, connection.options);
if (json === null) {
continue;
}
safeSend(connection.socket, json);
}
}
/** Authenticate the HTTP upgrade before a WebSocket object is allocated. */
authorizeUpgrade(request: IncomingMessage): boolean {
const authorized = isAuthorized(request, this.config.accessToken ?? '');
if (!authorized) {
this.log.debug('[%s] rejected unauthorized WebSocket upgrade', this.name);
}
return authorized;
}
accept(socket: WebSocket, request: IncomingMessage): void {
if (!this.acceptingActions || this.ctx.api.isAcceptingActions === false) {
safeClose(socket, 1012, 'server closing');
return;
}
// Defence in depth for custom/future listeners that bypass verifyClient.
if (!this.authorizeUpgrade(request)) {
safeClose(socket, 1008, 'invalid access token');
return;
}
const requestPath = parseRequestPath(request.url ?? '/');
const role = resolveForwardRole(requestPath, this.config);
if (role === null) {
this.log.warn('[%s] rejected WebSocket path after upgrade', this.name);
safeClose(socket, 1008, 'invalid path');
return;
}
const stopHeartbeat = startHeartbeat(
socket,
{ intervalMs: HEARTBEAT_INTERVAL_MS, maxMissed: HEARTBEAT_MAX_MISSED },
() => {
this.log.warn(
'[%s] client silent for ~%ds, terminating half-open connection',
this.name,
HEARTBEAT_DEAD_AFTER_S,
);
socket.terminate();
},
);
},
);
this.inFlightActions.add(tracked);
void tracked.then(() => { this.inFlightActions.delete(tracked); });
}
const connection: ForwardConnection = {
socket,
role,
options: this.options,
stopHeartbeat,
};
this.connections.set(socket, connection);
socket.on('message', (raw: Buffer) => {
// Token rotation removes the connection synchronously, before the close
// handshake necessarily reaches the peer. Ignore any frame arriving in
// that interval so old credentials cannot start another Action.
if (!this.connections.has(socket)) {
return;
}
if (this.ctx.api.isAcceptingActions === false) {
this.log.warn('[%s] rejected inbound action after instance quiesce', this.name);
if (role === 'Api' || role === 'Universal') {
const text = rawDataToString(raw);
if (text) {
this.ctx.api.traceQuiescedStreamRequest(text);
}
}
return;
}
this.trackInboundAction(() => this.handleApiMessage(socket, role, raw));
});
socket.on('close', () => {
stopHeartbeat();
this.connections.delete(socket);
});
socket.on('error', (error: Error) => {
this.log.warn(
'[%s] socket error: %s',
this.name,
error instanceof Error ? error.message : String(error),
);
});
if (role === 'Event' || role === 'Universal') {
for (const frame of this.meta.bootstrap(this.options)) {
safeSend(socket, frame);
}
}
}
async closeConnections(): Promise<void> {
this.stopAccepting();
const lifecycle = this.ctx.buildLifecycleEvent('disable');
for (const connection of this.connections.values()) {
if (connection.role === 'Api') {
continue;
}
const frame = this.meta.frame(lifecycle, connection.options);
if (frame) {
safeSend(connection.socket, frame);
}
}
this.disconnectAll();
await Promise.all(this.inFlightActions);
}
private disconnectAll(code = 1000, reason = 'normal'): void {
for (const connection of this.connections.values()) {
connection.stopHeartbeat();
safeClose(connection.socket, code, reason);
}
this.connections.clear();
}
/** Destroy sockets immediately. A graceful close frame can leave the
* listener waiting on a peer that will never answer. */
terminateAll(): void {
this.stopAccepting();
for (const connection of this.connections.values()) {
connection.stopHeartbeat();
try {
connection.socket.terminate();
} catch {
/* already gone */
}
}
this.connections.clear();
}
private async handleApiMessage(
socket: WebSocket,
role: WsRole,
raw: Buffer | string,
): Promise<void> {
const text = rawDataToString(raw);
if (!text) {
this.log.debug('[%s] ignored empty WebSocket frame', this.name);
return;
}
if (role !== 'Api' && role !== 'Universal') {
this.log.warn('[%s] rejected Action frame from Event-only connection', this.name);
return;
}
await this.ctx.api.processStreamRequest(
text,
(frame) => safeSendAsync(socket, frame),
() => socket.readyState === 1 && this.connections.has(socket),
);
}
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);
});
}
}
function resolveForwardRole(requestPath: string, config: WsServerConnectionConfig): WsRole | null {
if (
config.role !== undefined
&& (!requestPath.startsWith('/') || requestPath.startsWith('//'))
) return null;
if (
config.role !== undefined &&
(!requestPath.startsWith('/') || requestPath.startsWith('//'))
) {
return null;
}
const path = normalizePath(requestPath);
if (config.role === undefined) return classifyForwardRole(path);
const path = normalizePath(requestPath);
const basePath = normalizePath(config.path);
if (path === basePath) return config.role;
if (config.role !== 'Universal' || basePath !== '/') return null;
if (path === '/api') return 'Api';
if (path === '/event') return 'Event';
return null;
if (config.role === undefined) {
return classifyForwardRole(path);
}
const basePath = normalizePath(config.path);
if (path === basePath) {
return config.role;
}
if (config.role !== 'Universal' || basePath !== '/') {
return null;
}
if (path === '/api') {
return 'Api';
}
if (path === '/event') {
return 'Event';
}
return null;
}
function classifyForwardRole(path: string): WsRole {
if (path.endsWith('/api')) return 'Api';
if (path.endsWith('/event')) return 'Event';
return 'Universal';
if (path.endsWith('/api')) {
return 'Api';
}
if (path.endsWith('/event')) {
return 'Event';
}
return 'Universal';
}