fetch.js 3.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. "use strict";
  2. var __importDefault = (this && this.__importDefault) || function (mod) {
  3. return (mod && mod.__esModule) ? mod : { "default": mod };
  4. };
  5. Object.defineProperty(exports, "__esModule", { value: true });
  6. exports.fetchWithRetry = fetchWithRetry;
  7. /*
  8. Copyright 2023 The Sigstore Authors.
  9. Licensed under the Apache License, Version 2.0 (the "License");
  10. you may not use this file except in compliance with the License.
  11. You may obtain a copy of the License at
  12. http://www.apache.org/licenses/LICENSE-2.0
  13. Unless required by applicable law or agreed to in writing, software
  14. distributed under the License is distributed on an "AS IS" BASIS,
  15. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. See the License for the specific language governing permissions and
  17. limitations under the License.
  18. */
  19. const http2_1 = require("http2");
  20. const make_fetch_happen_1 = __importDefault(require("make-fetch-happen"));
  21. const proc_log_1 = require("proc-log");
  22. const promise_retry_1 = __importDefault(require("promise-retry"));
  23. const util_1 = require("../util");
  24. const error_1 = require("./error");
  25. const { HTTP2_HEADER_LOCATION, HTTP2_HEADER_CONTENT_TYPE, HTTP2_HEADER_USER_AGENT, HTTP_STATUS_INTERNAL_SERVER_ERROR, HTTP_STATUS_TOO_MANY_REQUESTS, HTTP_STATUS_REQUEST_TIMEOUT, } = http2_1.constants;
  26. async function fetchWithRetry(url, options) {
  27. return (0, promise_retry_1.default)(async (retry, attemptNum) => {
  28. const method = options.method || 'POST';
  29. const headers = {
  30. [HTTP2_HEADER_USER_AGENT]: util_1.ua.getUserAgent(),
  31. ...options.headers,
  32. };
  33. const response = await (0, make_fetch_happen_1.default)(url, {
  34. method,
  35. headers,
  36. body: options.body,
  37. timeout: options.timeout,
  38. retry: false, // We're handling retries ourselves
  39. }).catch((reason) => {
  40. proc_log_1.log.http('fetch', `${method} ${url} attempt ${attemptNum} failed with ${reason}`);
  41. return retry(reason);
  42. });
  43. if (response.ok) {
  44. return response;
  45. }
  46. else {
  47. const error = await errorFromResponse(response);
  48. proc_log_1.log.http('fetch', `${method} ${url} attempt ${attemptNum} failed with ${response.status}`);
  49. if (retryable(response.status)) {
  50. return retry(error);
  51. }
  52. else {
  53. throw error;
  54. }
  55. }
  56. }, retryOpts(options.retry));
  57. }
  58. // Translate a Response into an HTTPError instance. This will attempt to parse
  59. // the response body for a message, but will default to the statusText if none
  60. // is found.
  61. const errorFromResponse = async (response) => {
  62. let message = response.statusText;
  63. const location = response.headers.get(HTTP2_HEADER_LOCATION) || undefined;
  64. const contentType = response.headers.get(HTTP2_HEADER_CONTENT_TYPE);
  65. // If response type is JSON, try to parse the body for a message
  66. if (contentType?.includes('application/json')) {
  67. try {
  68. const body = await response.json();
  69. message = body.message || message;
  70. }
  71. catch (e) {
  72. // ignore
  73. }
  74. }
  75. return new error_1.HTTPError({
  76. status: response.status,
  77. message: message,
  78. location: location,
  79. });
  80. };
  81. // Determine if a status code is retryable. This includes 5xx errors, 408, and
  82. // 429.
  83. const retryable = (status) => [HTTP_STATUS_REQUEST_TIMEOUT, HTTP_STATUS_TOO_MANY_REQUESTS].includes(status) || status >= HTTP_STATUS_INTERNAL_SERVER_ERROR;
  84. // Normalize the retry options to the format expected by promise-retry
  85. const retryOpts = (retry) => {
  86. if (typeof retry === 'boolean') {
  87. return { retries: retry ? 1 : 0 };
  88. }
  89. else if (typeof retry === 'number') {
  90. return { retries: retry };
  91. }
  92. else {
  93. return { retries: 0, ...retry };
  94. }
  95. };