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
@@ -0,0 +1,239 @@
|
||||
import {
|
||||
afterEach,
|
||||
beforeEach,
|
||||
describe,
|
||||
expect,
|
||||
it,
|
||||
vi,
|
||||
} from 'vitest';
|
||||
import { defineStreamAction } from '../src/action-kit';
|
||||
import {
|
||||
currentRequestId,
|
||||
getLogLevel,
|
||||
nextRequestId,
|
||||
runWithRequestId,
|
||||
setLogLevel,
|
||||
subscribeLogs,
|
||||
type LogEntry,
|
||||
} from '@snowluma/common/logger';
|
||||
import { StreamTransportClosedError, StreamStatus } from '../src/streaming';
|
||||
import type { JsonObject } from '../src/types';
|
||||
import { createCompiledTestHandler, testAction } from './helpers/compiled-action-handler';
|
||||
|
||||
function emptyContext(): any {
|
||||
return {};
|
||||
}
|
||||
|
||||
function actionEntries(entries: LogEntry[], action: string): LogEntry[] {
|
||||
return entries.filter((entry) => (
|
||||
entry.scope === 'Bridge.Action'
|
||||
&& entry.level === 'trace'
|
||||
&& entry.message.includes(`action=${action}`)
|
||||
));
|
||||
}
|
||||
|
||||
describe('ApiHandler TRACE lifecycle', () => {
|
||||
let previousLevel: string;
|
||||
let entries: LogEntry[];
|
||||
let unsubscribe: () => void;
|
||||
|
||||
beforeEach(() => {
|
||||
previousLevel = getLogLevel();
|
||||
setLogLevel('trace');
|
||||
entries = [];
|
||||
unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
unsubscribe();
|
||||
setLogLevel(previousLevel);
|
||||
});
|
||||
|
||||
it('records complete input and returned response with one terminal', async () => {
|
||||
const secret = 'trace-secret-' + 'x'.repeat(200);
|
||||
const handler = createCompiledTestHandler(emptyContext(), [
|
||||
testAction('trace_ok', async () => ({
|
||||
status: 'ok',
|
||||
retcode: 0,
|
||||
data: { nested: { secret, values: [1, 2, 3] } },
|
||||
})),
|
||||
]);
|
||||
|
||||
await handler.handle('trace_ok', { nested: { access_token: secret } });
|
||||
|
||||
const lifecycle = actionEntries(entries, 'trace_ok');
|
||||
expect(lifecycle.filter((entry) => entry.message.startsWith('action_input'))).toHaveLength(1);
|
||||
expect(lifecycle.filter((entry) => entry.message.startsWith('action_terminal'))).toHaveLength(1);
|
||||
expect(lifecycle[0]?.message).toContain(secret);
|
||||
expect(lifecycle.at(-1)?.message).toContain(secret);
|
||||
expect(lifecycle.at(-1)?.message).toContain('outcome=ok');
|
||||
expect(lifecycle.at(-1)?.message).toContain('reason=response_returned');
|
||||
expect(new Set(lifecycle.map((entry) => entry.req)).size).toBe(1);
|
||||
expect(lifecycle[0]?.req).toBeTypeOf('number');
|
||||
});
|
||||
|
||||
it('distinguishes returned failure, handler throw, unknown action, and quiesce', async () => {
|
||||
const handler = createCompiledTestHandler(emptyContext(), [
|
||||
testAction('returned_failure', async () => ({
|
||||
status: 'failed', retcode: 1400, data: null, wording: 'invalid input',
|
||||
})),
|
||||
testAction('thrown_failure', async () => { throw new Error('exploded'); }),
|
||||
]);
|
||||
|
||||
await handler.handle('returned_failure', {});
|
||||
await handler.handle('thrown_failure', {});
|
||||
await handler.handle('unknown_trace_action', {});
|
||||
handler.quiesce();
|
||||
await handler.handle('returned_failure', {});
|
||||
|
||||
const returned = actionEntries(entries, 'returned_failure')
|
||||
.filter((entry) => entry.message.startsWith('action_terminal'));
|
||||
expect(returned[0]?.message).toContain('outcome=failed reason=response_returned');
|
||||
expect(returned[0]?.message).toContain('wording:"invalid input"');
|
||||
expect(returned[1]?.message).toContain('outcome=failed reason=quiesced');
|
||||
|
||||
const thrown = actionEntries(entries, 'thrown_failure')
|
||||
.filter((entry) => entry.message.startsWith('action_terminal'));
|
||||
expect(thrown).toHaveLength(1);
|
||||
expect(thrown[0]?.message).toContain('outcome=failed reason=handler_threw');
|
||||
expect(thrown[0]?.message).toContain('wording:"exploded"');
|
||||
|
||||
const unknown = actionEntries(entries, 'unknown_trace_action')
|
||||
.filter((entry) => entry.message.startsWith('action_terminal'));
|
||||
expect(unknown).toHaveLength(1);
|
||||
expect(unknown[0]?.message).toContain('outcome=failed reason=unknown_action');
|
||||
});
|
||||
|
||||
it('records parsed transport rejections without executing actions or observers', () => {
|
||||
const run = vi.fn(async () => ({ status: 'ok' as const, retcode: 0, data: null }));
|
||||
const observer = vi.fn();
|
||||
const handler = createCompiledTestHandler(emptyContext(), [
|
||||
testAction('transport_quiesced', run),
|
||||
]);
|
||||
handler.setObserver(observer);
|
||||
handler.quiesce();
|
||||
|
||||
handler.traceQuiescedStreamRequest(JSON.stringify({
|
||||
action: 'transport_quiesced',
|
||||
params: { access_token: 'complete-secret' },
|
||||
echo: 'not-part-of-params',
|
||||
}));
|
||||
handler.traceQuiescedStreamRequest('not json');
|
||||
handler.traceQuiescedStreamRequest(JSON.stringify({ params: {} }));
|
||||
|
||||
const lifecycle = actionEntries(entries, 'transport_quiesced');
|
||||
expect(lifecycle).toHaveLength(2);
|
||||
expect(lifecycle[0]?.message).toContain('action_input');
|
||||
expect(lifecycle[0]?.message).toContain('complete-secret');
|
||||
expect(lifecycle[0]?.message).not.toContain('not-part-of-params');
|
||||
expect(lifecycle[1]?.message).toContain('outcome=failed reason=quiesced');
|
||||
expect(new Set(lifecycle.map((entry) => entry.req)).size).toBe(1);
|
||||
expect(run).not.toHaveBeenCalled();
|
||||
expect(observer).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('ignores transport-rejection tracing while actions are still accepted', () => {
|
||||
const handler = createCompiledTestHandler(emptyContext(), [
|
||||
testAction('still_accepting', async () => ({ status: 'ok', retcode: 0, data: null })),
|
||||
]);
|
||||
|
||||
handler.traceQuiescedStreamRequest(JSON.stringify({
|
||||
action: 'still_accepting',
|
||||
params: {},
|
||||
}));
|
||||
|
||||
expect(actionEntries(entries, 'still_accepting')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('records successful stream frames and classifies transport closure only', async () => {
|
||||
const stream = defineStreamAction({
|
||||
name: 'trace_stream',
|
||||
params: {},
|
||||
run: async (_params, _ctx, _raw, sink) => {
|
||||
await sink.send({ type: StreamStatus.Stream, chunk: 'complete-frame' });
|
||||
return {
|
||||
status: 'ok',
|
||||
retcode: 0,
|
||||
data: { type: StreamStatus.Response },
|
||||
};
|
||||
},
|
||||
});
|
||||
const handler = createCompiledTestHandler(emptyContext(), [stream]);
|
||||
|
||||
await handler.handle('trace_stream', {}, { send: async () => {} });
|
||||
const frames = actionEntries(entries, 'trace_stream')
|
||||
.filter((entry) => entry.message.startsWith('action_stream_frame'));
|
||||
expect(frames).toHaveLength(1);
|
||||
expect(frames[0]?.message).toContain('complete-frame');
|
||||
|
||||
entries = [];
|
||||
await handler.handle('trace_stream', {}, {
|
||||
send: async () => { throw new StreamTransportClosedError(); },
|
||||
});
|
||||
const cancelled = actionEntries(entries, 'trace_stream')
|
||||
.filter((entry) => entry.message.startsWith('action_terminal'));
|
||||
expect(cancelled).toHaveLength(1);
|
||||
expect(cancelled[0]?.message).toContain('outcome=cancelled reason=transport_closed');
|
||||
expect(actionEntries(entries, 'trace_stream')
|
||||
.filter((entry) => entry.message.startsWith('action_stream_frame'))).toHaveLength(1);
|
||||
|
||||
entries = [];
|
||||
await handler.handle('trace_stream', {}, {
|
||||
send: async () => { throw new Error('arbitrary sink failure'); },
|
||||
});
|
||||
const failed = actionEntries(entries, 'trace_stream')
|
||||
.filter((entry) => entry.message.startsWith('action_terminal'));
|
||||
expect(failed).toHaveLength(1);
|
||||
expect(failed[0]?.message).toContain('outcome=failed reason=handler_threw');
|
||||
});
|
||||
|
||||
it('reuses an ambient request and gives separate top-level actions separate ids', async () => {
|
||||
let handler: ReturnType<typeof createCompiledTestHandler>;
|
||||
handler = createCompiledTestHandler(emptyContext(), [
|
||||
testAction('inner_trace', async () => ({ status: 'ok', retcode: 0, data: null })),
|
||||
testAction('outer_trace', async () => {
|
||||
await handler.handle('inner_trace', {});
|
||||
return { status: 'ok', retcode: 0, data: null };
|
||||
}),
|
||||
]);
|
||||
|
||||
await handler.handle('outer_trace', {});
|
||||
const nested = [
|
||||
...actionEntries(entries, 'outer_trace'),
|
||||
...actionEntries(entries, 'inner_trace'),
|
||||
];
|
||||
expect(new Set(nested.map((entry) => entry.req)).size).toBe(1);
|
||||
|
||||
entries = [];
|
||||
await handler.handle('inner_trace', {});
|
||||
await handler.handle('inner_trace', {});
|
||||
const topLevelInputs = actionEntries(entries, 'inner_trace')
|
||||
.filter((entry) => entry.message.startsWith('action_input'));
|
||||
expect(topLevelInputs).toHaveLength(2);
|
||||
expect(topLevelInputs[0]?.req).not.toBe(topLevelInputs[1]?.req);
|
||||
|
||||
entries = [];
|
||||
await runWithRequestId(424242, () => handler.handle('inner_trace', {}));
|
||||
expect(actionEntries(entries, 'inner_trace').every((entry) => entry.req === 424242)).toBe(true);
|
||||
});
|
||||
|
||||
it('does not allocate a request or render the complete object while TRACE is disabled', async () => {
|
||||
setLogLevel('info');
|
||||
const nested: JsonObject = {};
|
||||
Object.defineProperty(nested, 'danger', {
|
||||
enumerable: true,
|
||||
get: () => { throw new Error('verbose renderer ran'); },
|
||||
});
|
||||
const handler = createCompiledTestHandler(emptyContext(), [
|
||||
testAction('trace_off', async () => ({ status: 'ok', retcode: 0, data: null })),
|
||||
]);
|
||||
const before = nextRequestId();
|
||||
|
||||
await expect(handler.handle('trace_off', { nested })).resolves.toMatchObject({ status: 'ok' });
|
||||
|
||||
const after = nextRequestId();
|
||||
expect(after).toBe(before + 1);
|
||||
expect(currentRequestId()).toBeUndefined();
|
||||
expect(actionEntries(entries, 'trace_off')).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,13 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { getRecentLogs } from '@snowluma/common/logger';
|
||||
import {
|
||||
getLogLevel,
|
||||
getRecentLogs,
|
||||
nextRequestId,
|
||||
runWithRequestId,
|
||||
setLogLevel,
|
||||
subscribeLogs,
|
||||
type LogEntry,
|
||||
} from '@snowluma/common/logger';
|
||||
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
|
||||
|
||||
// Wrap convertEvent in a vi.fn that delegates to the real impl by
|
||||
@@ -100,6 +108,11 @@ function makeContext(extra: Partial<OneBotInstanceContext> = {}): {
|
||||
bus: BridgeEventBus;
|
||||
metaCalls: Array<{ id: number; meta: MessageMeta }>;
|
||||
dispatchCalls: JsonObject[];
|
||||
dispatchArgs: Array<{
|
||||
event: JsonObject;
|
||||
source: 'bridge' | 'send' | undefined;
|
||||
startedAt: number | undefined;
|
||||
}>;
|
||||
} {
|
||||
const bus = new BridgeEventBus();
|
||||
const fakeBridge: FakeBridge = { events: bus };
|
||||
@@ -112,6 +125,11 @@ function makeContext(extra: Partial<OneBotInstanceContext> = {}): {
|
||||
};
|
||||
const metaCalls: Array<{ id: number; meta: MessageMeta }> = [];
|
||||
const dispatchCalls: JsonObject[] = [];
|
||||
const dispatchArgs: Array<{
|
||||
event: JsonObject;
|
||||
source: 'bridge' | 'send' | undefined;
|
||||
startedAt: number | undefined;
|
||||
}> = [];
|
||||
|
||||
const ctx: OneBotInstanceContext = {
|
||||
uin: SELF_UIN,
|
||||
@@ -131,11 +149,14 @@ function makeContext(extra: Partial<OneBotInstanceContext> = {}): {
|
||||
converterCtx,
|
||||
config: { networks: { httpServers: [], httpClients: [], wsServers: [], wsClients: [] } } as never,
|
||||
cacheMessageMeta: (id, meta) => { metaCalls.push({ id, meta }); },
|
||||
dispatchEvent: (event) => { dispatchCalls.push(event); },
|
||||
dispatchEvent: (event, source, startedAt) => {
|
||||
dispatchCalls.push(event);
|
||||
dispatchArgs.push({ event, source, startedAt });
|
||||
},
|
||||
...extra,
|
||||
};
|
||||
|
||||
return { ctx, bus, metaCalls, dispatchCalls };
|
||||
return { ctx, bus, metaCalls, dispatchCalls, dispatchArgs };
|
||||
}
|
||||
|
||||
describe('registerEventPipeline', () => {
|
||||
@@ -382,4 +403,137 @@ describe('registerEventPipeline', () => {
|
||||
await bus.emit(makeFriendMessage());
|
||||
expect(dispatchCalls).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('traces complete input and conversion under one request before handoff', async () => {
|
||||
const previousLevel = getLogLevel();
|
||||
const entries: LogEntry[] = [];
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
setLogLevel('trace');
|
||||
try {
|
||||
const marker = 'complete-event-' + 'x'.repeat(200);
|
||||
const { ctx, bus, dispatchArgs } = makeContext();
|
||||
registerEventPipeline(ctx);
|
||||
|
||||
await bus.emit({
|
||||
...makeFriendMessage(),
|
||||
senderNick: marker,
|
||||
elements: [{ type: 'text', text: marker }],
|
||||
});
|
||||
|
||||
const lifecycle = entries.filter((entry) => (
|
||||
entry.scope === 'Event'
|
||||
&& entry.level === 'trace'
|
||||
&& (entry.message.startsWith('event_input kind=friend_message')
|
||||
|| entry.message.startsWith('event_converted kind=friend_message'))
|
||||
));
|
||||
expect(lifecycle).toHaveLength(2);
|
||||
expect(lifecycle[0]?.message).toContain(marker);
|
||||
expect(lifecycle[1]?.message).toContain(marker);
|
||||
expect(new Set(lifecycle.map((entry) => entry.req)).size).toBe(1);
|
||||
expect(lifecycle[0]?.req).toBeTypeOf('number');
|
||||
expect(dispatchArgs[0]).toMatchObject({ source: 'bridge' });
|
||||
expect(dispatchArgs[0]?.startedAt).toBeTypeOf('number');
|
||||
expect(entries.some((entry) => (
|
||||
entry.scope === 'Event'
|
||||
&& entry.message.startsWith('event_terminal kind=friend_message')
|
||||
))).toBe(false);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
setLogLevel(previousLevel);
|
||||
}
|
||||
});
|
||||
|
||||
it('classifies converter null, converter throw, recall, backfill failure, and internal consumption', async () => {
|
||||
const previousLevel = getLogLevel();
|
||||
const entries: LogEntry[] = [];
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
setLogLevel('trace');
|
||||
try {
|
||||
vi.mocked(convertEvent).mockResolvedValueOnce(null);
|
||||
const nullCase = makeContext();
|
||||
registerEventPipeline(nullCase.ctx);
|
||||
await nullCase.bus.emit(makeFriendMessage());
|
||||
|
||||
vi.mocked(convertEvent).mockRejectedValueOnce(new Error('converter exploded'));
|
||||
const throwCase = makeContext();
|
||||
registerEventPipeline(throwCase.ctx);
|
||||
await throwCase.bus.emit(makeFriendMessage());
|
||||
|
||||
const recalledCase = makeContext({
|
||||
messageStore: { isPrivateMessageRecalled: () => true } as never,
|
||||
});
|
||||
registerEventPipeline(recalledCase.ctx);
|
||||
await recalledCase.bus.emit(makeFriendMessage());
|
||||
|
||||
vi.mocked(backfillReplyTarget).mockRejectedValueOnce(new Error('backfill exploded'));
|
||||
const branchCase = makeContext();
|
||||
registerEventPipeline(branchCase.ctx);
|
||||
await branchCase.bus.emit(makeFriendMessage());
|
||||
|
||||
const internalCase = makeContext();
|
||||
registerEventPipeline(internalCase.ctx);
|
||||
await internalCase.bus.emit({
|
||||
kind: 'ptt_trans_result',
|
||||
time: 1700000000,
|
||||
selfUin: SELF_ID,
|
||||
msgId: 99,
|
||||
text: 'done',
|
||||
});
|
||||
|
||||
const terminals = entries
|
||||
.filter((entry) => entry.scope === 'Event' && entry.message.startsWith('event_terminal'))
|
||||
.map((entry) => entry.message);
|
||||
expect(terminals).toEqual(expect.arrayContaining([
|
||||
expect.stringContaining('outcome=dropped reason=converter_returned_null'),
|
||||
expect.stringContaining('outcome=failed reason=converter_threw'),
|
||||
expect.stringContaining('outcome=dropped reason=recalled_before_backfill'),
|
||||
expect.stringContaining('outcome=internal reason=waiter_notified'),
|
||||
]));
|
||||
expect(entries.some((entry) => (
|
||||
entry.scope === 'Event'
|
||||
&& entry.message.includes('event_branch kind=friend_message reason=reply_backfill_failed')
|
||||
&& entry.message.includes('backfill exploded')
|
||||
))).toBe(true);
|
||||
expect(branchCase.dispatchCalls).toHaveLength(1);
|
||||
expect(terminals.filter((message) => message.includes('converter exploded'))).toHaveLength(1);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
setLogLevel(previousLevel);
|
||||
}
|
||||
});
|
||||
|
||||
it('reuses an ambient request, separates top-level events, and allocates none while TRACE is disabled', async () => {
|
||||
const previousLevel = getLogLevel();
|
||||
const entries: LogEntry[] = [];
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
setLogLevel('trace');
|
||||
const { ctx, bus } = makeContext();
|
||||
registerEventPipeline(ctx);
|
||||
await runWithRequestId(515151, () => bus.emit(makeFriendMessage()));
|
||||
expect(entries.filter((entry) => (
|
||||
entry.scope === 'Event'
|
||||
&& entry.level === 'trace'
|
||||
&& entry.message.includes('kind=friend_message')
|
||||
)).every((entry) => entry.req === 515151)).toBe(true);
|
||||
|
||||
entries.length = 0;
|
||||
await bus.emit(makeFriendMessage());
|
||||
await bus.emit(makeFriendMessage());
|
||||
const inputs = entries.filter((entry) => (
|
||||
entry.scope === 'Event'
|
||||
&& entry.message.startsWith('event_input kind=friend_message')
|
||||
));
|
||||
expect(inputs).toHaveLength(2);
|
||||
expect(inputs[0]?.req).not.toBe(inputs[1]?.req);
|
||||
|
||||
setLogLevel('info');
|
||||
const before = nextRequestId();
|
||||
await bus.emit(makeFriendMessage());
|
||||
expect(nextRequestId()).toBe(before + 1);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
setLogLevel(previousLevel);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,11 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
getLogLevel,
|
||||
runWithRequestId,
|
||||
setLogLevel,
|
||||
subscribeLogs,
|
||||
type LogEntry,
|
||||
} from '@snowluma/common/logger';
|
||||
import { createHmac } from 'crypto';
|
||||
import { buildDispatchPayload } from '../src/event-filter';
|
||||
import { HttpPostAdapter } from '../src/network/http-post-adapter';
|
||||
@@ -42,6 +49,44 @@ describe('HttpPostAdapter event ownership', () => {
|
||||
expect(completed).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['accepted', () => Promise.resolve(new Response(null, { status: 204 })), 204],
|
||||
['rejected', () => Promise.resolve(new Response(null, { status: 503 })), 503],
|
||||
['transport_failed', () => Promise.reject(new Error('network down')), undefined],
|
||||
] as const)('traces a truthful %s terminal', async (outcome, fetchImpl, status) => {
|
||||
const previousLevel = getLogLevel();
|
||||
const entries: LogEntry[] = [];
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
setLogLevel('trace');
|
||||
vi.stubGlobal('fetch', vi.fn(fetchImpl));
|
||||
try {
|
||||
const config: HttpClientNetwork = {
|
||||
name: 'post',
|
||||
url: 'http://127.0.0.1:5700/events',
|
||||
messageFormat: 'array',
|
||||
reportSelfMessage: false,
|
||||
};
|
||||
const adapter = new HttpPostAdapter('post', config, CTX);
|
||||
adapter.open();
|
||||
const event: JsonObject = { post_type: 'notice', notice_type: 'trace' };
|
||||
|
||||
await runWithRequestId(7100, () => adapter.onEvent(event, buildDispatchPayload(event)));
|
||||
|
||||
const terminals = entries.filter((entry) => (
|
||||
entry.scope === 'OneBot.POST'
|
||||
&& entry.level === 'trace'
|
||||
&& entry.req === 7100
|
||||
&& entry.message.startsWith('http_report_terminal')
|
||||
));
|
||||
expect(terminals).toHaveLength(1);
|
||||
expect(terminals[0]?.message).toContain(`target=post outcome=${outcome}`);
|
||||
if (status !== undefined) expect(terminals[0]?.message).toContain(`status=${status}`);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
setLogLevel(previousLevel);
|
||||
}
|
||||
});
|
||||
|
||||
it('uses one coherent config epoch when reload races HMAC computation', async () => {
|
||||
const fetchMock = vi.fn(async () => new Response(null, { status: 204 }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
@@ -2,17 +2,187 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import http from 'http';
|
||||
import type { AddressInfo } from 'net';
|
||||
import { HttpServerAdapter } from '../src/network/http-server-adapter';
|
||||
import { StreamTransportClosedError, type StreamSink } from '../src/streaming';
|
||||
import type { NetworkAdapterContext } from '../src/network/adapter';
|
||||
import type { HttpServerNetwork } from '../src/types';
|
||||
import type { HttpServerNetwork, JsonObject } from '../src/types';
|
||||
|
||||
describe('HttpServerAdapter inbound Action ownership', () => {
|
||||
let adapter: HttpServerAdapter | null = null;
|
||||
|
||||
function request(
|
||||
port: number,
|
||||
path: string,
|
||||
): Promise<{ status: number; body: JsonObject }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const outgoing = http.request({
|
||||
host: '127.0.0.1',
|
||||
port,
|
||||
path,
|
||||
method: 'GET',
|
||||
}, (response) => {
|
||||
const chunks: Buffer[] = [];
|
||||
response.on('data', (chunk: Buffer) => chunks.push(chunk));
|
||||
response.once('end', () => {
|
||||
resolve({
|
||||
status: response.statusCode ?? 0,
|
||||
body: JSON.parse(Buffer.concat(chunks).toString('utf8')) as JsonObject,
|
||||
});
|
||||
});
|
||||
});
|
||||
outgoing.once('error', reject);
|
||||
outgoing.end();
|
||||
});
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
await adapter?.close();
|
||||
adapter = null;
|
||||
});
|
||||
|
||||
it('records a parsed HTTP action rejected by API quiesce while preserving 503', async () => {
|
||||
const traceQuiescedAction = vi.fn();
|
||||
const apiHandle = vi.fn();
|
||||
const ctx: NetworkAdapterContext = {
|
||||
uin: '10001',
|
||||
api: {
|
||||
isAcceptingActions: false,
|
||||
isStreamAction: vi.fn(() => false),
|
||||
handle: apiHandle,
|
||||
traceQuiescedAction,
|
||||
} as never,
|
||||
buildLifecycleEvent: () => ({}),
|
||||
buildHeartbeatEvent: () => ({}),
|
||||
};
|
||||
const config: HttpServerNetwork = {
|
||||
name: 'http-quiesced-action',
|
||||
host: '127.0.0.1',
|
||||
port: 0,
|
||||
path: '/',
|
||||
messageFormat: 'array',
|
||||
reportSelfMessage: false,
|
||||
};
|
||||
adapter = new HttpServerAdapter(config.name, config, ctx);
|
||||
await adapter.open();
|
||||
const server = (adapter as unknown as { server: http.Server }).server;
|
||||
const port = (server.address() as AddressInfo).port;
|
||||
|
||||
const actionResponse = await request(port, '/get_status?detail=%22complete%22');
|
||||
const healthResponse = await request(port, '/');
|
||||
|
||||
expect(actionResponse).toMatchObject({
|
||||
status: 503,
|
||||
body: {
|
||||
status: 'failed',
|
||||
retcode: 1200,
|
||||
data: null,
|
||||
wording: 'server closing',
|
||||
},
|
||||
});
|
||||
expect(healthResponse.status).toBe(503);
|
||||
expect(traceQuiescedAction).toHaveBeenCalledOnce();
|
||||
expect(traceQuiescedAction).toHaveBeenCalledWith(
|
||||
'get_status',
|
||||
{ detail: 'complete' },
|
||||
actionResponse.body,
|
||||
);
|
||||
expect(apiHandle).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not add an API-quiesced HTTP request to the action drain', async () => {
|
||||
let releaseTrace!: () => void;
|
||||
const traceGate = new Promise<void>((resolve) => { releaseTrace = resolve; });
|
||||
const ctx: NetworkAdapterContext = {
|
||||
uin: '10001',
|
||||
api: { isAcceptingActions: false } as never,
|
||||
buildLifecycleEvent: () => ({}),
|
||||
buildHeartbeatEvent: () => ({}),
|
||||
};
|
||||
const config: HttpServerNetwork = {
|
||||
name: 'http-quiesced-drain',
|
||||
host: '127.0.0.1',
|
||||
port: 0,
|
||||
path: '/',
|
||||
messageFormat: 'array',
|
||||
reportSelfMessage: false,
|
||||
};
|
||||
adapter = new HttpServerAdapter(config.name, config, ctx);
|
||||
const internals = adapter as unknown as {
|
||||
acceptingActions: boolean;
|
||||
handleRequest: () => Promise<void>;
|
||||
trackInboundAction: (req: http.IncomingMessage, res: http.ServerResponse) => void;
|
||||
inFlightActions: Set<Promise<void>>;
|
||||
};
|
||||
internals.acceptingActions = true;
|
||||
internals.handleRequest = vi.fn(() => traceGate);
|
||||
|
||||
internals.trackInboundAction({} as http.IncomingMessage, {} as http.ServerResponse);
|
||||
|
||||
expect(internals.handleRequest).toHaveBeenCalledOnce();
|
||||
expect(internals.inFlightActions.size).toBe(0);
|
||||
releaseTrace();
|
||||
await traceGate;
|
||||
adapter = null;
|
||||
});
|
||||
|
||||
it('classifies a disconnected streaming HTTP client as transport closure', async () => {
|
||||
let actionStarted!: () => void;
|
||||
const started = new Promise<void>((resolve) => { actionStarted = resolve; });
|
||||
let releaseFrame!: () => void;
|
||||
const frameGate = new Promise<void>((resolve) => { releaseFrame = resolve; });
|
||||
let streamError: unknown;
|
||||
const apiHandle = vi.fn(async (_action: string, _params: unknown, sink?: StreamSink) => {
|
||||
actionStarted();
|
||||
await frameGate;
|
||||
try {
|
||||
await sink!.send({ type: 'stream', chunk: 'after-disconnect' });
|
||||
} catch (error) {
|
||||
streamError = error;
|
||||
}
|
||||
return { status: 'ok' as const, retcode: 0, data: null };
|
||||
});
|
||||
const ctx: NetworkAdapterContext = {
|
||||
uin: '10001',
|
||||
api: { handle: apiHandle, isStreamAction: () => true } as never,
|
||||
buildLifecycleEvent: () => ({}),
|
||||
buildHeartbeatEvent: () => ({}),
|
||||
};
|
||||
const config: HttpServerNetwork = {
|
||||
name: 'http-stream-disconnect',
|
||||
host: '127.0.0.1',
|
||||
port: 0,
|
||||
path: '/',
|
||||
messageFormat: 'array',
|
||||
reportSelfMessage: false,
|
||||
};
|
||||
adapter = new HttpServerAdapter(config.name, config, ctx);
|
||||
await adapter.open();
|
||||
const server = (adapter as unknown as { server: http.Server }).server;
|
||||
const port = (server.address() as AddressInfo).port;
|
||||
const serverSocketClosed = new Promise<void>((resolve) => {
|
||||
server.once('connection', (socket) => {
|
||||
socket.once('close', () => resolve());
|
||||
});
|
||||
});
|
||||
|
||||
const request = http.request({
|
||||
host: '127.0.0.1',
|
||||
port,
|
||||
path: '/stream_action',
|
||||
method: 'GET',
|
||||
});
|
||||
request.on('error', () => { /* expected after destroy */ });
|
||||
request.end();
|
||||
await started;
|
||||
request.destroy();
|
||||
await serverSocketClosed;
|
||||
|
||||
releaseFrame();
|
||||
await vi.waitFor(() => {
|
||||
expect(apiHandle).toHaveResolved();
|
||||
});
|
||||
expect(streamError).toBeInstanceOf(StreamTransportClosedError);
|
||||
});
|
||||
|
||||
it('waits for a detached Action after the HTTP client disconnects', async () => {
|
||||
let releaseAction!: () => void;
|
||||
const actionGate = new Promise<void>((resolve) => { releaseAction = resolve; });
|
||||
|
||||
@@ -130,6 +130,48 @@ describe('HttpServerAdapter — optional WebSocket transport', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('records and drops a valid WebSocket action after API quiesce', async () => {
|
||||
const ctx = context();
|
||||
const api = ctx.api as unknown as {
|
||||
isAcceptingActions: boolean;
|
||||
processStreamRequest: ReturnType<typeof vi.fn>;
|
||||
traceQuiescedStreamRequest: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
api.traceQuiescedStreamRequest = vi.fn();
|
||||
const config = {
|
||||
name: 'quiesced-websocket',
|
||||
host: '127.0.0.1',
|
||||
port: 0,
|
||||
path: '/',
|
||||
enabled: true,
|
||||
enableWebSocket: true,
|
||||
messageFormat: 'array',
|
||||
reportSelfMessage: false,
|
||||
} satisfies HttpServerNetwork;
|
||||
adapter = new HttpServerAdapter(config.name, config, ctx);
|
||||
await adapter.open();
|
||||
const address = (adapter as unknown as { server: http.Server }).server.address() as AddressInfo;
|
||||
socket = new WebSocket(`ws://127.0.0.1:${String(address.port)}/api`);
|
||||
await waitForOpen(socket);
|
||||
const received = vi.fn();
|
||||
socket.on('message', received);
|
||||
api.isAcceptingActions = false;
|
||||
const raw = JSON.stringify({
|
||||
action: 'get_status',
|
||||
params: { detail: 'complete' },
|
||||
echo: 'dropped',
|
||||
});
|
||||
|
||||
socket.send(raw);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(api.traceQuiescedStreamRequest).toHaveBeenCalledWith(raw);
|
||||
});
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
expect(api.processStreamRequest).not.toHaveBeenCalled();
|
||||
expect(received).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('disconnects authenticated sockets when the shared token changes without rebinding HTTP', async () => {
|
||||
const config = {
|
||||
name: 'rotating-token',
|
||||
|
||||
@@ -1,4 +1,11 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
getLogLevel,
|
||||
runWithRequestId,
|
||||
setLogLevel,
|
||||
subscribeLogs,
|
||||
type LogEntry,
|
||||
} from '@snowluma/common/logger';
|
||||
import { IOneBotNetworkAdapter, NetworkReloadType, OneBotNetworkManager, type AdapterStatus } from '../src/network';
|
||||
import type { NetworkAdapterContext } from '../src/network';
|
||||
import type { JsonObject, NetworkBase } from '../src/types';
|
||||
@@ -139,6 +146,46 @@ describe('OneBotNetworkManager', () => {
|
||||
expect(bad.events).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('traces active targets, isolated failures, settlement, and no-target conclusion', async () => {
|
||||
const previousLevel = getLogLevel();
|
||||
const entries: LogEntry[] = [];
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
setLogLevel('trace');
|
||||
try {
|
||||
const mgr = new OneBotNetworkManager();
|
||||
const ok = makeAdapter('ok-target');
|
||||
const bad = makeAdapter('bad-target', { failOnEvent: true });
|
||||
mgr.register(ok);
|
||||
mgr.register(bad);
|
||||
await mgr.openAll();
|
||||
|
||||
await runWithRequestId(7001, () => mgr.emitEvent(SAMPLE_EVENT));
|
||||
const report = entries.filter((entry) => (
|
||||
entry.scope === 'OneBot.Network'
|
||||
&& entry.level === 'trace'
|
||||
&& entry.req === 7001
|
||||
));
|
||||
expect(report.find((entry) => entry.message.startsWith('report_targets'))?.message)
|
||||
.toContain('["ok-target","bad-target"]');
|
||||
expect(report.find((entry) => entry.message.startsWith('report_target_failed'))?.message)
|
||||
.toContain('target=bad-target');
|
||||
expect(report.filter((entry) => entry.message === 'report_terminal outcome=settled'))
|
||||
.toHaveLength(1);
|
||||
|
||||
entries.length = 0;
|
||||
const empty = new OneBotNetworkManager();
|
||||
await runWithRequestId(7002, () => empty.emitEvent(SAMPLE_EVENT));
|
||||
expect(entries.filter((entry) => (
|
||||
entry.scope === 'OneBot.Network'
|
||||
&& entry.req === 7002
|
||||
&& entry.message === 'report_terminal outcome=no_active_targets'
|
||||
))).toHaveLength(1);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
setLogLevel(previousLevel);
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects duplicate registration instead of detaching the old close', async () => {
|
||||
const mgr = new OneBotNetworkManager();
|
||||
const first = makeAdapter('dup');
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import type { WebSocket } from '@snowluma/websocket';
|
||||
import { StreamTransportClosedError } from '../src/streaming';
|
||||
import { safeSendAsync } from '../src/network/utils';
|
||||
|
||||
describe('safeSendAsync', () => {
|
||||
it('resolves after a successful WebSocket write callback', async () => {
|
||||
const socket = {
|
||||
readyState: 1,
|
||||
send: vi.fn((_payload: string, callback: (error?: Error | null) => void) => {
|
||||
callback(null);
|
||||
}),
|
||||
} as unknown as WebSocket;
|
||||
|
||||
await expect(safeSendAsync(socket, 'frame')).resolves.toBeUndefined();
|
||||
expect(socket.send).toHaveBeenCalledWith('frame', expect.any(Function));
|
||||
});
|
||||
|
||||
it('rejects when the socket is not open', async () => {
|
||||
const socket = {
|
||||
readyState: 3,
|
||||
send: vi.fn(),
|
||||
} as unknown as WebSocket;
|
||||
|
||||
await expect(safeSendAsync(socket, 'frame'))
|
||||
.rejects.toBeInstanceOf(StreamTransportClosedError);
|
||||
expect(socket.send).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects a synchronous WebSocket send failure', async () => {
|
||||
const socket = {
|
||||
readyState: 1,
|
||||
send: vi.fn(() => { throw new Error('socket gone'); }),
|
||||
} as unknown as WebSocket;
|
||||
|
||||
await expect(safeSendAsync(socket, 'frame'))
|
||||
.rejects.toBeInstanceOf(StreamTransportClosedError);
|
||||
});
|
||||
|
||||
it('rejects an asynchronous WebSocket write failure', async () => {
|
||||
const socket = {
|
||||
readyState: 1,
|
||||
send: vi.fn((_payload: string, callback: (error?: Error | null) => void) => {
|
||||
callback(new Error('write failed'));
|
||||
}),
|
||||
} as unknown as WebSocket;
|
||||
|
||||
await expect(safeSendAsync(socket, 'frame'))
|
||||
.rejects.toBeInstanceOf(StreamTransportClosedError);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,12 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
createLogger,
|
||||
getLogLevel,
|
||||
runWithRequestId,
|
||||
setLogLevel,
|
||||
subscribeLogs,
|
||||
type LogEntry,
|
||||
} from '@snowluma/common/logger';
|
||||
import type { BridgeInterface } from '../../core/src/bridge/bridge-interface';
|
||||
import { OneBotInstance } from '../src/instance';
|
||||
import { buildApiContext, type OneBotInstanceContext } from '../src/instance-context';
|
||||
@@ -97,7 +105,10 @@ interface InstanceHarness {
|
||||
stored: Map<number, JsonObject>;
|
||||
}
|
||||
|
||||
function makeInstanceHarness(): InstanceHarness {
|
||||
function makeInstanceHarness(options: {
|
||||
statusCommand?: { enabled: boolean; swallow: boolean; cooldownSeconds: number; trigger: string };
|
||||
logger?: ReturnType<typeof createLogger>;
|
||||
} = {}): InstanceHarness {
|
||||
const stored = new Map<number, JsonObject>();
|
||||
const emitEvent = vi.fn(async (_event: JsonObject) => {});
|
||||
const instance = Object.create(OneBotInstance.prototype) as OneBotInstance;
|
||||
@@ -105,10 +116,11 @@ function makeInstanceHarness(): InstanceHarness {
|
||||
bridge: { identity: {} },
|
||||
ctx: {
|
||||
config: {
|
||||
statusCommand: { enabled: false, swallow: false, cooldownSeconds: 5, trigger: '#sl' },
|
||||
statusCommand: options.statusCommand
|
||||
?? { enabled: false, swallow: false, cooldownSeconds: 5, trigger: '#sl' },
|
||||
},
|
||||
},
|
||||
log: { success: vi.fn(), trace: vi.fn(), warn: vi.fn() },
|
||||
log: options.logger ?? { success: vi.fn(), trace: vi.fn(), warn: vi.fn() },
|
||||
messageStore: {
|
||||
findEvent: (messageId: number) => stored.get(messageId) ?? null,
|
||||
storeEvent: (messageId: number, _isGroup: boolean, _sessionId: number, _sequence: number, _eventName: string, event: JsonObject) => {
|
||||
@@ -116,7 +128,9 @@ function makeInstanceHarness(): InstanceHarness {
|
||||
},
|
||||
},
|
||||
networkManager: { emitEvent },
|
||||
statusCommandCooldown: new Map(),
|
||||
acceptingActions: true,
|
||||
uin: String(SELF_ID),
|
||||
statusCommandCooldown: new Map([['p:20002', Date.now()]]),
|
||||
pendingSelfSentEchoes: new Map(),
|
||||
});
|
||||
const dispatch = (instance as unknown as {
|
||||
@@ -394,6 +408,56 @@ describe('OneBot self-sent events', () => {
|
||||
expect(stored.get(987654)?.raw_message).toBe('canonical echo');
|
||||
});
|
||||
|
||||
it('records one truthful handoff terminal for reporting, duplicate suppression, and status suppression', () => {
|
||||
const previousLevel = getLogLevel();
|
||||
const entries: LogEntry[] = [];
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
setLogLevel('trace');
|
||||
try {
|
||||
const logger = createLogger('Event').child({ uin: SELF_ID });
|
||||
const reporting = makeInstanceHarness({ logger });
|
||||
runWithRequestId(6001, () => reporting.dispatch(privateSentEvent(), 'send'));
|
||||
expect(reporting.emitEvent).toHaveBeenCalledOnce();
|
||||
|
||||
const duplicate = makeInstanceHarness({ logger });
|
||||
runWithRequestId(6002, () => {
|
||||
duplicate.dispatch(privateSentEvent(), 'send');
|
||||
duplicate.dispatch(privateSentEvent({ raw_message: 'canonical' }), 'bridge');
|
||||
});
|
||||
expect(duplicate.emitEvent).toHaveBeenCalledOnce();
|
||||
|
||||
const status = makeInstanceHarness({
|
||||
logger,
|
||||
statusCommand: { enabled: true, swallow: true, cooldownSeconds: 5, trigger: '#sl' },
|
||||
});
|
||||
runWithRequestId(6003, () => status.dispatch(privateSentEvent({
|
||||
post_type: 'message',
|
||||
user_id: PEER_ID,
|
||||
target_id: undefined,
|
||||
raw_message: '#sl',
|
||||
message: [{ type: 'text', data: { text: '#sl' } }],
|
||||
}), 'bridge'));
|
||||
expect(status.emitEvent).not.toHaveBeenCalled();
|
||||
|
||||
const terminals = entries.filter((entry) => (
|
||||
entry.scope === 'Event'
|
||||
&& entry.level === 'trace'
|
||||
&& entry.message.startsWith('event_terminal')
|
||||
));
|
||||
expect(terminals.filter((entry) => entry.req === 6001)).toHaveLength(1);
|
||||
expect(terminals.find((entry) => entry.req === 6001)?.message).toContain('outcome=reporting_started');
|
||||
expect(terminals.filter((entry) => entry.req === 6002)).toHaveLength(2);
|
||||
expect(terminals.find((entry) => (
|
||||
entry.req === 6002 && entry.message.includes('reason=duplicate_self_echo')
|
||||
))?.message).toContain('outcome=suppressed');
|
||||
expect(terminals.filter((entry) => entry.req === 6003)).toHaveLength(1);
|
||||
expect(terminals[terminals.length - 1]?.message).toContain('outcome=suppressed reason=status_command');
|
||||
} finally {
|
||||
unsubscribe();
|
||||
setLogLevel(previousLevel);
|
||||
}
|
||||
});
|
||||
|
||||
it('does not dispatch an event for a receipt without a reliable sequence', async () => {
|
||||
const { ctx, dispatchEvent } = makeContext({ ...RECEIPT, sequence: 0 });
|
||||
const api = buildApiContext(ctx);
|
||||
|
||||
@@ -126,6 +126,32 @@ describe('WsClientAdapter — stale-socket close guard (issue #97)', () => {
|
||||
expect(closed).toBe(true);
|
||||
});
|
||||
|
||||
it('records and drops a valid action after API quiesce', async () => {
|
||||
const processStreamRequest = vi.fn(async () => {});
|
||||
const traceQuiescedStreamRequest = vi.fn();
|
||||
const quiescedCtx: NetworkAdapterContext = {
|
||||
...ctx(),
|
||||
api: {
|
||||
isAcceptingActions: false,
|
||||
processStreamRequest,
|
||||
traceQuiescedStreamRequest,
|
||||
} as never,
|
||||
};
|
||||
const adapter = new WsClientAdapter('ws', cfg(), quiescedCtx);
|
||||
adapter.open();
|
||||
const socket = instances[0];
|
||||
const raw = Buffer.from(JSON.stringify({
|
||||
action: 'get_status',
|
||||
params: { detail: 'complete' },
|
||||
}));
|
||||
|
||||
socket.emit('message', raw);
|
||||
|
||||
expect(traceQuiescedStreamRequest).toHaveBeenCalledWith(raw.toString('utf8'));
|
||||
expect(processStreamRequest).not.toHaveBeenCalled();
|
||||
await adapter.close();
|
||||
});
|
||||
|
||||
it('ignores the close event from a socket replaced by a hot reload', async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
|
||||
Reference in new issue
Block a user