|
1 | 1 | import { readBoundedResponseText } from "../lib/bounded-response.ts"; |
| 2 | +import { readPositiveIntEnv } from "./lib/env-limits.mjs"; |
2 | 3 | |
3 | 4 | type JsonObject = Record<string, unknown>; |
4 | 5 | |
@@ -11,20 +12,26 @@ type TelegramBotApiOptions = {
|
11 | 12 | |
12 | 13 | const DEFAULT_BASE_URL = |
13 | 14 | process.env.OPENCLAW_TELEGRAM_USER_BOT_API_BASE_URL ?? "https://api.telegram.org"; |
14 | | -const DEFAULT_TIMEOUT_MS = readPositiveInt( |
15 | | -process.env.OPENCLAW_TELEGRAM_USER_BOT_API_TIMEOUT_MS, |
16 | | -30000, |
17 | | -); |
18 | | -const DEFAULT_BODY_MAX_BYTES = readPositiveInt( |
19 | | -process.env.OPENCLAW_TELEGRAM_USER_BOT_API_BODY_MAX_BYTES, |
20 | | -1024 * 1024, |
21 | | -); |
| 15 | +export type TelegramBotApiLimits = { |
| 16 | +bodyMaxBytes: number; |
| 17 | +timeoutMs: number; |
| 18 | +}; |
22 | 19 | |
23 | | -function readPositiveInt(raw: string | undefined, fallback: number) { |
24 | | -const parsed = Number.parseInt(raw ?? "", 10); |
25 | | -return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback; |
| 20 | +export function readTelegramBotApiLimits( |
| 21 | +env: NodeJS.ProcessEnv = process.env, |
| 22 | +): TelegramBotApiLimits { |
| 23 | +return { |
| 24 | +bodyMaxBytes: readPositiveIntEnv( |
| 25 | +"OPENCLAW_TELEGRAM_USER_BOT_API_BODY_MAX_BYTES", |
| 26 | +1024 * 1024, |
| 27 | +env, |
| 28 | +), |
| 29 | +timeoutMs: readPositiveIntEnv("OPENCLAW_TELEGRAM_USER_BOT_API_TIMEOUT_MS", 30000, env), |
| 30 | +}; |
26 | 31 | } |
27 | 32 | |
| 33 | +const DEFAULT_LIMITS = readTelegramBotApiLimits(); |
| 34 | + |
28 | 35 | function optionalString(source: JsonObject, key: string) { |
29 | 36 | const value = source[key]; |
30 | 37 | return typeof value === "string" && value.trim() ? value.trim() : undefined; |
@@ -49,8 +56,8 @@ export async function telegramBotApi(
|
49 | 56 | options: TelegramBotApiOptions = {}, |
50 | 57 | ) { |
51 | 58 | const baseUrl = options.baseUrl ?? DEFAULT_BASE_URL; |
52 | | -const timeoutMs = Math.max(1, options.timeoutMs ?? DEFAULT_TIMEOUT_MS); |
53 | | -const maxBodyBytes = Math.max(1, options.maxBodyBytes ?? DEFAULT_BODY_MAX_BYTES); |
| 59 | +const timeoutMs = Math.max(1, options.timeoutMs ?? DEFAULT_LIMITS.timeoutMs); |
| 60 | +const maxBodyBytes = Math.max(1, options.maxBodyBytes ?? DEFAULT_LIMITS.bodyMaxBytes); |
54 | 61 | const label = `Telegram Bot API ${method}`; |
55 | 62 | const timeoutError = taggedError(`${label} timed out after ${timeoutMs}ms`, "ETIMEDOUT"); |
56 | 63 | const controller = new AbortController(); |
|