All files / src/lib request-helper.ts

88.95% Statements 290/326
80% Branches 48/60
100% Functions 23/23
88.95% Lines 290/326

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 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543                                                1x 1x 1x 1x 1x 1x 1x       1x 1x 15x 15x 15x 15x 15x 15x 15x 15x     1x 5x 5x     1x 2x 2x     1x 3x 3x 1x   1x 1x 2x 2x 2x 1x       3x 3x 3x                 3x 3x 3x 3x 3x   3x   3x   3x 3x 3x                                                 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x   16x 16x   16x 19x 19x   19x 19x 19x 19x 19x   17x   19x   5x 5x 5x       5x 5x 5x 5x 5x 5x     5x 3x 3x 3x 3x 3x 3x 3x 3x   2x 2x     12x 19x 4x     4x 2x     2x                   2x 2x     4x                                             4x         2x 4x 4x 4x 4x 4x 4x 19x     16x 16x                     2x 2x 2x 2x 2x 2x   2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 2x               1x 1x 10x                   1x   13x 1x 1x   13x 13x 13x 3x 3x   13x 13x                       1x 3x 3x 3x 3x 3x 3x   3x 3x 3x 3x 3x 3x 3x 3x 3x     2x 2x   2x 3x   1x 1x   1x 1x 3x                     1x 1x 1x 1x 1x 1x 1x   1x 1x 1x               1x               1x 3x 3x 2x 2x 2x 2x 2x 1x 3x               1x 5x 5x             1x 1x 1x         1x 1x 3x 3x 1x 1x 1x 1x         1x 2x 2x 1x               1x             1x 1x 1x 1x 1x 1x 1x         1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x         1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x         1x 1x 1x 1x 1x 1x 1x         1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
/**
 * Request Helper Module
 *
 * Provides request timeout, automatic retry with exponential backoff,
 * and request cancellation support for API clients.
 *
 * @module lib/request-helper
 */
 
// === Configuration Types ===
 
export interface RequestConfig {
  /** Timeout in milliseconds, default 30000 */
  timeout?: number;
  /** Number of retry attempts, default 3 */
  retries?: number;
  /** Base retry delay in milliseconds, default 1000 (exponential backoff applied) */
  retryDelay?: number;
  /** HTTP status codes that trigger retry, default [408, 429, 500, 502, 503, 504] */
  retryOn?: number[];
  /** Maximum retry delay cap in milliseconds, default 30000 */
  maxRetryDelay?: number;
}
 
export const DEFAULT_REQUEST_CONFIG: Required<RequestConfig> = {
  timeout: 30000,
  retries: 3,
  retryDelay: 1000,
  retryOn: [408, 429, 500, 502, 503, 504],
  maxRetryDelay: 30000,
};
 
// === Error Types ===
 
export class RequestError extends Error {
  constructor(
    message: string,
    public readonly status: number,
    public readonly statusText: string,
    public readonly responseBody?: string
  ) {
    super(message);
    this.name = 'RequestError';
  }
 
  /** Check if error is retryable based on status code */
  isRetryable(retryCodes: number[] = DEFAULT_REQUEST_CONFIG.retryOn): boolean {
    return retryCodes.includes(this.status);
  }
 
  /** Check if error is a timeout */
  isTimeout(): boolean {
    return this.status === 408 || this.message.includes('timeout');
  }
 
  /** Check if error is an authentication error (should NOT retry) */
  isAuthError(): boolean {
    return this.status === 401 || this.status === 403;
  }
}
 
export class RequestCancelledError extends Error {
  constructor(message: string = 'Request cancelled') {
    super(message);
    this.name = 'RequestCancelledError';
  }
}
 
// === Helper Functions ===
 
function delay(ms: number): Promise<void> {
  return new Promise(resolve => setTimeout(resolve, ms));
}
 
/**
 * Calculate exponential backoff delay with jitter
 * @param baseDelay Base delay in ms
 * @param attempt Current attempt number (0-indexed)
 * @param maxDelay Maximum delay cap
 * @returns Delay in milliseconds
 */
function calculateBackoff(
  baseDelay: number,
  attempt: number,
  maxDelay: number = DEFAULT_REQUEST_CONFIG.maxRetryDelay
): number {
  // Exponential backoff: baseDelay * 2^attempt
  const exponentialDelay = baseDelay * Math.pow(2, attempt);
  // Cap at maxDelay
  const cappedDelay = Math.min(exponentialDelay, maxDelay);
  // Add jitter (0-25% of delay) to prevent thundering herd
  const jitter = cappedDelay * 0.25 * Math.random();
  return Math.floor(cappedDelay + jitter);
}
 
// === Request with Retry ===
 
export interface RequestWithRetryOptions extends RequestInit {
  /** Request configuration for timeout and retry */
  config?: RequestConfig;
}
 
