All files / src/api client.ts

87.01% Statements 181/208
77.55% Branches 76/98
89.65% Functions 26/29
88.83% Lines 175/197

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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 5074x 4x             4x             4x               21x             10x 10x   5x 5x 1x     4x 4x 3x 3x     1x               13x   1x 1x     12x 12x   12x       4x 4x 4x       50x           13x 2x 2x   11x       11x 11x     11x 11x     9x 9x 9x 9x     2x 2x 2x 2x     2x     11x 11x       11x 1x           13x 13x             7x 7x 7x                   7x 7x             4x           37x   37x 37x       37x 48x 48x 48x 42x 29x   13x 13x 13x 10x 10x 10x       10x   3x     11x 11x 3x   8x 3x   5x 3x 3x       3x   2x                   4x         9x 9x   3x     3x 3x                 4x           10x                           9x 3x     6x 6x 6x     6x           4x             1x                               1x 1x                                             4x               13x 13x                               11x 3x           8x             8x 8x     8x   8x             8x 8x 8x 8x     17x         17x       17x 17x 17x 13x     13x 13x 13x 13x   17x 4x     4x 4x 4x 4x     17x 1x 1x     17x 3x   3x       3x         3x 3x 3x     17x       17x 1x 1x     16x   13x                 8x 8x 17x 13x   9x 9x   9x 9x 9x   9x 16x 16x 8x 8x 4x 4x 3x               4x 4x 4x 4x 4x 4x                     4x 3x 3x 3x                       1x 1x       8x      
import { ConfigManager } from "../shared/config";
import {
  BASE_RETRY_DELAY_MS,
  BASE_URL,
  MAX_RETRY_DELAY_MS,
  STREAM_IDLE_TIMEOUT_MAX_MS,
  STREAM_IDLE_TIMEOUT_MIN_MS,
} from "../shared/constants";
import { debugLog } from "../shared/logging";
import {
  NvidiaModelListResponse,
  NvidiaModelSummary,
  NimChatRequest,
  NimStreamResponse,
} from "../types";
import { classifyApiError, isRetryableApiStatus, NvidiaApiError } from "./errors";
 
/**
 * Determine whether an HTTP status code is safe to retry.
 * Retries on 429 (rate limit), 529 (overloaded), 502, 503, 504 (server errors).
 * Never retries on 400, 401, 403, 404, 422 (client errors).
 */
function isRetryableHttpError(status: number): boolean {
  return isRetryableApiStatus(status);
}
 
/**
 * Read Retry-After header value (seconds or HTTP-date) if present.
 */
function getRetryAfterMs(response: Response): number | undefined {
  const raw = response.headers?.get("retry-after");
  if (!raw) return undefined;
 
  const seconds = Number.parseInt(raw, 10);
  if (Number.isFinite(seconds) && seconds > 0) {
    return seconds * 1000;
  }
 
  const dateValue = Date.parse(raw);
  if (Number.isFinite(dateValue)) {
    const deltaMs = dateValue - Date.now();
    return deltaMs > 0 ? deltaMs : undefined;
  }
 
  return undefined;
}
 
/**
 * Calculate delay with exponential backoff and full jitter.
 * This prevents thundering herd when multiple clients retry simultaneously.
 */
function calculateRetryDelay(attempt: number, retryAfter?: number): number {
  if (retryAfter !== undefined && retryAfter > 0) {
    // Add jitter to server-provided retry-after (±25%)
    const jitter = retryAfter * 0.25 * (Math.random() * 2 - 1);
    return Math.min(Math.max(Math.round(retryAfter + jitter), 0), MAX_RETRY_DELAY_MS);
  }
 
  const exponentialDelay = BASE_RETRY_DELAY_MS * Math.pow(2, attempt);
  const cappedDelay = Math.min(exponentialDelay, MAX_RETRY_DELAY_MS);
  // Full jitter: random delay between 0 and cappedDelay
  return Math.round(Math.random() * cappedDelay);
}
 
function createAbortError(): Error {
  const error = new Error("The operation was aborted");
  error.name = "AbortError";
  return error;
}
 
function throwIfAborted(signal: AbortSignal | undefined): void {
  Iif (signal?.aborted) {
    throw createAbortError();
  }
}
 
