fix(onebot): await malformed stream responses
Wait for asynchronous transports to flush bad-request frames before processStreamRequest returns. This prevents malformed Stream API requests from losing their terminal error response.
This commit is contained in:
2 files changed
+23
-5
No files matched your search
@@ -218,22 +218,24 @@ export class ApiHandler {
|
||||
emit: (json: string) => void | Promise<void>,
|
||||
isAlive?: () => boolean,
|
||||
): Promise<void> {
|
||||
const bad = (): void => { void emit(JSON.stringify(failedResponse(RETCODE.BAD_REQUEST, 'bad request'))); };
|
||||
if (!rawRequest.trim()) { bad(); return; }
|
||||
const bad = (): Promise<void> => Promise.resolve(
|
||||
emit(JSON.stringify(failedResponse(RETCODE.BAD_REQUEST, 'bad request'))),
|
||||
);
|
||||
if (!rawRequest.trim()) { await bad(); return; }
|
||||
|
||||
let action: string;
|
||||
let params: JsonObject;
|
||||
let echo: JsonValue | undefined;
|
||||
try {
|
||||
const parsed = JSON.parse(rawRequest) as unknown;
|
||||
if (!isJsonObject(parsed)) { bad(); return; }
|
||||
if (!isJsonObject(parsed)) { await bad(); return; }
|
||||
const a = asString(parsed.action);
|
||||
if (!a) { bad(); return; }
|
||||
if (!a) { await bad(); return; }
|
||||
action = a;
|
||||
params = isJsonObject(parsed.params) ? parsed.params : {};
|
||||
echo = parsed.echo !== undefined ? toJsonValue(parsed.echo) : undefined;
|
||||
} catch {
|
||||
bad();
|
||||
await bad();
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -164,4 +164,20 @@ describe('Stream API plumbing', () => {
|
||||
expect(frames).toHaveLength(3);
|
||||
for (const f of parse(frames)) expect(f).toMatchObject({ status: 'failed' });
|
||||
});
|
||||
|
||||
it('waits for an async bad-request frame to flush', async () => {
|
||||
const h = newHandler();
|
||||
let release!: () => void;
|
||||
const flushed = new Promise<void>((resolve) => { release = resolve; });
|
||||
let completed = false;
|
||||
|
||||
const request = h.processStreamRequest('', async () => flushed);
|
||||
void request.then(() => { completed = true; });
|
||||
await Promise.resolve();
|
||||
expect(completed).toBe(false);
|
||||
|
||||
release();
|
||||
await request;
|
||||
expect(completed).toBe(true);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user