/**
 * Execute a fetch request with timeout and automatic retry support.
 *
 * Features:
 * - Configurable timeout with AbortController
 * - Automatic retry with exponential backoff
 * - Configurable retry status codes
 * - Jitter to prevent thundering herd
 *
 * @param url Request URL
 * @param options Fetch options + request config
 * @param config Request configuration (timeout, retries, etc.)
 * @returns Promise<Response>
 * @throws RequestError on failure after all retries exhausted
 * @throws RequestCancelledError if request was cancelled
 */
export async function requestWithRetry(
  url: string,
  options: RequestInit = {},
  config: RequestConfig = {}
): Promise<Response> {
  const {
    timeout = DEFAULT_REQUEST_CONFIG.timeout,
    retries = DEFAULT_REQUEST_CONFIG.retries,
    retryDelay = DEFAULT_REQUEST_CONFIG.retryDelay,
    retryOn = DEFAULT_REQUEST_CONFIG.retryOn,
  } = config;
 
  let lastError: RequestError | null = null;
  let responseBody = '';
 
  for (let attempt = 0; attempt <= retries; attempt++) {
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), timeout);
 
    try {
      const response = await fetch(url, {
        ...options,
        signal: controller.signal,
      });
 
      clearTimeout(timeoutId);
 
      if (!response.ok) {
        // Try to read response body for error details
        try {
          responseBody = await response.text();
        } catch {
          responseBody = '';
        }
 
        const error = new RequestError(
          `Request failed: ${response.status} ${response.statusText}`,
          response.status,
          response.statusText,
          responseBody
        );
 
        // Check if we should retry
        if (retryOn.includes(response.status) && attempt < retries) {
          const backoff = calculateBackoff(retryDelay, attempt);
          console.warn(
            `[RequestHelper] Request failed (${response.status}), ` +
            `retrying in ${backoff}ms (attempt ${attempt + 1}/${retries})`
          );
          await delay(backoff);
          continue;
        }
 
        throw error;
      }
 
      // Success - return response
      return response;
    } catch (error) {
      clearTimeout(timeoutId);
 
      // Re-throw RequestError (already formatted)
      if (error instanceof RequestError) {
        lastError = error;
 
        // Check if we should retry
        if (error.isRetryable(retryOn) && attempt < retries) {
          const backoff = calculateBackoff(retryDelay, attempt);
          console.warn(
            `[RequestHelper] Request error (${error.status}), ` +
            `retrying in ${backoff}ms (attempt ${attempt + 1}/${retries})`
          );
          await delay(backoff);
          continue;
        }
 
        throw error;
      }
 
      // Handle AbortError (timeout)
      if (error instanceof Error && error.name === 'AbortError') {
        const timeoutError = new RequestError(
          `Request timeout after ${timeout}ms`,
          408,
          'Request Timeout'
        );
 
        // Retry on timeout
        if (attempt < retries) {
          const backoff = calculateBackoff(retryDelay, attempt);
          console.warn(
            `[RequestHelper] Request timed out, ` +
            `retrying in ${backoff}ms (attempt ${attempt + 1}/${retries})`
          );
          await delay(backoff);
          lastError = timeoutError;
          continue;
        }
 
        throw timeoutError;
      }
 
      // Handle cancellation
      if (error instanceof RequestCancelledError) {
        throw error;
      }
 
      // Unknown error - wrap and throw
      throw new RequestError(
        error instanceof Error ? error.message : 'Unknown error',
        0,
        'Unknown Error',
        error instanceof Error ? error.stack : String(error)
      );
    }
  }
 
  // All retries exhausted
  throw lastError || new RequestError('All retry attempts exhausted', 0, 'Retry Exhausted');
}
 
/**
 * Execute a request and parse JSON response.
 * Combines requestWithRetry with JSON parsing.
 *
 * @param url Request URL
 * @param options Fetch options
 * @param config Request configuration
 * @returns Parsed JSON response
 */
export async function requestJson<T = unknown>(
  url: string,
  options: RequestInit = {},
  config: RequestConfig = {}
): Promise<T> {
  const response = await requestWithRetry(url, options, config);
 
  try {
    return await response.json();
  } catch (error) {
    throw new RequestError(
      `Failed to parse JSON response: ${error instanceof Error ? error.message : 'Unknown error'}`,
      0,
      'Parse Error',
      await response.text().catch(() => '')
    );
  }
}
 
// === Request Manager (Cancellation Support) ===
 
/**
 * Manages multiple concurrent requests with cancellation support.
 * Provides centralized control over request lifecycle.
 */
export class RequestManager {
  private controllers = new Map<string, AbortController>();
  private requestConfigs = new Map<string, RequestConfig>();
 
  /**
   * Create a new request with an ID for tracking.
   * Returns the AbortController for signal attachment.
   *
   * @param id Unique request identifier
   * @param config Optional request configuration
   * @returns AbortController for the request
   */
  createRequest(id: string, config?: RequestConfig): AbortController {
    // Cancel existing request with same ID
    if (this.controllers.has(id)) {
      this.cancelRequest(id);
    }
 
    const controller = new AbortController();
    this.controllers.set(id, controller);
    if (config) {
      this.requestConfigs.set(id, config);
    }
 
    return controller;
  }
 
