All files / scripts/mcp-client/transport timeout.ts

100% Statements 13/13
100% Branches 3/3
100% Functions 2/2
100% Lines 12/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46                        34x                       7x 7x 7x 7x       4x 1x 1x       3x   4x 4x   7x      
/**
 * @module mcp-client/transport/timeout
 * @description Abortable fetch helper for non-MCP external URLs
 * (GitHub raw, regeringen.se, etc.). Wraps `globalThis.fetch` with an
 * `AbortController`-backed timeout so the news pipeline cannot hang on
 * slow public resources.
 *
 * @author Hack23 AB
 * @license Apache-2.0
 */
 
/** Timeout in milliseconds for fetching external URLs (GitHub, etc.) */
export const EXTERNAL_URL_FETCH_TIMEOUT_MS = 15_000;
 
/**
 * Fetch raw text content from an external URL with an abortable timeout.
 * Returns `null` (and emits a `console.warn`) on any non-2xx response or
 * network error — callers treat absence as "content unavailable" rather
 * than fatal.
 */
export async function fetchExternalUrlText(
  rawUrl: string,
  timeoutMs: number = EXTERNAL_URL_FETCH_TIMEOUT_MS,
): Promise<string | null> {
  const controller = new AbortController();
  const timeout = setTimeout(() => controller.abort(), timeoutMs);
  try {
    const response = await fetch(rawUrl, {
      signal: controller.signal,
      headers: { Accept: 'text/plain, text/markdown, text/html, */*' },
    });
    if (!response.ok) {
      console.warn(`⚠️ HTTP ${response.status} fetching external URL: ${rawUrl}`);
      return null;
    }
    // Keep the AbortController active across body consumption so a slow
    // or stalled response body cannot hang the news pipeline indefinitely.
    return await response.text();
  } catch (error: unknown) {
    console.warn(`⚠️ Could not fetch external URL ${rawUrl}: ${(error as Error).message}`);
    return null;
  } finally {
    clearTimeout(timeout);
  }
}