summaryrefslogtreecommitdiff
path: root/SPECS/network/http-client.js
blob: d40003b7259797f9fde907805324abc1fccbac9b (plain)
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
/**
 * HTTP Client with Rate Limiting and Retry Logic
 *
 * Provides comprehensive HTTP client functionality:
 * - Rate limiting with configurable strategies
 * - Retry mechanisms with exponential backoff
 * - Request/response interception
 * - Error handling and recovery
 * - Timeout management
 */

const DEFAULT_RETRY_AFTER = 60000; // 60 seconds

/**
 * HTTP Client with advanced features
 */
class HttpClient {
  constructor(options = {}) {
    this.options = {
      timeout: options.timeout || 30000,
      retries: options.retries || 3,
      retryDelay: options.retryDelay || 1000,
      maxRetryDelay: options.maxRetryDelay || 30000,
      retryOn: options.retryOn || [408, 429, 500, 502, 503, 504],
      ...options,
    };

    this.rateLimits = {};
    this.interceptors = {
      request: [],
      response: [],
    };
  }

  /**
   * Add request interceptor
   * @param {Function} interceptor - Function to modify request
   */
  addRequestInterceptor(interceptor) {
    this.interceptors.request.push(interceptor);
  }

  /**
   * Add response interceptor
   * @param {Function} interceptor - Function to modify response
   */
  addResponseInterceptor(interceptor) {
    this.interceptors.response.push(interceptor);
  }

  /**
   * Make HTTP request with rate limiting and retry logic
   * @param {string|Object} urlOrConfig - URL string or config object
   * @param {Object} config - Request configuration
   * @returns {Promise} Response promise
   */
  async request(urlOrConfig, config = {}) {
    const requestConfig =
      typeof urlOrConfig === "string"
        ? { url: urlOrConfig, ...config }
        : { ...urlOrConfig, ...config };

    // Apply request interceptors
    let processedConfig = requestConfig;
    for (const interceptor of this.interceptors.request) {
      processedConfig = await interceptor(processedConfig);
    }

    return this.executeWithRetry(processedConfig);
  }

  /**
   * Execute request with retry logic
   * @param {Object} config - Request configuration
   * @param {number} attempt - Current attempt number
   * @returns {Promise} Response promise
   */
  async executeWithRetry(config, attempt = 1) {
    const { method = "GET", url } = config;

    // Check rate limits
    if (this.isRateLimited(method, url)) {
      const retryAfter = this.getRetryAfter(method, url);
      throw new Error(`Rate limited. Retry after ${retryAfter}ms`);
    }

    try {
      const response = await this.executeRequest(config);

      // Update rate limits from response
      this.updateRateLimitsFromResponse(response, method, url);

      // Apply response interceptors
      let processedResponse = response;
      for (const interceptor of this.interceptors.response) {
        processedResponse = await interceptor(processedResponse);
      }

      return processedResponse;
    } catch (error) {
      // Update rate limits from error response
      if (error.response) {
        this.updateRateLimitsFromResponse(error.response, method, url);
      }

      // Check if we should retry
      if (this.shouldRetry(error, attempt)) {
        const delay = this.calculateRetryDelay(attempt, error);
        await this.sleep(delay);
        return this.executeWithRetry(config, attempt + 1);
      }

      throw error;
    }
  }

  /**
   * Execute the actual HTTP request
   * @param {Object} config - Request configuration
   * @returns {Promise} Response promise
   */
  async executeRequest(config) {
    const {
      method = "GET",
      url,
      headers = {},
      data,
      timeout = this.options.timeout,
    } = config;

    // Use fetch if available, otherwise fallback to XHR
    if (typeof fetch !== "undefined") {
      return this.executeFetchRequest(config);
    } else {
      return this.executeXhrRequest(config);
    }
  }

  /**
   * Execute request using fetch API
   * @param {Object} config - Request configuration
   * @returns {Promise} Response promise
   */
  async executeFetchRequest(config) {
    const {
      method = "GET",
      url,
      headers = {},
      data,
      timeout = this.options.timeout,
    } = config;

    const fetchOptions = {
      method,
      headers,
      body: data && method !== "GET" && method !== "HEAD" ? data : undefined,
    };

    // Create timeout promise
    const timeoutPromise = new Promise((_, reject) => {
      setTimeout(() => reject(new Error("Request timeout")), timeout);
    });

    try {
      const response = await Promise.race([
        fetch(url, fetchOptions),
        timeoutPromise,
      ]);

      return {
        status: response.status,
        statusText: response.statusText,
        headers: this.extractFetchHeaders(response.headers),
        data: await this.parseFetchResponse(response),
        config,
      };
    } catch (error) {
      throw this.createRequestError(error, config);
    }
  }

