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>,
|
emit: (json: string) => void | Promise<void>,
|
||||||
isAlive?: () => boolean,
|
isAlive?: () => boolean,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const bad = (): void => { void emit(JSON.stringify(failedResponse(RETCODE.BAD_REQUEST, 'bad request'))); };
|
const bad = (): Promise<void> => Promise.resolve(
|
||||||
if (!rawRequest.trim()) { bad(); return; }
|
emit(JSON.stringify(failedResponse(RETCODE.BAD_REQUEST, 'bad request'))),
|
||||||
|
);
|
||||||
|
if (!rawRequest.trim()) { await bad(); return; }
|
||||||
|
|
||||||
let action: string;
|
let action: string;
|
||||||
let params: JsonObject;
|
let params: JsonObject;
|
||||||
let echo: JsonValue | undefined;
|
let echo: JsonValue | undefined;
|
||||||
try {
|
try {
|
||||||
const parsed = JSON.parse(rawRequest) as unknown;
|
const parsed = JSON.parse(rawRequest) as unknown;
|
||||||
if (!isJsonObject(parsed)) { bad(); return; }
|
if (!isJsonObject(parsed)) { await bad(); return; }
|
||||||
const a = asString(parsed.action);
|
const a = asString(parsed.action);
|
||||||
if (!a) { bad(); return; }
|
if (!a) { await bad(); return; }
|
||||||
action = a;
|
action = a;
|
||||||
params = isJsonObject(parsed.params) ? parsed.params : {};
|
params = isJsonObject(parsed.params) ? parsed.params : {};
|
||||||
echo = parsed.echo !== undefined ? toJsonValue(parsed.echo) : undefined;
|
echo = parsed.echo !== undefined ? toJsonValue(parsed.echo) : undefined;
|
||||||
} catch {
|
} catch {
|
||||||
bad();
|
await bad();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -164,4 +164,20 @@ describe('Stream API plumbing', () => {
|
|||||||
expect(frames).toHaveLength(3);
|
expect(frames).toHaveLength(3);
|
||||||
for (const f of parse(frames)) expect(f).toMatchObject({ status: 'failed' });
|
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