function waitForRetry(delayMs: number, signal: AbortSignal | undefined): Promise<void> {
  if (delayMs <= 0) {
    throwIfAborted(signal);
    return Promise.resolve();
  }
  Iif (signal?.aborted) {
    return Promise.reject(createAbortError());
  }
 
  return new Promise<void>((resolve, reject) => {
    let settled = false;
 
    function cleanup(): void {
      clearTimeout(timeoutId);
      signal?.removeEventListener("abort", onAbort);
    }
    function resolveOnce(): void {
      Iif (settled) return;
      settled = true;
      cleanup();
      resolve();
    }
    function rejectOnce(error: Error): void {
      Iif (settled) return;
      settled = true;
      cleanup();
      reject(error);
    }
    function onAbort(): void {
      rejectOnce(createAbortError());
    }
 
    const timeoutId = setTimeout(resolveOnce, delayMs);
    signal?.addEventListener("abort", onAbort, { once: true });
    // The signal can be aborted between the pre-subscription check above and
    // registering the listener. Re-check after subscribing so that narrow
    // race cannot leave the retry sleeping until the full backoff expires.
    if (signal?.aborted) {
      onAbort();
    }
  });
}
 
async function discardResponseBody(response: Response): Promise<void> {
  try {
    await response.body?.cancel();
  } catch {
    // Cleanup must never mask the original retryable failure.
  }
}
 
async function readResponseDetail(response: Response): Promise<string | undefined> {
  try {
    const detail = await response.text();
    return detail || undefined;
  } catch {
    return undefined;
  }
}
 
async function classifyResponseError(
  response: Response,
  context: { operation: string; model?: string },
): Promise<Error> {
  const detail = await readResponseDetail(response);
  return classifyApiError(new Error(`HTTP ${response.status} ${response.statusText}`), {
    ...context,
    status: response.status,
    detail,
  });
}
 
export async function fetchWithRetry(
  url: string,
  init: RequestInit,
  retries?: number,
  errorContext: { operation?: string; model?: string } = {},
): Promise<Response> {
  const maxRetries = retries ?? ConfigManager.getNetworkConfig().maxHttpRetries;
  let lastError: Error | undefined;
  const signal = init.signal ?? undefined;
  const classificationContext = {
    operation: errorContext.operation ?? "request",
    ...(errorContext.model ? { model: errorContext.model } : {}),
  };
  for (let i = 0; i < maxRetries; i++) {
    throwIfAborted(signal);
    try {
      const response = await fetch(url, init);
      if (response.ok || !isRetryableHttpError(response.status)) {
        return response;
      }
      lastError = new Error(`HTTP ${response.status} ${response.statusText}`);
      await discardResponseBody(response);
      if (i < maxRetries - 1) {
        const retryAfter = getRetryAfterMs(response);
        const delay = calculateRetryDelay(i, retryAfter);
        debugLog(
          "fetchWithRetry",
          `Attempt ${i + 1} failed with ${response.status}, retrying after ${delay}ms`,
        );
        await waitForRetry(delay, signal);
      } else {
        throw classifyApiError(lastError, { status: response.status, ...classificationContext });
      }
    } catch (error) {
      lastError = error instanceof Error ? error : new Error(String(error));
      if (lastError.name === "AbortError" || signal?.aborted) {
        throw lastError;
      }
      if (lastError instanceof NvidiaApiError) {
        throw lastError;
      }
      if (i < maxRetries - 1) {
        const delay = calculateRetryDelay(i);
        debugLog(
          "fetchWithRetry",
          `Attempt ${i + 1} failed with network error, retrying after ${delay}ms`,
        );
        await waitForRetry(delay, signal);
      } else {
        throw classifyApiError(lastError, classificationContext);
      }
    }
  }
  throw classifyApiError(
    lastError ?? new Error("Network request failed after retries"),
    classificationContext,
  );
}
 
export async function fetchModels(
  apiKey: string,
  signal?: AbortSignal,
  userAgent?: string,
): Promise<NvidiaModelSummary[] | null> {
  try {
    return await fetchModelsOrThrow(apiKey, signal, userAgent);
  } catch (error) {
    Iif (error instanceof Error && error.name === "AbortError") {
      throw error;
    }
    debugLog("fetchModels", classifyApiError(error, { operation: "models" }));
    return null;
  }
}
 
/**
 * Fetch the model list while preserving structured API failures for callers
 * such as manual refresh. `fetchModels` remains the nullable compatibility
 * wrapper used by older integrations.
 */