  /**
   * Execute request using XMLHttpRequest
   * @param {Object} config - Request configuration
   * @returns {Promise} Response promise
   */
  executeXhrRequest(config) {
    return new Promise((resolve, reject) => {
      const {
        method = "GET",
        url,
        headers = {},
        data,
        timeout = this.options.timeout,
      } = config;

      const xhr = new XMLHttpRequest();

      xhr.timeout = timeout;
      xhr.open(method, url);

      // Set headers
      Object.entries(headers).forEach(([key, value]) => {
        xhr.setRequestHeader(key, value);
      });

      xhr.onload = () => {
        const response = {
          status: xhr.status,
          statusText: xhr.statusText,
          headers: this.parseXhrHeaders(xhr.getAllResponseHeaders()),
          data: xhr.responseText,
          config,
        };

        if (xhr.status >= 200 && xhr.status < 300) {
          resolve(response);
        } else {
          reject(
            this.createRequestError(
              new Error(`HTTP ${xhr.status}`),
              config,
              response,
            ),
          );
        }
      };

      xhr.onerror = () => {
        reject(this.createRequestError(new Error("Network error"), config));
      };

      xhr.ontimeout = () => {
        reject(this.createRequestError(new Error("Request timeout"), config));
      };

      xhr.send(data || null);
    });
  }

  /**
   * Check if request is rate limited
   * @param {string} method - HTTP method
   * @param {string} url - Request URL
   * @returns {boolean} True if rate limited
   */
  isRateLimited(method, url) {
    const key = this.getRateLimitKey(method, url);
    const rateLimitTime = this.getRateLimitTime(key);
    return rateLimitTime > Date.now();
  }

  /**
   * Get retry after time for rate limited request
   * @param {string} method - HTTP method
   * @param {string} url - Request URL
   * @returns {number} Retry after time in milliseconds
   */
  getRetryAfter(method, url) {
    const key = this.getRateLimitKey(method, url);
    const rateLimitTime = this.getRateLimitTime(key);
    return Math.max(0, rateLimitTime - Date.now());
  }

  /**
   * Update rate limits based on response headers
   * @param {Object} response - HTTP response
   * @param {string} method - HTTP method
   * @param {string} url - Request URL
   */
  updateRateLimitsFromResponse(response, method, url) {
    const { status, headers } = response;
    const now = Date.now();

    const rateLimitHeader = headers["x-sentry-rate-limits"];
    const retryAfterHeader = headers["retry-after"];

    if (rateLimitHeader) {
      this.parseRateLimitHeader(rateLimitHeader, now);
    } else if (retryAfterHeader) {
      const retryAfter = this.parseRetryAfter(retryAfterHeader, now);
      this.rateLimits.all = now + retryAfter;
    } else if (status === 429) {
      this.rateLimits.all = now + DEFAULT_RETRY_AFTER;
    }
  }

  /**
   * Parse retry-after header
   * @param {string} retryAfter - Retry-after header value
   * @param {number} now - Current timestamp
   * @returns {number} Retry after time in milliseconds
   */
  parseRetryAfter(retryAfter, now = Date.now()) {
    const seconds = parseInt(`${retryAfter}`, 10);

    if (!isNaN(seconds)) {
      return seconds * 1000;
    }

    const date = Date.parse(`${retryAfter}`);
    if (!isNaN(date)) {
      return date - now;
    }

    return DEFAULT_RETRY_AFTER;
  }

  /**
   * Parse rate limit header (Sentry format)
   * @param {string} header - Rate limit header value
   * @param {number} now - Current timestamp
   */
  parseRateLimitHeader(header, now) {
    const limits = header.trim().split(",");

    for (const limit of limits) {
      const [seconds, categories, , , scope] = limit.split(":", 5);
      const retryAfter = (parseInt(seconds, 10) || 60) * 1000;

      if (!categories) {
        this.rateLimits.all = now + retryAfter;
      } else {
        for (const category of categories.split(";")) {
          if (category === "metric_bucket") {
            if (!scope || scope.split(";").includes("custom")) {
              this.rateLimits[category] = now + retryAfter;
            }
          } else {
            this.rateLimits[category] = now + retryAfter;
          }
        }
      }
    }
  }

