UNPKG

11.9 kBTypeScriptView Raw
1import { GaxiosOptions, GaxiosPromise, GaxiosResponse } from 'gaxios';
2import { GoogleAuthOptions } from 'google-auth-library';
3import { Writable, WritableOptions } from 'stream';
4import { RetryOptions, PreconditionOptions } from './storage.js';
5import { GCCL_GCS_CMD_KEY } from './nodejs-common/util.js';
6import { FileMetadata } from './file.js';
7export declare const PROTOCOL_REGEX: RegExp;
8export interface ErrorWithCode extends Error {
9 code: number;
10 status?: number | string;
11}
12export type CreateUriCallback = (err: Error | null, uri?: string) => void;
13export interface Encryption {
14 key: {};
15 hash: {};
16}
17export type PredefinedAcl = 'authenticatedRead' | 'bucketOwnerFullControl' | 'bucketOwnerRead' | 'private' | 'projectPrivate' | 'publicRead';
18export interface QueryParameters extends PreconditionOptions {
19 contentEncoding?: string;
20 kmsKeyName?: string;
21 predefinedAcl?: PredefinedAcl;
22 projection?: 'full' | 'noAcl';
23 userProject?: string;
24}
25export interface UploadConfig extends Pick<WritableOptions, 'highWaterMark'> {
26 /**
27 * The API endpoint used for the request.
28 * Defaults to `storage.googleapis.com`.
29 *
30 * **Warning**:
31 * If this value does not match the current GCP universe an emulator context
32 * will be assumed and authentication will be bypassed.
33 */
34 apiEndpoint?: string;
35 /**
36 * The name of the destination bucket.
37 */
38 bucket: string;
39 /**
40 * The name of the destination file.
41 */
42 file: string;
43 /**
44 * The GoogleAuthOptions passed to google-auth-library
45 */
46 authConfig?: GoogleAuthOptions;
47 /**
48 * If you want to re-use an auth client from google-auto-auth, pass an
49 * instance here.
50 * Defaults to GoogleAuth and gets automatically overridden if an
51 * emulator context is detected.
52 */
53 authClient?: {
54 request: <T>(opts: GaxiosOptions) => Promise<GaxiosResponse<T>> | GaxiosPromise<T>;
55 };
56 /**
57 * Create a separate request per chunk.
58 *
59 * This value is in bytes and should be a multiple of 256 KiB (2^18).
60 * We recommend using at least 8 MiB for the chunk size.
61 *
62 * @link https://cloud.google.com/storage/docs/performing-resumable-uploads#chunked-upload
63 */
64 chunkSize?: number;
65 /**
66 * For each API request we send, you may specify custom request options that
67 * we'll add onto the request. The request options follow the gaxios API:
68 * https://github.com/googleapis/gaxios#request-options.
69 */
70 customRequestOptions?: GaxiosOptions;
71 /**
72 * This will cause the upload to fail if the current generation of the remote
73 * object does not match the one provided here.
74 */
75 generation?: number;
76 /**
77 * Set to `true` if the upload is only a subset of the overall object to upload.
78 * This can be used when planning to continue the upload an object in another
79 * session.
80 *
81 * **Must be used with {@link UploadConfig.chunkSize} != `0`**.
82 *
83 * If this is a continuation of a previous upload, {@link UploadConfig.offset}
84 * should be set.
85 *
86 * @see {@link checkUploadStatus} for checking the status of an existing upload.
87 */
88 isPartialUpload?: boolean;
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 in relation to the final uploaded object.
107 * **Must be used with {@link UploadConfig.uri}**.
108 *
109 * If resuming an interrupted stream, do not supply this argument unless you
110 * know the exact number of bytes the service has AND the provided stream's
111 * first byte is a continuation from that provided offset. If resuming an
112 * interrupted stream and this option has not been provided, we will treat
113 * the provided upload stream as the object to upload - where the first byte
114 * of the upload stream is the first byte of the object to upload; skipping
115 * any bytes that are already present on the server.
116 *
117 * @see {@link checkUploadStatus} for checking the status of an existing upload.
118 * @see {@link https://cloud.google.com/storage/docs/json_api/v1/how-tos/resumable-upload#resume-upload.}
119 */
120 offset?: number;
121 /**
122 * Set an Origin header when creating the resumable upload URI.
123 */
124 origin?: string;
125 /**
126 * Specify query parameters that go along with the initial upload request. See
127 * https://cloud.google.com/storage/docs/json_api/v1/objects/insert#parameters
128 */
129 params?: QueryParameters;
130 /**
131 * Apply a predefined set of access controls to the created file.
132 */
133 predefinedAcl?: PredefinedAcl;
134 /**
135 * Make the uploaded file private. (Alias for config.predefinedAcl =
136 * 'private')
137 */
138 private?: boolean;
139 /**
140 * Make the uploaded file public. (Alias for config.predefinedAcl =
141 * 'publicRead')
142 */
143 public?: boolean;
144 /**
145 * The service domain for a given Cloud universe.
146 */
147 universeDomain?: string;
148 /**
149 * If you already have a resumable URI from a previously-created resumable
150 * upload, just pass it in here and we'll use that.
151 *
152 * If resuming an interrupted stream and the {@link UploadConfig.offset}
153 * option has not been provided, we will treat the provided upload stream as
154 * the object to upload - where the first byte of the upload stream is the
155 * first byte of the object to upload; skipping any bytes that are already
156 * present on the server.
157 *
158 * @see {@link checkUploadStatus} for checking the status of an existing upload.
159 */
160 uri?: string;
161 /**
162 * If the bucket being accessed has requesterPays functionality enabled, this
163 * can be set to control which project is billed for the access of this file.
164 */
165 userProject?: string;
166 /**
167 * Configuration options for retrying retryable errors.
168 */
169 retryOptions: RetryOptions;
170 [GCCL_GCS_CMD_KEY]?: string;
171}
172export interface ConfigMetadata {
173 [key: string]: any;
174 /**
175 * Set the length of the object being uploaded. If uploading a partial
176 * object, this is the overall size of the finalized object.
177 */
178 contentLength?: number;
179 /**
180 * Set the content type of the incoming data.
181 */
182 contentType?: string;
183}
184export interface GoogleInnerError {
185 reason?: string;
186}
187export interface ApiError extends Error {
188 code?: number;
189 errors?: GoogleInnerError[];
190}
191export interface CheckUploadStatusConfig {
192 /**
193 * Set to `false` to disable retries within this method.
194 *
195 * @defaultValue `true`
196 */
197 retry?: boolean;
198}
199export declare class Upload extends Writable {
200 #private;
201 bucket: string;
202 file: string;
203 apiEndpoint: string;
204 baseURI: string;
205 authConfig?: {
206 scopes?: string[];
207 };
208 authClient: {
209 request: <T>(opts: GaxiosOptions) => Promise<GaxiosResponse<T>> | GaxiosPromise<T>;
210 };
211 cacheKey: string;
212 chunkSize?: number;
213 customRequestOptions: GaxiosOptions;
214 generation?: number;
215 key?: string | Buffer;
216 kmsKeyName?: string;
217 metadata: ConfigMetadata;
218 offset?: number;
219 origin?: string;
220 params: QueryParameters;
221 predefinedAcl?: PredefinedAcl;
222 private?: boolean;
223 public?: boolean;
224 uri?: string;
225 userProject?: string;
226 encryption?: Encryption;
227 uriProvidedManually: boolean;
228 numBytesWritten: number;
229 numRetries: number;
230 contentLength: number | '*';
231 retryOptions: RetryOptions;
232 timeOfFirstRequest: number;
233 isPartialUpload: boolean;
234 private currentInvocationId;
235 /**
236 * A cache of buffers written to this instance, ready for consuming
237 */
238 private writeBuffers;
239 private numChunksReadInRequest;
240 /**
241 * An array of buffers used for caching the most recent upload chunk.
242 * We should not assume that the server received all bytes sent in the request.
243 * - https://cloud.google.com/storage/docs/performing-resumable-uploads#chunked-upload
244 */
245 private localWriteCache;
246 private localWriteCacheByteLength;
247 private upstreamEnded;
248 constructor(cfg: UploadConfig);
249 /**
250 * Prevent 'finish' event until the upload has succeeded.
251 *
252 * @param fireFinishEvent The finish callback
253 */
254 _final(fireFinishEvent?: () => void): void;
255 /**
256 * Handles incoming data from upstream
257 *
258 * @param chunk The chunk to append to the buffer
259 * @param encoding The encoding of the chunk
260 * @param readCallback A callback for when the buffer has been read downstream
261 */
262 _write(chunk: Buffer | string, encoding: BufferEncoding, readCallback?: () => void): void;
263 /**
264 * Prepends the local buffer to write buffer and resets it.
265 *
266 * @param keepLastBytes number of bytes to keep from the end of the local buffer.
267 */
268 private prependLocalBufferToUpstream;
269 /**
270 * Retrieves data from upstream's buffer.
271 *
272 * @param limit The maximum amount to return from the buffer.
273 */
274 private pullFromChunkBuffer;
275 /**
276 * A handler for determining if data is ready to be read from upstream.
277 *
278 * @returns If there will be more chunks to read in the future
279 */
280 private waitForNextChunk;
281 /**
282 * Reads data from upstream up to the provided `limit`.
283 * Ends when the limit has reached or no data is expected to be pushed from upstream.
284 *
285 * @param limit The most amount of data this iterator should return. `Infinity` by default.
286 */
287 private upstreamIterator;
288 createURI(): Promise<string>;
289 createURI(callback: CreateUriCallback): void;
290 protected createURIAsync(): Promise<string>;
291 private continueUploading;
292 startUploading(): Promise<void>;
293 private responseHandler;
294 /**
295 * Check the status of an existing resumable upload.
296 *
297 * @param cfg A configuration to use. `uri` is required.
298 * @returns the current upload status
299 */
300 checkUploadStatus(config?: CheckUploadStatusConfig): Promise<GaxiosResponse<FileMetadata | void>>;
301 private getAndSetOffset;
302 private makeRequest;
303 private makeRequestStream;
304 /**
305 * @return {bool} is the request good?
306 */
307 private onResponse;
308 /**
309 * @param resp GaxiosResponse object from previous attempt
310 */
311 private attemptDelayedRetry;
312 /**
313 * The amount of time to wait before retrying the request, in milliseconds.
314 * If negative, do not retry.
315 *
316 * @returns the amount of time to wait, in milliseconds.
317 */
318 private getRetryDelay;
319 private sanitizeEndpoint;
320 /**
321 * Check if a given status code is 2xx
322 *
323 * @param status The status code to check
324 * @returns if the status is 2xx
325 */
326 isSuccessfulResponse(status: number): boolean;
327}
328export declare function upload(cfg: UploadConfig): Upload;
329export declare function createURI(cfg: UploadConfig): Promise<string>;
330export declare function createURI(cfg: UploadConfig, callback: CreateUriCallback): void;
331/**
332 * Check the status of an existing resumable upload.
333 *
334 * @param cfg A configuration to use. `uri` is required.
335 * @returns the current upload status
336 */
337export declare function checkUploadStatus(cfg: UploadConfig & Required<Pick<UploadConfig, 'uri'>>): Promise<GaxiosResponse<void | FileMetadata>>;