export async function fetchModelsOrThrow(
  apiKey: string,
  signal?: AbortSignal,
  userAgent?: string,
  retries?: number,
): Promise<NvidiaModelSummary[]> {
  const response = await fetchWithRetry(
    `${BASE_URL}/models`,
    {
      method: "GET",
      headers: {
        Authorization: `Bearer ${apiKey}`,
        "Content-Type": "application/json",
        ...(userAgent ? { "User-Agent": userAgent } : {}),
      },
      signal,
    },
    retries ?? ConfigManager.getNetworkConfig().maxHttpRetries,
    { operation: "models" },
  );
  if (!response.ok) {
    throw await classifyResponseError(response, { operation: "models" });
  }
 
  try {
    const data = (await response.json()) as NvidiaModelListResponse;
    Iif (!Array.isArray(data.data)) {
      throw new Error("NVIDIA NIM models response did not contain a data array");
    }
    return data.data;
  } catch (error) {
    throw classifyApiError(error, { operation: "models" });
  }
}
 
export async function chatCompletion(
  apiKey: string,
  requestBody: NimChatRequest,
  signal?: AbortSignal,
  userAgent?: string,
  retries?: number,
): Promise<string> {
  const response = await fetchWithRetry(
    `${BASE_URL}/chat/completions`,
    {
      method: "POST",
      headers: {
        Authorization: `Bearer ${apiKey}`,
        "Content-Type": "application/json",
        ...(userAgent ? { "User-Agent": userAgent } : {}),
      },
      body: JSON.stringify({ ...requestBody, stream: false }),
      signal,
    },
    retries ?? ConfigManager.getNetworkConfig().maxHttpRetries,
    { operation: "completion", model: requestBody.model },
  );
 
  if (!response.ok) {
    throw await classifyResponseError(response, {
      operation: "completion",
      model: requestBody.model,
    });
  }
 
  try {
    const data = (await response.json()) as {
      choices?: Array<{ message?: { content?: string } }>;
    };
    return data.choices?.[0]?.message?.content ?? "";
  } catch (error) {
    throw classifyApiError(error, { operation: "completion", model: requestBody.model });
  }
}
 
export interface StreamChatCompletionOptions {
  maxOutputTokens?: number;
  maxFetchAttempts?: number;
  idleTimeoutMs?: number;
  firstTokenTimeoutMs?: number;
}
 
