Skip to content

Commit f174acb

Browse files
committed
fix(telegram): bound stalled diagnostic response reads
1 parent 8a2da4b commit f174acb

6 files changed

Lines changed: 471 additions & 7 deletions

File tree

‎extensions/telegram/src/audit-membership-runtime.ts‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
// Telegram plugin module implements audit membership runtime behavior.
22
import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
3-
import { readResponseWithLimit } from "openclaw/plugin-sdk/response-limit-runtime";
43
import { isRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
54
import { fetchWithTimeout } from "openclaw/plugin-sdk/text-utility-runtime";
65
import type {
@@ -10,6 +9,7 @@ import type {
109
} from "./audit.types.js";
1110
import { resolveTelegramApiBase, resolveTelegramFetch } from "./fetch.js";
1211
import { makeProxyFetch } from "./proxy.js";
12+
import { readTelegramResponseBodyWithTimeout } from "./response-body-timeout.js";
1313

1414
type TelegramApiOk<T> = { ok: true; result: T };
1515
type TelegramApiErr = { ok: false; description?: string };
@@ -18,6 +18,20 @@ type TelegramGroupMembershipAuditData = Omit<TelegramGroupMembershipAudit, "elap
1818
const TELEGRAM_BOT_API_MAX_RESPONSE_BYTES = 4 * 1024 * 1024;
1919
type TelegramChatMemberResult = { status?: string };
2020

21+
async function readTelegramMembershipAuditBody(
22+
response: Response,
23+
timeoutMs: number,
24+
): Promise<Buffer> {
25+
return await readTelegramResponseBodyWithTimeout(response, {
26+
maxBytes: TELEGRAM_BOT_API_MAX_RESPONSE_BYTES,
27+
timeoutMs,
28+
onIdleTimeout: ({ timeoutMs: idleTimeoutMs }) =>
29+
new Error(`Telegram membership audit response body stalled for ${idleTimeoutMs}ms`),
30+
onDeadlineTimeout: ({ timeoutMs: deadlineTimeoutMs }) =>
31+
new Error(`Telegram membership audit response body timed out after ${deadlineTimeoutMs}ms`),
32+
});
33+
}
34+
2135
export async function auditTelegramGroupMembershipImpl(
2236
params: AuditTelegramGroupMembershipParams,
2337
): Promise<TelegramGroupMembershipAuditData> {
@@ -34,7 +48,7 @@ export async function auditTelegramGroupMembershipImpl(
3448
const url = `${base}/getChatMember?chat_id=${encodeURIComponent(chatId)}&user_id=${encodeURIComponent(String(params.botId))}`;
3549
const res = await fetchWithTimeout(url, {}, params.timeoutMs, fetcher);
3650
const json = JSON.parse(
37-
(await readResponseWithLimit(res, TELEGRAM_BOT_API_MAX_RESPONSE_BYTES)).toString("utf8"),
51+
(await readTelegramMembershipAuditBody(res, params.timeoutMs)).toString("utf8"),
3852
) as TelegramApiOk<TelegramChatMemberResult> | TelegramApiErr;
3953
if (!res.ok || !isRecord(json) || !json.ok) {
4054
const desc =

‎extensions/telegram/src/audit.test.ts‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,21 @@ async function auditSingleGroup() {
4141
});
4242
}
4343

44+
function makeStallingJsonResponse(payload: unknown, cancel: (reason?: unknown) => void): Response {
45+
return new Response(
46+
new ReadableStream<Uint8Array>({
47+
start(controller) {
48+
controller.enqueue(new TextEncoder().encode(JSON.stringify(payload)));
49+
},
50+
cancel,
51+
}),
52+
{
53+
status: 200,
54+
headers: { "content-type": "application/json" },
55+
},
56+
);
57+
}
58+
4459
describe("telegram audit", () => {
4560
beforeAll(async () => {
4661
vi.doMock("./fetch.js", () => ({
@@ -86,4 +101,34 @@ describe("telegram audit", () => {
86101
expect(res.groups[0]?.ok).toBe(false);
87102
expect(res.groups[0]?.status).toBe("left");
88103
});
104+
105+
it("reports stalled getChatMember response bodies quickly", async () => {
106+
const cancel = vi.fn();
107+
fetchWithTimeoutMock.mockResolvedValueOnce(
108+
makeStallingJsonResponse({ ok: true, result: { status: "member" } }, cancel),
109+
);
110+
111+
vi.useFakeTimers();
112+
try {
113+
const auditPromise = auditTelegramGroupMembership({
114+
token: "t",
115+
botId: 123,
116+
groupIds: ["-1001"],
117+
timeoutMs: 50,
118+
});
119+
await vi.advanceTimersByTimeAsync(0);
120+
await vi.advanceTimersByTimeAsync(60);
121+
122+
const res = await auditPromise;
123+
expect(res.ok).toBe(false);
124+
expect(res.groups[0]?.ok).toBe(false);
125+
expect(res.groups[0]?.error).toBe(
126+
"Telegram membership audit response body stalled for 25ms",
127+
);
128+
expect(cancel).toHaveBeenCalledTimes(1);
129+
expect(cancel.mock.calls[0]?.[0]).toBeInstanceOf(Error);
130+
} finally {
131+
vi.useRealTimers();
132+
}
133+
});
89134
});
Lines changed: 168 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,168 @@
1+
// Telegram tests cover stalled diagnostic response body handling.
2+
import { afterEach, describe, expect, it, vi, type Mock } from "vitest";
3+
import { probeTelegram, resetTelegramProbeFetcherCacheForTests } from "./probe.js";
4+
5+
const resolveTelegramTransport = vi.hoisted(() => vi.fn());
6+
const makeProxyFetch = vi.hoisted(() => vi.fn());
7+
8+
vi.mock("./fetch.js", () => ({
9+
resolveTelegramTransport,
10+
resolveTelegramApiBase: (apiRoot?: string) =>
11+
apiRoot?.trim()?.replace(/\/+$/, "") || "https://api.telegram.org",
12+
}));
13+
14+
vi.mock("./proxy.js", () => ({
15+
makeProxyFetch,
16+
}));
17+
18+
function installFetchMock(): Mock {
19+
const fetchMock = vi.fn();
20+
resolveTelegramTransport.mockImplementation((proxyFetch?: typeof fetch) => ({
21+
fetch: proxyFetch ?? (fetchMock as unknown as typeof fetch),
22+
sourceFetch: proxyFetch ?? (fetchMock as unknown as typeof fetch),
23+
forceFallback: vi.fn().mockReturnValue(true),
24+
close: async () => {},
25+
}));
26+
makeProxyFetch.mockImplementation(() => fetchMock as unknown as typeof fetch);
27+
return fetchMock;
28+
}
29+
30+
function makeJsonResponse(payload: unknown): Response {
31+
return new Response(JSON.stringify(payload), {
32+
status: 200,
33+
headers: { "content-type": "application/json" },
34+
});
35+
}
36+
37+
function makeStallingJsonResponse(payload: unknown, cancel: (reason?: unknown) => void): Response {
38+
return new Response(
39+
new ReadableStream<Uint8Array>({
40+
start(controller) {
41+
controller.enqueue(new TextEncoder().encode(JSON.stringify(payload)));
42+
},
43+
cancel,
44+
}),
45+
{
46+
status: 200,
47+
headers: { "content-type": "application/json" },
48+
},
49+
);
50+
}
51+
52+
function makeTricklingJsonResponse(cancel: (reason?: unknown) => void): Response {
53+
const encoder = new TextEncoder();
54+
let timer: ReturnType<typeof setTimeout> | undefined;
55+
let cancelled = false;
56+
const response = new Response(
57+
new ReadableStream<Uint8Array>({
58+
start(controller) {
59+
let index = 0;
60+
const chunks = ["{", '"ok"', ":", "true", ","];
61+
const enqueue = () => {
62+
if (cancelled) {
63+
return;
64+
}
65+
controller.enqueue(encoder.encode(chunks[index % chunks.length]));
66+
index += 1;
67+
timer = setTimeout(enqueue, 40);
68+
};
69+
enqueue();
70+
},
71+
cancel(reason) {
72+
cancelled = true;
73+
if (timer) {
74+
clearTimeout(timer);
75+
}
76+
cancel(reason);
77+
},
78+
}),
79+
{
80+
status: 200,
81+
headers: { "content-type": "application/json" },
82+
},
83+
);
84+
return response;
85+
}
86+
87+
describe("probeTelegram response body timeouts", () => {
88+
afterEach(() => {
89+
resetTelegramProbeFetcherCacheForTests();
90+
resolveTelegramTransport.mockReset();
91+
makeProxyFetch.mockReset();
92+
vi.useRealTimers();
93+
vi.clearAllMocks();
94+
});
95+
96+
it("fails quickly when getMe returns a stalled response body", async () => {
97+
const fetchMock = installFetchMock();
98+
const cancel = vi.fn();
99+
fetchMock.mockResolvedValueOnce(
100+
makeStallingJsonResponse(
101+
{
102+
ok: true,
103+
result: { id: 123, is_bot: true, first_name: "Test", username: "bot" },
104+
},
105+
cancel,
106+
),
107+
);
108+
109+
vi.useFakeTimers();
110+
const probePromise = probeTelegram("placeholder", 50, {
111+
includeWebhookInfo: false,
112+
});
113+
await vi.advanceTimersByTimeAsync(0);
114+
await vi.advanceTimersByTimeAsync(60);
115+
116+
const result = await probePromise;
117+
expect(result.ok).toBe(false);
118+
expect(result.error).toBe("Telegram diagnostic response body stalled for 25ms");
119+
expect(fetchMock).toHaveBeenCalledTimes(1);
120+
expect(cancel).toHaveBeenCalledTimes(1);
121+
expect(cancel.mock.calls[0]?.[0]).toBeInstanceOf(Error);
122+
});
123+
124+
it("fails on the body deadline when getMe trickles without becoming complete JSON", async () => {
125+
const fetchMock = installFetchMock();
126+
const cancel = vi.fn();
127+
vi.useFakeTimers();
128+
fetchMock.mockResolvedValueOnce(makeTricklingJsonResponse(cancel));
129+
130+
const probePromise = probeTelegram("placeholder", 100, {
131+
includeWebhookInfo: false,
132+
});
133+
await vi.advanceTimersByTimeAsync(0);
134+
await vi.advanceTimersByTimeAsync(120);
135+
136+
const result = await probePromise;
137+
expect(result.ok).toBe(false);
138+
expect(result.error).toBe("Telegram diagnostic response body timed out after 100ms");
139+
expect(fetchMock).toHaveBeenCalledTimes(1);
140+
expect(cancel).toHaveBeenCalledTimes(1);
141+
expect(cancel.mock.calls[0]?.[0]).toBeInstanceOf(Error);
142+
});
143+
144+
it("keeps webhook diagnostics best-effort when webhookInfo response body stalls", async () => {
145+
const fetchMock = installFetchMock();
146+
const cancel = vi.fn();
147+
fetchMock.mockResolvedValueOnce(
148+
makeJsonResponse({
149+
ok: true,
150+
result: { id: 123, is_bot: true, first_name: "Test", username: "bot" },
151+
}),
152+
);
153+
fetchMock.mockResolvedValueOnce(
154+
makeStallingJsonResponse({ ok: true, result: { url: "https://example.test/hook" } }, cancel),
155+
);
156+
157+
vi.useFakeTimers();
158+
const probePromise = probeTelegram("placeholder", 50);
159+
await vi.advanceTimersByTimeAsync(0);
160+
await vi.advanceTimersByTimeAsync(60);
161+
162+
const result = await probePromise;
163+
expect(result.ok).toBe(true);
164+
expect(result.webhook).toBeUndefined();
165+
expect(fetchMock).toHaveBeenCalledTimes(2);
166+
expect(cancel).toHaveBeenCalledTimes(1);
167+
});
168+
});

‎extensions/telegram/src/probe.ts‎

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
import type { BaseProbeResult } from "openclaw/plugin-sdk/channel-contract";
33
import type { TelegramNetworkConfig } from "openclaw/plugin-sdk/config-contracts";
44
import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
5-
import { readResponseWithLimit } from "openclaw/plugin-sdk/response-limit-runtime";
65
import { fetchWithTimeout } from "openclaw/plugin-sdk/text-utility-runtime";
76
import { normalizeTelegramBotInfo, type TelegramBotInfo } from "./bot-info.js";
87
import {
@@ -11,6 +10,7 @@ import {
1110
type TelegramTransport,
1211
} from "./fetch.js";
1312
import { makeProxyFetch } from "./proxy.js";
13+
import { readTelegramResponseBodyWithTimeout } from "./response-body-timeout.js";
1414

1515
export type TelegramProbe = BaseProbeResult & {
1616
status?: number | null;
@@ -121,6 +121,20 @@ function normalizeBoolean(value: unknown): boolean | null {
121121
return typeof value === "boolean" ? value : null;
122122
}
123123

124+
async function readTelegramDiagnosticBody(
125+
response: Response,
126+
timeoutMs: number,
127+
): Promise<Buffer> {
128+
return await readTelegramResponseBodyWithTimeout(response, {
129+
maxBytes: TELEGRAM_BOT_API_MAX_RESPONSE_BYTES,
130+
timeoutMs,
131+
onIdleTimeout: ({ timeoutMs: idleTimeoutMs }) =>
132+
new Error(`Telegram diagnostic response body stalled for ${idleTimeoutMs}ms`),
133+
onDeadlineTimeout: ({ timeoutMs: deadlineTimeoutMs }) =>
134+
new Error(`Telegram diagnostic response body timed out after ${deadlineTimeoutMs}ms`),
135+
});
136+
}
137+
124138
export async function probeTelegram(
125139
token: string,
126140
timeoutMs: number,
@@ -193,7 +207,12 @@ export async function probeTelegram(
193207
}
194208

195209
const meJson = JSON.parse(
196-
(await readResponseWithLimit(meRes, TELEGRAM_BOT_API_MAX_RESPONSE_BYTES)).toString("utf8"),
210+
(
211+
await readTelegramDiagnosticBody(
212+
meRes,
213+
Math.min(timeoutBudgetMs, resolveRemainingBudgetMs()),
214+
)
215+
).toString("utf8"),
197216
) as {
198217
ok?: boolean;
199218
description?: string;
@@ -238,9 +257,12 @@ export async function probeTelegram(
238257
fetcher,
239258
);
240259
const webhookJson = JSON.parse(
241-
(await readResponseWithLimit(webhookRes, TELEGRAM_BOT_API_MAX_RESPONSE_BYTES)).toString(
242-
"utf8",
243-
),
260+
(
261+
await readTelegramDiagnosticBody(
262+
webhookRes,
263+
Math.min(timeoutBudgetMs, resolveRemainingBudgetMs()),
264+
)
265+
).toString("utf8"),
244266
) as {
245267
ok?: boolean;
246268
result?: { url?: string; has_custom_certificate?: boolean };
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
// Telegram tests cover bounded Bot API response body helper behavior.
2+
import { describe, expect, it, vi } from "vitest";
3+
import { readTelegramResponseBodyWithTimeout } from "./response-body-timeout.js";
4+
5+
function makeOptions(overrides?: { maxBytes?: number; timeoutMs?: number }) {
6+
return {
7+
maxBytes: overrides?.maxBytes ?? 16,
8+
timeoutMs: overrides?.timeoutMs ?? 100,
9+
onIdleTimeout: ({ timeoutMs }: { timeoutMs: number }) => new Error(`idle ${timeoutMs}`),
10+
onDeadlineTimeout: ({ timeoutMs }: { timeoutMs: number }) => new Error(`deadline ${timeoutMs}`),
11+
};
12+
}
13+
14+
describe("readTelegramResponseBodyWithTimeout", () => {
15+
it("cancels streamed response bodies when they exceed the byte cap", async () => {
16+
const cancel = vi.fn();
17+
const response = new Response(
18+
new ReadableStream<Uint8Array>({
19+
start(controller) {
20+
controller.enqueue(new Uint8Array([1, 2, 3]));
21+
},
22+
cancel,
23+
}),
24+
{ status: 200 },
25+
);
26+
27+
await expect(
28+
readTelegramResponseBodyWithTimeout(response, makeOptions({ maxBytes: 2 })),
29+
).rejects.toThrow("Content too large: 3 bytes (limit: 2 bytes)");
30+
expect(cancel).toHaveBeenCalledTimes(1);
31+
});
32+
33+
it("fails and cancels getReader-less response bodies on the deadline", async () => {
34+
vi.useFakeTimers();
35+
try {
36+
const cancel = vi.fn(async () => undefined);
37+
const response = {
38+
body: { cancel },
39+
arrayBuffer: async () => await new Promise<ArrayBuffer>(() => {}),
40+
} as unknown as Response;
41+
42+
const read = readTelegramResponseBodyWithTimeout(response, makeOptions({ timeoutMs: 50 }));
43+
const assertion = expect(read).rejects.toThrow("deadline 50");
44+
45+
await vi.advanceTimersByTimeAsync(50);
46+
await assertion;
47+
expect(cancel).toHaveBeenCalledTimes(1);
48+
expect(cancel.mock.calls[0]?.[0]).toBeInstanceOf(Error);
49+
} finally {
50+
vi.useRealTimers();
51+
}
52+
});
53+
});

0 commit comments

Comments
 (0)