  /**
   * Execute a managed request with automatic tracking.
   * The request will be automatically removed when complete.
   *
   * @param id Unique request identifier
   * @param url Request URL
   * @param options Fetch options
   * @param config Request configuration
   * @returns Response promise
   */
  async executeManaged(
    id: string,
    url: string,
    options: RequestInit = {},
    config: RequestConfig = {}
  ): Promise<Response> {
    const controller = this.createRequest(id, config);
 
    try {
      const response = await requestWithRetry(
        url,
        {
          ...options,
          signal: controller.signal,
        },
        config
      );
 
      // Clean up on success
      this.controllers.delete(id);
      this.requestConfigs.delete(id);
 
      return response;
    } catch (error) {
      // Clean up on error
      this.controllers.delete(id);
      this.requestConfigs.delete(id);
 
      throw error;
    }
  }
 
  /**
   * Execute a managed JSON request with automatic tracking.
   *
   * @param id Unique request identifier
   * @param url Request URL
   * @param options Fetch options
   * @param config Request configuration
   * @returns Parsed JSON response
   */
  async executeManagedJson<T = unknown>(
    id: string,
    url: string,
    options: RequestInit = {},
    config: RequestConfig = {}
  ): Promise<T> {
    const response = await this.executeManaged(id, url, options, config);
 
    try {
      return await response.json();
    } catch (error) {
      throw new RequestError(
        `Failed to parse JSON response: ${error instanceof Error ? error.message : 'Unknown error'}`,
        0,
        'Parse Error',
        await response.text().catch(() => '')
      );
    }
  }
 
  /**
   * Cancel a specific request by ID.
   *
   * @param id Request identifier
   * @returns true if request was cancelled, false if not found
   */
  cancelRequest(id: string): boolean {
    const controller = this.controllers.get(id);
    if (controller) {
      controller.abort();
      this.controllers.delete(id);
      this.requestConfigs.delete(id);
      return true;
    }
    return false;
  }
 
  /**
   * Check if a request is currently in progress.
   *
   * @param id Request identifier
   * @returns true if request is active
   */
  isRequestActive(id: string): boolean {
    return this.controllers.has(id);
  }
 
  /**
   * Get all active request IDs.
   *
   * @returns Array of active request IDs
   */
  getActiveRequestIds(): string[] {
    return Array.from(this.controllers.keys());
  }
 
  /**
   * Cancel all active requests.
   */
  cancelAll(): void {
    this.controllers.forEach((controller, id) => {
      controller.abort();
      console.log(`[RequestManager] Cancelled request: ${id}`);
    });
    this.controllers.clear();
    this.requestConfigs.clear();
  }
 
  /**
   * Get the number of active requests.
   */
  get activeCount(): number {
    return this.controllers.size;
  }
}
 
// === Default Request Manager Instance ===
 
/**
 * Global request manager instance for application-wide request tracking.
 * Use this for simple cases; create new instances for isolated contexts.
 */
export const globalRequestManager = new RequestManager();
 
// === Convenience Functions ===
 
/**
 * Create a GET request with retry support.
 */
export async function get(
  url: string,
  headers?: HeadersInit,
  config?: RequestConfig
): Promise<Response> {
  return requestWithRetry(url, { method: 'GET', headers }, config);
}
 
/**
 * Create a POST request with retry support.
 */
export async function post(
  url: string,
  body?: unknown,
  headers?: HeadersInit,
  config?: RequestConfig
): Promise<Response> {
  return requestWithRetry(
    url,
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        ...headers,
      },
      body: body ? JSON.stringify(body) : undefined,
    },
    config
  );
}
 
/**
 * Create a PUT request with retry support.
 */
export async function put(
  url: string,
  body?: unknown,
  headers?: HeadersInit,
  config?: RequestConfig
): Promise<Response> {
  return requestWithRetry(
    url,
    {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        ...headers,
      },
      body: body ? JSON.stringify(body) : undefined,
    },
    config
  );
}
 
/**
 * Create a DELETE request with retry support.
 */
export async function del(
  url: string,
  headers?: HeadersInit,
  config?: RequestConfig
): Promise<Response> {
  return requestWithRetry(url, { method: 'DELETE', headers }, config);
}
 
/**
 * Create a PATCH request with retry support.
 */
export async function patch(
  url: string,
  body?: unknown,
  headers?: HeadersInit,
  config?: RequestConfig
): Promise<Response> {
  return requestWithRetry(
    url,
    {
      method: 'PATCH',
      headers: {
        'Content-Type': 'application/json',
        ...headers,
      },
      body: body ? JSON.stringify(body) : undefined,
    },
    config
  );
}
 
export default {
  requestWithRetry,
  requestJson,
  RequestManager,
  globalRequestManager,
  RequestError,
  RequestCancelledError,
  get,
  post,
  put,
  del,
  patch,
  DEFAULT_REQUEST_CONFIG,
};