export async function* streamChatCompletion(
  apiKey: string,
  requestBody: NimChatRequest,
  signal?: AbortSignal,
  userAgent?: string,
  options?: StreamChatCompletionOptions,
): AsyncGenerator<NimStreamResponse, void, unknown> {
  const fetchAttempts =
    options?.maxFetchAttempts ?? ConfigManager.getNetworkConfig().maxHttpRetries;
  const response = await fetchWithRetry(
    `${BASE_URL}/chat/completions`,
    {
      method: "POST",
      headers: {
        Authorization: `Bearer ${apiKey}`,
        "Content-Type": "application/json",
        ...(userAgent ? { "User-Agent": userAgent } : {}),
      },
      body: JSON.stringify(requestBody),
      signal,
    },
    Math.max(1, fetchAttempts),
    { operation: "stream", model: requestBody.model },
  );
 
  if (!response.ok) {
    throw await classifyResponseError(response, {
      operation: "stream",
      model: requestBody.model,
    });
  }
 
  Iif (!response.body) {
    throw classifyApiError(new Error("No response body from NVIDIA NIM API"), {
      operation: "stream",
      model: requestBody.model,
    });
  }
 
  const reader = response.body.getReader();
  const decoder = new TextDecoder();
 
  const configuredIdleTimeoutMs =
    options?.idleTimeoutMs ?? ConfigManager.getNetworkConfig().streamIdleTimeout * 1000;
 
  const idleTimeoutMs = options?.maxOutputTokens
    ? Math.min(
        STREAM_IDLE_TIMEOUT_MAX_MS,
        Math.max(STREAM_IDLE_TIMEOUT_MIN_MS, Math.round(options.maxOutputTokens / 10) * 1000),
      )
    : configuredIdleTimeoutMs;
 
  const firstTokenTimeoutMs = options?.firstTokenTimeoutMs;
  let isFirstChunk = true;
  let buffer = "";
  let lastChunkTime = Date.now();
 
  function readWithTimeout() {
    Iif (signal?.aborted) {
      return Promise.reject(createAbortError());
    }
 
    const currentTimeoutMs =
      isFirstChunk && typeof firstTokenTimeoutMs === "number" && firstTokenTimeoutMs > 0
        ? Math.min(idleTimeoutMs, firstTokenTimeoutMs)
        : idleTimeoutMs;
 
    return new Promise<Awaited<ReturnType<typeof reader.read>>>((resolve, reject) => {
      let settled = false;
      const resolveOnce = (result: Awaited<ReturnType<typeof reader.read>>) => {
        Iif (settled) {
          return;
        }
        settled = true;
        clearTimeout(timeoutId);
        signal?.removeEventListener("abort", onAbort);
        resolve(result);
      };
      const rejectOnce = (error: unknown) => {
        Iif (settled) {
          return;
        }
        settled = true;
        clearTimeout(timeoutId);
        signal?.removeEventListener("abort", onAbort);
        reject(error);
      };
 
      const onAbort = (): void => {
        void reader.cancel(createAbortError()).catch(() => undefined);
        rejectOnce(createAbortError());
      };
 
      const timeoutId = setTimeout(() => {
        const idleSec = Math.round((Date.now() - lastChunkTime) / 1000);
        const isFirstTokenTimeout =
          isFirstChunk &&
          typeof firstTokenTimeoutMs === "number" &&
          firstTokenTimeoutMs > 0 &&
          currentTimeoutMs === firstTokenTimeoutMs;
        const err = new Error(
          isFirstTokenTimeout
            ? `NVIDIA NIM first token timeout: no response received for ${idleSec}s`
            : `Stream idle timeout: no data for ${idleSec}s`,
        );
        err.name = "TimeoutError";
        void reader.cancel(err).catch(() => undefined);
        rejectOnce(err);
      }, currentTimeoutMs);
 
      signal?.addEventListener("abort", onAbort, { once: true });
      // Close the same check/subscribe race as waitForRetry(): an abort that
      // happens just before listener registration must still cancel the read
      // immediately instead of waiting for the idle timeout.
      if (signal?.aborted) {
        onAbort();
        return;
      }
 
      reader.read().then(
        (result) => {
          resolveOnce(result);
        },
        (error) => {
          rejectOnce(error);
        },
      );
    });
  }
 
  try {
    while (true) {
      const { done, value } = await readWithTimeout();
      if (done) break;
 
      isFirstChunk = false;
      lastChunkTime = Date.now();
 
      buffer += decoder.decode(value, { stream: true });
      const lines = buffer.split("\n");
      buffer = lines.pop() ?? "";
 
      for (const line of lines) {
        const trimmed = line.trim();
        if (!trimmed.startsWith("data: ")) continue;
        const data = trimmed.slice(6);
        if (data === "[DONE]") continue;
        try {
          const parsed = JSON.parse(data) as NimStreamResponse;
          yield parsed;
        } catch {
          // Ignore malformed lines
        }
      }
    }
 
    // Flush decoder internal state and process any remaining lines
    const remaining = decoder.decode();
    buffer += remaining;
    const finalLines = buffer.split("\n");
    for (const line of finalLines) {
      const trimmed = line.trim();
      if (!trimmed.startsWith("data: ")) continue;
      const data = trimmed.slice(6);
      Iif (data === "[DONE]") continue;
      try {
        const parsed = JSON.parse(data) as NimStreamResponse;
        yield parsed;
      } catch {
        // Ignore malformed lines
      }
    }
  } catch (error) {
    if (error instanceof Error && error.name === "TimeoutError") {
      const idleSec = Math.round((Date.now() - lastChunkTime) / 1000);
      const isFirstToken = error.message.includes("first token timeout");
      throw classifyApiError(
        new Error(
          isFirstToken
            ? `NVIDIA NIM first token timeout: no response received for ${idleSec}s`
            : `NVIDIA NIM streaming timeout: no data received for ${idleSec}s`,
        ),
        {
          operation: "stream",
          model: requestBody.model,
        },
      );
    }
    if (error instanceof Error && error.name === "AbortError") {
      throw error;
    }
    throw classifyApiError(error, { operation: "stream", model: requestBody.model });
  } finally {
    reader.releaseLock();
  }
}