UNPKG

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