UNPKG

10.1 kBTypeScriptView Raw
1/*!
2 * Copyright 2018 Google LLC
3 *
4 * Use of this source code is governed by an MIT-style
5 * license that can be found in the LICENSE file or at
6 * https://opensource.org/licenses/MIT.
7 */
8/// <reference types="node" />
9import * as ConfigStore from 'configstore';
10import { GaxiosOptions, GaxiosPromise, GaxiosResponse } from 'gaxios';
11import { GoogleAuthOptions } from 'google-auth-library';
12import * as Pumpify from 'pumpify';
13export declare const PROTOCOL_REGEX: RegExp;
14export interface ErrorWithCode extends Error {
15 code: number;
16}
17export declare type CreateUriCallback = (err: Error | null, uri?: string) => void;
18export interface Encryption {
19 key: {};
20 hash: {};
21}
22export declare type PredefinedAcl = 'authenticatedRead' | 'bucketOwnerFullControl' | 'bucketOwnerRead' | 'private' | 'projectPrivate' | 'publicRead';
23export interface QueryParameters {
24 contentEncoding?: string;
25 ifGenerationMatch?: number;
26 ifGenerationNotMatch?: number;
27 ifMetagenerationMatch?: number;
28 ifMetagenerationNotMatch?: number;
29 kmsKeyName?: string;
30 predefinedAcl?: PredefinedAcl;
31 projection?: 'full' | 'noAcl';
32 userProject?: string;
33}
34export interface UploadConfig {
35 /**
36 * The API endpoint used for the request.
37 * Defaults to `storage.googleapis.com`.
38 * **Warning**:
39 * If this value does not match the pattern *.googleapis.com,
40 * an emulator context will be assumed and authentication will be bypassed.
41 */
42 apiEndpoint?: string;
43 /**
44 * The name of the destination bucket.
45 */
46 bucket: string;
47 /**
48 * The name of the destination file.
49 */
50 file: string;
51 /**
52 * The GoogleAuthOptions passed to google-auth-library
53 */
54 authConfig?: GoogleAuthOptions;
55 /**
56 * If you want to re-use an auth client from google-auto-auth, pass an
57 * instance here.
58 * Defaults to GoogleAuth and gets automatically overridden if an
59 * emulator context is detected.
60 */
61 authClient?: {
62 request: <T>(opts: GaxiosOptions) => Promise<GaxiosResponse<T>> | GaxiosPromise<T>;
63 };
64 /**
65 * Where the gcs-resumable-upload configuration file should be stored on your
66 * system. This maps to the configstore option by the same name.
67 */
68 configPath?: string;
69 /**
70 * Create a separate request per chunk.
71 *
72 * Should be a multiple of 256 KiB (2^18).
73 * We recommend using at least 8 MiB for the chunk size.
74 *
75 * @link https://cloud.google.com/storage/docs/performing-resumable-uploads#chunked-upload
76 */
77 chunkSize?: number;
78 /**
79 * For each API request we send, you may specify custom request options that
80 * we'll add onto the request. The request options follow the gaxios API:
81 * https://github.com/googleapis/gaxios#request-options.
82 */
83 customRequestOptions?: GaxiosOptions;
84 /**
85 * This will cause the upload to fail if the current generation of the remote
86 * object does not match the one provided here.
87 */
88 generation?: number;
89 /**
90 * A customer-supplied encryption key. See
91 * https://cloud.google.com/storage/docs/encryption#customer-supplied.
92 */
93 key?: string | Buffer;
94 /**
95 * Resource name of the Cloud KMS key, of the form
96 * `projects/my-project/locations/global/keyRings/my-kr/cryptoKeys/my-key`,
97 * that will be used to encrypt the object. Overrides the object metadata's
98 * `kms_key_name` value, if any.
99 */
100 kmsKeyName?: string;
101 /**
102 * Any metadata you wish to set on the object.
103 */
104 metadata?: ConfigMetadata;
105 /**
106 * The starting byte of the upload stream, for resuming an interrupted upload.
107 * See
108 * https://cloud.google.com/storage/docs/json_api/v1/how-tos/resumable-upload#resume-upload.
109 */
110 offset?: number;
111 /**
112 * Set an Origin header when creating the resumable upload URI.
113 */
114 origin?: string;
115 /**
116 * Specify query parameters that go along with the initial upload request. See
117 * https://cloud.google.com/storage/docs/json_api/v1/objects/insert#parameters
118 */
119 params?: QueryParameters;
120 /**
121 * Apply a predefined set of access controls to the created file.
122 */
123 predefinedAcl?: PredefinedAcl;
124 /**
125 * Make the uploaded file private. (Alias for config.predefinedAcl =
126 * 'private')
127 */
128 private?: boolean;
129 /**
130 * Make the uploaded file public. (Alias for config.predefinedAcl =
131 * 'publicRead')
132 */
133 public?: boolean;
134 /**
135 * If you already have a resumable URI from a previously-created resumable
136 * upload, just pass it in here and we'll use that.
137 */
138 uri?: string;
139 /**
140 * If the bucket being accessed has requesterPays functionality enabled, this
141 * can be set to control which project is billed for the access of this file.
142 */
143 userProject?: string;
144 /**
145 * Configuration options for retrying retryable errors.
146 */
147 retryOptions?: RetryOptions;
148}
149export interface ConfigMetadata {
150 [key: string]: any;
151 /**
152 * Set the length of the file being uploaded.
153 */
154 contentLength?: number;
155 /**
156 * Set the content type of the incoming data.
157 */
158 contentType?: string;
159}
160export interface RetryOptions {
161 retryDelayMultiplier?: number;
162 totalTimeout?: number;
163 maxRetryDelay?: number;
164 autoRetry?: boolean;
165 maxRetries?: number;
166 retryableErrorFn?: (err: ApiError) => boolean;
167}
168export interface GoogleInnerError {
169 reason?: string;
170}
171export interface ApiError extends Error {
172 code?: number;
173 errors?: GoogleInnerError[];
174}
175export declare class Upload extends Pumpify {
176 bucket: string;
177 file: string;
178 apiEndpoint: string;
179 baseURI: string;
180 authConfig?: {
181 scopes?: string[];
182 };
183 authClient: {
184 request: <T>(opts: GaxiosOptions) => Promise<GaxiosResponse<T>> | GaxiosPromise<T>;
185 };
186 cacheKey: string;
187 chunkSize?: number;
188 customRequestOptions: GaxiosOptions;
189 generation?: number;
190 key?: string | Buffer;
191 kmsKeyName?: string;
192 metadata: ConfigMetadata;
193 offset?: number;
194 origin?: string;
195 params: QueryParameters;
196 predefinedAcl?: PredefinedAcl;
197 private?: boolean;
198 public?: boolean;
199 uri?: string;
200 userProject?: string;
201 encryption?: Encryption;
202 configStore: ConfigStore;
203 uriProvidedManually: boolean;
204 numBytesWritten: number;
205 numRetries: number;
206 contentLength: number | '*';
207 retryLimit: number;
208 maxRetryDelay: number;
209 retryDelayMultiplier: number;
210 maxRetryTotalTimeout: number;
211 timeOfFirstRequest: number;
212 retryableErrorFn?: (err: ApiError) => boolean;
213 private upstreamChunkBuffer;
214 private chunkBufferEncoding?;
215 private numChunksReadInRequest;
216 /**
217 * A chunk used for caching the most recent upload chunk.
218 * We should not assume that the server received all bytes sent in the request.
219 * - https://cloud.google.com/storage/docs/performing-resumable-uploads#chunked-upload
220 */
221 private lastChunkSent;
222 private upstreamEnded;
223 constructor(cfg: UploadConfig);
224 /** A stream representing the incoming data to upload */
225 private readonly upstream;
226 /**
227 * A handler for `upstream` to write and buffer its data.
228 *
229 * @param chunk The chunk to append to the buffer
230 * @param encoding The encoding of the chunk
231 * @param readCallback A callback for when the buffer has been read downstream
232 */
233 private writeToChunkBuffer;
234 /**
235 * Prepends data back to the upstream chunk buffer.
236 *
237 * @param chunk The data to prepend
238 */
239 private unshiftChunkBuffer;
240 /**
241 * Retrieves data from upstream's buffer.
242 *
243 * @param limit The maximum amount to return from the buffer.
244 * @returns The data requested.
245 */
246 private pullFromChunkBuffer;
247 /**
248 * A handler for determining if data is ready to be read from upstream.
249 *
250 * @returns If there will be more chunks to read in the future
251 */
252 private waitForNextChunk;
253 /**
254 * Reads data from upstream up to the provided `limit`.
255 * Ends when the limit has reached or no data is expected to be pushed from upstream.
256 *
257 * @param limit The most amount of data this iterator should return. `Infinity` by default.
258 * @param oneChunkMode Determines if one, exhaustive chunk is yielded for the iterator
259 */
260 private upstreamIterator;
261 createURI(): Promise<string>;
262 createURI(callback: CreateUriCallback): void;
263 protected createURIAsync(): Promise<string>;
264 private continueUploading;
265 startUploading(): Promise<void>;
266 private responseHandler;
267 /**
268 * Check if this is the same content uploaded previously. This caches a
269 * slice of the first chunk, then compares it with the first byte of
270 * incoming data.
271 *
272 * @returns if the request is ok to continue as-is
273 */
274 private ensureUploadingSameObject;
275 private getAndSetOffset;
276 private makeRequest;
277 private makeRequestStream;
278 private restart;
279 private get;
280 private set;
281 deleteConfig(): void;
282 /**
283 * @return {bool} is the request good?
284 */
285 private onResponse;
286 /**
287 * @param resp GaxiosResponse object from previous attempt
288 */
289 private attemptDelayedRetry;
290 /**
291 * @returns {number} the amount of time to wait before retrying the request
292 */
293 private getRetryDelay;
294 private sanitizeEndpoint;
295 /**
296 * Check if a given status code is 2xx
297 *
298 * @param status The status code to check
299 * @returns if the status is 2xx
300 */
301 isSuccessfulResponse(status: number): boolean;
302 /**
303 * Check if a given status code is 5xx
304 *
305 * @param status The status code to check
306 * @returns if the status is 5xx
307 */
308 isServerErrorResponse(status: number): boolean;
309}
310export declare function upload(cfg: UploadConfig): Upload;
311export declare function createURI(cfg: UploadConfig): Promise<string>;
312export declare function createURI(cfg: UploadConfig, callback: CreateUriCallback): void;