feat(onebot): complete trace operation chains
Make short TRACE captures independently explain OneBot action and event lifecycles from complete input through a truthful terminal conclusion. Preserve request correlation across asynchronous work while keeping disabled TRACE paths allocation-free and lazy. Cover shutdown rejection, stream cancellation, event conversion and suppression, reporter invocation settlement, and HTTP delivery outcomes without changing established transport or observer behavior. Add focused regression coverage for lifecycle uniqueness, context reuse, disconnect handling, and quiesce ingress boundaries.
This commit is contained in:
20 files changed
+1304
-154
No files matched your search
@@ -80,29 +80,57 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
|
||||
}
|
||||
|
||||
const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||
const startedAt = Date.now();
|
||||
let response: Response;
|
||||
try {
|
||||
const response = await fetch(config.url, {
|
||||
response = await fetch(config.url, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: payload,
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
});
|
||||
if (response.ok) {
|
||||
this.lastDelivery = { at: Date.now(), ok: true };
|
||||
const contentType = response.headers.get('content-type') ?? '';
|
||||
if (contentType.includes('application/json')) {
|
||||
const body = await response.text();
|
||||
if (body.trim()) {
|
||||
await this.handleQuickOperation(event, body);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
this.lastDelivery = { at: Date.now(), ok: false };
|
||||
this.log.warn('[%s] POST %s returned %d', this.name, config.url, response.status);
|
||||
}
|
||||
} catch (error) {
|
||||
this.lastDelivery = { at: Date.now(), ok: false };
|
||||
this.log.warn('[%s] POST %s failed: %s', this.name, config.url, error instanceof Error ? error.message : String(error));
|
||||
this.log.trace(() => [
|
||||
'http_report_terminal target=%s outcome=transport_failed ms=%d error=%s',
|
||||
this.name,
|
||||
Date.now() - startedAt,
|
||||
error instanceof Error ? (error.stack ?? error.message) : String(error),
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
this.lastDelivery = { at: Date.now(), ok: false };
|
||||
this.log.warn('[%s] POST %s returned %d', this.name, config.url, response.status);
|
||||
this.log.trace(
|
||||
'http_report_terminal target=%s outcome=rejected status=%d ms=%d',
|
||||
this.name,
|
||||
response.status,
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
this.lastDelivery = { at: Date.now(), ok: true };
|
||||
this.log.trace(
|
||||
'http_report_terminal target=%s outcome=accepted status=%d ms=%d',
|
||||
this.name,
|
||||
response.status,
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
const contentType = response.headers.get('content-type') ?? '';
|
||||
if (!contentType.includes('application/json')) return;
|
||||
try {
|
||||
const body = await response.text();
|
||||
if (body.trim()) await this.handleQuickOperation(event, body);
|
||||
} catch (error) {
|
||||
this.log.warn(
|
||||
'[%s] quick operation response read failed: %s',
|
||||
this.name,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,12 @@ import {
|
||||
import type { ApiHandler } from '../api-handler';
|
||||
import type { DispatchPayload } from '../event-filter';
|
||||
import type { ApiResponse, HttpServerNetwork, JsonObject, JsonValue } from '../types';
|
||||
import { type StreamSink, wrapStreamFrame, wrapStreamTerminal } from '../streaming';
|
||||
import {
|
||||
StreamTransportClosedError,
|
||||
type StreamSink,
|
||||
wrapStreamFrame,
|
||||
wrapStreamTerminal,
|
||||
} from '../streaming';
|
||||
import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter';
|
||||
import { isAuthorized, normalizePath } from './utils';
|
||||
import { WsServerConnections } from './ws-server-connections';
|
||||
@@ -233,6 +238,14 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
|
||||
}
|
||||
|
||||
private async handleRequest(req: IncomingMessage, res: ServerResponse): Promise<void> {
|
||||
const apiQuiescedAtIngress = this.ctx.api.isAcceptingActions === false;
|
||||
if (apiQuiescedAtIngress) {
|
||||
writeJson(res, 503, serverClosingResponse());
|
||||
}
|
||||
const respond = (statusCode: number, data: unknown): void => {
|
||||
if (apiQuiescedAtIngress) return;
|
||||
writeJson(res, statusCode, data);
|
||||
};
|
||||
const expectedPath = normalizePath(this.config.path ?? '/');
|
||||
const accessToken = this.config.accessToken ?? '';
|
||||
const parsedUrl = new URL(req.url ?? '/', 'http://127.0.0.1');
|
||||
@@ -245,17 +258,17 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
|
||||
} else if (incomingPath.startsWith(ep)) {
|
||||
action = incomingPath.substring(ep.length);
|
||||
} else {
|
||||
writeJson(res, 404, { status: 'failed', retcode: 1404, data: null, wording: 'not found' });
|
||||
respond(404, { status: 'failed', retcode: 1404, data: null, wording: 'not found' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isAuthorized(req, accessToken)) {
|
||||
writeJson(res, 401, { status: 'failed', retcode: 1401, data: null, wording: 'unauthorized' });
|
||||
respond(401, { status: 'failed', retcode: 1401, data: null, wording: 'unauthorized' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.method === 'GET' && !action) {
|
||||
writeJson(res, 200, { status: 'ok', retcode: 0, data: { online: true } });
|
||||
respond(200, { status: 'ok', retcode: 0, data: { online: true } });
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -306,7 +319,7 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
|
||||
}
|
||||
} catch {
|
||||
if (contentType.includes('application/json')) {
|
||||
writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: 'bad request: invalid json' });
|
||||
respond(400, { status: 'failed', retcode: 1400, data: null, wording: 'bad request: invalid json' });
|
||||
return;
|
||||
}
|
||||
// 无 content-type,JSON 失败则 fallback 到 urlencoded
|
||||
@@ -328,17 +341,28 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
|
||||
}
|
||||
}
|
||||
} else {
|
||||
writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: `bad request: unsupported content-type: ${contentType}` });
|
||||
respond(400, { status: 'failed', retcode: 1400, data: null, wording: `bad request: unsupported content-type: ${contentType}` });
|
||||
return;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
writeJson(res, 405, { status: 'failed', retcode: 1400, data: null, wording: 'method not allowed' });
|
||||
respond(405, { status: 'failed', retcode: 1400, data: null, wording: 'method not allowed' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (!action) {
|
||||
writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: 'bad request: missing action' });
|
||||
respond(400, { status: 'failed', retcode: 1400, data: null, wording: 'bad request: missing action' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (apiQuiescedAtIngress) {
|
||||
const response = serverClosingResponse();
|
||||
this.ctx.api.traceQuiescedAction(
|
||||
action,
|
||||
params as JsonObject,
|
||||
response,
|
||||
);
|
||||
respond(503, response);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -353,16 +377,26 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
|
||||
if (echo !== undefined) {
|
||||
response.echo = echo as JsonValue;
|
||||
}
|
||||
writeJson(res, 200, response);
|
||||
respond(200, response);
|
||||
} catch (error) {
|
||||
const wording = error instanceof Error ? error.message : 'internal error';
|
||||
writeJson(res, 500, { status: 'failed', retcode: 1200, data: null, wording });
|
||||
respond(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' });
|
||||
if (!this.acceptingActions) {
|
||||
writeJson(res, 503, serverClosingResponse());
|
||||
return;
|
||||
}
|
||||
if (this.ctx.api.isAcceptingActions === false) {
|
||||
void this.handleRequest(req, res).catch((error) => {
|
||||
this.log.warn(
|
||||
'[%s] quiesced inbound action trace failed: %s',
|
||||
this.name,
|
||||
error instanceof Error ? (error.stack ?? error.message) : String(error),
|
||||
);
|
||||
});
|
||||
return;
|
||||
}
|
||||
let action: Promise<void>;
|
||||
@@ -384,6 +418,15 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
|
||||
}
|
||||
}
|
||||
|
||||
function serverClosingResponse(): ApiResponse {
|
||||
return {
|
||||
status: 'failed',
|
||||
retcode: 1200,
|
||||
data: null,
|
||||
wording: 'server closing',
|
||||
};
|
||||
}
|
||||
|
||||
function isAlreadyClosedError(error: Error): boolean {
|
||||
return (error as NodeJS.ErrnoException).code === 'ERR_SERVER_NOT_RUNNING';
|
||||
}
|
||||
@@ -431,13 +474,21 @@ async function streamHttpResponse(
|
||||
): Promise<void> {
|
||||
res.statusCode = 200;
|
||||
const writeFrame = (frame: ApiResponse): Promise<void> =>
|
||||
new Promise((resolve) => {
|
||||
if (res.writableEnded || res.destroyed) { resolve(); return; }
|
||||
res.write(JSON.stringify(frame) + '\r\n\r\n', () => resolve());
|
||||
new Promise((resolve, reject) => {
|
||||
if (res.writableEnded || res.destroyed) {
|
||||
reject(new StreamTransportClosedError('stream client disconnected'));
|
||||
return;
|
||||
}
|
||||
res.write(JSON.stringify(frame) + '\r\n\r\n', (error) => {
|
||||
if (error) {
|
||||
reject(new StreamTransportClosedError('stream client disconnected'));
|
||||
return;
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
const sink: StreamSink = {
|
||||
send: async (frame) => {
|
||||
if (res.writableEnded || res.destroyed) throw new Error('stream client disconnected');
|
||||
await writeFrame(wrapStreamFrame(frame, echo));
|
||||
},
|
||||
};
|
||||
|
||||
@@ -250,20 +250,34 @@ export class OneBotNetworkManager {
|
||||
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()) {
|
||||
if (!adapter.isActive) continue;
|
||||
tasks.push(
|
||||
Promise.resolve()
|
||||
.then(() => adapter.onEvent(event, payload))
|
||||
.catch((error) => {
|
||||
log.warn('adapter [%s] onEvent error: %s', adapter.name, errMessage(error));
|
||||
}),
|
||||
);
|
||||
|
||||
const active = [...this.adapters.values()]
|
||||
.map(({ adapter }) => adapter)
|
||||
.filter((adapter) => adapter.isActive);
|
||||
if (active.length === 0) {
|
||||
log.trace('report_terminal outcome=no_active_targets');
|
||||
return;
|
||||
}
|
||||
log.trace(() => [
|
||||
'report_targets targets=%s',
|
||||
JSON.stringify(active.map((adapter) => adapter.name)),
|
||||
]);
|
||||
|
||||
const payload = buildDispatchPayload(event);
|
||||
const tasks = active.map((adapter) => (
|
||||
Promise.resolve()
|
||||
.then(() => adapter.onEvent(event, payload))
|
||||
.catch((error) => {
|
||||
log.warn('adapter [%s] onEvent error: %s', adapter.name, errMessage(error));
|
||||
log.trace(() => [
|
||||
'report_target_failed target=%s error=%s',
|
||||
adapter.name,
|
||||
error instanceof Error ? (error.stack ?? error.message) : String(error),
|
||||
]);
|
||||
})
|
||||
));
|
||||
await Promise.allSettled(tasks);
|
||||
log.trace('report_terminal outcome=settled');
|
||||
}
|
||||
|
||||
private async reconcileNow(desired: DesiredNetworkAdapter[]): Promise<NetworkReconcileResult> {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { StreamTransportClosedError } from '../streaming';
|
||||
import type { WebSocket } from '@snowluma/websocket';
|
||||
import type { IncomingMessage } from 'http';
|
||||
|
||||
@@ -34,13 +35,25 @@ export function safeSend(socket: WebSocket, payload: string, onError?: (err: Err
|
||||
/** Backpressure-aware send: resolves only once `ws` has flushed `payload` to
|
||||
* the socket (the `send` callback fires post-write), so a streaming producer
|
||||
* that awaits this won't outrun a slow client and balloon the send buffer.
|
||||
* Never rejects — a closed socket or send error resolves quietly (the stream
|
||||
* sink handles liveness/abort separately so a dead client can't crash the
|
||||
* per-message handler with an unhandled rejection). */
|
||||
* A closed socket or failed write rejects with the shared transport sentinel,
|
||||
* allowing the action boundary to classify an in-progress stream cancellation. */
|
||||
export function safeSendAsync(socket: WebSocket, payload: string): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
if (socket.readyState !== 1 /* WebSocket.OPEN */) { resolve(); return; }
|
||||
socket.send(payload, () => resolve());
|
||||
return new Promise((resolve, reject) => {
|
||||
if (socket.readyState !== 1 /* WebSocket.OPEN */) {
|
||||
reject(new StreamTransportClosedError('stream client disconnected'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
socket.send(payload, (error?: Error | null) => {
|
||||
if (error) {
|
||||
reject(new StreamTransportClosedError('stream client disconnected'));
|
||||
return;
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
} catch {
|
||||
reject(new StreamTransportClosedError('stream client disconnected'));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -149,6 +149,14 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
this.log.warn('[%s] rejected inbound action from stale socket', this.name);
|
||||
return;
|
||||
}
|
||||
if (this.ctx.api.isAcceptingActions === false) {
|
||||
this.log.warn('[%s] rejected inbound action after instance quiesce', this.name);
|
||||
if (this.role === 'Api' || this.role === 'Universal') {
|
||||
const text = rawDataToString(raw);
|
||||
if (text) this.ctx.api.traceQuiescedStreamRequest(text);
|
||||
}
|
||||
return;
|
||||
}
|
||||
this.trackInboundAction(() => this.handleApiMessage(socket, raw));
|
||||
});
|
||||
|
||||
@@ -210,7 +218,10 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
}
|
||||
|
||||
private trackInboundAction(start: () => Promise<void>): void {
|
||||
if (!this.acceptingActions || this.ctx.api.isAcceptingActions === false) {
|
||||
if (
|
||||
!this.acceptingActions
|
||||
|| this.ctx.api.isAcceptingActions === false
|
||||
) {
|
||||
this.log.warn('[%s] rejected inbound action while adapter is closing', this.name);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -146,6 +146,14 @@ export class WsServerConnections {
|
||||
// handshake necessarily reaches the peer. Ignore any frame arriving in
|
||||
// that interval so old credentials cannot start another Action.
|
||||
if (!this.connections.has(socket)) return;
|
||||
if (this.ctx.api.isAcceptingActions === false) {
|
||||
this.log.warn('[%s] rejected inbound action after instance quiesce', this.name);
|
||||
if (role === 'Api' || role === 'Universal') {
|
||||
const text = rawDataToString(raw);
|
||||
if (text) this.ctx.api.traceQuiescedStreamRequest(text);
|
||||
}
|
||||
return;
|
||||
}
|
||||
this.trackInboundAction(() => this.handleApiMessage(socket, role, raw));
|
||||
});
|
||||
socket.on('close', () => {
|
||||
@@ -203,7 +211,10 @@ export class WsServerConnections {
|
||||
}
|
||||
|
||||
trackInboundAction(start: () => Promise<void>): void {
|
||||
if (!this.acceptingActions || this.ctx.api.isAcceptingActions === false) {
|
||||
if (
|
||||
!this.acceptingActions
|
||||
|| this.ctx.api.isAcceptingActions === false
|
||||
) {
|
||||
this.log.warn('[%s] rejected inbound action while adapter is closing', this.name);
|
||||
return;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user