@google-cloud/storage
Version:
Cloud Storage Client Library for Node.js
176 lines (175 loc) • 7.02 kB
JavaScript
/*!
* Copyright 2022 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Transform } from 'stream';
import * as crypto from 'crypto';
import { getModuleFormat, getRuntimeTrackingString, getUserAgentString, } from '../util.js';
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import { getPackageJSON } from '../package-json-helper.cjs';
const packageJson = getPackageJSON();
/**
* A unique symbol for providing a `gccl-gcs-cmd` value
* for the `X-Goog-API-Client` header.
*
* E.g. the `V` in `X-Goog-API-Client: gccl-gcs-cmd/V`
**/
export const GCCL_GCS_CMD_KEY = Symbol.for('GCCL_GCS_CMD');
export class Util {
/**
* No op.
*
* @example
* function doSomething(callback) {
* callback = callback || noop;
* }
*/
noop() { }
/**
* Returns true if the API request should be retried, given the error that was
* given the first time the request was attempted. This is used for rate limit
* related errors as well as intermittent server errors.
*
* @param {error} err - The API error to check if it is appropriate to retry.
* @return {boolean} True if the API request should be retried, false otherwise.
*/
shouldRetryRequest(err) {
if (err) {
if ([408, 429, 500, 502, 503, 504].indexOf(err.status) !== -1) {
return true;
}
if (err.error || err.code) {
const reason = err.code;
if (reason === 'rateLimitExceeded') {
return true;
}
if (reason === 'userRateLimitExceeded') {
return true;
}
if (reason &&
typeof reason === 'string' &&
reason.includes('EAI_AGAIN')) {
return true;
}
}
}
return false;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
isCustomType(unknown, module) {
function getConstructorName(obj) {
return obj.constructor && obj.constructor.name.toLowerCase();
}
const moduleNameParts = module.split('/');
const parentModuleName = moduleNameParts[0] && moduleNameParts[0].toLowerCase();
const subModuleName = moduleNameParts[1] && moduleNameParts[1].toLowerCase();
if (subModuleName && getConstructorName(unknown) !== subModuleName) {
return false;
}
let walkingModule = unknown;
// eslint-disable-next-line no-constant-condition
while (true) {
if (getConstructorName(walkingModule) === parentModuleName) {
return true;
}
walkingModule = walkingModule.parent;
if (!walkingModule) {
return false;
}
}
}
/**
* Given two parameters, figure out if this is either:
* - Just a callback function
* - An options object, and then a callback function
* @param optionsOrCallback An options object or callback.
* @param cb A potentially undefined callback.
*/
maybeOptionsOrCallback(optionsOrCallback, cb) {
return typeof optionsOrCallback === 'function'
? [{}, optionsOrCallback]
: [optionsOrCallback, cb];
}
decorateHeaders(headers, options) {
return decorateHeaders(headers, options);
}
_getDefaultHeaders(gcclGcsCmd) {
return decorateHeaders(undefined, { gcclGcsCmd }).headers;
}
}
/**
* Decorates and sanitizes headers for GCS requests:
* - Checks for user-provided `x-goog-gcs-idempotency-token` case-insensitively.
* - If a valid non-empty string user token is provided, uses it as the idempotency token and preserves the header.
* - If not provided or invalid, removes any invalid header key and sets `x-goog-gcs-idempotency-token` to either the provided fallback token or a generated UUID.
* - Adds `User-Agent` and `x-goog-api-client` (with tracking string, package version, gccl-invocation-id, and optional gccl-gcs-cmd).
*
* @param headers Existing headers object (optional).
* @param options Decoration options (idempotencyToken, packageJson, providedUserAgent, gcclGcsCmd).
* @returns An object containing the decorated headers and the effective idempotency token.
*/
export function decorateHeaders(headers, options) {
const sanitizedHeaders = headers instanceof globalThis.Headers
? Object.assign(Object.fromEntries(headers.entries()), headers)
: Array.isArray(headers)
? Object.fromEntries(headers)
: { ...headers };
const userTokenKey = Object.keys(sanitizedHeaders).find(key => key.toLowerCase() === 'x-goog-gcs-idempotency-token');
const userTokenValue = userTokenKey
? sanitizedHeaders[userTokenKey]
: undefined;
const hasValidUserToken = typeof userTokenValue === 'string' && userTokenValue.trim() !== '';
const idempotencyToken = hasValidUserToken
? userTokenValue
: options?.idempotencyToken || crypto.randomUUID();
let userAgent = getUserAgentString();
if (options?.providedUserAgent) {
userAgent = `${options.providedUserAgent} ${userAgent}`;
}
const pkg = options?.packageJson || packageJson;
let googAPIClient = `${getRuntimeTrackingString()} gccl/${pkg.version}-${getModuleFormat()} gccl-invocation-id/${idempotencyToken}`;
const gcclGcsCmd = options?.gcclGcsCmd;
if (gcclGcsCmd) {
googAPIClient += ` gccl-gcs-cmd/${gcclGcsCmd}`;
}
sanitizedHeaders['User-Agent'] = userAgent;
sanitizedHeaders['x-goog-api-client'] = googAPIClient;
if (!hasValidUserToken) {
if (userTokenKey) {
delete sanitizedHeaders[userTokenKey];
}
sanitizedHeaders['x-goog-gcs-idempotency-token'] = idempotencyToken;
}
return {
headers: sanitizedHeaders,
idempotencyToken,
};
}
/**
* Basic Passthrough Stream that records the number of bytes read
* every time the cursor is moved.
*/
export class ProgressStream extends Transform {
bytesRead = 0;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
_transform(chunk, encoding, callback) {
this.bytesRead += chunk.length;
this.emit('progress', { bytesWritten: this.bytesRead, contentLength: '*' });
this.push(chunk);
callback();
}
}
const util = new Util();
export { util };