feat(onebot): reconcile and drain network adapters
Serialize desired network plans, isolate per-adapter apply failures, restore prior bindings when possible, and report saved versus applied state. Quiesce Action and event ingress, await in-flight dispatches and transport closes, retain failed generations for retry, and propagate shutdown failures.
This commit is contained in:
29 files changed
+2700
-305
No files matched your search
@@ -101,6 +101,10 @@ export class ApiHandler {
|
||||
private readonly handlers = new Map<string, RegisteredHandler>();
|
||||
private readonly registry: CompiledActionRegistry;
|
||||
private registrationOpen = true;
|
||||
/** Sticky instance-lifecycle gate. A failed transport close may restore its
|
||||
* own listener for retry, but it must never reopen execution against a
|
||||
* retiring Bridge/store generation. */
|
||||
private acceptingActions = true;
|
||||
private readonly log: Logger;
|
||||
/** Debug-stream taps — notified after every handled action. Attached
|
||||
* on-demand (ref-counted) by the WebUI debug stream. */
|
||||
@@ -209,7 +213,30 @@ export class ApiHandler {
|
||||
return this.handlers.get(action)?.kind === 'stream';
|
||||
}
|
||||
|
||||
/** Whether the owning OneBot instance still accepts new Action execution. */
|
||||
get isAcceptingActions(): boolean {
|
||||
return this.acceptingActions;
|
||||
}
|
||||
|
||||
/** Permanently reject new Actions for this handler generation.
|
||||
*
|
||||
* Existing calls have already been admitted and are drained by their owning
|
||||
* transport/instance. There is intentionally no resume operation: hot reload
|
||||
* keeps the same live generation open, while teardown creates a new handler
|
||||
* only after the previous generation has fully retired. */
|
||||
quiesce(): void {
|
||||
if (!this.acceptingActions) return;
|
||||
this.acceptingActions = false;
|
||||
this.log.info('Action ingress quiesced');
|
||||
}
|
||||
|
||||
async handle(action: string, params: JsonObject, sink?: StreamSink): Promise<import('./types').ApiResponse> {
|
||||
if (!this.acceptingActions) {
|
||||
const response = failedResponse(RETCODE.ACTION_FAILED, 'OneBot instance is shutting down');
|
||||
this.log.warn('rejected Action %s after instance quiesce', action);
|
||||
this.notifyObservers(action, params, response, 0);
|
||||
return response;
|
||||
}
|
||||
const registered = this.handlers.get(action);
|
||||
if (!registered) {
|
||||
this.log.debug('unknown action %s', action);
|
||||
|
||||
@@ -9,54 +9,115 @@ import { deliverPttTransText, pttTransKey } from './modules/ptt-trans-waiter';
|
||||
|
||||
const moduleLog = createLogger('Event');
|
||||
|
||||
export function registerEventPipeline(ctx: OneBotInstanceContext): () => void {
|
||||
/** Lifecycle handle for the asynchronous bridge-event pipeline.
|
||||
*
|
||||
* `stop()` is synchronous and idempotent: it removes every subscription so no
|
||||
* new conversion can start. `drain()` resolves only after conversions that had
|
||||
* already started have settled. Instance teardown must call them in that order
|
||||
* before closing stores used by conversion/backfill/dispatch. */
|
||||
export interface EventPipelineHandle {
|
||||
stop(): void;
|
||||
drain(): Promise<void>;
|
||||
}
|
||||
|
||||
export function registerEventPipeline(ctx: OneBotInstanceContext): EventPipelineHandle {
|
||||
const uinNum = Number.parseInt(ctx.uin, 10);
|
||||
const log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
|
||||
const disposers: Array<() => void> = [];
|
||||
const inFlight = new Set<Promise<void>>();
|
||||
let accepting = true;
|
||||
|
||||
const track = (
|
||||
kind: QQEventVariant['kind'],
|
||||
start: () => void | Promise<void>,
|
||||
): Promise<void> => {
|
||||
if (!accepting) return Promise.resolve();
|
||||
let operation: Promise<void>;
|
||||
try {
|
||||
operation = Promise.resolve(start());
|
||||
} catch (error) {
|
||||
operation = Promise.reject(error);
|
||||
}
|
||||
const tracked = operation.then(
|
||||
() => undefined,
|
||||
(error) => {
|
||||
log.error(
|
||||
'event pipeline handler failed kind=%s: %s',
|
||||
kind,
|
||||
error instanceof Error ? (error.stack ?? error.message) : String(error),
|
||||
);
|
||||
},
|
||||
);
|
||||
inFlight.add(tracked);
|
||||
void tracked.then(() => { inFlight.delete(tracked); });
|
||||
return tracked;
|
||||
};
|
||||
|
||||
disposers.push(
|
||||
ctx.bridge.events.on('group_message', async (event) => {
|
||||
ctx.bridge.events.on('group_message', (event) => track(event.kind, async () => {
|
||||
cacheGroupMessageMeta(ctx, event);
|
||||
await convertAndDispatch(ctx, log, event);
|
||||
}),
|
||||
})),
|
||||
);
|
||||
disposers.push(
|
||||
ctx.bridge.events.on('friend_message', async (event) => {
|
||||
ctx.bridge.events.on('friend_message', (event) => track(event.kind, async () => {
|
||||
cachePrivateMessageMeta(ctx, event.senderUin, event.msgSeq, event.time, event.msgId);
|
||||
await convertAndDispatch(ctx, log, event);
|
||||
}),
|
||||
})),
|
||||
);
|
||||
disposers.push(
|
||||
ctx.bridge.events.on('temp_message', async (event) => {
|
||||
ctx.bridge.events.on('temp_message', (event) => track(event.kind, async () => {
|
||||
cachePrivateMessageMeta(ctx, event.senderUin, event.msgSeq, event.time, 0);
|
||||
// Record this group temp session so a later reply is limited to sessions
|
||||
// the peer opened.
|
||||
ctx.tempSessions.record(event.senderUin, event.groupId);
|
||||
await convertAndDispatch(ctx, log, event);
|
||||
}),
|
||||
})),
|
||||
);
|
||||
for (const kind of NOTICE_KINDS) {
|
||||
disposers.push(
|
||||
ctx.bridge.events.on(kind, async (event) => {
|
||||
ctx.bridge.events.on(kind, (event) => track(event.kind, async () => {
|
||||
if (event.kind === 'group_msg_emoji_like') {
|
||||
cacheReaction(ctx, event);
|
||||
}
|
||||
await convertAndDispatch(ctx, log, event);
|
||||
}),
|
||||
})),
|
||||
);
|
||||
}
|
||||
// Internal-only: voice-to-text result push. Not converted to a OneBot event —
|
||||
// it just unblocks the fetch_ptt_text call waiting on this msgId.
|
||||
disposers.push(
|
||||
ctx.bridge.events.on('ptt_trans_result', (event) => {
|
||||
ctx.bridge.events.on('ptt_trans_result', (event) => track(event.kind, () => {
|
||||
deliverPttTransText(pttTransKey(event.selfUin, event.msgId), event.text);
|
||||
}),
|
||||
})),
|
||||
);
|
||||
|
||||
return () => {
|
||||
const stop = (): void => {
|
||||
if (!accepting) return;
|
||||
accepting = false;
|
||||
for (const dispose of disposers) {
|
||||
try { dispose(); } catch { /* ignore */ }
|
||||
try {
|
||||
dispose();
|
||||
} catch (error) {
|
||||
log.error(
|
||||
'event pipeline unsubscribe failed: %s',
|
||||
error instanceof Error ? (error.stack ?? error.message) : String(error),
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
stop,
|
||||
async drain(): Promise<void> {
|
||||
// `stop()` makes the set monotonic: no later event can be admitted while
|
||||
// this snapshot is settling.
|
||||
if (accepting) {
|
||||
throw new Error('event pipeline must be stopped before it can be drained');
|
||||
}
|
||||
await Promise.allSettled([...inFlight]);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const NOTICE_KINDS = [
|
||||
@@ -110,7 +171,15 @@ async function runConvertAndDispatch(ctx: OneBotInstanceContext, log: Logger, ev
|
||||
// back-fill failure block delivery of the live message.
|
||||
try {
|
||||
await backfillReplyTarget(ctx, event);
|
||||
} catch { /* best-effort — dispatch the live event regardless */ }
|
||||
} catch (error) {
|
||||
// Best-effort — dispatch the live event regardless, but keep the failure
|
||||
// attributable so a repeated store/server miss is diagnosable.
|
||||
log.warn(
|
||||
'reply backfill failed kind=%s: %s',
|
||||
event.kind,
|
||||
error instanceof Error ? (error.stack ?? error.message) : String(error),
|
||||
);
|
||||
}
|
||||
ctx.dispatchEvent(converted);
|
||||
log.trace(() => [`recv ${event.kind} ⇒ ${String(converted.post_type ?? '?')} (${Date.now() - startedAt}ms)`]);
|
||||
}
|
||||
|
||||
+148
-85
@@ -4,7 +4,7 @@ import { formatGroup, formatMessageSegments, formatReply, formatUser } from '@sn
|
||||
import path from 'path';
|
||||
import { ApiHandler, type ActionObserver } from './api-handler';
|
||||
import type { ConverterContext } from './event-converter';
|
||||
import { registerEventPipeline } from './event-pipeline';
|
||||
import { registerEventPipeline, type EventPipelineHandle } from './event-pipeline';
|
||||
import { buildApiContext, type OneBotInstanceContext } from './instance-context';
|
||||
import { TempSessionStore } from './temp-session-store';
|
||||
import { RKeyCache } from './instance-rkey';
|
||||
@@ -23,10 +23,13 @@ import {
|
||||
WsClientAdapter,
|
||||
WsServerAdapter,
|
||||
type AdapterStatus,
|
||||
type DesiredNetworkAdapter,
|
||||
type NetworkAdapterContext,
|
||||
type NetworkReconcileResult,
|
||||
type NetworkShutdownResult,
|
||||
} from './network';
|
||||
import { ReactionStore } from './reaction-store';
|
||||
import type { ApiResponse, JsonObject, JsonValue, MessageMeta, NetworkBase, OneBotConfig } from './types';
|
||||
import type { ApiResponse, JsonObject, JsonValue, MessageMeta, OneBotConfig } from './types';
|
||||
|
||||
const moduleLog = createLogger('Event');
|
||||
|
||||
@@ -40,13 +43,25 @@ export class OneBotInstance {
|
||||
private readonly mediaStore: MediaStore;
|
||||
private readonly reactionStore: ReactionStore;
|
||||
private readonly networkManager: OneBotNetworkManager;
|
||||
private readonly networkReady: Promise<NetworkReconcileResult>;
|
||||
private lifecycleTail: Promise<void>;
|
||||
private readonly rkeyCache: RKeyCache;
|
||||
private readonly ctx: OneBotInstanceContext;
|
||||
/** Process-uptime baseline for the `#sl` status reply. */
|
||||
private readonly startedAt = Date.now();
|
||||
/** Per-conversation last-reply timestamp for the `#sl` cooldown. */
|
||||
private readonly statusCommandCooldown = new Map<string, number>();
|
||||
private disposeEventPipeline: (() => void) | null = null;
|
||||
private eventPipeline: EventPipelineHandle | null = null;
|
||||
private eventPipelineDrain: Promise<void> = Promise.resolve();
|
||||
private disposePromise: Promise<NetworkShutdownResult> | null = null;
|
||||
private disposeRequested = false;
|
||||
private acceptingActions = true;
|
||||
private readonly inFlightActions = new Set<Promise<void>>();
|
||||
private readonly storeCloseState = {
|
||||
message: false,
|
||||
media: false,
|
||||
reaction: false,
|
||||
};
|
||||
|
||||
private readonly pids = new Set<number>();
|
||||
private online = true;
|
||||
@@ -72,7 +87,7 @@ export class OneBotInstance {
|
||||
}
|
||||
/** Invoke an OneBot action against this account (debug tester). */
|
||||
invokeAction(action: string, params: JsonObject): Promise<ApiResponse> {
|
||||
return this.apiHandler.handle(action, params);
|
||||
return this.trackAction(`debug action ${action}`, () => this.apiHandler.handle(action, params));
|
||||
}
|
||||
/** Drive an action through the streaming seam (debug tester, stream actions).
|
||||
* `rawRequest` is a `{action, params, echo?}` JSON string; `emit` receives
|
||||
@@ -82,7 +97,7 @@ export class OneBotInstance {
|
||||
emit: (json: string) => void | Promise<void>,
|
||||
isAlive?: () => boolean,
|
||||
): Promise<void> {
|
||||
return this.apiHandler.processStreamRequest(rawRequest, emit, isAlive);
|
||||
return this.trackAction('debug stream action', () => this.apiHandler.processStreamRequest(rawRequest, emit, isAlive));
|
||||
}
|
||||
|
||||
constructor(uin: string, bridge: BridgeInterface, config: OneBotConfig, globalSettings: GlobalSettings) {
|
||||
@@ -127,23 +142,34 @@ export class OneBotInstance {
|
||||
this.ctx = ctx;
|
||||
|
||||
this.apiHandler = new ApiHandler(buildApiContext(ctx), uinNum > 0 ? uinNum : undefined);
|
||||
this.networkManager = new OneBotNetworkManager();
|
||||
this.installAdaptersFromConfig(config);
|
||||
void this.networkManager.openAll().catch((err) => {
|
||||
this.log.warn('openAll failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
const networkCtx = this.buildNetworkContext();
|
||||
this.networkManager = new OneBotNetworkManager((desired) => this.createNetworkAdapter(desired, networkCtx));
|
||||
this.networkReady = this.networkManager.reconcile(config);
|
||||
this.lifecycleTail = this.networkReady.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
|
||||
this.startHeartbeat();
|
||||
this.rkeyCache.warmUp(this.bridge, this.uin);
|
||||
this.disposeEventPipeline = registerEventPipeline(ctx);
|
||||
this.eventPipeline = registerEventPipeline(ctx);
|
||||
}
|
||||
|
||||
reloadConfig(config: OneBotConfig): void {
|
||||
// Keep the shared context's config in sync so live readers (e.g. the
|
||||
// `#sl` handler reading `statusCommand`) pick up edits without a restart.
|
||||
this.ctx.config = config;
|
||||
void this.applyConfigDiff(config).catch((err) => {
|
||||
this.log.warn('applyConfigDiff failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
waitUntilNetworkReady(): Promise<NetworkReconcileResult> {
|
||||
return this.networkReady;
|
||||
}
|
||||
|
||||
reloadConfig(config: OneBotConfig): Promise<NetworkReconcileResult> {
|
||||
if (this.disposeRequested) return Promise.reject(new Error(`OneBot instance UIN=${this.uin} is disposing`));
|
||||
const snapshot = structuredClone(config);
|
||||
// Validate before entering the FIFO so deterministic errors fail fast.
|
||||
this.networkManager.compileDesiredPlan(snapshot);
|
||||
return this.enqueueLifecycle(async () => {
|
||||
// Keep the shared context's config in sync for exactly the same ordered
|
||||
// snapshot the network manager is applying. Concurrent POSTs therefore
|
||||
// linearize as A then B instead of publishing B while A is reconciling.
|
||||
this.ctx.config = snapshot;
|
||||
return this.networkManager.reconcile(snapshot);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -154,17 +180,75 @@ export class OneBotInstance {
|
||||
this.ctx.musicSignUrl = globalSettings.musicSignUrl;
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
/** Synchronously stop every ingress seam for this instance generation.
|
||||
*
|
||||
* This operation is sticky and idempotent. It is intentionally separate
|
||||
* from the asynchronous resource release so the manager can quiesce all
|
||||
* generations before waiting for older lifecycle work to settle. */
|
||||
quiesce(): void {
|
||||
if (this.disposeRequested) return;
|
||||
this.disposeRequested = true;
|
||||
this.acceptingActions = false;
|
||||
this.apiHandler.quiesce();
|
||||
this.online = false;
|
||||
this.stopHeartbeat();
|
||||
this.disposeEventPipeline?.();
|
||||
this.disposeEventPipeline = null;
|
||||
void this.networkManager.closeAll().catch((err) => {
|
||||
this.log.warn('closeAll failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
const pipeline = this.eventPipeline;
|
||||
if (pipeline) {
|
||||
pipeline.stop();
|
||||
this.eventPipeline = null;
|
||||
this.eventPipelineDrain = pipeline.drain();
|
||||
}
|
||||
}
|
||||
|
||||
dispose(): Promise<NetworkShutdownResult> {
|
||||
if (this.disposePromise) return this.disposePromise;
|
||||
this.quiesce();
|
||||
const attempt = this.enqueueLifecycle(async () => {
|
||||
await Promise.all([
|
||||
Promise.all(this.inFlightActions),
|
||||
this.eventPipelineDrain,
|
||||
]);
|
||||
const shutdown = await this.networkManager.shutdown();
|
||||
if (!shutdown.closed) {
|
||||
throw new AggregateError(
|
||||
shutdown.errors.map((error) => new Error(
|
||||
`adapter ${error.name} ${error.phase} failed: ${error.message}`,
|
||||
)),
|
||||
`network shutdown incomplete for UIN=${this.uin}; stores remain open`,
|
||||
);
|
||||
}
|
||||
// Stores are intentionally closed only after every queued network
|
||||
// reconcile and every transport have actually closed.
|
||||
const closeErrors: unknown[] = [];
|
||||
const stores = [
|
||||
['message', () => this.messageStore.close()],
|
||||
['media', () => this.mediaStore.close()],
|
||||
['reaction', () => this.reactionStore.close()],
|
||||
] as const;
|
||||
for (const [name, close] of stores) {
|
||||
if (this.storeCloseState[name]) continue;
|
||||
try {
|
||||
close();
|
||||
this.storeCloseState[name] = true;
|
||||
} catch (error) {
|
||||
closeErrors.push(error);
|
||||
}
|
||||
}
|
||||
if (closeErrors.length > 0) {
|
||||
throw new AggregateError(closeErrors, `failed to close OneBot stores for UIN=${this.uin}`);
|
||||
}
|
||||
return shutdown;
|
||||
});
|
||||
this.messageStore.close();
|
||||
this.mediaStore.close();
|
||||
this.reactionStore.close();
|
||||
this.disposePromise = attempt;
|
||||
void attempt.then(
|
||||
() => undefined,
|
||||
() => {
|
||||
// Network-close and per-store completion state are retained. Let a
|
||||
// later dispose call retry only the meaningful unfinished remainder.
|
||||
if (this.disposePromise === attempt) this.disposePromise = null;
|
||||
},
|
||||
);
|
||||
return attempt;
|
||||
}
|
||||
|
||||
addPid(pid: number): void {
|
||||
@@ -219,9 +303,7 @@ export class OneBotInstance {
|
||||
const now = Date.now();
|
||||
if (statusCooldownElapsed(this.statusCommandCooldown.get(key), now, cfg.cooldownSeconds)) {
|
||||
this.statusCommandCooldown.set(key, now);
|
||||
void this.replyStatus(isGroup, sessionId).catch((err) => {
|
||||
this.log.warn('status command reply failed: %s', err instanceof Error ? err.message : String(err));
|
||||
});
|
||||
void this.trackAction('status command reply', () => this.replyStatus(isGroup, sessionId));
|
||||
}
|
||||
return cfg.swallow;
|
||||
}
|
||||
@@ -246,70 +328,51 @@ export class OneBotInstance {
|
||||
};
|
||||
}
|
||||
|
||||
private installAdaptersFromConfig(config: OneBotConfig): void {
|
||||
const ctx = this.buildNetworkContext();
|
||||
for (const net of config.networks.httpServers) {
|
||||
if (net.enabled === false) continue;
|
||||
this.networkManager.register(new HttpServerAdapter(net.name, net, ctx));
|
||||
}
|
||||
for (const net of config.networks.httpClients) {
|
||||
if (net.enabled === false || !net.url) continue;
|
||||
this.networkManager.register(new HttpPostAdapter(net.name, net, ctx));
|
||||
}
|
||||
for (const net of config.networks.wsServers) {
|
||||
if (net.enabled === false) continue;
|
||||
this.networkManager.register(new WsServerAdapter(net.name, net, ctx));
|
||||
}
|
||||
for (const net of config.networks.wsClients) {
|
||||
if (net.enabled === false || !net.url) continue;
|
||||
this.networkManager.register(new WsClientAdapter(net.name, net, ctx));
|
||||
private createNetworkAdapter(desired: DesiredNetworkAdapter, ctx: NetworkAdapterContext) {
|
||||
switch (desired.kind) {
|
||||
case 'httpServer': return new HttpServerAdapter(desired.name, desired.config, ctx);
|
||||
case 'httpClient': return new HttpPostAdapter(desired.name, desired.config, ctx);
|
||||
case 'wsServer': return new WsServerAdapter(desired.name, desired.config, ctx);
|
||||
case 'wsClient': return new WsClientAdapter(desired.name, desired.config, ctx);
|
||||
}
|
||||
}
|
||||
|
||||
private async applyConfigDiff(next: OneBotConfig): Promise<void> {
|
||||
const ctx = this.buildNetworkContext();
|
||||
const desired = new Map<string, NetworkBase>();
|
||||
const factories = new Map<string, () => void>();
|
||||
private enqueueLifecycle<T>(operation: () => Promise<T>): Promise<T> {
|
||||
const result = this.lifecycleTail.then(operation);
|
||||
this.lifecycleTail = result.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
return result;
|
||||
}
|
||||
|
||||
for (const net of next.networks.httpServers) {
|
||||
desired.set(net.name, net);
|
||||
factories.set(net.name, () => this.networkManager.register(new HttpServerAdapter(net.name, net, ctx)));
|
||||
private trackAction<T>(label: string, start: () => Promise<T>): Promise<T> {
|
||||
if (!this.acceptingActions) {
|
||||
return this.rejectedAction(label, new Error(`OneBot instance UIN=${this.uin} is disposing; ${label} rejected`));
|
||||
}
|
||||
for (const net of next.networks.httpClients) {
|
||||
desired.set(net.name, net);
|
||||
factories.set(net.name, () => this.networkManager.register(new HttpPostAdapter(net.name, net, ctx)));
|
||||
}
|
||||
for (const net of next.networks.wsServers) {
|
||||
desired.set(net.name, net);
|
||||
factories.set(net.name, () => this.networkManager.register(new WsServerAdapter(net.name, net, ctx)));
|
||||
}
|
||||
for (const net of next.networks.wsClients) {
|
||||
desired.set(net.name, net);
|
||||
factories.set(net.name, () => this.networkManager.register(new WsClientAdapter(net.name, net, ctx)));
|
||||
let action: Promise<T>;
|
||||
try {
|
||||
action = start();
|
||||
} catch (error) {
|
||||
return this.rejectedAction(label, error);
|
||||
}
|
||||
const tracked = action.then(
|
||||
() => undefined,
|
||||
(error) => {
|
||||
this.log.error('%s failed: %s', label, error instanceof Error ? (error.stack ?? error.message) : String(error));
|
||||
},
|
||||
);
|
||||
this.inFlightActions.add(tracked);
|
||||
void tracked.then(() => { this.inFlightActions.delete(tracked); });
|
||||
return action;
|
||||
}
|
||||
|
||||
// Close adapters whose entry has been removed entirely.
|
||||
for (const adapter of this.networkManager.list()) {
|
||||
if (!desired.has(adapter.name)) {
|
||||
await this.networkManager.closeOne(adapter.name);
|
||||
}
|
||||
}
|
||||
for (const [name, net] of desired) {
|
||||
const existing = this.networkManager.get(name);
|
||||
if (existing) {
|
||||
try {
|
||||
await existing.reload(net);
|
||||
} catch (err) {
|
||||
this.log.warn('reload [%s] failed: %s', name, err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
} else if (net.enabled !== false) {
|
||||
const factory = factories.get(name);
|
||||
if (factory) {
|
||||
factory();
|
||||
await this.networkManager.get(name)?.open();
|
||||
}
|
||||
}
|
||||
}
|
||||
private rejectedAction<T>(label: string, error: unknown): Promise<T> {
|
||||
const rejected = Promise.reject<T>(error);
|
||||
void rejected.catch((reason) => {
|
||||
this.log.error('%s rejected: %s', label, reason instanceof Error ? (reason.stack ?? reason.message) : String(reason));
|
||||
});
|
||||
return rejected;
|
||||
}
|
||||
|
||||
private logReceivedMessage(event: JsonObject): void {
|
||||
|
||||
+192
-16
@@ -4,11 +4,19 @@ import type { BridgeManager } from '@snowluma/core/manager';
|
||||
import { loadOneBotConfig } from './config';
|
||||
import { loadGlobalSettings } from './global-config';
|
||||
import { OneBotInstance } from './instance';
|
||||
import type { AdapterStatus } from './network';
|
||||
import type { AdapterStatus, NetworkApplyError } from './network';
|
||||
import type { OneBotConfig } from './types';
|
||||
|
||||
const log = createLogger('OneBot');
|
||||
const VERBOSE_WARMUP = process.env.SNOWLUMA_VERBOSE_WARMUP === '1';
|
||||
|
||||
class InstanceLifecycleError extends Error {
|
||||
constructor(readonly instance: OneBotInstance, readonly rootCause: unknown) {
|
||||
super(rootCause instanceof Error ? rootCause.message : String(rootCause));
|
||||
this.name = 'InstanceLifecycleError';
|
||||
}
|
||||
}
|
||||
|
||||
/** Per-account OneBot connection health, surfaced to the WebUI dashboard. */
|
||||
export interface AccountConnections {
|
||||
uin: string;
|
||||
@@ -16,8 +24,25 @@ export interface AccountConnections {
|
||||
adapters: AdapterStatus[];
|
||||
}
|
||||
|
||||
export interface ConfigApplyResult {
|
||||
online: boolean;
|
||||
applied: boolean;
|
||||
errors: NetworkApplyError[];
|
||||
adapters: AdapterStatus[];
|
||||
}
|
||||
|
||||
export class OneBotManager {
|
||||
private readonly instances = new Map<string, OneBotInstance>();
|
||||
private readonly pendingLifecycle = new Set<Promise<void>>();
|
||||
private readonly retiringInstances = new Set<OneBotInstance>();
|
||||
private readonly lifecycleFailures: Array<{
|
||||
label: string;
|
||||
error: unknown;
|
||||
instances?: Set<OneBotInstance>;
|
||||
}> = [];
|
||||
private readonly pendingStarts = new Map<string, { bridge: BridgeInterface; cancelled: boolean }>();
|
||||
private disposePromise: Promise<void> | null = null;
|
||||
private disposed = false;
|
||||
|
||||
bind(bridgeManager: BridgeManager): void {
|
||||
bridgeManager.addSessionStartedListener((uin, bridge) => {
|
||||
@@ -37,23 +62,36 @@ export class OneBotManager {
|
||||
return [...this.instances.values()];
|
||||
}
|
||||
|
||||
/** Live OneBot adapter status for every account, for the WebUI dashboard. */
|
||||
/** Live OneBot adapter status for active accounts plus failed retiring
|
||||
* generations. A zombie that still owns a port must remain observable. */
|
||||
getConnectionStatuses(): AccountConnections[] {
|
||||
return this.getInstances().map((i) => ({
|
||||
const visible = [...this.instances.values()];
|
||||
for (const instance of this.retiringInstances) {
|
||||
if (!visible.includes(instance)) visible.push(instance);
|
||||
}
|
||||
return visible.map((i) => ({
|
||||
uin: i.uin,
|
||||
nickname: i.nickname,
|
||||
adapters: i.getConnectionStatuses(),
|
||||
}));
|
||||
}
|
||||
|
||||
reloadConfig(uin: string): boolean {
|
||||
async reloadConfig(uin: string, config: OneBotConfig): Promise<ConfigApplyResult> {
|
||||
const instance = this.instances.get(uin);
|
||||
if (!instance) return false;
|
||||
if (!instance) return { online: false, applied: false, errors: [], adapters: [] };
|
||||
|
||||
const config = loadOneBotConfig(uin, { persistDefaults: true });
|
||||
instance.reloadConfig(config);
|
||||
log.info('configuration reloaded: UIN=%s', uin);
|
||||
return true;
|
||||
const result = await instance.reloadConfig(config);
|
||||
if (result.applied) {
|
||||
log.info('configuration applied: UIN=%s adapters=%d', uin, result.statuses.length);
|
||||
} else {
|
||||
log.warn('configuration saved but not fully applied: UIN=%s failures=%d', uin, result.errors.length);
|
||||
}
|
||||
return {
|
||||
online: true,
|
||||
applied: result.applied,
|
||||
errors: result.errors,
|
||||
adapters: result.statuses,
|
||||
};
|
||||
}
|
||||
|
||||
/** Re-read global (all-accounts) settings from config/snowluma.json and push
|
||||
@@ -66,15 +104,80 @@ export class OneBotManager {
|
||||
log.info('global settings reloaded for %d instance(s)', this.instances.size);
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
for (const instance of this.instances.values()) {
|
||||
instance.dispose();
|
||||
}
|
||||
dispose(): Promise<void> {
|
||||
if (this.disposePromise) return this.disposePromise;
|
||||
this.disposed = true;
|
||||
for (const instance of this.instances.values()) this.retiringInstances.add(instance);
|
||||
// Quiesce every live generation before awaiting older startup/shutdown
|
||||
// work. A deferred lifecycle operation must not leave Action ingress open
|
||||
// during process teardown.
|
||||
for (const instance of this.retiringInstances) instance.quiesce();
|
||||
this.instances.clear();
|
||||
const attempt = (async () => {
|
||||
// Let already-tracked startup/session-close work settle first. Rejected
|
||||
// operations are recorded by trackLifecycle and their instances remain
|
||||
// in retiringInstances for the retry below.
|
||||
await Promise.all(this.pendingLifecycle);
|
||||
let failures = this.lifecycleFailures.splice(0);
|
||||
const targets = [...this.retiringInstances];
|
||||
const settled = await Promise.allSettled(targets.map((instance) => instance.dispose()));
|
||||
for (let index = 0; index < settled.length; index += 1) {
|
||||
const instance = targets[index];
|
||||
const result = settled[index];
|
||||
const shutdownLabel = `network shutdown UIN=${instance.uin}`;
|
||||
if (result.status === 'rejected') {
|
||||
failures.push({ label: shutdownLabel, error: result.reason, instances: new Set([instance]) });
|
||||
continue;
|
||||
}
|
||||
this.retirementSucceeded(instance);
|
||||
// A later successful retry supersedes failures only for this exact
|
||||
// generation. Same-UIN instances must never clear one another.
|
||||
failures = failures.flatMap((failure) => {
|
||||
if (!failure.instances?.has(instance)) return [failure];
|
||||
const remaining = new Set(failure.instances);
|
||||
remaining.delete(instance);
|
||||
return remaining.size > 0 ? [{ ...failure, instances: remaining }] : [];
|
||||
});
|
||||
}
|
||||
if (failures.length > 0) {
|
||||
throw new AggregateError(
|
||||
failures.map(({ label, error }) => new Error(
|
||||
`${label}: ${error instanceof Error ? error.message : String(error)}`,
|
||||
)),
|
||||
'failed to dispose OneBot manager cleanly',
|
||||
);
|
||||
}
|
||||
this.pendingStarts.clear();
|
||||
})();
|
||||
this.disposePromise = attempt;
|
||||
void attempt.then(
|
||||
() => undefined,
|
||||
() => {
|
||||
if (this.disposePromise === attempt) this.disposePromise = null;
|
||||
},
|
||||
);
|
||||
return attempt;
|
||||
}
|
||||
|
||||
private onSessionStarted(uin: string, bridge: BridgeInterface): void {
|
||||
if (this.instances.has(uin)) return;
|
||||
if (this.disposed || this.instances.has(uin) || this.pendingStarts.has(uin)) return;
|
||||
|
||||
const retiring = [...this.retiringInstances].filter((instance) => instance.uin === uin);
|
||||
if (retiring.length > 0) {
|
||||
const pending = { bridge, cancelled: false };
|
||||
this.pendingStarts.set(uin, pending);
|
||||
this.trackLifecycle(
|
||||
`session handoff UIN=${uin}`,
|
||||
this.finishRetiringBeforeStart(uin, pending, retiring),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
this.startSession(uin, bridge);
|
||||
}
|
||||
|
||||
private startSession(uin: string, bridge: BridgeInterface): void {
|
||||
if (this.disposed || this.instances.has(uin)) return;
|
||||
|
||||
const config = loadOneBotConfig(uin, { persistDefaults: true });
|
||||
const instance = new OneBotInstance(uin, bridge, config, loadGlobalSettings());
|
||||
@@ -87,6 +190,10 @@ export class OneBotManager {
|
||||
|
||||
this.instances.set(uin, instance);
|
||||
log.info('session started: UIN=%s', uin);
|
||||
this.trackLifecycle(`network startup UIN=${uin}`, instance.waitUntilNetworkReady().then((result) => {
|
||||
if (result.applied) log.info('network startup applied: UIN=%s adapters=%d', uin, result.statuses.length);
|
||||
else log.warn('network startup degraded: UIN=%s failures=%d', uin, result.errors.length);
|
||||
}));
|
||||
warmUpBridgeState(uin, bridge).catch((err) => {
|
||||
log.warn('warmup error for UIN %s: %s', uin, err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
@@ -94,13 +201,82 @@ export class OneBotManager {
|
||||
|
||||
private onSessionClosed(uin: string): void {
|
||||
const instance = this.instances.get(uin);
|
||||
if (!instance) return;
|
||||
if (!instance) {
|
||||
const pending = this.pendingStarts.get(uin);
|
||||
if (pending) {
|
||||
pending.cancelled = true;
|
||||
this.pendingStarts.delete(uin);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
instance.dispose();
|
||||
this.instances.delete(uin);
|
||||
this.retiringInstances.add(instance);
|
||||
this.trackLifecycle(
|
||||
`network shutdown UIN=${uin}`,
|
||||
instance.dispose().then((result) => {
|
||||
this.retirementSucceeded(instance);
|
||||
return result;
|
||||
}),
|
||||
[instance],
|
||||
);
|
||||
log.info('session closed: UIN=%s', uin);
|
||||
}
|
||||
|
||||
private async finishRetiringBeforeStart(
|
||||
uin: string,
|
||||
pending: { bridge: BridgeInterface; cancelled: boolean },
|
||||
retiring: OneBotInstance[],
|
||||
): Promise<void> {
|
||||
for (const instance of retiring) {
|
||||
try {
|
||||
await instance.dispose();
|
||||
} catch (error) {
|
||||
// Do not leave this UIN permanently guarded by a failed handoff. A
|
||||
// later session-start observation may retry the still-visible retire.
|
||||
if (this.pendingStarts.get(uin) === pending) this.pendingStarts.delete(uin);
|
||||
throw new InstanceLifecycleError(instance, error);
|
||||
}
|
||||
this.retirementSucceeded(instance);
|
||||
}
|
||||
if (this.pendingStarts.get(uin) !== pending) return;
|
||||
this.pendingStarts.delete(uin);
|
||||
if (pending.cancelled || this.disposed) return;
|
||||
this.startSession(uin, pending.bridge);
|
||||
}
|
||||
|
||||
private trackLifecycle(
|
||||
label: string,
|
||||
operation: Promise<unknown>,
|
||||
instances?: OneBotInstance[],
|
||||
): void {
|
||||
const tracked = operation.then(
|
||||
() => undefined,
|
||||
(error) => {
|
||||
const rootCause = error instanceof InstanceLifecycleError ? error.rootCause : error;
|
||||
const relatedInstances = error instanceof InstanceLifecycleError ? [error.instance] : instances;
|
||||
log.error('%s failed: %s', label, rootCause instanceof Error ? (rootCause.stack ?? rootCause.message) : String(rootCause));
|
||||
this.lifecycleFailures.push({
|
||||
label,
|
||||
error: rootCause,
|
||||
...(relatedInstances && relatedInstances.length > 0 ? { instances: new Set(relatedInstances) } : {}),
|
||||
});
|
||||
},
|
||||
);
|
||||
this.pendingLifecycle.add(tracked);
|
||||
void tracked.then(() => { this.pendingLifecycle.delete(tracked); });
|
||||
}
|
||||
|
||||
private retirementSucceeded(instance: OneBotInstance): void {
|
||||
this.retiringInstances.delete(instance);
|
||||
for (let index = this.lifecycleFailures.length - 1; index >= 0; index -= 1) {
|
||||
const failure = this.lifecycleFailures[index];
|
||||
if (!failure.instances?.has(instance)) continue;
|
||||
failure.instances.delete(instance);
|
||||
if (failure.instances.size === 0) this.lifecycleFailures.splice(index, 1);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
async function warmUpBridgeState(uin: string, bridge: BridgeInterface): Promise<void> {
|
||||
|
||||
@@ -17,7 +17,7 @@ export enum NetworkReloadType {
|
||||
Opened = 3,
|
||||
}
|
||||
|
||||
export type AdapterStatusLevel = 'ok' | 'warn' | 'down' | 'disabled';
|
||||
export type AdapterStatusLevel = 'ok' | 'warn' | 'down' | 'disabled' | 'degraded';
|
||||
|
||||
/** Live runtime status of a single network adapter, surfaced to the WebUI
|
||||
* dashboard (and the per-node config cards) so the gateway's own
|
||||
@@ -28,6 +28,11 @@ export interface AdapterStatus {
|
||||
kind: 'httpServer' | 'httpClient' | 'wsServer' | 'wsClient';
|
||||
status: AdapterStatusLevel;
|
||||
detail: string;
|
||||
/** Present when the desired config could not be applied or the bound
|
||||
* transport later failed. The adapter may still be serving its restored
|
||||
* previous config; `degraded` describes reconciliation, not only liveness. */
|
||||
lastError?: string;
|
||||
lastErrorAt?: number;
|
||||
}
|
||||
|
||||
export abstract class IOneBotNetworkAdapter<C extends NetworkBase> {
|
||||
@@ -36,6 +41,7 @@ export abstract class IOneBotNetworkAdapter<C extends NetworkBase> {
|
||||
protected readonly ctx: NetworkAdapterContext;
|
||||
protected readonly log: Logger;
|
||||
protected isEnabled = false;
|
||||
private applyFailure: { message: string; at: number } | null = null;
|
||||
|
||||
constructor(name: string, config: C, ctx: NetworkAdapterContext, moduleLog?: Logger) {
|
||||
this.name = name;
|
||||
@@ -50,6 +56,8 @@ export abstract class IOneBotNetworkAdapter<C extends NetworkBase> {
|
||||
|
||||
get currentConfig(): Readonly<C> { return this.config; }
|
||||
|
||||
get hasApplyFailure(): boolean { return this.applyFailure !== null; }
|
||||
|
||||
abstract open(): void | Promise<void>;
|
||||
abstract close(): void | Promise<void>;
|
||||
|
||||
@@ -58,6 +66,35 @@ export abstract class IOneBotNetworkAdapter<C extends NetworkBase> {
|
||||
/** Report live connection health for the WebUI dashboard. */
|
||||
abstract describeStatus(): AdapterStatus;
|
||||
|
||||
/** Status with the manager-owned desired/live mismatch overlaid. Concrete
|
||||
* adapters continue to describe transport health; reconciliation failures
|
||||
* are kept here so a successfully restored old binding is still visible. */
|
||||
describeManagedStatus(): AdapterStatus {
|
||||
const status = this.describeStatus();
|
||||
if (!this.applyFailure) return status;
|
||||
return {
|
||||
...status,
|
||||
status: 'degraded',
|
||||
detail: `应用失败:${this.applyFailure.message}`,
|
||||
lastError: this.applyFailure.message,
|
||||
lastErrorAt: this.applyFailure.at,
|
||||
};
|
||||
}
|
||||
|
||||
/** NetworkManager lifecycle seam. A failure is cleared only after a later
|
||||
* reconciliation reaches the desired state. */
|
||||
markApplyFailure(error: unknown, at = Date.now()): void {
|
||||
this.applyFailure = { message: errorMessage(error), at };
|
||||
}
|
||||
|
||||
clearApplyFailure(): void {
|
||||
this.applyFailure = null;
|
||||
}
|
||||
|
||||
protected recordTransportFailure(error: unknown, at = Date.now()): void {
|
||||
this.markApplyFailure(error, at);
|
||||
}
|
||||
|
||||
// ── meta-event framing: shared by the connection-oriented adapters ─────
|
||||
//
|
||||
// Lifecycle (connect/enable/disable) and heartbeat meta events don't flow
|
||||
@@ -99,9 +136,10 @@ export abstract class IOneBotNetworkAdapter<C extends NetworkBase> {
|
||||
// three things that genuinely differ per adapter are the hooks below.
|
||||
//
|
||||
// NOTE: the returned `NetworkReloadType` is a *test-observability* seam.
|
||||
// The sole production caller (`instance.applyConfigDiff`) discards it —
|
||||
// it exists so tests can assert "which transition did this config cause"
|
||||
// without poking private state. Behaviour, not the label, is the contract.
|
||||
// OneBotNetworkManager awaits the transition but derives apply truth from
|
||||
// success/failure rather than this label. Tests use it to assert "which
|
||||
// transition did this config cause" without poking private state.
|
||||
// Behaviour, not the label, is the contract.
|
||||
|
||||
/** Stable string identity of the bound resource (host:port / url / token …).
|
||||
* A change here means the live binding must be torn down and re-opened. */
|
||||
@@ -121,27 +159,36 @@ export abstract class IOneBotNetworkAdapter<C extends NetworkBase> {
|
||||
const prevSig = this.bindingSignature(this.config);
|
||||
const wasEnabled = this.isEnabled;
|
||||
const willEnable = this.willEnable(next);
|
||||
|
||||
this.config = structuredClone(next);
|
||||
this.onConfigReplaced(next);
|
||||
|
||||
const sigChanged = prevSig !== this.bindingSignature(next);
|
||||
if (sigChanged && wasEnabled) {
|
||||
|
||||
// Keep currentConfig truthful while the old live resource is being
|
||||
// released. Only publish the desired config after close succeeds; an
|
||||
// opening adapter necessarily sees the new config, while a close failure
|
||||
// leaves the previous config intact for recovery and diagnostics.
|
||||
if (wasEnabled && (sigChanged || !willEnable)) {
|
||||
await this.close();
|
||||
this.replaceConfig(next);
|
||||
if (willEnable) {
|
||||
await this.open();
|
||||
return NetworkReloadType.Reopened;
|
||||
}
|
||||
return NetworkReloadType.Closed;
|
||||
}
|
||||
|
||||
this.replaceConfig(next);
|
||||
if (!wasEnabled && willEnable) {
|
||||
await this.open();
|
||||
return NetworkReloadType.Opened;
|
||||
}
|
||||
if (wasEnabled && !willEnable) {
|
||||
await this.close();
|
||||
return NetworkReloadType.Closed;
|
||||
}
|
||||
return NetworkReloadType.Normal;
|
||||
}
|
||||
|
||||
private replaceConfig(next: C): void {
|
||||
this.config = structuredClone(next);
|
||||
this.onConfigReplaced(next);
|
||||
}
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
@@ -52,16 +52,22 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
|
||||
this.options = resolveReportOptions(next);
|
||||
}
|
||||
|
||||
onEvent(event: JsonObject, payload: DispatchPayload): void {
|
||||
async onEvent(event: JsonObject, payload: DispatchPayload): Promise<void> {
|
||||
if (!this.isEnabled) return;
|
||||
const json = pickDispatchJson(payload, this.options);
|
||||
if (json === null) return;
|
||||
void this.postEvent(json, event).catch((err) => {
|
||||
this.log.warn('[%s] postEvent threw: %s', this.name, err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
// A reconcile may replace this.config while HMAC computation or fetch is
|
||||
// awaiting. Keep one event on one immutable config epoch so an old token
|
||||
// can never sign a request sent to a new URL (or vice versa).
|
||||
const config = structuredClone(this.config);
|
||||
await this.postEvent(json, event, config);
|
||||
}
|
||||
|
||||
private async postEvent(payload: string, event: JsonObject): Promise<void> {
|
||||
private async postEvent(
|
||||
payload: string,
|
||||
event: JsonObject,
|
||||
config: HttpClientNetwork,
|
||||
): Promise<void> {
|
||||
if (!this.isEnabled) return;
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
@@ -69,13 +75,13 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
|
||||
'User-Agent': 'OneBot',
|
||||
'X-Self-ID': this.ctx.uin,
|
||||
};
|
||||
if (this.config.accessToken) {
|
||||
headers['X-Signature'] = await computeHmacSha1(this.config.accessToken, payload);
|
||||
if (config.accessToken) {
|
||||
headers['X-Signature'] = await computeHmacSha1(config.accessToken, payload);
|
||||
}
|
||||
|
||||
const timeoutMs = this.config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||
const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||
try {
|
||||
const response = await fetch(this.config.url, {
|
||||
const response = await fetch(config.url, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: payload,
|
||||
@@ -92,13 +98,11 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
|
||||
}
|
||||
} else {
|
||||
this.lastDelivery = { at: Date.now(), ok: false };
|
||||
this.log.warn('[%s] POST %s returned %d', this.name, this.config.url, response.status);
|
||||
this.log.warn('[%s] POST %s returned %d', this.name, config.url, response.status);
|
||||
}
|
||||
} catch (error) {
|
||||
this.lastDelivery = { at: Date.now(), ok: false };
|
||||
if (this.isEnabled) {
|
||||
this.log.warn('[%s] POST %s failed: %s', this.name, this.config.url, error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
this.log.warn('[%s] POST %s failed: %s', this.name, config.url, error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -17,24 +17,56 @@ const moduleLog = createLogger('OneBot.HTTP');
|
||||
export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork> {
|
||||
private server: Server | null = null;
|
||||
private listening = false;
|
||||
private closePromise: Promise<void> | null = null;
|
||||
private acceptingActions = false;
|
||||
private readonly inFlightActions = new Set<Promise<void>>();
|
||||
|
||||
constructor(name: string, config: HttpServerNetwork, ctx: NetworkAdapterContext) {
|
||||
super(name, config, ctx, moduleLog);
|
||||
}
|
||||
|
||||
open(): void {
|
||||
if (this.isEnabled) return;
|
||||
async open(): Promise<void> {
|
||||
if (this.isEnabled && this.listening) return;
|
||||
if (this.config.enabled === false) return;
|
||||
this.startServer();
|
||||
if (this.server) throw new Error(`HTTP adapter [${this.name}] still owns a previous server`);
|
||||
await this.startServer();
|
||||
this.isEnabled = true;
|
||||
this.clearApplyFailure();
|
||||
}
|
||||
|
||||
close(): void {
|
||||
if (!this.isEnabled && !this.server) return;
|
||||
async close(): Promise<void> {
|
||||
if (this.closePromise) return this.closePromise;
|
||||
if (!this.isEnabled && !this.server && this.inFlightActions.size === 0) return;
|
||||
const wasEnabled = this.isEnabled;
|
||||
const wasListening = this.listening;
|
||||
const wasAcceptingActions = this.acceptingActions;
|
||||
this.acceptingActions = false;
|
||||
this.isEnabled = false;
|
||||
this.listening = false;
|
||||
this.server?.close();
|
||||
this.server = null;
|
||||
const server = this.server;
|
||||
const release = server
|
||||
? new Promise<void>((resolve, reject) => {
|
||||
server.close((error) => {
|
||||
if (error && !isAlreadyClosedError(error)) reject(error);
|
||||
else resolve();
|
||||
});
|
||||
})
|
||||
: Promise.resolve();
|
||||
const attempt = Promise.all([release, Promise.all(this.inFlightActions)]).then(() => undefined);
|
||||
this.closePromise = attempt;
|
||||
try {
|
||||
await attempt;
|
||||
if (this.server === server) this.server = null;
|
||||
} catch (error) {
|
||||
// A failed close callback cannot prove the listener was released. Keep
|
||||
// ownership and live-state truth so shutdown/reconcile can retry it.
|
||||
this.isEnabled = wasEnabled;
|
||||
this.listening = wasListening;
|
||||
this.acceptingActions = wasAcceptingActions;
|
||||
throw error;
|
||||
} finally {
|
||||
this.closePromise = null;
|
||||
}
|
||||
}
|
||||
|
||||
override describeStatus(): AdapterStatus {
|
||||
@@ -49,28 +81,57 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
|
||||
|
||||
onEvent(_event: JsonObject, _payload: DispatchPayload): void { /* no-op */ }
|
||||
|
||||
private startServer(): void {
|
||||
const server = createServer((req, res) => {
|
||||
void this.handleRequest(req, res);
|
||||
});
|
||||
this.server = server;
|
||||
private startServer(): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const server = createServer((req, res) => {
|
||||
this.trackInboundAction(req, res);
|
||||
});
|
||||
this.server = server;
|
||||
let opening = true;
|
||||
|
||||
server.on('listening', () => {
|
||||
this.listening = true;
|
||||
this.log.success(
|
||||
'[%s] listening %s:%d%s',
|
||||
this.name,
|
||||
this.config.host ?? '0.0.0.0',
|
||||
this.config.port,
|
||||
normalizePath(this.config.path ?? '/'),
|
||||
);
|
||||
});
|
||||
server.on('error', (err) => {
|
||||
this.listening = false;
|
||||
this.log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err));
|
||||
});
|
||||
server.once('listening', () => {
|
||||
opening = false;
|
||||
if (this.server !== server || this.closePromise) {
|
||||
server.close();
|
||||
reject(new Error(`HTTP adapter [${this.name}] was closed while binding`));
|
||||
return;
|
||||
}
|
||||
this.listening = true;
|
||||
this.isEnabled = true;
|
||||
this.acceptingActions = true;
|
||||
this.log.success(
|
||||
'[%s] listening %s:%d%s',
|
||||
this.name,
|
||||
this.config.host ?? '0.0.0.0',
|
||||
this.config.port,
|
||||
normalizePath(this.config.path ?? '/'),
|
||||
);
|
||||
resolve();
|
||||
});
|
||||
server.on('error', (error) => {
|
||||
if (this.server === server) {
|
||||
this.listening = false;
|
||||
this.isEnabled = false;
|
||||
this.acceptingActions = false;
|
||||
this.recordTransportFailure(error);
|
||||
if (opening) this.server = null;
|
||||
}
|
||||
this.log.error('[%s] server error: %s', this.name, error instanceof Error ? error.message : String(error));
|
||||
if (opening) {
|
||||
opening = false;
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
|
||||
server.listen(this.config.port, this.config.host ?? '0.0.0.0');
|
||||
try {
|
||||
server.listen(this.config.port, this.config.host ?? '0.0.0.0');
|
||||
} catch (error) {
|
||||
opening = false;
|
||||
if (this.server === server) this.server = null;
|
||||
this.recordTransportFailure(error);
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private async handleRequest(req: IncomingMessage, res: ServerResponse): Promise<void> {
|
||||
@@ -200,6 +261,33 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
|
||||
writeJson(res, 500, { status: 'failed', retcode: 1200, data: null, wording });
|
||||
}
|
||||
}
|
||||
|
||||
private trackInboundAction(req: IncomingMessage, res: ServerResponse): void {
|
||||
if (!this.acceptingActions || this.ctx.api.isAcceptingActions === false) {
|
||||
writeJson(res, 503, { status: 'failed', retcode: 1200, data: null, wording: 'server closing' });
|
||||
return;
|
||||
}
|
||||
let action: Promise<void>;
|
||||
try {
|
||||
action = this.handleRequest(req, res);
|
||||
} catch (error) {
|
||||
this.log.error('[%s] inbound action start failed: %s', this.name, error instanceof Error ? (error.stack ?? error.message) : String(error));
|
||||
writeJson(res, 500, { status: 'failed', retcode: 1200, data: null, wording: 'internal error' });
|
||||
return;
|
||||
}
|
||||
const tracked = action.then(
|
||||
() => undefined,
|
||||
(error) => {
|
||||
this.log.error('[%s] inbound action failed: %s', this.name, error instanceof Error ? (error.stack ?? error.message) : String(error));
|
||||
},
|
||||
);
|
||||
this.inFlightActions.add(tracked);
|
||||
void tracked.then(() => { this.inFlightActions.delete(tracked); });
|
||||
}
|
||||
}
|
||||
|
||||
function isAlreadyClosedError(error: Error): boolean {
|
||||
return (error as NodeJS.ErrnoException).code === 'ERR_SERVER_NOT_RUNNING';
|
||||
}
|
||||
|
||||
function readRequestBody(req: IncomingMessage, maxBytes = 2 * 1024 * 1024): Promise<string> {
|
||||
@@ -223,7 +311,7 @@ function readRequestBody(req: IncomingMessage, maxBytes = 2 * 1024 * 1024): Prom
|
||||
function writeJson(res: ServerResponse, statusCode: number, data: unknown): void {
|
||||
// A streaming response may already have flushed headers (and even ended); a
|
||||
// late error must not double-send and trip ERR_HTTP_HEADERS_SENT.
|
||||
if (res.headersSent || res.writableEnded) return;
|
||||
if (res.headersSent || res.writableEnded || res.destroyed) return;
|
||||
res.statusCode = statusCode;
|
||||
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
||||
res.end(JSON.stringify(data));
|
||||
|
||||
@@ -7,8 +7,16 @@ export {
|
||||
} from './adapter';
|
||||
export { HttpPostAdapter } from './http-post-adapter';
|
||||
export { HttpServerAdapter } from './http-server-adapter';
|
||||
export { OneBotNetworkManager } from './network-manager';
|
||||
export {
|
||||
OneBotNetworkManager,
|
||||
type DesiredNetworkAdapter,
|
||||
type NetworkAdapterFactory,
|
||||
type NetworkAdapterKind,
|
||||
type NetworkApplyError,
|
||||
type NetworkApplyPhase,
|
||||
type NetworkReconcileResult,
|
||||
type NetworkShutdownResult,
|
||||
} from './network-manager';
|
||||
export { executeQuickOperation } from './quick-operation';
|
||||
export { WsClientAdapter } from './ws-client-adapter';
|
||||
export { WsServerAdapter } from './ws-server-adapter';
|
||||
|
||||
@@ -1,113 +1,468 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { assertValidOneBotConfig } from '../config';
|
||||
import { buildDispatchPayload } from '../event-filter';
|
||||
import type { JsonObject, NetworkBase } from '../types';
|
||||
import type {
|
||||
HttpClientNetwork,
|
||||
HttpServerNetwork,
|
||||
JsonObject,
|
||||
NetworkBase,
|
||||
OneBotConfig,
|
||||
WsClientNetwork,
|
||||
WsServerNetwork,
|
||||
} from '../types';
|
||||
import { IOneBotNetworkAdapter, type AdapterStatus } from './adapter';
|
||||
|
||||
const log = createLogger('OneBot.Network');
|
||||
|
||||
type AnyAdapter = IOneBotNetworkAdapter<NetworkBase>;
|
||||
export type NetworkAdapterKind = AdapterStatus['kind'];
|
||||
|
||||
export type DesiredNetworkAdapter =
|
||||
| { name: string; kind: 'httpServer'; config: HttpServerNetwork }
|
||||
| { name: string; kind: 'httpClient'; config: HttpClientNetwork }
|
||||
| { name: string; kind: 'wsServer'; config: WsServerNetwork }
|
||||
| { name: string; kind: 'wsClient'; config: WsClientNetwork };
|
||||
|
||||
export type NetworkApplyPhase = 'open' | 'reload' | 'close' | 'replace' | 'restore' | 'shutdown';
|
||||
|
||||
export interface NetworkApplyError {
|
||||
name: string;
|
||||
kind: NetworkAdapterKind;
|
||||
phase: NetworkApplyPhase;
|
||||
message: string;
|
||||
at: number;
|
||||
/** True when the previous live adapter/config was restored. The desired
|
||||
* config remains unapplied and the adapter stays visibly degraded. */
|
||||
restored?: boolean;
|
||||
}
|
||||
|
||||
export interface NetworkReconcileResult {
|
||||
applied: boolean;
|
||||
errors: NetworkApplyError[];
|
||||
statuses: AdapterStatus[];
|
||||
}
|
||||
|
||||
export interface NetworkShutdownResult {
|
||||
closed: boolean;
|
||||
errors: NetworkApplyError[];
|
||||
}
|
||||
|
||||
export type NetworkAdapterFactory = (desired: DesiredNetworkAdapter) => AnyAdapter;
|
||||
|
||||
interface ManagedAdapter {
|
||||
kind: NetworkAdapterKind;
|
||||
adapter: AnyAdapter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Single owner of the configured network topology.
|
||||
*
|
||||
* Configs are first compiled into a globally-name-unique desired plan. Every
|
||||
* startup/reload/shutdown operation then runs through one FIFO, so a reload can
|
||||
* never race another reload or teardown. Runtime failures are isolated per
|
||||
* adapter and returned as data; deterministic plan errors throw before the
|
||||
* operation is queued.
|
||||
*/
|
||||
export class OneBotNetworkManager {
|
||||
private readonly adapters = new Map<string, AnyAdapter>();
|
||||
private readonly adapters = new Map<string, ManagedAdapter>();
|
||||
private readonly factory: NetworkAdapterFactory | null;
|
||||
private operationTail: Promise<void> = Promise.resolve();
|
||||
private acceptingReconciles = true;
|
||||
private acceptingEvents = true;
|
||||
private readonly inFlightEmits = new Set<Promise<void>>();
|
||||
private shutdownPromise: Promise<NetworkShutdownResult> | null = null;
|
||||
private shutdownResult: NetworkShutdownResult | null = null;
|
||||
|
||||
/** Debug-stream taps — notified for every emitted event regardless of adapter
|
||||
* state. Attached on-demand (ref-counted) by the WebUI debug stream. */
|
||||
private readonly debugSubscribers = new Set<(event: JsonObject) => void>();
|
||||
|
||||
constructor(factory?: NetworkAdapterFactory) {
|
||||
this.factory = factory ?? null;
|
||||
}
|
||||
|
||||
subscribeDebug(cb: (event: JsonObject) => void): () => void {
|
||||
this.debugSubscribers.add(cb);
|
||||
return () => { this.debugSubscribers.delete(cb); };
|
||||
}
|
||||
|
||||
/** Test/embedding seam for pre-built adapters. Production topology changes
|
||||
* go through reconcile(), which refuses duplicate names. */
|
||||
register<C extends NetworkBase>(adapter: IOneBotNetworkAdapter<C>): void {
|
||||
const existing = this.adapters.get(adapter.name);
|
||||
if (existing) {
|
||||
log.info('replacing adapter [%s]', adapter.name);
|
||||
Promise.resolve(existing.close()).catch(() => {
|
||||
/* best-effort */
|
||||
// 应该该打个日志以便排查问题,但不应当让调用者感知到这个失败。
|
||||
});
|
||||
if (!this.acceptingReconciles) {
|
||||
throw new Error('network manager is shutting down');
|
||||
}
|
||||
this.adapters.set(adapter.name, adapter as AnyAdapter);
|
||||
if (this.adapters.has(adapter.name)) {
|
||||
throw new Error(`network adapter name already registered: ${adapter.name}`);
|
||||
}
|
||||
const kind = adapter.describeStatus().kind;
|
||||
this.adapters.set(adapter.name, { kind, adapter: adapter as AnyAdapter });
|
||||
}
|
||||
|
||||
has(name: string): boolean { return this.adapters.has(name); }
|
||||
|
||||
get(name: string): AnyAdapter | null {
|
||||
return this.adapters.get(name) ?? null;
|
||||
return this.adapters.get(name)?.adapter ?? null;
|
||||
}
|
||||
|
||||
list(): AnyAdapter[] { return [...this.adapters.values()]; }
|
||||
list(): AnyAdapter[] { return [...this.adapters.values()].map((entry) => entry.adapter); }
|
||||
|
||||
/** Live status of every registered adapter, for the WebUI dashboard. */
|
||||
/** Live status of every registered adapter, including desired/live apply
|
||||
* failures even when an older binding was restored and remains active. */
|
||||
describeStatuses(): AdapterStatus[] {
|
||||
return this.list().map((a) => a.describeStatus());
|
||||
return this.list().map((adapter) => adapter.describeManagedStatus());
|
||||
}
|
||||
|
||||
hasActiveAdapters(): boolean {
|
||||
for (const a of this.adapters.values()) if (a.isActive) return true;
|
||||
for (const { adapter } of this.adapters.values()) if (adapter.isActive) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
async openAll(): Promise<void> {
|
||||
const tasks = this.list().map(async (a) => {
|
||||
try {
|
||||
await a.open();
|
||||
} catch (err) {
|
||||
log.error('adapter [%s] open failed: %s', a.name, errMessage(err));
|
||||
}
|
||||
});
|
||||
await Promise.all(tasks);
|
||||
/** Compile and validate outside the queue: deterministic errors never wait
|
||||
* behind network I/O and can be rejected before a WebUI save. */
|
||||
compileDesiredPlan(config: OneBotConfig): DesiredNetworkAdapter[] {
|
||||
assertValidOneBotConfig(config);
|
||||
return [
|
||||
...config.networks.httpServers.map((network) => ({
|
||||
name: network.name,
|
||||
kind: 'httpServer' as const,
|
||||
config: structuredClone(network),
|
||||
})),
|
||||
...config.networks.httpClients.map((network) => ({
|
||||
name: network.name,
|
||||
kind: 'httpClient' as const,
|
||||
config: structuredClone(network),
|
||||
})),
|
||||
...config.networks.wsServers.map((network) => ({
|
||||
name: network.name,
|
||||
kind: 'wsServer' as const,
|
||||
config: structuredClone(network),
|
||||
})),
|
||||
...config.networks.wsClients.map((network) => ({
|
||||
name: network.name,
|
||||
kind: 'wsClient' as const,
|
||||
config: structuredClone(network),
|
||||
})),
|
||||
];
|
||||
}
|
||||
|
||||
async closeAll(): Promise<void> {
|
||||
const tasks = this.list().map(async (a) => {
|
||||
try {
|
||||
await a.close();
|
||||
} catch (err) {
|
||||
log.warn('adapter [%s] close failed: %s', a.name, errMessage(err));
|
||||
}
|
||||
});
|
||||
await Promise.all(tasks);
|
||||
this.adapters.clear();
|
||||
}
|
||||
|
||||
async closeOne(name: string): Promise<void> {
|
||||
const adapter = this.adapters.get(name);
|
||||
if (!adapter) return;
|
||||
this.adapters.delete(name);
|
||||
try {
|
||||
await adapter.close();
|
||||
} catch (err) {
|
||||
log.warn('adapter [%s] close failed: %s', adapter.name, errMessage(err));
|
||||
reconcile(config: OneBotConfig): Promise<NetworkReconcileResult> {
|
||||
const desired = this.compileDesiredPlan(config);
|
||||
if (!this.acceptingReconciles) {
|
||||
return Promise.reject(new Error('network manager is shutting down'));
|
||||
}
|
||||
return this.enqueue(() => this.reconcileNow(desired));
|
||||
}
|
||||
|
||||
async emitEvent(event: JsonObject): Promise<void> {
|
||||
/** Compatibility seam for tests/pre-built adapters. Opens sequentially and
|
||||
* reports each failure instead of hiding it in a detached Promise. */
|
||||
openAll(): Promise<NetworkReconcileResult> {
|
||||
if (!this.acceptingReconciles) return Promise.reject(new Error('network manager is shutting down'));
|
||||
return this.enqueue(async () => {
|
||||
const errors: NetworkApplyError[] = [];
|
||||
for (const entry of this.adapters.values()) {
|
||||
try {
|
||||
await entry.adapter.open();
|
||||
entry.adapter.clearApplyFailure();
|
||||
} catch (error) {
|
||||
entry.adapter.markApplyFailure(error);
|
||||
errors.push(this.report(entry.adapter.name, entry.kind, 'open', error));
|
||||
}
|
||||
}
|
||||
return this.result(errors);
|
||||
});
|
||||
}
|
||||
|
||||
closeOne(name: string): Promise<void> {
|
||||
if (!this.acceptingReconciles) return Promise.reject(new Error('network manager is shutting down'));
|
||||
return this.enqueue(async () => {
|
||||
const entry = this.adapters.get(name);
|
||||
if (!entry) return;
|
||||
await entry.adapter.close();
|
||||
this.adapters.delete(name);
|
||||
});
|
||||
}
|
||||
|
||||
/** Ordered, idempotent shutdown. Reconcile calls made before shutdown finish
|
||||
* first; calls made after shutdown is requested fail immediately. */
|
||||
shutdown(): Promise<NetworkShutdownResult> {
|
||||
if (this.shutdownResult?.closed) return Promise.resolve(this.shutdownResult);
|
||||
if (this.shutdownPromise) return this.shutdownPromise;
|
||||
this.acceptingReconciles = false;
|
||||
this.acceptingEvents = false;
|
||||
const attempt = this.enqueue(async () => {
|
||||
const errors: NetworkApplyError[] = [];
|
||||
const dispatches = await Promise.allSettled([...this.inFlightEmits]);
|
||||
for (const dispatch of dispatches) {
|
||||
if (dispatch.status === 'rejected') {
|
||||
log.error('in-flight event dispatch failed during shutdown: %s', errMessage(dispatch.reason));
|
||||
}
|
||||
}
|
||||
const entries = [...this.adapters.entries()].reverse();
|
||||
for (const [name, entry] of entries) {
|
||||
try {
|
||||
await entry.adapter.close();
|
||||
this.adapters.delete(name);
|
||||
} catch (error) {
|
||||
entry.adapter.markApplyFailure(error);
|
||||
errors.push(this.report(name, entry.kind, 'shutdown', error));
|
||||
}
|
||||
}
|
||||
this.debugSubscribers.clear();
|
||||
return { closed: errors.length === 0, errors };
|
||||
});
|
||||
this.shutdownPromise = attempt;
|
||||
void attempt.then(
|
||||
(result) => {
|
||||
this.shutdownResult = result.closed ? result : null;
|
||||
this.shutdownPromise = null;
|
||||
},
|
||||
() => {
|
||||
this.shutdownPromise = null;
|
||||
},
|
||||
);
|
||||
return attempt;
|
||||
}
|
||||
|
||||
closeAll(): Promise<NetworkShutdownResult> {
|
||||
return this.shutdown();
|
||||
}
|
||||
|
||||
emitEvent(event: JsonObject): Promise<void> {
|
||||
if (!this.acceptingEvents) {
|
||||
return Promise.reject(new Error('network manager is shutting down; event dispatch rejected'));
|
||||
}
|
||||
const operation = this.emitEventNow(event);
|
||||
this.inFlightEmits.add(operation);
|
||||
void operation.then(
|
||||
() => { this.inFlightEmits.delete(operation); },
|
||||
() => { this.inFlightEmits.delete(operation); },
|
||||
);
|
||||
return operation;
|
||||
}
|
||||
|
||||
private async emitEventNow(event: JsonObject): Promise<void> {
|
||||
// Notify debug taps first — before the adapter check — so the debug stream
|
||||
// sees every event even when no adapter is connected. Never let a tap throw
|
||||
// into the dispatch path.
|
||||
// sees every event even when no adapter is connected. A diagnostic tap is
|
||||
// isolated, but its failure is always logged with the root message.
|
||||
if (this.debugSubscribers.size) {
|
||||
for (const cb of this.debugSubscribers) {
|
||||
try { cb(event); } catch (err) { log.warn('debug subscriber error: %s', errMessage(err)); }
|
||||
try { cb(event); } catch (error) { log.warn('debug subscriber error: %s', errMessage(error)); }
|
||||
}
|
||||
}
|
||||
if (!this.hasActiveAdapters()) return;
|
||||
const payload = buildDispatchPayload(event);
|
||||
const tasks: Promise<unknown>[] = [];
|
||||
for (const adapter of this.adapters.values()) {
|
||||
for (const { adapter } of this.adapters.values()) {
|
||||
if (!adapter.isActive) continue;
|
||||
tasks.push(
|
||||
Promise.resolve()
|
||||
.then(() => adapter.onEvent(event, payload))
|
||||
.catch((err) => {
|
||||
log.warn('adapter [%s] onEvent error: %s', adapter.name, errMessage(err));
|
||||
.catch((error) => {
|
||||
log.warn('adapter [%s] onEvent error: %s', adapter.name, errMessage(error));
|
||||
}),
|
||||
);
|
||||
}
|
||||
await Promise.allSettled(tasks);
|
||||
}
|
||||
|
||||
private async reconcileNow(desired: DesiredNetworkAdapter[]): Promise<NetworkReconcileResult> {
|
||||
const errors: NetworkApplyError[] = [];
|
||||
const desiredByName = new Map(desired.map((entry) => [entry.name, entry]));
|
||||
|
||||
// Retire removed adapters first so their ports/resources are available to
|
||||
// newly added entries in the same plan. Close is deliberately sequential.
|
||||
for (const [name, live] of [...this.adapters]) {
|
||||
if (desiredByName.has(name)) continue;
|
||||
try {
|
||||
await live.adapter.close();
|
||||
this.adapters.delete(name);
|
||||
} catch (error) {
|
||||
live.adapter.markApplyFailure(error);
|
||||
errors.push(this.report(name, live.kind, 'close', error));
|
||||
}
|
||||
}
|
||||
|
||||
for (const next of desired) {
|
||||
const live = this.adapters.get(next.name);
|
||||
if (!live) {
|
||||
await this.createAndOpen(next, errors);
|
||||
} else if (live.kind === next.kind) {
|
||||
await this.reloadSameKind(live, next, errors);
|
||||
} else {
|
||||
await this.replaceKind(live, next, errors);
|
||||
}
|
||||
}
|
||||
|
||||
return this.result(errors);
|
||||
}
|
||||
|
||||
private async createAndOpen(next: DesiredNetworkAdapter, errors: NetworkApplyError[]): Promise<void> {
|
||||
let adapter: AnyAdapter;
|
||||
try {
|
||||
adapter = this.create(next);
|
||||
} catch (error) {
|
||||
errors.push(this.report(next.name, next.kind, 'open', error));
|
||||
return;
|
||||
}
|
||||
this.adapters.set(next.name, { kind: next.kind, adapter });
|
||||
try {
|
||||
await adapter.open();
|
||||
adapter.clearApplyFailure();
|
||||
} catch (error) {
|
||||
adapter.markApplyFailure(error);
|
||||
errors.push(this.report(next.name, next.kind, 'open', error));
|
||||
}
|
||||
}
|
||||
|
||||
private async reloadSameKind(
|
||||
live: ManagedAdapter,
|
||||
next: DesiredNetworkAdapter,
|
||||
errors: NetworkApplyError[],
|
||||
): Promise<void> {
|
||||
const previous = structuredClone(live.adapter.currentConfig);
|
||||
try {
|
||||
// A degraded adapter may still own a failed/ambiguous transport even if
|
||||
// the desired binding signature is unchanged. Force a real release and
|
||||
// reopen instead of letting reload() return Normal and clearing the
|
||||
// evidence without recovery.
|
||||
if (live.adapter.hasApplyFailure) await live.adapter.close();
|
||||
await live.adapter.reload(next.config);
|
||||
live.adapter.clearApplyFailure();
|
||||
} catch (error) {
|
||||
let restored = false;
|
||||
try {
|
||||
await live.adapter.reload(previous);
|
||||
restored = true;
|
||||
} catch (restoreError) {
|
||||
errors.push(this.report(next.name, live.kind, 'restore', restoreError));
|
||||
}
|
||||
live.adapter.markApplyFailure(error);
|
||||
errors.push(this.report(next.name, next.kind, 'reload', error, restored));
|
||||
}
|
||||
}
|
||||
|
||||
private async replaceKind(
|
||||
live: ManagedAdapter,
|
||||
next: DesiredNetworkAdapter,
|
||||
errors: NetworkApplyError[],
|
||||
): Promise<void> {
|
||||
try {
|
||||
await live.adapter.close();
|
||||
} catch (error) {
|
||||
live.adapter.markApplyFailure(error);
|
||||
errors.push(this.report(next.name, live.kind, 'replace', error));
|
||||
return;
|
||||
}
|
||||
|
||||
let replacement: AnyAdapter;
|
||||
try {
|
||||
replacement = this.create(next);
|
||||
} catch (error) {
|
||||
let restored = false;
|
||||
try {
|
||||
await live.adapter.open();
|
||||
restored = true;
|
||||
} catch (restoreError) {
|
||||
errors.push(this.report(next.name, live.kind, 'restore', restoreError));
|
||||
}
|
||||
// Whether restoration succeeds or not, the desired kind was not
|
||||
// applied. Preserve that root failure on the still-managed old adapter.
|
||||
live.adapter.markApplyFailure(error);
|
||||
errors.push(this.report(next.name, next.kind, 'replace', error, restored));
|
||||
return;
|
||||
}
|
||||
this.adapters.set(next.name, { kind: next.kind, adapter: replacement });
|
||||
try {
|
||||
await replacement.open();
|
||||
replacement.clearApplyFailure();
|
||||
return;
|
||||
} catch (error) {
|
||||
// The desired kind failed after the old resource was released. Clean up
|
||||
// the partial replacement, then make a best-effort restoration of the
|
||||
// previous live adapter. The original apply error remains the primary
|
||||
// degraded reason even when restoration succeeds.
|
||||
try {
|
||||
await replacement.close();
|
||||
} catch (cleanupError) {
|
||||
// The replacement may still own a bound resource. Keep it in the map
|
||||
// and do not start the old adapter: overwriting this reference would
|
||||
// orphan a potentially-live transport and could double-bind a port.
|
||||
replacement.markApplyFailure(error);
|
||||
errors.push(this.report(next.name, next.kind, 'close', cleanupError));
|
||||
errors.push(this.report(next.name, next.kind, 'replace', error, false));
|
||||
return;
|
||||
}
|
||||
|
||||
let restored = false;
|
||||
try {
|
||||
await live.adapter.open();
|
||||
live.adapter.markApplyFailure(error);
|
||||
this.adapters.set(next.name, live);
|
||||
restored = true;
|
||||
} catch (restoreError) {
|
||||
replacement.markApplyFailure(error);
|
||||
errors.push(this.report(next.name, live.kind, 'restore', restoreError));
|
||||
}
|
||||
errors.push(this.report(next.name, next.kind, 'replace', error, restored));
|
||||
}
|
||||
}
|
||||
|
||||
private create(next: DesiredNetworkAdapter): AnyAdapter {
|
||||
if (!this.factory) throw new Error(`no network adapter factory configured for ${next.name}`);
|
||||
const adapter = this.factory(next);
|
||||
if (adapter.name !== next.name) {
|
||||
throw new Error(`network adapter factory returned name ${adapter.name} for desired ${next.name}`);
|
||||
}
|
||||
return adapter;
|
||||
}
|
||||
|
||||
private result(errors: NetworkApplyError[]): NetworkReconcileResult {
|
||||
return {
|
||||
applied: errors.length === 0,
|
||||
errors,
|
||||
statuses: this.describeStatuses(),
|
||||
};
|
||||
}
|
||||
|
||||
private report(
|
||||
name: string,
|
||||
kind: NetworkAdapterKind,
|
||||
phase: NetworkApplyPhase,
|
||||
error: unknown,
|
||||
restored?: boolean,
|
||||
): NetworkApplyError {
|
||||
const detail: NetworkApplyError = {
|
||||
name,
|
||||
kind,
|
||||
phase,
|
||||
message: errMessage(error),
|
||||
at: Date.now(),
|
||||
...(restored === undefined ? {} : { restored }),
|
||||
};
|
||||
log.error(
|
||||
'adapter [%s] kind=%s phase=%s failed%s: %s',
|
||||
name,
|
||||
kind,
|
||||
phase,
|
||||
restored === undefined ? '' : ` restored=${String(restored)}`,
|
||||
detail.message,
|
||||
);
|
||||
return detail;
|
||||
}
|
||||
|
||||
private enqueue<T>(operation: () => Promise<T>): Promise<T> {
|
||||
const result = this.operationTail.then(operation);
|
||||
// Keep the FIFO usable after a rejected invariant/programming error. The
|
||||
// returned promise still rejects, so no error is hidden from its caller.
|
||||
this.operationTail = result.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
function errMessage(err: unknown): string {
|
||||
return err instanceof Error ? err.message : String(err);
|
||||
function errMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
@@ -27,6 +27,8 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
private options: EventReportOptions;
|
||||
private role: WsRole;
|
||||
private explicitlyClosed = false;
|
||||
private acceptingActions = false;
|
||||
private readonly inFlightActions = new Set<Promise<void>>();
|
||||
// Stop fn for the CURRENT socket's keepalive, so close()/reload can halt it
|
||||
// immediately instead of waiting for the deferred 'close' event. The per-socket
|
||||
// closure in connect() still owns the #97 stale-socket case; this is idempotent
|
||||
@@ -45,11 +47,22 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
if (!this.config.url) return;
|
||||
this.explicitlyClosed = false;
|
||||
this.isEnabled = true;
|
||||
this.connect();
|
||||
try {
|
||||
this.connect();
|
||||
this.acceptingActions = true;
|
||||
this.clearApplyFailure();
|
||||
} catch (error) {
|
||||
this.isEnabled = false;
|
||||
this.explicitlyClosed = true;
|
||||
this.acceptingActions = false;
|
||||
this.recordTransportFailure(error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
close(): void {
|
||||
async close(): Promise<void> {
|
||||
this.explicitlyClosed = true;
|
||||
this.acceptingActions = false;
|
||||
this.isEnabled = false;
|
||||
this.connected = false;
|
||||
this.cancelReconnect();
|
||||
@@ -59,6 +72,7 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
safeClose(this.socket);
|
||||
this.socket = null;
|
||||
}
|
||||
await Promise.all(this.inFlightActions);
|
||||
}
|
||||
|
||||
override describeStatus(): AdapterStatus {
|
||||
@@ -131,9 +145,11 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
});
|
||||
|
||||
socket.on('message', (raw: Buffer) => {
|
||||
void this.handleApiMessage(socket, raw).catch((err) => {
|
||||
this.log.warn('[%s] handleApiMessage threw: %s', this.name, err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
if (this.socket !== socket) {
|
||||
this.log.warn('[%s] rejected inbound action from stale socket', this.name);
|
||||
return;
|
||||
}
|
||||
this.trackInboundAction(() => this.handleApiMessage(socket, raw));
|
||||
});
|
||||
|
||||
socket.on('close', () => {
|
||||
@@ -193,9 +209,30 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
);
|
||||
}
|
||||
|
||||
private trackInboundAction(start: () => Promise<void>): void {
|
||||
if (!this.acceptingActions || this.ctx.api.isAcceptingActions === false) {
|
||||
this.log.warn('[%s] rejected inbound action while adapter is closing', this.name);
|
||||
return;
|
||||
}
|
||||
let action: Promise<void>;
|
||||
try {
|
||||
action = start();
|
||||
} catch (error) {
|
||||
this.log.error('[%s] inbound action start failed: %s', this.name, error instanceof Error ? (error.stack ?? error.message) : String(error));
|
||||
return;
|
||||
}
|
||||
const tracked = action.then(
|
||||
() => undefined,
|
||||
(error) => {
|
||||
this.log.error('[%s] inbound action failed: %s', this.name, error instanceof Error ? (error.stack ?? error.message) : String(error));
|
||||
},
|
||||
);
|
||||
this.inFlightActions.add(tracked);
|
||||
void tracked.then(() => { this.inFlightActions.delete(tracked); });
|
||||
}
|
||||
|
||||
private sendBootstrapMetaEvents(socket: WebSocket): void {
|
||||
if (this.role !== 'Event' && this.role !== 'Universal') return;
|
||||
for (const frame of this.bootstrapMetaFrames(this.options)) safeSend(socket, frame);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,6 +30,9 @@ interface ForwardConn {
|
||||
export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
private wss: WebSocketServer | null = null;
|
||||
private listening = false;
|
||||
private closePromise: Promise<void> | null = null;
|
||||
private acceptingActions = false;
|
||||
private readonly inFlightActions = new Set<Promise<void>>();
|
||||
private connections = new Map<WebSocket, ForwardConn>();
|
||||
private options: EventReportOptions;
|
||||
|
||||
@@ -38,15 +41,22 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
this.options = resolveReportOptions(config);
|
||||
}
|
||||
|
||||
open(): void {
|
||||
if (this.isEnabled) return;
|
||||
async open(): Promise<void> {
|
||||
if (this.isEnabled && this.listening) return;
|
||||
if (this.config.enabled === false) return;
|
||||
this.startServer();
|
||||
if (this.wss) throw new Error(`WebSocket adapter [${this.name}] still owns a previous server`);
|
||||
await this.startServer();
|
||||
this.isEnabled = true;
|
||||
this.clearApplyFailure();
|
||||
}
|
||||
|
||||
close(): void {
|
||||
if (!this.isEnabled && this.connections.size === 0 && !this.wss) return;
|
||||
async close(): Promise<void> {
|
||||
if (this.closePromise) return this.closePromise;
|
||||
if (!this.isEnabled && this.connections.size === 0 && !this.wss && this.inFlightActions.size === 0) return;
|
||||
const wasEnabled = this.isEnabled;
|
||||
const wasListening = this.listening;
|
||||
const wasAcceptingActions = this.acceptingActions;
|
||||
this.acceptingActions = false;
|
||||
// Final lifecycle broadcast before tearing down so attached event clients
|
||||
// see the disable transition.
|
||||
const lifecycle = this.ctx.buildLifecycleEvent('disable');
|
||||
@@ -63,8 +73,31 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
safeClose(conn.socket);
|
||||
}
|
||||
this.connections.clear();
|
||||
this.wss?.close();
|
||||
this.wss = null;
|
||||
const wss = this.wss;
|
||||
const releaseResult: Promise<{ error?: Error }> = wss
|
||||
? new Promise<{ error?: Error }>((resolve) => {
|
||||
wss.close((error) => resolve(error && !isAlreadyClosedError(error) ? { error } : {}));
|
||||
})
|
||||
: Promise.resolve({});
|
||||
const attempt = (async () => {
|
||||
await Promise.all(this.inFlightActions);
|
||||
const release = await releaseResult;
|
||||
if (release.error) throw release.error;
|
||||
})();
|
||||
this.closePromise = attempt;
|
||||
try {
|
||||
await attempt;
|
||||
if (wss && this.wss === wss) this.wss = null;
|
||||
} catch (error) {
|
||||
// A failed close callback leaves release ambiguous. Retain the server
|
||||
// reference and active binding state so a later shutdown can retry.
|
||||
this.isEnabled = wasEnabled;
|
||||
this.listening = wasListening;
|
||||
this.acceptingActions = wasAcceptingActions;
|
||||
throw error;
|
||||
} finally {
|
||||
this.closePromise = null;
|
||||
}
|
||||
}
|
||||
|
||||
override describeStatus(): AdapterStatus {
|
||||
@@ -92,34 +125,67 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
}
|
||||
}
|
||||
|
||||
private startServer(): void {
|
||||
const wss = new WebSocketServer({
|
||||
host: this.config.host ?? '0.0.0.0',
|
||||
port: this.config.port,
|
||||
path: this.config.path ?? '/',
|
||||
});
|
||||
this.wss = wss;
|
||||
private startServer(): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
let wss: WebSocketServer;
|
||||
try {
|
||||
wss = new WebSocketServer({
|
||||
host: this.config.host ?? '0.0.0.0',
|
||||
port: this.config.port,
|
||||
path: normalizePath(this.config.path),
|
||||
});
|
||||
} catch (error) {
|
||||
this.recordTransportFailure(error);
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
this.wss = wss;
|
||||
let opening = true;
|
||||
|
||||
wss.on('listening', () => {
|
||||
this.listening = true;
|
||||
this.log.success(
|
||||
'[%s] listening %s:%d%s',
|
||||
this.name,
|
||||
this.config.host ?? '0.0.0.0',
|
||||
this.config.port,
|
||||
this.config.path ?? '/',
|
||||
);
|
||||
});
|
||||
wss.once('listening', () => {
|
||||
opening = false;
|
||||
if (this.wss !== wss || this.closePromise) {
|
||||
wss.close();
|
||||
reject(new Error(`WebSocket adapter [${this.name}] was closed while binding`));
|
||||
return;
|
||||
}
|
||||
this.listening = true;
|
||||
this.isEnabled = true;
|
||||
this.acceptingActions = true;
|
||||
this.log.success(
|
||||
'[%s] listening %s:%d%s',
|
||||
this.name,
|
||||
this.config.host ?? '0.0.0.0',
|
||||
this.config.port,
|
||||
this.config.path ?? '/',
|
||||
);
|
||||
resolve();
|
||||
});
|
||||
|
||||
wss.on('error', (err: Error) => {
|
||||
this.listening = false;
|
||||
this.log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err));
|
||||
});
|
||||
wss.on('error', (error: Error) => {
|
||||
if (this.wss === wss) {
|
||||
this.listening = false;
|
||||
this.isEnabled = false;
|
||||
this.acceptingActions = false;
|
||||
this.recordTransportFailure(error);
|
||||
if (opening) this.wss = null;
|
||||
}
|
||||
this.log.error('[%s] server error: %s', this.name, error instanceof Error ? error.message : String(error));
|
||||
if (opening) {
|
||||
opening = false;
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
|
||||
wss.on('connection', (socket: WebSocket, request: IncomingMessage) => this.onConnection(socket, request));
|
||||
wss.on('connection', (socket: WebSocket, request: IncomingMessage) => this.onConnection(socket, request));
|
||||
});
|
||||
}
|
||||
|
||||
private onConnection(socket: WebSocket, request: IncomingMessage): void {
|
||||
if (!this.acceptingActions || this.ctx.api.isAcceptingActions === false) {
|
||||
safeClose(socket, 1012, 'server closing');
|
||||
return;
|
||||
}
|
||||
if (!isAuthorized(request, this.config.accessToken ?? '')) {
|
||||
safeClose(socket, 1008, 'invalid access token');
|
||||
return;
|
||||
@@ -138,9 +204,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
this.connections.set(socket, conn);
|
||||
|
||||
socket.on('message', (raw: Buffer) => {
|
||||
void this.handleApiMessage(socket, role, raw).catch((err) => {
|
||||
this.log.warn('[%s] handleApiMessage threw: %s', this.name, err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
this.trackInboundAction(() => this.handleApiMessage(socket, role, raw));
|
||||
});
|
||||
socket.on('close', () => {
|
||||
stopHeartbeat();
|
||||
@@ -170,11 +234,37 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
);
|
||||
}
|
||||
|
||||
private trackInboundAction(start: () => Promise<void>): void {
|
||||
if (!this.acceptingActions || this.ctx.api.isAcceptingActions === false) {
|
||||
this.log.warn('[%s] rejected inbound action while adapter is closing', this.name);
|
||||
return;
|
||||
}
|
||||
let action: Promise<void>;
|
||||
try {
|
||||
action = start();
|
||||
} catch (error) {
|
||||
this.log.error('[%s] inbound action start failed: %s', this.name, error instanceof Error ? (error.stack ?? error.message) : String(error));
|
||||
return;
|
||||
}
|
||||
const tracked = action.then(
|
||||
() => undefined,
|
||||
(error) => {
|
||||
this.log.error('[%s] inbound action failed: %s', this.name, error instanceof Error ? (error.stack ?? error.message) : String(error));
|
||||
},
|
||||
);
|
||||
this.inFlightActions.add(tracked);
|
||||
void tracked.then(() => { this.inFlightActions.delete(tracked); });
|
||||
}
|
||||
|
||||
private sendBootstrapMetaEvents(socket: WebSocket): void {
|
||||
for (const frame of this.bootstrapMetaFrames(this.options)) safeSend(socket, frame);
|
||||
}
|
||||
}
|
||||
|
||||
function isAlreadyClosedError(error: Error): boolean {
|
||||
return (error as NodeJS.ErrnoException).code === 'ERR_SERVER_NOT_RUNNING';
|
||||
}
|
||||
|
||||
function classifyForwardRole(request: IncomingMessage): WsRole {
|
||||
const path = parseRequestPath(request.url ?? '/');
|
||||
if (path.endsWith('/api')) return 'Api';
|
||||
|
||||
Reference in new issue
Block a user