feat(onebot): reconcile and drain network adapters

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

No files matched your search

+192 -16
View File
@@ -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> {