api-request.d.ts 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. /*! firebase-admin v12.1.1 */
  2. /*!
  3. * @license
  4. * Copyright 2017 Google Inc.
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. /// <reference types="node" />
  19. /// <reference types="node" />
  20. /// <reference types="node" />
  21. import { FirebaseApp } from '../app/firebase-app';
  22. import http = require('http');
  23. import { EventEmitter } from 'events';
  24. /** Http method type definition. */
  25. export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD';
  26. /** API callback function type definition. */
  27. export type ApiCallbackFunction = (data: object) => void;
  28. /**
  29. * Configuration for constructing a new HTTP request.
  30. */
  31. export interface HttpRequestConfig {
  32. method: HttpMethod;
  33. /** Target URL of the request. Should be a well-formed URL including protocol, hostname, port and path. */
  34. url: string;
  35. headers?: {
  36. [key: string]: string;
  37. };
  38. data?: string | object | Buffer | null;
  39. /** Connect and read timeout (in milliseconds) for the outgoing request. */
  40. timeout?: number;
  41. httpAgent?: http.Agent;
  42. }
  43. /**
  44. * Represents an HTTP response received from a remote server.
  45. */
  46. export interface HttpResponse {
  47. readonly status: number;
  48. readonly headers: any;
  49. /** Response data as a raw string. */
  50. readonly text?: string;
  51. /** Response data as a parsed JSON object. */
  52. readonly data?: any;
  53. /** For multipart responses, the payloads of individual parts. */
  54. readonly multipart?: Buffer[];
  55. /**
  56. * Indicates if the response content is JSON-formatted or not. If true, data field can be used
  57. * to retrieve the content as a parsed JSON object.
  58. */
  59. isJson(): boolean;
  60. }
  61. export declare class HttpError extends Error {
  62. readonly response: HttpResponse;
  63. constructor(response: HttpResponse);
  64. }
  65. /**
  66. * Specifies how failing HTTP requests should be retried.
  67. */
  68. export interface RetryConfig {
  69. /** Maximum number of times to retry a given request. */
  70. maxRetries: number;
  71. /** HTTP status codes that should be retried. */
  72. statusCodes?: number[];
  73. /** Low-level I/O error codes that should be retried. */
  74. ioErrorCodes?: string[];
  75. /**
  76. * The multiplier for exponential back off. The retry delay is calculated in seconds using the formula
  77. * `(2^n) * backOffFactor`, where n is the number of retries performed so far. When the backOffFactor is set
  78. * to 0, retries are not delayed. When the backOffFactor is 1, retry duration is doubled each iteration.
  79. */
  80. backOffFactor?: number;
  81. /** Maximum duration to wait before initiating a retry. */
  82. maxDelayInMillis: number;
  83. }
  84. /**
  85. * Default retry configuration for HTTP requests. Retries up to 4 times on connection reset and timeout errors
  86. * as well as HTTP 503 errors. Exposed as a function to ensure that every HttpClient gets its own RetryConfig
  87. * instance.
  88. */
  89. export declare function defaultRetryConfig(): RetryConfig;
  90. export declare class HttpClient {
  91. private readonly retry;
  92. constructor(retry?: RetryConfig | null);
  93. /**
  94. * Sends an HTTP request to a remote server. If the server responds with a successful response (2xx), the returned
  95. * promise resolves with an HttpResponse. If the server responds with an error (3xx, 4xx, 5xx), the promise rejects
  96. * with an HttpError. In case of all other errors, the promise rejects with a FirebaseAppError. If a request fails
  97. * due to a low-level network error, transparently retries the request once before rejecting the promise.
  98. *
  99. * If the request data is specified as an object, it will be serialized into a JSON string. The application/json
  100. * content-type header will also be automatically set in this case. For all other payload types, the content-type
  101. * header should be explicitly set by the caller. To send a JSON leaf value (e.g. "foo", 5), parse it into JSON,
  102. * and pass as a string or a Buffer along with the appropriate content-type header.
  103. *
  104. * @param config - HTTP request to be sent.
  105. * @returns A promise that resolves with the response details.
  106. */
  107. send(config: HttpRequestConfig): Promise<HttpResponse>;
  108. /**
  109. * Sends an HTTP request. In the event of an error, retries the HTTP request according to the
  110. * RetryConfig set on the HttpClient.
  111. *
  112. * @param config - HTTP request to be sent.
  113. * @param retryAttempts - Number of retries performed up to now.
  114. * @returns A promise that resolves with the response details.
  115. */
  116. private sendWithRetry;
  117. private createHttpResponse;
  118. private waitForRetry;
  119. /**
  120. * Checks if a failed request is eligible for a retry, and if so returns the duration to wait before initiating
  121. * the retry.
  122. *
  123. * @param retryAttempts - Number of retries completed up to now.
  124. * @param err - The last encountered error.
  125. * @returns A 2-tuple where the 1st element is the duration to wait before another retry, and the
  126. * 2nd element is a boolean indicating whether the request is eligible for a retry or not.
  127. */
  128. private getRetryDelayMillis;
  129. private isRetryEligible;
  130. /**
  131. * Parses the Retry-After HTTP header as a milliseconds value. Return value is negative if the Retry-After header
  132. * contains an expired timestamp or otherwise malformed.
  133. */
  134. private parseRetryAfterIntoMillis;
  135. private backOffDelayMillis;
  136. }
  137. /**
  138. * Parses a full HTTP response message containing both a header and a body.
  139. *
  140. * @param response - The HTTP response to be parsed.
  141. * @param config - The request configuration that resulted in the HTTP response.
  142. * @returns An object containing the parsed HTTP status, headers and the body.
  143. */
  144. export declare function parseHttpResponse(response: string | Buffer, config: HttpRequestConfig): HttpResponse;
  145. export declare class AuthorizedHttpClient extends HttpClient {
  146. private readonly app;
  147. constructor(app: FirebaseApp);
  148. send(request: HttpRequestConfig): Promise<HttpResponse>;
  149. protected getToken(): Promise<string>;
  150. }
  151. /**
  152. * Class that defines all the settings for the backend API endpoint.
  153. *
  154. * @param endpoint - The Firebase Auth backend endpoint.
  155. * @param httpMethod - The http method for that endpoint.
  156. * @constructor
  157. */
  158. export declare class ApiSettings {
  159. private endpoint;
  160. private httpMethod;
  161. private requestValidator;
  162. private responseValidator;
  163. constructor(endpoint: string, httpMethod?: HttpMethod);
  164. /** @returns The backend API endpoint. */
  165. getEndpoint(): string;
  166. /** @returns The request HTTP method. */
  167. getHttpMethod(): HttpMethod;
  168. /**
  169. * @param requestValidator - The request validator.
  170. * @returns The current API settings instance.
  171. */
  172. setRequestValidator(requestValidator: ApiCallbackFunction | null): ApiSettings;
  173. /** @returns The request validator. */
  174. getRequestValidator(): ApiCallbackFunction;
  175. /**
  176. * @param responseValidator - The response validator.
  177. * @returns The current API settings instance.
  178. */
  179. setResponseValidator(responseValidator: ApiCallbackFunction | null): ApiSettings;
  180. /** @returns The response validator. */
  181. getResponseValidator(): ApiCallbackFunction;
  182. }
  183. /**
  184. * Class used for polling an endpoint with exponential backoff.
  185. *
  186. * Example usage:
  187. * ```
  188. * const poller = new ExponentialBackoffPoller();
  189. * poller
  190. * .poll(() => {
  191. * return myRequestToPoll()
  192. * .then((responseData: any) => {
  193. * if (!isValid(responseData)) {
  194. * // Continue polling.
  195. * return null;
  196. * }
  197. *
  198. * // Polling complete. Resolve promise with final response data.
  199. * return responseData;
  200. * });
  201. * })
  202. * .then((responseData: any) => {
  203. * console.log(`Final response: ${responseData}`);
  204. * });
  205. * ```
  206. */
  207. export declare class ExponentialBackoffPoller<T> extends EventEmitter {
  208. private readonly initialPollingDelayMillis;
  209. private readonly maxPollingDelayMillis;
  210. private readonly masterTimeoutMillis;
  211. private numTries;
  212. private completed;
  213. private masterTimer;
  214. private repollTimer;
  215. private pollCallback?;
  216. private resolve;
  217. private reject;
  218. constructor(initialPollingDelayMillis?: number, maxPollingDelayMillis?: number, masterTimeoutMillis?: number);
  219. /**
  220. * Poll the provided callback with exponential backoff.
  221. *
  222. * @param callback - The callback to be called for each poll. If the
  223. * callback resolves to a falsey value, polling will continue. Otherwise, the truthy
  224. * resolution will be used to resolve the promise returned by this method.
  225. * @returns A Promise which resolves to the truthy value returned by the provided
  226. * callback when polling is complete.
  227. */
  228. poll(callback: () => Promise<T>): Promise<T>;
  229. private repoll;
  230. private getPollingDelayMillis;
  231. private markCompleted;
  232. }