UNPKG

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