  /**
   * Get rate limit key for method/URL combination
   * @param {string} method - HTTP method
   * @param {string} url - Request URL
   * @returns {string} Rate limit key
   */
  getRateLimitKey(method, url) {
    // For now, use a simple approach
    // Could be enhanced to parse URL and use specific categories
    return "all";
  }

  /**
   * Get rate limit time for a specific key
   * @param {string} key - Rate limit key
   * @returns {number} Rate limit time
   */
  getRateLimitTime(key) {
    return this.rateLimits[key] || this.rateLimits.all || 0;
  }

  /**
   * Determine if request should be retried
   * @param {Error} error - Request error
   * @param {number} attempt - Current attempt number
   * @returns {boolean} True if should retry
   */
  shouldRetry(error, attempt) {
    if (attempt >= this.options.retries) {
      return false;
    }

    if (error.response && error.response.status) {
      return this.options.retryOn.includes(error.response.status);
    }

    // Retry on network errors
    return (
      error.message.includes("Network") || error.message.includes("timeout")
    );
  }

  /**
   * Calculate retry delay with exponential backoff
   * @param {number} attempt - Current attempt number
   * @param {Error} error - Request error
   * @returns {number} Delay in milliseconds
   */
  calculateRetryDelay(attempt, error) {
    // Base delay with exponential backoff
    let delay = this.options.retryDelay * Math.pow(2, attempt - 1);

    // Add jitter to prevent thundering herd
    delay += Math.random() * 1000;

    // Respect max delay
    delay = Math.min(delay, this.options.maxRetryDelay);

    // If we have a retry-after header, respect it
    if (error.response && error.response.headers["retry-after"]) {
      const retryAfter = this.parseRetryAfter(
        error.response.headers["retry-after"],
      );
      delay = Math.max(delay, retryAfter);
    }

    return delay;
  }

  /**
   * Sleep for specified milliseconds
   * @param {number} ms - Milliseconds to sleep
   * @returns {Promise} Promise that resolves after delay
   */
  sleep(ms) {
    return new Promise((resolve) => setTimeout(resolve, ms));
  }

  /**
   * Extract headers from fetch Response
   * @param {Headers} headers - Fetch headers object
   * @returns {Object} Headers object
   */
  extractFetchHeaders(headers) {
    const result = {};
    for (const [key, value] of headers.entries()) {
      result[key.toLowerCase()] = value;
    }
    return result;
  }

  /**
   * Parse fetch response body
   * @param {Response} response - Fetch response
   * @returns {Promise} Parsed response body
   */
  async parseFetchResponse(response) {
    const contentType = response.headers.get("content-type") || "";

    if (contentType.includes("application/json")) {
      return response.json();
    } else if (contentType.includes("text/")) {
      return response.text();
    } else {
      return response.arrayBuffer();
    }
  }

  /**
   * Parse XHR headers string
   * @param {string} headersString - XHR headers string
   * @returns {Object} Headers object
   */
  parseXhrHeaders(headersString) {
    const headers = {};
    if (!headersString) return headers;

    const lines = headersString.split("\r\n");
    for (const line of lines) {
      const colonIndex = line.indexOf(":");
      if (colonIndex > 0) {
        const key = line.slice(0, colonIndex).trim().toLowerCase();
        const value = line.slice(colonIndex + 1).trim();
        headers[key] = value;
      }
    }

    return headers;
  }

  /**
   * Create standardized request error
   * @param {Error} error - Original error
   * @param {Object} config - Request config
   * @param {Object} response - Response object (if available)
   * @returns {Error} Formatted error
   */
  createRequestError(error, config, response = null) {
    const requestError = new Error(error.message);
    requestError.config = config;
    requestError.response = response;
    requestError.isRequestError = true;

    return requestError;
  }

  // Convenience methods
  get(url, config) {
    return this.request(url, { ...config, method: "GET" });
  }

  post(url, data, config) {
    return this.request(url, { ...config, method: "POST", data });
  }

  put(url, data, config) {
    return this.request(url, { ...config, method: "PUT", data });
  }

  delete(url, config) {
    return this.request(url, { ...config, method: "DELETE" });
  }
}

module.exports = {
  HttpClient,
  DEFAULT_RETRY_AFTER,
};