-
Notifications
You must be signed in to change notification settings - Fork 2.2k
fix(telegram): add socket timeout and extract tgApi into shared module #1399
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
tommylin-signalpro
wants to merge
5
commits into
NVIDIA:main
Choose a base branch
from
tommylin-signalpro:refactor/telegram-api-module
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+251
−22
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
241c738
refactor(telegram): extract tgApi into shared module with socket timeout
tommylin-signalpro 5bc35da
fix(telegram): handle mid-response errors and improve test teardown
tommylin-signalpro fb945d8
Merge branch 'main' into refactor/telegram-api-module
tommylin-signalpro 891ab5f
fix(telegram): set UTF-8 encoding on response stream
tommylin-signalpro ee9cf0d
Merge branch 'main' into refactor/telegram-api-module
tommylin-signalpro File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,77 @@ | ||
| // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| /** | ||
| * Telegram Bot API client with socket timeout protection. | ||
| * | ||
| * Exported so both the bridge script and tests use the same implementation. | ||
| */ | ||
|
|
||
| const https = require("https"); | ||
|
|
||
| const DEFAULT_TIMEOUT_MS = 60000; | ||
|
|
||
| /** | ||
| * Call a Telegram Bot API method. | ||
| * | ||
| * @param {string} token — Bot token from @BotFather | ||
| * @param {string} method — API method name (e.g. "getUpdates") | ||
| * @param {object} body — JSON-serialisable request body | ||
| * @param {object} [opts] | ||
| * @param {number} [opts.timeout] — socket idle timeout in ms (default 60 000) | ||
| * @param {string} [opts.hostname] — override hostname (useful for tests) | ||
| * @param {number} [opts.port] — override port (useful for tests) | ||
| * @param {boolean} [opts.rejectUnauthorized] — TLS cert check (default true) | ||
| * @returns {Promise<object>} parsed JSON response | ||
| */ | ||
| function tgApi(token, method, body, opts = {}) { | ||
| const { | ||
| timeout = DEFAULT_TIMEOUT_MS, | ||
| hostname = "api.telegram.org", | ||
| port, | ||
| rejectUnauthorized, | ||
| } = opts; | ||
|
|
||
| return new Promise((resolve, reject) => { | ||
| let settled = false; | ||
| const settle = (fn, value) => { | ||
| if (settled) return; | ||
| settled = true; | ||
| fn(value); | ||
| }; | ||
|
|
||
| const data = JSON.stringify(body); | ||
| const reqOpts = { | ||
| hostname, | ||
| path: `/bot${token}/${method}`, | ||
| method: "POST", | ||
| timeout, | ||
| headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(data) }, | ||
| }; | ||
| if (port != null) reqOpts.port = port; | ||
| if (rejectUnauthorized != null) reqOpts.rejectUnauthorized = rejectUnauthorized; | ||
|
|
||
| const req = https.request(reqOpts, (res) => { | ||
| let buf = ""; | ||
| res.setEncoding("utf8"); | ||
| res.on("data", (c) => (buf += c)); | ||
| res.on("aborted", () => settle(reject, new Error(`Telegram API ${method} response aborted`))); | ||
| res.on("error", (err) => settle(reject, err)); | ||
| res.on("end", () => { | ||
| try { | ||
| settle(resolve, JSON.parse(buf)); | ||
| } catch { | ||
| settle(resolve, { ok: false, error: buf }); | ||
| } | ||
| }); | ||
| }); | ||
| req.on("timeout", () => { | ||
| req.destroy(new Error(`Telegram API ${method} timed out`)); | ||
| }); | ||
| req.on("error", (err) => settle(reject, err)); | ||
| req.write(data); | ||
| req.end(); | ||
| }); | ||
| } | ||
|
|
||
| module.exports = { tgApi, DEFAULT_TIMEOUT_MS }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,172 @@ | ||
| // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| /** | ||
| * Tests for bin/lib/telegram-api.js — the shared Telegram API client. | ||
| * | ||
| * Uses local TLS servers to simulate Telegram API behavior without | ||
| * hitting the real API. Verifies socket timeout, recovery, and error | ||
| * handling using the actual production tgApi function. | ||
| */ | ||
|
|
||
| import { describe, it, expect, afterEach } from "vitest"; | ||
| import { createRequire } from "node:module"; | ||
| import https from "node:https"; | ||
| import net from "node:net"; | ||
| import { execFileSync } from "node:child_process"; | ||
| import fs from "node:fs"; | ||
| import path from "node:path"; | ||
|
|
||
| const require = createRequire(import.meta.url); | ||
| const { tgApi } = require("../bin/lib/telegram-api"); | ||
|
|
||
| // ── Self-signed cert for local test servers ────────────────────────── | ||
| const tmpDir = fs.mkdtempSync("/tmp/tg-api-test-"); | ||
| const keyPath = path.join(tmpDir, "key.pem"); | ||
| const certPath = path.join(tmpDir, "cert.pem"); | ||
| execFileSync( | ||
| "openssl", | ||
| [ | ||
| "req", | ||
| "-x509", | ||
| "-newkey", | ||
| "rsa:2048", | ||
| "-keyout", | ||
| keyPath, | ||
| "-out", | ||
| certPath, | ||
| "-days", | ||
| "1", | ||
| "-nodes", | ||
| "-subj", | ||
| "/CN=localhost", | ||
| ], | ||
| { stdio: "ignore" }, | ||
| ); | ||
| const key = fs.readFileSync(keyPath); | ||
| const cert = fs.readFileSync(certPath); | ||
| fs.rmSync(tmpDir, { recursive: true }); | ||
|
|
||
| // ── Helpers ────────────────────────────────────────────────────────── | ||
| const servers = []; | ||
|
|
||
| function createServer(handler) { | ||
| return new Promise((resolve) => { | ||
| const server = https.createServer({ key, cert }, handler); | ||
| server.listen(0, "127.0.0.1", () => { | ||
| servers.push(server); | ||
| const { port } = server.address(); | ||
| resolve({ server, port }); | ||
| }); | ||
| }); | ||
| } | ||
|
|
||
| /** Build opts that point tgApi at a local test server. */ | ||
| function localOpts(port, timeoutMs = 2000) { | ||
| return { hostname: "127.0.0.1", port, timeout: timeoutMs, rejectUnauthorized: false }; | ||
| } | ||
|
|
||
| afterEach(async () => { | ||
| const toClose = servers.splice(0, servers.length); | ||
| await Promise.all( | ||
| toClose.map( | ||
| (s) => | ||
| new Promise((resolve) => { | ||
| if (s.closeAllConnections) s.closeAllConnections(); | ||
| s.close(() => resolve()); | ||
| }), | ||
| ), | ||
| ); | ||
| }); | ||
|
|
||
| // ── Tests ──────────────────────────────────────────────────────────── | ||
|
|
||
| describe("tgApi (bin/lib/telegram-api)", () => { | ||
| it("resolves normally when server responds promptly", async () => { | ||
| const { port } = await createServer((_req, res) => { | ||
| res.writeHead(200, { "Content-Type": "application/json" }); | ||
| res.end(JSON.stringify({ ok: true, result: { update_id: 1 } })); | ||
| }); | ||
|
|
||
| const result = await tgApi("fake-token", "getUpdates", { offset: 0 }, localOpts(port)); | ||
| expect(result.ok).toBe(true); | ||
| }); | ||
|
|
||
| it("rejects with timeout when server hangs (simulates network drop)", async () => { | ||
| const { port } = await createServer(() => { | ||
| // never respond — simulates dead TCP connection | ||
| }); | ||
|
|
||
| const start = Date.now(); | ||
| await expect( | ||
| tgApi("fake-token", "getUpdates", { offset: 0 }, localOpts(port, 1000)), | ||
| ).rejects.toThrow("timed out"); | ||
| const elapsed = Date.now() - start; | ||
| expect(elapsed).toBeGreaterThanOrEqual(900); | ||
| expect(elapsed).toBeLessThan(5000); | ||
| }); | ||
|
|
||
| it("timeout fires within expected window", async () => { | ||
| const { port } = await createServer(() => { | ||
| /* never respond */ | ||
| }); | ||
|
|
||
| const start = Date.now(); | ||
| await expect( | ||
| tgApi("fake-token", "getUpdates", { offset: 0 }, localOpts(port, 500)), | ||
| ).rejects.toThrow("timed out"); | ||
| const elapsed = Date.now() - start; | ||
| expect(elapsed).toBeGreaterThanOrEqual(450); | ||
| expect(elapsed).toBeLessThan(2000); | ||
| }); | ||
|
|
||
| it("poll loop recovers after timeout", async () => { | ||
| let reqCount = 0; | ||
| const { port } = await createServer((_req, res) => { | ||
| reqCount++; | ||
| if (reqCount === 1) return; // first: hang | ||
| res.writeHead(200, { "Content-Type": "application/json" }); | ||
| res.end(JSON.stringify({ ok: true, result: [] })); | ||
| }); | ||
|
|
||
| // First call: timeout | ||
| await expect( | ||
| tgApi("fake-token", "getUpdates", { offset: 0 }, localOpts(port, 500)), | ||
| ).rejects.toThrow("timed out"); | ||
|
|
||
| // Second call: should succeed (poll loop recovery) | ||
| const result = await tgApi("fake-token", "getUpdates", { offset: 0 }, localOpts(port, 500)); | ||
| expect(result.ok).toBe(true); | ||
| }); | ||
|
|
||
| it("rejects when server closes connection mid-response", async () => { | ||
| const { port } = await createServer((req, res) => { | ||
| res.writeHead(200, { "Content-Type": "application/json" }); | ||
| res.write('{"ok":'); | ||
| setTimeout(() => req.socket.destroy(), 50); | ||
| }); | ||
|
|
||
| // With res.on("aborted") and res.on("error") handlers, a | ||
| // mid-response socket destroy now rejects instead of hanging. | ||
| const result = await Promise.race([ | ||
| tgApi("fake-token", "getUpdates", { offset: 0 }, localOpts(port, 2000)) | ||
| .then(() => "resolved") | ||
| .catch(() => "rejected"), | ||
| new Promise((r) => setTimeout(() => r("hung"), 3000)), | ||
| ]); | ||
| expect(result).not.toBe("hung"); | ||
| }); | ||
|
|
||
| it("handles connection refused (server down)", async () => { | ||
| const tempServer = net.createServer(); | ||
| await new Promise((r) => tempServer.listen(0, "127.0.0.1", r)); | ||
| const { port } = tempServer.address(); | ||
| await new Promise((resolve, reject) => | ||
| tempServer.close((err) => (err ? reject(err) : resolve())), | ||
| ); | ||
|
|
||
| await expect( | ||
| tgApi("fake-token", "getUpdates", { offset: 0 }, localOpts(port, 2000)), | ||
| ).rejects.toThrow(); | ||
| }); | ||
| }); |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.