@google-cloud/storage
Version:
Cloud Storage Client Library for Node.js
215 lines (214 loc) • 8.69 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.
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.util = exports.ProgressStream = exports.Util = exports.GCCL_GCS_CMD_KEY = void 0;
exports.decorateHeaders = decorateHeaders;
const stream_1 = require("stream");
const crypto = __importStar(require("crypto"));
const util_js_1 = require("../util.js");
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const package_json_helper_cjs_1 = require("../package-json-helper.cjs");
const packageJson = (0, package_json_helper_cjs_1.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`
**/
exports.GCCL_GCS_CMD_KEY = Symbol.for('GCCL_GCS_CMD');
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;
}
}
exports.Util = Util;
/**
* 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.
*/
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 = (0, util_js_1.getUserAgentString)();
if (options?.providedUserAgent) {
userAgent = `${options.providedUserAgent} ${userAgent}`;
}
const pkg = options?.packageJson || packageJson;
let googAPIClient = `${(0, util_js_1.getRuntimeTrackingString)()} gccl/${pkg.version}-${(0, util_js_1.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.
*/
class ProgressStream extends stream_1.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();
}
}
exports.ProgressStream = ProgressStream;
const util = new Util();
exports.util = util;