push all website files

This commit is contained in:
Jacob Levine
2019-01-06 13:14:45 -06:00
parent d7301e26c3
commit d2d5d4c04e
15662 changed files with 2166516 additions and 0 deletions

View File

@@ -0,0 +1,4 @@
export declare class GoogleError extends Error {
code?: number;
note?: string;
}

View File

@@ -0,0 +1,54 @@
"use strict";
/*
* Copyright 2018, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
}
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var GoogleError = /** @class */ (function (_super) {
__extends(GoogleError, _super);
function GoogleError() {
return _super !== null && _super.apply(this, arguments) || this;
}
return GoogleError;
}(Error));
exports.GoogleError = GoogleError;
//# sourceMappingURL=GoogleError.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"GoogleError.js","sourceRoot":"","sources":["../../src/GoogleError.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;;;;;;;;;;;;;;;AAEH;IAAiC,+BAAK;IAAtC;;IAGA,CAAC;IAAD,kBAAC;AAAD,CAAC,AAHD,CAAiC,KAAK,GAGrC;AAHY,kCAAW"}

View File

@@ -0,0 +1,118 @@
import { CallSettings } from './gax';
import { GoogleError } from './GoogleError';
export interface ArgumentFunction {
(argument: {}, callback: APICallback): void;
}
/**
* @callback APICallback
* @param {?Error} error
* @param {?Object} response
*/
export declare type APICallback = (err: GoogleError | null, response?: any, next?: {} | null, rawResponse?: {} | null) => void;
/**
* @callback APIFunc
* @param {Object} argument
* @param {grpc.Metadata} metadata
* @param {Object} options
* @param {APICallback} callback
*/
export declare type APIFunc = (argument: {}, metadata: {}, options: {}, callback: APICallback) => Canceller;
/**
* @callback APICall
* @param {Object} argument
* @param {CallOptions} callOptions
* @param {APICallback} callback
* @return {Promise|Stream|undefined}
*/
export interface APICall {
(argument?: {} | null, callOptions?: {} | null, callback?: APICallback): any;
}
export declare class Canceller {
callback?: APICallback;
cancelFunc?: () => void;
completed: boolean;
/**
* Canceller manages callback, API calls, and cancellation
* of the API calls.
* @param {APICallback=} callback
* The callback to be called asynchronously when the API call
* finishes.
* @constructor
* @property {APICallback} callback
* The callback function to be called.
* @private
*/
constructor(callback?: APICallback);
/**
* Cancels the ongoing promise.
*/
cancel(): void;
/**
* Call calls the specified function. Result will be used to fulfill
* the promise.
*
* @param {function(Object, APICallback=)} aFunc
* A function for an API call.
* @param {Object} argument
* A request object.
*/
call(aFunc: (obj: {}, callback: APICallback) => PromiseCanceller, argument: {}): void;
}
export interface CancellablePromise<T = any> extends Promise<T> {
cancel(): void;
}
export declare class PromiseCanceller<T = any> extends Canceller {
promise: CancellablePromise<T>;
/**
* PromiseCanceller is Canceller, but it holds a promise when
* the API call finishes.
* @param {Function} PromiseCtor - A constructor for a promise that implements
* the ES6 specification of promise.
* @constructor
* @private
*/
constructor(PromiseCtor: PromiseConstructor);
}
export interface ApiCallOtherArgs {
options?: {
deadline?: Date;
};
headers?: {};
metadataBuilder: (abTests?: {}, headers?: {}) => {};
}
/**
* Creates an API caller for normal methods.
*
* @private
* @constructor
*/
export declare class NormalApiCaller {
init(settings: {
promise: PromiseConstructor;
}, callback: APICallback): PromiseCanceller | Canceller;
wrap(func: Function): Function;
call(apiCall: APICall, argument: {}, settings: {}, canceller: PromiseCanceller): void;
fail(canceller: PromiseCanceller, err: GoogleError): void;
result(canceller: PromiseCanceller): CancellablePromise<any> | undefined;
}
/**
* Converts an rpc call into an API call governed by the settings.
*
* In typical usage, `func` will be a promsie to a callable used to make an rpc
* request. This will mostly likely be a bound method from a request stub used
* to make an rpc call. It is not a direct function but a Promise instance,
* because of its asynchronism (typically, obtaining the auth information).
*
* The result is a function which manages the API call with the given settings
* and the options on the invocation.
*
* @param {Promise.<APIFunc>} funcWithAuth - is a promise to be used to make
* a bare rpc call. This is a Promise instead of a bare function because
* the rpc call will be involeved with asynchronous authentications.
* @param {CallSettings} settings - provides the settings for this call
* @param {Object=} optDescriptor - optionally specify the descriptor for
* the method call.
* @return {APICall} func - a bound method on a request stub used
* to make an rpc call.
*/
export declare function createApiCall(funcWithAuth: Promise<APIFunc>, settings: CallSettings, optDescriptor?: any): APICall;

View File

@@ -0,0 +1,349 @@
/*
* Copyright 2016, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Provides function wrappers that implement page streaming and retrying.
*/
'use strict';
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
}
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var Canceller = /** @class */ (function () {
/**
* Canceller manages callback, API calls, and cancellation
* of the API calls.
* @param {APICallback=} callback
* The callback to be called asynchronously when the API call
* finishes.
* @constructor
* @property {APICallback} callback
* The callback function to be called.
* @private
*/
function Canceller(callback) {
this.callback = callback;
this.completed = false;
}
/**
* Cancels the ongoing promise.
*/
Canceller.prototype.cancel = function () {
if (this.completed) {
return;
}
this.completed = true;
if (this.cancelFunc) {
this.cancelFunc();
}
else {
this.callback(new Error('cancelled'));
}
};
/**
* Call calls the specified function. Result will be used to fulfill
* the promise.
*
* @param {function(Object, APICallback=)} aFunc
* A function for an API call.
* @param {Object} argument
* A request object.
*/
Canceller.prototype.call = function (aFunc, argument) {
var _this = this;
if (this.completed) {
return;
}
// tslint:disable-next-line no-any
var canceller = aFunc(argument, function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
_this.completed = true;
args.unshift(_this.callback);
setImmediate.apply(null, args);
});
this.cancelFunc = function () {
canceller.cancel();
};
};
return Canceller;
}());
exports.Canceller = Canceller;
// tslint:disable-next-line no-any
var PromiseCanceller = /** @class */ (function (_super) {
__extends(PromiseCanceller, _super);
/**
* PromiseCanceller is Canceller, but it holds a promise when
* the API call finishes.
* @param {Function} PromiseCtor - A constructor for a promise that implements
* the ES6 specification of promise.
* @constructor
* @private
*/
// tslint:disable-next-line variable-name
function PromiseCanceller(PromiseCtor) {
var _this = _super.call(this) || this;
_this.promise = new PromiseCtor(function (resolve, reject) {
_this.callback = function (err, response, next, rawResponse) {
if (err) {
reject(err);
}
else {
resolve([response, next, rawResponse]);
}
};
});
_this.promise.cancel = function () {
_this.cancel();
};
return _this;
}
return PromiseCanceller;
}(Canceller));
exports.PromiseCanceller = PromiseCanceller;
/**
* Updates aFunc so that it gets called with the timeout as its final arg.
*
* This converts a function, aFunc, into another function with updated deadline.
*
* @private
*
* @param {APIFunc} aFunc - a function to be updated.
* @param {number} timeout - to be added to the original function as it final
* positional arg.
* @param {Object} otherArgs - the additional arguments to be passed to aFunc.
* @param {Object=} abTests - the A/B testing key/value pairs.
* @return {function(Object, APICallback)}
* the function with other arguments and the timeout.
*/
function addTimeoutArg(aFunc, timeout, otherArgs, abTests) {
// TODO: this assumes the other arguments consist of metadata and options,
// which is specific to gRPC calls. Remove the hidden dependency on gRPC.
return function timeoutFunc(argument, callback) {
var now = new Date();
var options = otherArgs.options || {};
options.deadline = new Date(now.getTime() + timeout);
var metadata = otherArgs.metadataBuilder ?
otherArgs.metadataBuilder(abTests, otherArgs.headers || {}) :
null;
return aFunc(argument, metadata, options, callback);
};
}
/**
* Creates a function equivalent to aFunc, but that retries on certain
* exceptions.
*
* @private
*
* @param {APIFunc} aFunc - A function.
* @param {RetryOptions} retry - Configures the exceptions upon which the
* function eshould retry, and the parameters to the exponential backoff retry
* algorithm.
* @param {Object} otherArgs - the additional arguments to be passed to aFunc.
* @return {function(Object, APICallback)} A function that will retry.
*/
function retryable(aFunc, retry, otherArgs) {
var delayMult = retry.backoffSettings.retryDelayMultiplier;
var maxDelay = retry.backoffSettings.maxRetryDelayMillis;
var timeoutMult = retry.backoffSettings.rpcTimeoutMultiplier;
var maxTimeout = retry.backoffSettings.maxRpcTimeoutMillis;
var delay = retry.backoffSettings.initialRetryDelayMillis;
var timeout = retry.backoffSettings.initialRpcTimeoutMillis;
/**
* Equivalent to ``aFunc``, but retries upon transient failure.
*
* Retrying is done through an exponential backoff algorithm configured
* by the options in ``retry``.
* @param {Object} argument The request object.
* @param {APICallback} callback The callback.
* @return {function()} cancel function.
*/
return function retryingFunc(argument, callback) {
var canceller;
var timeoutId;
var now = new Date();
var deadline;
if (retry.backoffSettings.totalTimeoutMillis) {
deadline = now.getTime() + retry.backoffSettings.totalTimeoutMillis;
}
var retries = 0;
var maxRetries = retry.backoffSettings.maxRetries;
// TODO: define A/B testing values for retry behaviors.
/** Repeat the API call as long as necessary. */
function repeat() {
timeoutId = null;
if (deadline && now.getTime() >= deadline) {
callback(new Error('Retry total timeout exceeded before any ' +
'response was received'));
return;
}
if (retries && retries >= maxRetries) {
callback(new Error('Exceeded maximum number of retries before any ' +
'response was received'));
return;
}
retries++;
var toCall = addTimeoutArg(aFunc, timeout, otherArgs);
canceller = toCall(argument, function (err, response, next, rawResponse) {
if (!err) {
callback(null, response, next, rawResponse);
return;
}
canceller = null;
if (retry.retryCodes.indexOf(err.code) < 0) {
err.note = 'Exception occurred in retry method that was ' +
'not classified as transient';
callback(err);
}
else {
var toSleep = Math.random() * delay;
timeoutId = setTimeout(function () {
now = new Date();
delay = Math.min(delay * delayMult, maxDelay);
timeout = Math.min(timeout * timeoutMult, maxTimeout, deadline - now.getTime());
repeat();
}, toSleep);
}
});
}
if (maxRetries && deadline) {
callback(new Error('Cannot set both totalTimeoutMillis and maxRetries ' +
'in backoffSettings.'));
}
else {
repeat();
}
return {
cancel: function () {
if (timeoutId) {
clearTimeout(timeoutId);
}
if (canceller) {
canceller.cancel();
}
else {
callback(new Error('cancelled'));
}
},
};
};
}
/**
* Creates an API caller for normal methods.
*
* @private
* @constructor
*/
var NormalApiCaller = /** @class */ (function () {
function NormalApiCaller() {
}
NormalApiCaller.prototype.init = function (settings, callback) {
if (callback) {
return new Canceller(callback);
}
return new PromiseCanceller(settings.promise);
};
NormalApiCaller.prototype.wrap = function (func) {
return func;
};
NormalApiCaller.prototype.call = function (apiCall, argument, settings, canceller) {
canceller.call(apiCall, argument);
};
NormalApiCaller.prototype.fail = function (canceller, err) {
canceller.callback(err);
};
NormalApiCaller.prototype.result = function (canceller) {
if (canceller.promise) {
return canceller.promise;
}
return;
};
return NormalApiCaller;
}());
exports.NormalApiCaller = NormalApiCaller;
/**
* Converts an rpc call into an API call governed by the settings.
*
* In typical usage, `func` will be a promsie to a callable used to make an rpc
* request. This will mostly likely be a bound method from a request stub used
* to make an rpc call. It is not a direct function but a Promise instance,
* because of its asynchronism (typically, obtaining the auth information).
*
* The result is a function which manages the API call with the given settings
* and the options on the invocation.
*
* @param {Promise.<APIFunc>} funcWithAuth - is a promise to be used to make
* a bare rpc call. This is a Promise instead of a bare function because
* the rpc call will be involeved with asynchronous authentications.
* @param {CallSettings} settings - provides the settings for this call
* @param {Object=} optDescriptor - optionally specify the descriptor for
* the method call.
* @return {APICall} func - a bound method on a request stub used
* to make an rpc call.
*/
function createApiCall(funcWithAuth, settings,
// tslint:disable-next-line no-any
optDescriptor) {
var apiCaller = optDescriptor ? optDescriptor.apiCaller(settings) : new NormalApiCaller();
return function apiCallInner(request, callOptions, callback) {
var thisSettings = settings.merge(callOptions);
var status = apiCaller.init(thisSettings, callback);
funcWithAuth
.then(function (func) {
func = apiCaller.wrap(func);
var retry = thisSettings.retry;
if (retry && retry.retryCodes && retry.retryCodes.length > 0) {
return retryable(func, thisSettings.retry, thisSettings.otherArgs);
}
return addTimeoutArg(func, thisSettings.timeout, thisSettings.otherArgs);
})
.then(function (apiCall) {
apiCaller.call(apiCall, request, thisSettings, status);
})
.catch(function (err) {
apiCaller.fail(status, err);
});
return apiCaller.result(status);
};
}
exports.createApiCall = createApiCall;
//# sourceMappingURL=api_callable.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,26 @@
import { GoogleError } from './GoogleError';
/**
* @callback GetCredentialsFunc
*
* To authorize requests through gRPC, we must get the raw google-auth-library
* auth client object.
*
* @param {function()} callback - The callback function.
* @param {Object} opts - options values for configuring auth
* @param {(String|String[])} opts.scopes - the scope or scopes to use when
* obtaining the credentials.
* @param {Object} opts.sslCreds - when specified, this is used instead
* of default credentials.
*/
/**
* Creates a promise which resolves a auth credential.
*
* @param {GetCredentialsFunc} getCredentials - the callback used to
* obtain the credentials.
* @param {Object} opts - the optional arguments to be passed to
* getCredentials.
* @return {Promise} A promise which resolves to the credential.
*/
export declare function createCredPromise(getCredentials: GetCredentialsFunc, opts?: {}): Promise<{}>;
export declare type GetCredentialsCallback = (err: GoogleError | null, credentials: {}) => void;
export declare type GetCredentialsFunc = (callback: GetCredentialsCallback, opts?: {}) => void;

View File

@@ -0,0 +1,70 @@
/*
*
* Copyright 2016, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
/**
* @callback GetCredentialsFunc
*
* To authorize requests through gRPC, we must get the raw google-auth-library
* auth client object.
*
* @param {function()} callback - The callback function.
* @param {Object} opts - options values for configuring auth
* @param {(String|String[])} opts.scopes - the scope or scopes to use when
* obtaining the credentials.
* @param {Object} opts.sslCreds - when specified, this is used instead
* of default credentials.
*/
/**
* Creates a promise which resolves a auth credential.
*
* @param {GetCredentialsFunc} getCredentials - the callback used to
* obtain the credentials.
* @param {Object} opts - the optional arguments to be passed to
* getCredentials.
* @return {Promise} A promise which resolves to the credential.
*/
function createCredPromise(getCredentials, opts) {
return new Promise(function (resolve, reject) {
getCredentials(function (err, credentials) {
if (err) {
reject(err);
}
else {
resolve(credentials);
}
}, opts);
});
}
exports.createCredPromise = createCredPromise;
//# sourceMappingURL=auth.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"auth.js","sourceRoot":"","sources":["../../src/auth.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,YAAY,CAAC;;AAIb;;;;;;;;;;;;GAYG;AAEH;;;;;;;;GAQG;AACH,SAAgB,iBAAiB,CAC7B,cAAkC,EAAE,IAAS;IAC/C,OAAO,IAAI,OAAO,CAAC,UAAC,OAAO,EAAE,MAAM;QACjC,cAAc,CAAC,UAAC,GAAG,EAAE,WAAW;YAC9B,IAAI,GAAG,EAAE;gBACP,MAAM,CAAC,GAAG,CAAC,CAAC;aACb;iBAAM;gBACL,OAAO,CAAC,WAAW,CAAC,CAAC;aACtB;QACH,CAAC,EAAE,IAAI,CAAC,CAAC;IACX,CAAC,CAAC,CAAC;AACL,CAAC;AAXD,8CAWC"}

View File

@@ -0,0 +1,216 @@
/// <reference types="node" />
import { NormalApiCaller, APICall, PromiseCanceller, APICallback } from './api_callable';
import { CallSettings } from './gax';
/**
* Compute the identifier of the `obj`. The objects of the same ID
* will be bundled together.
*
* @param {Object} obj - The request object.
* @param {String[]} discriminatorFields - The array of field names.
* A field name may include '.' as a separator, which is used to
* indicate object traversal.
* @return {String|undefined} - the identifier string, or undefined if any
* discriminator.
* fields do not exist.
*/
export declare function computeBundleId(obj: {}, discriminatorFields: string[]): string | undefined;
export interface SubResponseInfo {
field: string;
start?: number;
end?: number;
}
export interface TaskElement {
}
export interface TaskData {
elements: TaskElement[];
bytes: number;
callback: TaskCallback;
cancelled?: boolean;
}
export interface TaskCallback extends APICallback {
id?: string;
}
/**
* Creates a deep copy of the object with the consideration of subresponse
* fields for bundling.
*
* @param {Object} obj - The source object.
* @param {Object?} subresponseInfo - The information to copy the subset of
* the field for the response. Do nothing if it's null.
* @param {String} subresponseInfo.field - The field name.
* @param {number} subresponseInfo.start - The offset where the copying
* element should starts with.
* @param {number} subresponseInfo.end - The ending index where the copying
* region of the elements ends.
* @return {Object} The copied object.
* @private
*/
export declare function deepCopyForResponse(obj: any, subresponseInfo: SubResponseInfo | null): any;
export declare class Task {
_apiCall: APICall;
_request: {
[index: string]: TaskElement[];
};
_bundledField: string;
_subresponseField?: string | null;
_data: TaskData[];
callCanceller?: PromiseCanceller;
/**
* A task coordinates the execution of a single bundle.
*
* @param {function} apiCall - The function to conduct calling API.
* @param {Object} bundlingRequest - The base request object to be used
* for the actual API call.
* @param {string} bundledField - The name of the field in bundlingRequest
* to be bundled.
* @param {string=} subresponseField - The name of the field in the response
* to be passed to the callback.
* @constructor
* @private
*/
constructor(apiCall: APICall, bundlingRequest: {}, bundledField: string, subresponseField?: string | null);
/**
* Returns the number of elements in a task.
* @return {number} The number of elements.
*/
getElementCount(): number;
/**
* Returns the total byte size of the elements in a task.
* @return {number} The byte size.
*/
getRequestByteSize(): number;
/**
* Invokes the actual API call with current elements.
* @return {string[]} - the list of ids for invocations to be run.
*/
run(): string[];
/**
* Appends the list of elements into the task.
* @param {Object[]} elements - the new list of elements.
* @param {number} bytes - the byte size required to encode elements in the API.
* @param {APICallback} callback - the callback of the method call.
*/
extend(elements: TaskElement[], bytes: number, callback: TaskCallback): void;
/**
* Cancels a part of elements.
* @param {string} id - The identifier of the part of elements.
* @return {boolean} Whether the entire task will be canceled or not.
*/
cancel(id: string): boolean;
}
export interface BundleOptions {
elementCountLimit: number;
requestByteLimit: number;
elementCountThreshold: number;
requestByteThreshold: number;
delayThreshold: number;
}
export declare class BundleExecutor {
_options: BundleOptions;
_descriptor: BundleDescriptor;
_tasks: {
[index: string]: Task;
};
_timers: {
[index: string]: NodeJS.Timer;
};
_invocations: {
[index: string]: string;
};
_invocationId: number;
/**
* Organizes requests for an api service that requires to bundle them.
*
* @param {BundleOptions} bundleOptions - configures strategy this instance
* uses when executing bundled functions.
* @param {BundleDescriptor} bundleDescriptor - the description of the bundling.
* @constructor
*/
constructor(bundleOptions: BundleOptions, bundleDescriptor: BundleDescriptor);
/**
* Schedule a method call.
*
* @param {function} apiCall - the function for an API call.
* @param {Object} request - the request object to be bundled with others.
* @param {APICallback} callback - the callback to be called when the method finished.
* @return {function()} - the function to cancel the scheduled invocation.
*/
schedule(apiCall: APICall, request: {
[index: string]: Array<{}> | string;
}, callback?: TaskCallback): any;
/**
* Clears scheduled timeout if it exists.
*
* @param {String} bundleId - the id for the task whose timeout needs to be
* cleared.
* @private
*/
_maybeClearTimeout(bundleId: string): void;
/**
* Cancels an event.
*
* @param {String} id - The id for the event in the task.
* @private
*/
_cancel(id: string): void;
/**
* Invokes a task.
*
* @param {String} bundleId - The id for the task.
* @private
*/
_runNow(bundleId: string): void;
}
export declare class Bundleable extends NormalApiCaller {
bundler: BundleExecutor;
/**
* Creates an API caller that bundles requests.
*
* @private
* @constructor
* @param {BundleExecutor} bundler - bundles API calls.
*/
constructor(bundler: BundleExecutor);
call(apiCall: APICall, argument: {}, settings: CallSettings, status: any): void;
}
export declare class BundleDescriptor {
bundledField: string;
requestDiscriminatorFields: string[];
subresponseField: string | null;
byteLengthFunction: Function;
/**
* Describes the structure of bundled call.
*
* requestDiscriminatorFields may include '.' as a separator, which is used to
* indicate object traversal. This allows fields in nested objects to be used
* to determine what request to bundle.
*
* @property {String} bundledField
* @property {String} requestDiscriminatorFields
* @property {String} subresponseField
* @property {Function} byteLengthFunction
*
* @param {String} bundledField - the repeated field in the request message
* that will have its elements aggregated by bundling.
* @param {String} requestDiscriminatorFields - a list of fields in the
* target request message class that are used to detemrine which request
* messages should be bundled together.
* @param {String} subresponseField - an optional field, when present it
* indicates the field in the response message that should be used to
* demultiplex the response into multiple response messages.
* @param {Function} byteLengthFunction - a function to obtain the byte
* length to be consumed for the bundled field messages. Because Node.JS
* protobuf.js/gRPC uses builtin Objects for the user-visible data and
* internally they are encoded/decoded in protobuf manner, this function
* is actually necessary to calculate the byte length.
* @constructor
*/
constructor(bundledField: string, requestDiscriminatorFields: string[], subresponseField: string | null, byteLengthFunction: Function);
/**
* Returns a new API caller.
* @private
* @param {CallSettings} settings - the current settings.
* @return {Bundleable} - the new bundling API caller.
*/
apiCaller(settings: CallSettings): Bundleable;
}

View File

@@ -0,0 +1,523 @@
/*
* Copyright 2016, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Provides behavior that supports request bundling.
*/
'use strict';
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
}
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var _ = require("lodash");
var api_callable_1 = require("./api_callable");
/**
* A function which does nothing. Used for an empty cancellation funciton.
* @private
*/
function noop() { }
/**
* Compute the identifier of the `obj`. The objects of the same ID
* will be bundled together.
*
* @param {Object} obj - The request object.
* @param {String[]} discriminatorFields - The array of field names.
* A field name may include '.' as a separator, which is used to
* indicate object traversal.
* @return {String|undefined} - the identifier string, or undefined if any
* discriminator.
* fields do not exist.
*/
function computeBundleId(obj, discriminatorFields) {
var ids = [];
var hasIds = false;
for (var i = 0; i < discriminatorFields.length; ++i) {
var id = _.at(obj, discriminatorFields[i])[0];
if (id === undefined) {
ids.push(null);
}
else {
hasIds = true;
ids.push(id);
}
}
if (!hasIds) {
return undefined;
}
return JSON.stringify(ids);
}
exports.computeBundleId = computeBundleId;
/**
* Creates a deep copy of the object with the consideration of subresponse
* fields for bundling.
*
* @param {Object} obj - The source object.
* @param {Object?} subresponseInfo - The information to copy the subset of
* the field for the response. Do nothing if it's null.
* @param {String} subresponseInfo.field - The field name.
* @param {number} subresponseInfo.start - The offset where the copying
* element should starts with.
* @param {number} subresponseInfo.end - The ending index where the copying
* region of the elements ends.
* @return {Object} The copied object.
* @private
*/
function deepCopyForResponse(
// tslint:disable-next-line no-any
obj, subresponseInfo) {
// tslint:disable-next-line no-any
var result;
if (obj === null) {
return null;
}
if (obj === undefined) {
return undefined;
}
if (Array.isArray(obj)) {
result = [];
obj.forEach(function (element) {
result.push(deepCopyForResponse(element, null));
});
return result;
}
// Some objects (such as ByteBuffer) have copy method.
if (obj.copy !== undefined) {
return obj.copy();
}
// ArrayBuffer should be copied through slice().
if (obj instanceof ArrayBuffer) {
return obj.slice(0);
}
if (typeof obj === 'object') {
result = {};
Object.keys(obj).forEach(function (key) {
if (subresponseInfo && key === subresponseInfo.field &&
Array.isArray(obj[key])) {
// Note that subresponses are not deep-copied. This is safe because
// those subresponses are not shared among callbacks.
result[key] =
obj[key].slice(subresponseInfo.start, subresponseInfo.end);
}
else {
result[key] = deepCopyForResponse(obj[key], null);
}
});
return result;
}
return obj;
}
exports.deepCopyForResponse = deepCopyForResponse;
var Task = /** @class */ (function () {
/**
* A task coordinates the execution of a single bundle.
*
* @param {function} apiCall - The function to conduct calling API.
* @param {Object} bundlingRequest - The base request object to be used
* for the actual API call.
* @param {string} bundledField - The name of the field in bundlingRequest
* to be bundled.
* @param {string=} subresponseField - The name of the field in the response
* to be passed to the callback.
* @constructor
* @private
*/
function Task(apiCall, bundlingRequest, bundledField, subresponseField) {
this._apiCall = apiCall;
this._request = bundlingRequest;
this._bundledField = bundledField;
this._subresponseField = subresponseField;
this._data = [];
}
/**
* Returns the number of elements in a task.
* @return {number} The number of elements.
*/
Task.prototype.getElementCount = function () {
var count = 0;
for (var i = 0; i < this._data.length; ++i) {
count += this._data[i].elements.length;
}
return count;
};
/**
* Returns the total byte size of the elements in a task.
* @return {number} The byte size.
*/
Task.prototype.getRequestByteSize = function () {
var size = 0;
for (var i = 0; i < this._data.length; ++i) {
size += this._data[i].bytes;
}
return size;
};
/**
* Invokes the actual API call with current elements.
* @return {string[]} - the list of ids for invocations to be run.
*/
Task.prototype.run = function () {
if (this._data.length === 0) {
return [];
}
var request = this._request;
var elements = [];
var ids = [];
for (var i = 0; i < this._data.length; ++i) {
elements.push.apply(elements, this._data[i].elements);
ids.push(this._data[i].callback.id);
}
request[this._bundledField] = elements;
var self = this;
this.callCanceller =
this._apiCall(request, function (err, response) {
var responses = [];
if (err) {
self._data.forEach(function () {
responses.push(null);
});
}
else {
var subresponseInfo_1 = null;
if (self._subresponseField) {
subresponseInfo_1 = {
field: self._subresponseField,
start: 0,
};
}
self._data.forEach(function (data) {
if (subresponseInfo_1) {
subresponseInfo_1.end =
subresponseInfo_1.start + data.elements.length;
}
responses.push(deepCopyForResponse(response, subresponseInfo_1));
if (subresponseInfo_1) {
subresponseInfo_1.start = subresponseInfo_1.end;
}
});
}
for (var i = 0; i < self._data.length; ++i) {
if (self._data[i].cancelled) {
self._data[i].callback(new Error('cancelled'));
}
else {
self._data[i].callback(err, responses[i]);
}
}
});
return ids;
};
/**
* Appends the list of elements into the task.
* @param {Object[]} elements - the new list of elements.
* @param {number} bytes - the byte size required to encode elements in the API.
* @param {APICallback} callback - the callback of the method call.
*/
Task.prototype.extend = function (elements, bytes, callback) {
this._data.push({
elements: elements,
bytes: bytes,
callback: callback,
});
};
/**
* Cancels a part of elements.
* @param {string} id - The identifier of the part of elements.
* @return {boolean} Whether the entire task will be canceled or not.
*/
Task.prototype.cancel = function (id) {
if (this.callCanceller) {
var allCancelled_1 = true;
this._data.forEach(function (d) {
if (d.callback.id === id) {
d.cancelled = true;
}
if (!d.cancelled) {
allCancelled_1 = false;
}
});
if (allCancelled_1) {
this.callCanceller.cancel();
}
return allCancelled_1;
}
for (var i = 0; i < this._data.length; ++i) {
if (this._data[i].callback.id === id) {
this._data[i].callback(new Error('cancelled'));
this._data.splice(i, 1);
break;
}
}
return this._data.length === 0;
};
return Task;
}());
exports.Task = Task;
var BundleExecutor = /** @class */ (function () {
/**
* Organizes requests for an api service that requires to bundle them.
*
* @param {BundleOptions} bundleOptions - configures strategy this instance
* uses when executing bundled functions.
* @param {BundleDescriptor} bundleDescriptor - the description of the bundling.
* @constructor
*/
function BundleExecutor(bundleOptions, bundleDescriptor) {
this._options = bundleOptions;
this._descriptor = bundleDescriptor;
this._tasks = {};
this._timers = {};
this._invocations = {};
this._invocationId = 0;
}
/**
* Schedule a method call.
*
* @param {function} apiCall - the function for an API call.
* @param {Object} request - the request object to be bundled with others.
* @param {APICallback} callback - the callback to be called when the method finished.
* @return {function()} - the function to cancel the scheduled invocation.
*/
BundleExecutor.prototype.schedule = function (apiCall, request, callback) {
var _this = this;
var bundleId = computeBundleId(request, this._descriptor.requestDiscriminatorFields);
callback = (callback || noop);
if (bundleId === undefined) {
console.warn('The request does not have enough information for request bundling. ' +
'Invoking immediately. Request: ' + JSON.stringify(request) +
' discriminator fields: ' +
this._descriptor.requestDiscriminatorFields);
return apiCall(request, callback);
}
if (!(bundleId in this._tasks)) {
this._tasks[bundleId] = new Task(apiCall, request, this._descriptor.bundledField, this._descriptor.subresponseField);
}
var task = this._tasks[bundleId];
callback.id = String(this._invocationId++);
this._invocations[callback.id] = bundleId;
var bundledField = request[this._descriptor.bundledField];
var elementCount = bundledField.length;
var requestBytes = 0;
var self = this;
bundledField.forEach(function (obj) {
requestBytes += _this._descriptor.byteLengthFunction(obj);
});
var countLimit = this._options.elementCountLimit || 0;
var byteLimit = this._options.requestByteLimit || 0;
if ((countLimit > 0 && elementCount >= countLimit) ||
(byteLimit > 0 && requestBytes >= byteLimit)) {
var message = void 0;
if (countLimit > 0 && elementCount >= countLimit) {
message = 'The number of elements ' + elementCount +
' exceeds the limit ' + this._options.elementCountLimit;
}
else {
message = 'The required bytes ' + requestBytes + ' exceeds the limit ' +
this._options.requestByteLimit;
}
callback(new Error(message));
return {
cancel: noop,
};
}
var existingCount = task.getElementCount();
var existingBytes = task.getRequestByteSize();
if ((countLimit > 0 && elementCount + existingCount >= countLimit) ||
(byteLimit > 0 && requestBytes + existingBytes >= byteLimit)) {
this._runNow(bundleId);
this._tasks[bundleId] = new Task(apiCall, request, this._descriptor.bundledField, this._descriptor.subresponseField);
task = this._tasks[bundleId];
}
task.extend(bundledField, requestBytes, callback);
var ret = {
cancel: function () {
self._cancel(callback.id);
},
};
var countThreshold = this._options.elementCountThreshold || 0;
var sizeThreshold = this._options.requestByteThreshold || 0;
if ((countThreshold > 0 && task.getElementCount() >= countThreshold) ||
(sizeThreshold > 0 && task.getRequestByteSize() >= sizeThreshold)) {
this._runNow(bundleId);
return ret;
}
if (!(bundleId in this._timers) && this._options.delayThreshold > 0) {
this._timers[bundleId] = setTimeout(function () {
delete _this._timers[bundleId];
_this._runNow(bundleId);
}, this._options.delayThreshold);
}
return ret;
};
/**
* Clears scheduled timeout if it exists.
*
* @param {String} bundleId - the id for the task whose timeout needs to be
* cleared.
* @private
*/
BundleExecutor.prototype._maybeClearTimeout = function (bundleId) {
if (bundleId in this._timers) {
var timerId = this._timers[bundleId];
delete this._timers[bundleId];
clearTimeout(timerId);
}
};
/**
* Cancels an event.
*
* @param {String} id - The id for the event in the task.
* @private
*/
BundleExecutor.prototype._cancel = function (id) {
if (!(id in this._invocations)) {
return;
}
var bundleId = this._invocations[id];
if (!(bundleId in this._tasks)) {
return;
}
var task = this._tasks[bundleId];
delete this._invocations[id];
if (task.cancel(id)) {
this._maybeClearTimeout(bundleId);
delete this._tasks[bundleId];
}
};
/**
* Invokes a task.
*
* @param {String} bundleId - The id for the task.
* @private
*/
BundleExecutor.prototype._runNow = function (bundleId) {
var _this = this;
if (!(bundleId in this._tasks)) {
console.warn('no such bundleid: ' + bundleId);
return;
}
this._maybeClearTimeout(bundleId);
var task = this._tasks[bundleId];
delete this._tasks[bundleId];
task.run().forEach(function (id) {
delete _this._invocations[id];
});
};
return BundleExecutor;
}());
exports.BundleExecutor = BundleExecutor;
var Bundleable = /** @class */ (function (_super) {
__extends(Bundleable, _super);
/**
* Creates an API caller that bundles requests.
*
* @private
* @constructor
* @param {BundleExecutor} bundler - bundles API calls.
*/
function Bundleable(bundler) {
var _this = _super.call(this) || this;
_this.bundler = bundler;
return _this;
}
// tslint:disable-next-line no-any
Bundleable.prototype.call = function (apiCall, argument, settings, status) {
var _this = this;
if (settings.isBundling) {
status.call(function (argument, callback) {
_this.bundler.schedule(apiCall, argument, callback);
}, argument);
}
else {
api_callable_1.NormalApiCaller.prototype.call.call(this, apiCall, argument, settings, status);
}
};
return Bundleable;
}(api_callable_1.NormalApiCaller));
exports.Bundleable = Bundleable;
var BundleDescriptor = /** @class */ (function () {
/**
* Describes the structure of bundled call.
*
* requestDiscriminatorFields may include '.' as a separator, which is used to
* indicate object traversal. This allows fields in nested objects to be used
* to determine what request to bundle.
*
* @property {String} bundledField
* @property {String} requestDiscriminatorFields
* @property {String} subresponseField
* @property {Function} byteLengthFunction
*
* @param {String} bundledField - the repeated field in the request message
* that will have its elements aggregated by bundling.
* @param {String} requestDiscriminatorFields - a list of fields in the
* target request message class that are used to detemrine which request
* messages should be bundled together.
* @param {String} subresponseField - an optional field, when present it
* indicates the field in the response message that should be used to
* demultiplex the response into multiple response messages.
* @param {Function} byteLengthFunction - a function to obtain the byte
* length to be consumed for the bundled field messages. Because Node.JS
* protobuf.js/gRPC uses builtin Objects for the user-visible data and
* internally they are encoded/decoded in protobuf manner, this function
* is actually necessary to calculate the byte length.
* @constructor
*/
function BundleDescriptor(bundledField, requestDiscriminatorFields, subresponseField, byteLengthFunction) {
if (!byteLengthFunction && typeof subresponseField === 'function') {
byteLengthFunction = subresponseField;
subresponseField = null;
}
this.bundledField = bundledField;
this.requestDiscriminatorFields = requestDiscriminatorFields;
this.subresponseField = subresponseField;
this.byteLengthFunction = byteLengthFunction;
}
/**
* Returns a new API caller.
* @private
* @param {CallSettings} settings - the current settings.
* @return {Bundleable} - the new bundling API caller.
*/
BundleDescriptor.prototype.apiCaller = function (settings) {
return new Bundleable(new BundleExecutor(settings.bundleOptions, this));
};
return BundleDescriptor;
}());
exports.BundleDescriptor = BundleDescriptor;
//# sourceMappingURL=bundling.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,391 @@
/**
* Copyright 2016, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import { BundleOptions } from './bundling';
/**
* Encapsulates the overridable settings for a particular API call.
*
* ``CallOptions`` is an optional arg for all GAX API calls. It is used to
* configure the settings of a specific API call.
*
* When provided, its values override the GAX service defaults for that
* particular call.
*
* Typically the API clients will accept this as the second to the last
* argument. See the examples below.
* @typedef {Object} CallOptions
* @property {number=} timeout - The client-side timeout for API calls.
* @property {RetryOptions=} retry - determines whether and how to retry
* on transient errors. When set to null, the call will not retry.
* @property {boolean=} autoPaginate - If set to false and the call is
* configured for paged iteration, page unrolling is not performed, instead
* the callback will be called with the response object.
* @property {Object=} pageToken - If set and the call is configured for
* paged iteration, paged iteration is not performed and requested with this
* pageToken.
* @property {number} maxResults - If set and the call is configured for
* paged iteration, the call will stop when the number of response elements
* reaches to the specified size. By default, it will unroll the page to
* the end of the list.
* @property {boolean=} isBundling - If set to false and the call is configured
* for bundling, bundling is not performed.
* @property {BackoffSettings=} longrunning - BackoffSettings used for polling.
* @property {Function=} promise - A constructor for a promise that implements the ES6
* specification of promise which will be used to create promises. If not
* provided, native promises will be used.
* @example
* // suppress bundling for bundled method.
* api.bundlingMethod(
* param, {optParam: aValue, isBundling: false}, function(err, response) {
* // handle response.
* });
* @example
* // suppress streaming for page-streaming method.
* api.pageStreamingMethod(
* param, {optParam: aValue, autoPaginate: false}, function(err, page) {
* // not returning a stream, but callback is called with the paged response.
* });
*/
/**
* Per-call configurable settings for retrying upon transient failure.
* @typedef {Object} RetryOptions
* @property {String[]} retryCodes
* @property {BackoffSettings} backoffSettings
*/
export declare class RetryOptions {
retryCodes: number[];
backoffSettings: BackoffSettings;
constructor(retryCodes: number[], backoffSettings: BackoffSettings);
}
/**
* Parameters to the exponential backoff algorithm for retrying.
* @typedef {Object} BackoffSettings
* @property {number} initialRetryDelayMillis - the initial delay time,
* in milliseconds, between the completion of the first failed request and the
* initiation of the first retrying request.
* @property {number} retryDelayMultiplier - the multiplier by which to
* increase the delay time between the completion of failed requests, and the
* initiation of the subsequent retrying request.
* @property {number} maxRetryDelayMillis - the maximum delay time, in
* milliseconds, between requests. When this value is reached,
* ``retryDelayMultiplier`` will no longer be used to increase delay time.
* @property {number} initialRpcTimeoutMillis - the initial timeout parameter
* to the request.
* @propetry {number} rpcTimeoutMultiplier - the multiplier by which to
* increase the timeout parameter between failed requests.
* @property {number} maxRpcTimeoutMillis - the maximum timeout parameter, in
* milliseconds, for a request. When this value is reached,
* ``rpcTimeoutMultiplier`` will no longer be used to increase the timeout.
* @property {number} totalTimeoutMillis - the total time, in milliseconds,
* starting from when the initial request is sent, after which an error will
* be returned, regardless of the retrying attempts made meanwhile.
*/
export interface BackoffSettings {
maxRetries?: number;
initialRetryDelayMillis: number;
retryDelayMultiplier: number;
maxRetryDelayMillis: number;
initialRpcTimeoutMillis: number | null;
maxRpcTimeoutMillis: number | null;
totalTimeoutMillis: number | null;
rpcTimeoutMultiplier: number | null;
}
/**
* Parameter to configure bundling behavior.
* @typedef {Object} BundleOptions
* @property {number} elementCountThreshold -
* the bundled request will be sent once the count of outstanding elements
* in the repeated field reaches this value.
* @property {number} elementCountLimit -
* represents a hard limit on the number of elements in the repeated field
* of the bundle; if adding a request to a bundle would exceed this value,
* the bundle is sent and the new request is added to a fresh bundle. It is
* invalid for a single request to exceed this limit.
* @property {number} requestByteThreshold -
* the bundled request will be sent once the count of bytes in the request
* reaches this value. Note that this value is pessimistically approximated
* by summing the bytesizes of the elements in the repeated field, and
* therefore may be an under-approximation.
* @property {number} requestByteLimit -
* represents a hard limit on the size of the bundled request; if adding
* a request to a bundle would exceed this value, the bundle is sent and
* the new request is added to a fresh bundle. It is invalid for a single
* request to exceed this limit. Note that this value is pessimistically
* approximated by summing the bytesizes of the elements in the repeated
* field, with a buffer applied to correspond to the resulting
* under-approximation.
* @property {number} delayThreshold -
* the bundled request will be sent this amount of time after the first
* element in the bundle was added to it.
*/
export interface CallOptions {
timeout?: number;
retry?: RetryOptions | null;
autoPaginate?: boolean;
pageToken?: number;
maxResults?: number;
maxRetries?: number;
otherArgs?: {
[index: string]: any;
};
bundleOptions?: BundleOptions | null;
isBundling?: boolean;
longrunning?: boolean | null;
promise?: PromiseConstructor;
}
export declare class CallSettings {
timeout: number;
retry?: RetryOptions | null;
autoPaginate?: boolean;
pageToken?: number;
maxResults?: number;
otherArgs: {
[index: string]: any;
};
bundleOptions?: BundleOptions | null;
isBundling: boolean;
longrunning?: boolean | null;
promise: PromiseConstructor;
/**
* @param {Object} settings - An object containing parameters of this settings.
* @param {number} settings.timeout - The client-side timeout for API calls.
* This parameter is ignored for retrying calls.
* @param {RetryOptions} settings.retry - The configuration for retrying upon
* transient error. If set to null, this call will not retry.
* @param {boolean} settings.autoPaginate - If there is no `pageDescriptor`,
* this attrbute has no meaning. Otherwise, determines whether a page
* streamed response should make the page structure transparent to the user by
* flattening the repeated field in the returned generator.
* @param {number} settings.pageToken - If there is no `pageDescriptor`,
* this attribute has no meaning. Otherwise, determines the page token used
* in the page streaming request.
* @param {Object} settings.otherArgs - Additional arguments to be passed to
* the API calls.
* @param {Function=} settings.promise - A constructor for a promise that
* implements the ES6 specification of promise. If not provided, native
* promises will be used.
*
* @constructor
*/
constructor(settings?: CallOptions);
/**
* Returns a new CallSettings merged from this and a CallOptions object.
*
* @param {CallOptions} options - an instance whose values override
* those in this object. If null, ``merge`` returns a copy of this
* object
* @return {CallSettings} The merged CallSettings instance.
*/
merge(options?: CallOptions | null): CallSettings;
}
/**
* Per-call configurable settings for retrying upon transient failure.
*
* @param {String[]} retryCodes - a list of Google API canonical error codes
* upon which a retry should be attempted.
* @param {BackoffSettings} backoffSettings - configures the retry
* exponential backoff algorithm.
* @return {RetryOptions} A new RetryOptions object.
*
*/
export declare function createRetryOptions(retryCodes: number[], backoffSettings: BackoffSettings): RetryOptions;
/**
* Parameters to the exponential backoff algorithm for retrying.
*
* @param {number} initialRetryDelayMillis - the initial delay time,
* in milliseconds, between the completion of the first failed request and the
* initiation of the first retrying request.
* @param {number} retryDelayMultiplier - the multiplier by which to
* increase the delay time between the completion of failed requests, and the
* initiation of the subsequent retrying request.
* @param {number} maxRetryDelayMillis - the maximum delay time, in
* milliseconds, between requests. When this value is reached,
* ``retryDelayMultiplier`` will no longer be used to increase delay time.
* @param {number} initialRpcTimeoutMillis - the initial timeout parameter
* to the request.
* @param {number} rpcTimeoutMultiplier - the multiplier by which to
* increase the timeout parameter between failed requests.
* @param {number} maxRpcTimeoutMillis - the maximum timeout parameter, in
* milliseconds, for a request. When this value is reached,
* ``rpcTimeoutMultiplier`` will no longer be used to increase the timeout.
* @param {number} totalTimeoutMillis - the total time, in milliseconds,
* starting from when the initial request is sent, after which an error will
* be returned, regardless of the retrying attempts made meanwhile.
* @return {BackoffSettings} a new settings.
*
*/
export declare function createBackoffSettings(initialRetryDelayMillis: number, retryDelayMultiplier: number, maxRetryDelayMillis: number, initialRpcTimeoutMillis: number | null, rpcTimeoutMultiplier: number | null, maxRpcTimeoutMillis: number | null, totalTimeoutMillis: number | null): BackoffSettings;
/**
* Parameters to the exponential backoff algorithm for retrying.
* This function is unsupported, and intended for internal use only.
*
* @param {number} initialRetryDelayMillis - the initial delay time,
* in milliseconds, between the completion of the first failed request and the
* initiation of the first retrying request.
* @param {number} retryDelayMultiplier - the multiplier by which to
* increase the delay time between the completion of failed requests, and the
* initiation of the subsequent retrying request.
* @param {number} maxRetryDelayMillis - the maximum delay time, in
* milliseconds, between requests. When this value is reached,
* ``retryDelayMultiplier`` will no longer be used to increase delay time.
* @param {number} initialRpcTimeoutMillis - the initial timeout parameter
* to the request.
* @param {number} rpcTimeoutMultiplier - the multiplier by which to
* increase the timeout parameter between failed requests.
* @param {number} maxRpcTimeoutMillis - the maximum timeout parameter, in
* milliseconds, for a request. When this value is reached,
* ``rpcTimeoutMultiplier`` will no longer be used to increase the timeout.
* @param {number} maxRetries - the maximum number of retrying attempts that
* will be made. If reached, an error will be returned.
* @return {BackoffSettings} a new settings.
*
*/
export declare function createMaxRetriesBackoffSettings(initialRetryDelayMillis: number, retryDelayMultiplier: number, maxRetryDelayMillis: number, initialRpcTimeoutMillis: number, rpcTimeoutMultiplier: number, maxRpcTimeoutMillis: number, maxRetries: number): {
initialRetryDelayMillis: number;
retryDelayMultiplier: number;
maxRetryDelayMillis: number;
initialRpcTimeoutMillis: number;
rpcTimeoutMultiplier: number;
maxRpcTimeoutMillis: number;
maxRetries: number;
};
/**
* Creates a new {@link BundleOptions}.
*
* @private
* @param {Object} options - An object to hold optional parameters. See
* properties for the content of options.
* @return {BundleOptions} - A new options.
*/
export declare function createBundleOptions(options: BundlingConfig): BundleOptions;
export interface ServiceConfig {
retry_codes: {
[index: string]: string[];
};
retry_params: {
[index: string]: RetryParamsConfig;
};
methods: {
[index: string]: MethodConfig;
};
}
export interface RetryParamsConfig {
initial_retry_delay_millis: number;
retry_delay_multiplier: number;
max_retry_delay_millis: number;
initial_rpc_timeout_millis: number;
rpc_timeout_multiplier: number;
max_rpc_timeout_millis: number;
total_timeout_millis: number;
}
export interface MethodConfig {
retry_codes_name: string;
retry_params_name: string;
bundling: BundlingConfig;
timeout_millis?: number;
}
export interface BundlingConfig {
[index: string]: number;
element_count_threshold: number;
element_count_limit: number;
request_byte_threshold: number;
request_byte_limit: number;
delay_threshold_millis: number;
}
export interface ClientConfig {
interfaces?: {
[index: string]: ServiceConfig;
};
}
/**
* Constructs a dictionary mapping method names to {@link CallSettings}.
*
* The `clientConfig` parameter is parsed from a client configuration JSON
* file of the form:
*
* {
* "interfaces": {
* "google.fake.v1.ServiceName": {
* "retry_codes": {
* "idempotent": ["UNAVAILABLE", "DEADLINE_EXCEEDED"],
* "non_idempotent": []
* },
* "retry_params": {
* "default": {
* "initial_retry_delay_millis": 100,
* "retry_delay_multiplier": 1.2,
* "max_retry_delay_millis": 1000,
* "initial_rpc_timeout_millis": 2000,
* "rpc_timeout_multiplier": 1.5,
* "max_rpc_timeout_millis": 30000,
* "total_timeout_millis": 45000
* }
* },
* "methods": {
* "CreateFoo": {
* "retry_codes_name": "idempotent",
* "retry_params_name": "default"
* },
* "Publish": {
* "retry_codes_name": "non_idempotent",
* "retry_params_name": "default",
* "bundling": {
* "element_count_threshold": 40,
* "element_count_limit": 200,
* "request_byte_threshold": 90000,
* "request_byte_limit": 100000,
* "delay_threshold_millis": 100
* }
* }
* }
* }
* }
* }
*
* @param {String} serviceName - The fully-qualified name of this
* service, used as a key into the client config file (in the
* example above, this value should be 'google.fake.v1.ServiceName').
* @param {Object} clientConfig - A dictionary parsed from the
* standard API client config file.
* @param {Object} configOverrides - A dictionary in the same structure of
* client_config to override the settings.
* @param {Object.<string, string[]>} retryNames - A dictionary mapping the strings
* referring to response status codes to objects representing
* those codes.
* @param {Object} otherArgs - the non-request arguments to be passed to the API
* calls.
* @param {Function=} promise - A constructor for a promise that implements the
* ES6 specification of promise. If not provided, native promises will be used.
* @return {Object} A mapping from method name to CallSettings, or null if the
* service is not found in the config.
*/
export declare function constructSettings(serviceName: string, clientConfig: ClientConfig, configOverrides: ClientConfig, retryNames: {
[index: string]: number;
}, otherArgs?: {}, promise?: PromiseConstructor): any;

View File

@@ -0,0 +1,508 @@
/**
* Copyright 2016, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Google API Extensions
*/
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Encapsulates the overridable settings for a particular API call.
*
* ``CallOptions`` is an optional arg for all GAX API calls. It is used to
* configure the settings of a specific API call.
*
* When provided, its values override the GAX service defaults for that
* particular call.
*
* Typically the API clients will accept this as the second to the last
* argument. See the examples below.
* @typedef {Object} CallOptions
* @property {number=} timeout - The client-side timeout for API calls.
* @property {RetryOptions=} retry - determines whether and how to retry
* on transient errors. When set to null, the call will not retry.
* @property {boolean=} autoPaginate - If set to false and the call is
* configured for paged iteration, page unrolling is not performed, instead
* the callback will be called with the response object.
* @property {Object=} pageToken - If set and the call is configured for
* paged iteration, paged iteration is not performed and requested with this
* pageToken.
* @property {number} maxResults - If set and the call is configured for
* paged iteration, the call will stop when the number of response elements
* reaches to the specified size. By default, it will unroll the page to
* the end of the list.
* @property {boolean=} isBundling - If set to false and the call is configured
* for bundling, bundling is not performed.
* @property {BackoffSettings=} longrunning - BackoffSettings used for polling.
* @property {Function=} promise - A constructor for a promise that implements the ES6
* specification of promise which will be used to create promises. If not
* provided, native promises will be used.
* @example
* // suppress bundling for bundled method.
* api.bundlingMethod(
* param, {optParam: aValue, isBundling: false}, function(err, response) {
* // handle response.
* });
* @example
* // suppress streaming for page-streaming method.
* api.pageStreamingMethod(
* param, {optParam: aValue, autoPaginate: false}, function(err, page) {
* // not returning a stream, but callback is called with the paged response.
* });
*/
/**
* Per-call configurable settings for retrying upon transient failure.
* @typedef {Object} RetryOptions
* @property {String[]} retryCodes
* @property {BackoffSettings} backoffSettings
*/
var RetryOptions = /** @class */ (function () {
function RetryOptions(retryCodes, backoffSettings) {
this.retryCodes = retryCodes;
this.backoffSettings = backoffSettings;
}
return RetryOptions;
}());
exports.RetryOptions = RetryOptions;
var CallSettings = /** @class */ (function () {
/**
* @param {Object} settings - An object containing parameters of this settings.
* @param {number} settings.timeout - The client-side timeout for API calls.
* This parameter is ignored for retrying calls.
* @param {RetryOptions} settings.retry - The configuration for retrying upon
* transient error. If set to null, this call will not retry.
* @param {boolean} settings.autoPaginate - If there is no `pageDescriptor`,
* this attrbute has no meaning. Otherwise, determines whether a page
* streamed response should make the page structure transparent to the user by
* flattening the repeated field in the returned generator.
* @param {number} settings.pageToken - If there is no `pageDescriptor`,
* this attribute has no meaning. Otherwise, determines the page token used
* in the page streaming request.
* @param {Object} settings.otherArgs - Additional arguments to be passed to
* the API calls.
* @param {Function=} settings.promise - A constructor for a promise that
* implements the ES6 specification of promise. If not provided, native
* promises will be used.
*
* @constructor
*/
function CallSettings(settings) {
settings = settings || {};
this.timeout = settings.timeout || 30 * 1000;
this.retry = settings.retry;
this.autoPaginate =
'autoPaginate' in settings ? settings.autoPaginate : true;
this.pageToken = settings.pageToken;
this.maxResults = settings.maxResults;
this.otherArgs = settings.otherArgs || {};
this.bundleOptions = settings.bundleOptions;
this.isBundling = 'isBundling' in settings ? settings.isBundling : true;
this.longrunning = 'longrunning' in settings ? settings.longrunning : null;
this.promise = 'promise' in settings ? settings.promise : Promise;
}
/**
* Returns a new CallSettings merged from this and a CallOptions object.
*
* @param {CallOptions} options - an instance whose values override
* those in this object. If null, ``merge`` returns a copy of this
* object
* @return {CallSettings} The merged CallSettings instance.
*/
CallSettings.prototype.merge = function (options) {
if (!options) {
return new CallSettings(this);
}
var timeout = this.timeout;
var retry = this.retry;
var autoPaginate = this.autoPaginate;
var pageToken = this.pageToken;
var maxResults = this.maxResults;
var otherArgs = this.otherArgs;
var isBundling = this.isBundling;
var longrunning = this.longrunning;
var promise = this.promise;
if ('timeout' in options) {
timeout = options.timeout;
}
if ('retry' in options) {
retry = options.retry;
}
if ('autoPaginate' in options && !options.autoPaginate) {
autoPaginate = false;
}
if ('pageToken' in options) {
autoPaginate = false;
pageToken = options.pageToken;
}
if ('maxResults' in options) {
maxResults = options.maxResults;
}
if ('otherArgs' in options) {
otherArgs = {};
// tslint:disable-next-line forin
for (var key in this.otherArgs) {
otherArgs[key] = this.otherArgs[key];
}
// tslint:disable-next-line forin
for (var optionsKey in options.otherArgs) {
otherArgs[optionsKey] = options.otherArgs[optionsKey];
}
}
if ('isBundling' in options) {
isBundling = options.isBundling;
}
if ('maxRetries' in options) {
retry.backoffSettings.maxRetries = options.maxRetries;
delete retry.backoffSettings.totalTimeoutMillis;
}
if ('longrunning' in options) {
longrunning = options.longrunning;
}
if ('promise' in options) {
promise = options.promise;
}
return new CallSettings({
timeout: timeout,
retry: retry,
bundleOptions: this.bundleOptions,
longrunning: longrunning,
autoPaginate: autoPaginate,
pageToken: pageToken,
maxResults: maxResults,
otherArgs: otherArgs,
isBundling: isBundling,
promise: promise,
});
};
return CallSettings;
}());
exports.CallSettings = CallSettings;
/**
* Per-call configurable settings for retrying upon transient failure.
*
* @param {String[]} retryCodes - a list of Google API canonical error codes
* upon which a retry should be attempted.
* @param {BackoffSettings} backoffSettings - configures the retry
* exponential backoff algorithm.
* @return {RetryOptions} A new RetryOptions object.
*
*/
function createRetryOptions(retryCodes, backoffSettings) {
return {
retryCodes: retryCodes,
backoffSettings: backoffSettings,
};
}
exports.createRetryOptions = createRetryOptions;
/**
* Parameters to the exponential backoff algorithm for retrying.
*
* @param {number} initialRetryDelayMillis - the initial delay time,
* in milliseconds, between the completion of the first failed request and the
* initiation of the first retrying request.
* @param {number} retryDelayMultiplier - the multiplier by which to
* increase the delay time between the completion of failed requests, and the
* initiation of the subsequent retrying request.
* @param {number} maxRetryDelayMillis - the maximum delay time, in
* milliseconds, between requests. When this value is reached,
* ``retryDelayMultiplier`` will no longer be used to increase delay time.
* @param {number} initialRpcTimeoutMillis - the initial timeout parameter
* to the request.
* @param {number} rpcTimeoutMultiplier - the multiplier by which to
* increase the timeout parameter between failed requests.
* @param {number} maxRpcTimeoutMillis - the maximum timeout parameter, in
* milliseconds, for a request. When this value is reached,
* ``rpcTimeoutMultiplier`` will no longer be used to increase the timeout.
* @param {number} totalTimeoutMillis - the total time, in milliseconds,
* starting from when the initial request is sent, after which an error will
* be returned, regardless of the retrying attempts made meanwhile.
* @return {BackoffSettings} a new settings.
*
*/
function createBackoffSettings(initialRetryDelayMillis, retryDelayMultiplier, maxRetryDelayMillis, initialRpcTimeoutMillis, rpcTimeoutMultiplier, maxRpcTimeoutMillis, totalTimeoutMillis) {
return {
initialRetryDelayMillis: initialRetryDelayMillis,
retryDelayMultiplier: retryDelayMultiplier,
maxRetryDelayMillis: maxRetryDelayMillis,
initialRpcTimeoutMillis: initialRpcTimeoutMillis,
rpcTimeoutMultiplier: rpcTimeoutMultiplier,
maxRpcTimeoutMillis: maxRpcTimeoutMillis,
totalTimeoutMillis: totalTimeoutMillis,
};
}
exports.createBackoffSettings = createBackoffSettings;
/**
* Parameters to the exponential backoff algorithm for retrying.
* This function is unsupported, and intended for internal use only.
*
* @param {number} initialRetryDelayMillis - the initial delay time,
* in milliseconds, between the completion of the first failed request and the
* initiation of the first retrying request.
* @param {number} retryDelayMultiplier - the multiplier by which to
* increase the delay time between the completion of failed requests, and the
* initiation of the subsequent retrying request.
* @param {number} maxRetryDelayMillis - the maximum delay time, in
* milliseconds, between requests. When this value is reached,
* ``retryDelayMultiplier`` will no longer be used to increase delay time.
* @param {number} initialRpcTimeoutMillis - the initial timeout parameter
* to the request.
* @param {number} rpcTimeoutMultiplier - the multiplier by which to
* increase the timeout parameter between failed requests.
* @param {number} maxRpcTimeoutMillis - the maximum timeout parameter, in
* milliseconds, for a request. When this value is reached,
* ``rpcTimeoutMultiplier`` will no longer be used to increase the timeout.
* @param {number} maxRetries - the maximum number of retrying attempts that
* will be made. If reached, an error will be returned.
* @return {BackoffSettings} a new settings.
*
*/
function createMaxRetriesBackoffSettings(initialRetryDelayMillis, retryDelayMultiplier, maxRetryDelayMillis, initialRpcTimeoutMillis, rpcTimeoutMultiplier, maxRpcTimeoutMillis, maxRetries) {
return {
initialRetryDelayMillis: initialRetryDelayMillis,
retryDelayMultiplier: retryDelayMultiplier,
maxRetryDelayMillis: maxRetryDelayMillis,
initialRpcTimeoutMillis: initialRpcTimeoutMillis,
rpcTimeoutMultiplier: rpcTimeoutMultiplier,
maxRpcTimeoutMillis: maxRpcTimeoutMillis,
maxRetries: maxRetries,
};
}
exports.createMaxRetriesBackoffSettings = createMaxRetriesBackoffSettings;
/**
* Creates a new {@link BundleOptions}.
*
* @private
* @param {Object} options - An object to hold optional parameters. See
* properties for the content of options.
* @return {BundleOptions} - A new options.
*/
function createBundleOptions(options) {
var params = [
'element_count_threshold',
'element_count_limit',
'request_byte_threshold',
'request_byte_limit',
'delay_threshold_millis',
];
params.forEach(function (param) {
if (param in options && typeof options[param] !== 'number') {
throw new Error(param + " should be a number");
}
});
var elementCountThreshold = options.element_count_threshold || 0;
var elementCountLimit = options.element_count_limit || 0;
var requestByteThreshold = options.request_byte_threshold || 0;
var requestByteLimit = options.request_byte_limit || 0;
var delayThreshold = options.delay_threshold_millis || 0;
if (elementCountThreshold === 0 && requestByteThreshold === 0 &&
delayThreshold === 0) {
throw new Error('one threshold should be > 0');
}
return {
elementCountThreshold: elementCountThreshold,
elementCountLimit: elementCountLimit,
requestByteThreshold: requestByteThreshold,
requestByteLimit: requestByteLimit,
delayThreshold: delayThreshold,
};
}
exports.createBundleOptions = createBundleOptions;
/**
* Helper for {@link constructSettings}
*
* @private
*
* @param {Object} methodConfig - A dictionary representing a single
* `methods` entry of the standard API client config file. (See
* {@link constructSettings} for information on this yaml.)
* @param {?Object} retryCodes - A dictionary parsed from the
* `retry_codes_def` entry of the standard API client config
* file. (See {@link constructSettings} for information on this yaml.)
* @param {Object} retryParams - A dictionary parsed from the
* `retry_params` entry of the standard API client config
* file. (See {@link constructSettings} for information on this yaml.)
* @param {Object} retryNames - A dictionary mapping the string names
* used in the standard API client config file to API response
* status codes.
* @return {?RetryOptions} The new retry options.
*/
function constructRetry(methodConfig, retryCodes, retryParams, retryNames) {
if (!methodConfig) {
return null;
}
var codes = null;
if (retryCodes && 'retry_codes_name' in methodConfig) {
var retryCodesName = methodConfig['retry_codes_name'];
codes = (retryCodes[retryCodesName] || []).map(function (name) {
return Number(retryNames[name]);
});
}
var backoffSettings = null;
if (retryParams && 'retry_params_name' in methodConfig) {
var params = retryParams[methodConfig.retry_params_name];
backoffSettings = createBackoffSettings(params.initial_retry_delay_millis, params.retry_delay_multiplier, params.max_retry_delay_millis, params.initial_rpc_timeout_millis, params.rpc_timeout_multiplier, params.max_rpc_timeout_millis, params.total_timeout_millis);
}
return createRetryOptions(codes, backoffSettings);
}
/**
* Helper for {@link constructSettings}
*
* Takes two retry options, and merges them into a single RetryOption instance.
*
* @private
*
* @param {RetryOptions} retry - The base RetryOptions.
* @param {RetryOptions} overrides - The RetryOptions used for overriding
* `retry`. Use the values if it is not null. If entire `overrides` is null,
* ignore the base retry and return null.
* @return {?RetryOptions} The merged RetryOptions.
*/
function mergeRetryOptions(retry, overrides) {
if (!overrides) {
return null;
}
if (!overrides.retryCodes && !overrides.backoffSettings) {
return retry;
}
var codes = retry.retryCodes;
if (overrides.retryCodes) {
codes = overrides.retryCodes;
}
var backoffSettings = retry.backoffSettings;
if (overrides.backoffSettings) {
backoffSettings = overrides.backoffSettings;
}
return createRetryOptions(codes, backoffSettings);
}
/**
* Constructs a dictionary mapping method names to {@link CallSettings}.
*
* The `clientConfig` parameter is parsed from a client configuration JSON
* file of the form:
*
* {
* "interfaces": {
* "google.fake.v1.ServiceName": {
* "retry_codes": {
* "idempotent": ["UNAVAILABLE", "DEADLINE_EXCEEDED"],
* "non_idempotent": []
* },
* "retry_params": {
* "default": {
* "initial_retry_delay_millis": 100,
* "retry_delay_multiplier": 1.2,
* "max_retry_delay_millis": 1000,
* "initial_rpc_timeout_millis": 2000,
* "rpc_timeout_multiplier": 1.5,
* "max_rpc_timeout_millis": 30000,
* "total_timeout_millis": 45000
* }
* },
* "methods": {
* "CreateFoo": {
* "retry_codes_name": "idempotent",
* "retry_params_name": "default"
* },
* "Publish": {
* "retry_codes_name": "non_idempotent",
* "retry_params_name": "default",
* "bundling": {
* "element_count_threshold": 40,
* "element_count_limit": 200,
* "request_byte_threshold": 90000,
* "request_byte_limit": 100000,
* "delay_threshold_millis": 100
* }
* }
* }
* }
* }
* }
*
* @param {String} serviceName - The fully-qualified name of this
* service, used as a key into the client config file (in the
* example above, this value should be 'google.fake.v1.ServiceName').
* @param {Object} clientConfig - A dictionary parsed from the
* standard API client config file.
* @param {Object} configOverrides - A dictionary in the same structure of
* client_config to override the settings.
* @param {Object.<string, string[]>} retryNames - A dictionary mapping the strings
* referring to response status codes to objects representing
* those codes.
* @param {Object} otherArgs - the non-request arguments to be passed to the API
* calls.
* @param {Function=} promise - A constructor for a promise that implements the
* ES6 specification of promise. If not provided, native promises will be used.
* @return {Object} A mapping from method name to CallSettings, or null if the
* service is not found in the config.
*/
function constructSettings(serviceName, clientConfig, configOverrides, retryNames, otherArgs, promise) {
otherArgs = otherArgs || {};
// tslint:disable-next-line no-any
var defaults = {};
var serviceConfig = (clientConfig.interfaces || {})[serviceName];
if (!serviceConfig) {
return null;
}
var overrides = (configOverrides.interfaces || {})[serviceName] || {};
var methods = serviceConfig.methods;
var overridingMethods = overrides.methods || {};
// tslint:disable-next-line forin
for (var methodName in methods) {
var methodConfig = methods[methodName];
var jsName = methodName[0].toLowerCase() + methodName.slice(1);
var retry = constructRetry(methodConfig, serviceConfig.retry_codes, serviceConfig.retry_params, retryNames);
var bundlingConfig = methodConfig.bundling;
var timeout = methodConfig.timeout_millis;
if (methodName in overridingMethods) {
var overridingMethod = overridingMethods[methodName];
if (overridingMethod) {
if ('bundling' in overridingMethod) {
bundlingConfig = overridingMethod.bundling;
}
if ('timeout_millis' in overridingMethod) {
timeout = overridingMethod.timeout_millis;
}
}
retry = mergeRetryOptions(retry, constructRetry(overridingMethod, overrides.retry_codes, overrides.retry_params, retryNames));
}
defaults[jsName] = new CallSettings({
timeout: timeout,
retry: retry,
bundleOptions: bundlingConfig ? createBundleOptions(bundlingConfig) :
null,
otherArgs: otherArgs,
promise: promise || Promise,
});
}
return defaults;
}
exports.constructSettings = constructSettings;
//# sourceMappingURL=gax.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,166 @@
/// <reference types="node" />
import * as grpcTypes from 'grpc';
import * as grpcProtoLoaderTypes from '@grpc/proto-loader';
import * as protobuf from 'protobufjs';
import { GoogleAuth, GoogleAuthOptions } from 'google-auth-library';
import * as gax from './gax';
import { OutgoingHttpHeaders } from 'http';
/**
* Options accepted by grpc.load, which was formerly called by GrpcClient#load.
*/
export interface GrpcLoadOldOptions {
convertFieldsToCamelCase?: boolean;
binaryAsBase64?: boolean;
longsAsStrings?: boolean;
enumsAsStrings?: boolean;
}
/**
* Acceptable types for values of `filename` in GrpcClient#load.
*/
export declare type GrpcLoadFileArg = string | {
root?: string;
file: string;
};
/**
* Options accepted by GrpcClient#load.
*/
export declare type GrpcLoadOptions = GrpcLoadOldOptions & grpcProtoLoaderTypes.Options;
/**
* GrpcClient#load accepts its arguments in either load(args) or load(...args)
* format. This is the type of `args` in the former of the two.
*/
export declare type GrpcLoadArgs = [GrpcLoadFileArg, null, GrpcLoadOptions];
export interface GrpcClientOptions extends GoogleAuthOptions {
auth: GoogleAuth;
promise?: PromiseConstructor;
grpc?: GrpcModule;
}
export interface MetadataValue {
equals: Function;
}
export interface Metadata {
new (): Metadata;
set: (key: {}, value?: {} | null) => void;
clone: () => Metadata;
value: MetadataValue;
get: (key: {}) => {};
}
export declare type GrpcModule = typeof grpcTypes & {
status: {
[index: string]: number;
};
};
export interface StubOptions {
[index: string]: {};
servicePath: string;
port: number;
sslCreds: {};
}
export interface Stub {
new (serviceAddress: string, credentials: {}, grpcOptions: {}): Stub;
}
export declare class GrpcClient {
auth: GoogleAuth;
promise: PromiseConstructor;
grpc: GrpcModule;
grpcVersion: string;
grpcProtoLoader: typeof grpcProtoLoaderTypes;
/**
* A class which keeps the context of gRPC and auth for the gRPC.
*
* @param {Object=} options - The optional parameters. It will be directly
* passed to google-auth-library library, so parameters like keyFile or
* credentials will be valid.
* @param {Object=} options.auth - An instance of google-auth-library.
* When specified, this auth instance will be used instead of creating
* a new one.
* @param {Object=} options.grpc - When specified, this will be used
* for the 'grpc' module in this context. By default, it will load the grpc
* module in the standard way.
* @param {Function=} options.promise - A constructor for a promise that
* implements the ES6 specification of promise. If not provided, native
* promises will be used.
* @constructor
*/
constructor(options: GrpcClientOptions);
/**
* Creates a gRPC credentials. It asks the auth data if necessary.
* @private
* @param {Object} opts - options values for configuring credentials.
* @param {Object=} opts.sslCreds - when specified, this is used instead
* of default channel credentials.
* @return {Promise} The promise which will be resolved to the gRPC credential.
*/
_getCredentials(opts: StubOptions): Promise<{}>;
/**
* Loads the gRPC service from the proto file at the given path and with the
* given options.
* @param filename The path to the proto file.
* @param options Options for loading the proto file.
*/
loadFromProto(filename: string, options: grpcProtoLoaderTypes.Options): grpcTypes.GrpcObject;
/**
* Load grpc proto services with the specific arguments.
* Pending deprecation: use GrpcClient#loadFromProto.
* @param {Array=} args - The argument list to be passed to grpc.load().
* @return {Object} The gRPC loaded result (the toplevel namespace object).
*/
load(args: Array<{}>): any;
/**
* Load grpc proto service from a filename hooking in googleapis common protos
* when necessary.
* Pending deprecation: use GrpcClient#loadFromProto.
* @param {String} protoPath - The directory to search for the protofile.
* @param {String} filename - The filename of the proto to be loaded.
* @return {Object<string, *>} The gRPC loaded result (the toplevel namespace
* object).
*/
loadProto(protoPath: string, filename: string): grpcTypes.GrpcObject;
static _resolveFile(protoPath: string, filename: string): string;
metadataBuilder(headers: OutgoingHttpHeaders): (abTests?: {} | undefined, moreHeaders?: OutgoingHttpHeaders | undefined) => grpcTypes.Metadata;
/**
* A wrapper of {@link constructSettings} function under the gRPC context.
*
* Most of parameters are common among constructSettings, please take a look.
* @param {string} serviceName - The fullly-qualified name of the service.
* @param {Object} clientConfig - A dictionary of the client config.
* @param {Object} configOverrides - A dictionary of overriding configs.
* @param {Object} headers - A dictionary of additional HTTP header name to
* its value.
* @return {Object} A mapping of method names to CallSettings.
*/
constructSettings(serviceName: string, clientConfig: gax.ClientConfig, configOverrides: gax.ClientConfig, headers: OutgoingHttpHeaders): any;
/**
* Creates a gRPC stub with current gRPC and auth.
* @param {function} CreateStub - The constructor function of the stub.
* @param {Object} options - The optional arguments to customize
* gRPC connection. This options will be passed to the constructor of
* gRPC client too.
* @param {string} options.servicePath - The name of the server of the service.
* @param {number} options.port - The port of the service.
* @param {grpcTypes.ClientCredentials=} options.sslCreds - The credentials to be used
* to set up gRPC connection.
* @return {Promise} A promse which resolves to a gRPC stub instance.
*/
createStub(CreateStub: Stub, options: StubOptions): Promise<Stub>;
/**
* Creates a 'bytelength' function for a given proto message class.
*
* See {@link BundleDescriptor} about the meaning of the return value.
*
* @param {function} message - a constructor function that is generated by
* protobuf.js. Assumes 'encoder' field in the message.
* @return {function(Object):number} - a function to compute the byte length
* for an object.
*/
static createByteLengthFunction(message: {
encode: (obj: {}) => {
finish: () => Array<{}>;
};
}): (obj: {}) => number;
}
export declare class GoogleProtoFilesRoot extends protobuf.Root {
constructor(...args: Array<{}>);
resolvePath(originPath: string, includePath: string): string;
static _findIncludePath(originPath: string, includePath: string): string;
}

View File

@@ -0,0 +1,369 @@
/*
* Copyright 2016, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
'use strict';
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
}
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
var fs = require("fs");
var globby = require("globby");
var grpcProtoLoaderTypes = require("@grpc/proto-loader"); // for types only
var path = require("path");
var protobuf = require("protobufjs");
var google_auth_library_1 = require("google-auth-library");
var gax = require("./gax");
var googleProtoFilesDir = require('google-proto-files')('..');
googleProtoFilesDir = path.normalize(googleProtoFilesDir);
var COMMON_PROTO_DIRS = [
// This list of directories is defined here:
// https://github.com/googleapis/googleapis/blob/master/gapic/packaging/common_protos.yaml
'api',
path.join('iam', 'v1'),
path.join('logging', 'type'),
'longrunning',
'protobuf',
'rpc',
'type',
];
var COMMON_PROTO_GLOB_PATTERNS = COMMON_PROTO_DIRS.map(function (dir) {
return path.join(googleProtoFilesDir, 'google', dir, '**', '*.proto');
});
var COMMON_PROTO_FILES = globby.sync(COMMON_PROTO_GLOB_PATTERNS)
.map(function (filename) {
return path.normalize(filename);
})
.map(function (filename) {
return filename.substring(googleProtoFilesDir.length + 1);
});
var GrpcClient = /** @class */ (function () {
/**
* A class which keeps the context of gRPC and auth for the gRPC.
*
* @param {Object=} options - The optional parameters. It will be directly
* passed to google-auth-library library, so parameters like keyFile or
* credentials will be valid.
* @param {Object=} options.auth - An instance of google-auth-library.
* When specified, this auth instance will be used instead of creating
* a new one.
* @param {Object=} options.grpc - When specified, this will be used
* for the 'grpc' module in this context. By default, it will load the grpc
* module in the standard way.
* @param {Function=} options.promise - A constructor for a promise that
* implements the ES6 specification of promise. If not provided, native
* promises will be used.
* @constructor
*/
function GrpcClient(options) {
// if (!(this instanceof GrpcClient)) {
// return new GrpcClient(options);
// }
options = options || {};
this.auth = options.auth || new google_auth_library_1.GoogleAuth(options);
this.promise = options.promise || Promise;
if ('grpc' in options) {
this.grpc = options.grpc;
this.grpcVersion = '';
}
else {
this.grpc = require('grpc');
this.grpcVersion = require('grpc/package.json').version;
}
this.grpcProtoLoader = require('@grpc/proto-loader');
}
/**
* Creates a gRPC credentials. It asks the auth data if necessary.
* @private
* @param {Object} opts - options values for configuring credentials.
* @param {Object=} opts.sslCreds - when specified, this is used instead
* of default channel credentials.
* @return {Promise} The promise which will be resolved to the gRPC credential.
*/
GrpcClient.prototype._getCredentials = function (opts) {
return __awaiter(this, void 0, void 0, function () {
var grpc, sslCreds, client, credentials;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (opts.sslCreds) {
return [2 /*return*/, opts.sslCreds];
}
grpc = this.grpc;
sslCreds = grpc.credentials.createSsl();
return [4 /*yield*/, this.auth.getClient()];
case 1:
client = _a.sent();
credentials = grpc.credentials.combineChannelCredentials(sslCreds, grpc.credentials.createFromGoogleCredential(client));
return [2 /*return*/, credentials];
}
});
});
};
/**
* Loads the gRPC service from the proto file at the given path and with the
* given options.
* @param filename The path to the proto file.
* @param options Options for loading the proto file.
*/
GrpcClient.prototype.loadFromProto = function (filename, options) {
var packageDef = grpcProtoLoaderTypes.loadSync(filename, options);
return this.grpc.loadPackageDefinition(packageDef);
};
/**
* Load grpc proto services with the specific arguments.
* Pending deprecation: use GrpcClient#loadFromProto.
* @param {Array=} args - The argument list to be passed to grpc.load().
* @return {Object} The gRPC loaded result (the toplevel namespace object).
*/
GrpcClient.prototype.load = function (args) {
if (!args) {
args = [];
}
else if (!Array.isArray(args)) {
args = [args];
}
if (args.length === 1) {
args.push('proto', { convertFieldsToCamelCase: true });
}
return this.grpc.load.apply(this.grpc, args);
};
/**
* Load grpc proto service from a filename hooking in googleapis common protos
* when necessary.
* Pending deprecation: use GrpcClient#loadFromProto.
* @param {String} protoPath - The directory to search for the protofile.
* @param {String} filename - The filename of the proto to be loaded.
* @return {Object<string, *>} The gRPC loaded result (the toplevel namespace
* object).
*/
GrpcClient.prototype.loadProto = function (protoPath, filename) {
var resolvedPath = GrpcClient._resolveFile(protoPath, filename);
return this.grpc.loadObject(protobuf.loadSync(resolvedPath, new GoogleProtoFilesRoot()));
};
GrpcClient._resolveFile = function (protoPath, filename) {
if (fs.existsSync(path.join(protoPath, filename))) {
return path.join(protoPath, filename);
}
else if (COMMON_PROTO_FILES.indexOf(filename) > -1) {
return path.join(googleProtoFilesDir, filename);
}
throw new Error(filename + ' could not be found in ' + protoPath);
};
GrpcClient.prototype.metadataBuilder = function (headers) {
var Metadata = this.grpc.Metadata;
var baseMetadata = new Metadata();
var _loop_1 = function (key) {
var value = headers[key];
if (Array.isArray(value)) {
value.forEach(function (v) { return baseMetadata.add(key, v); });
}
else {
baseMetadata.set(key, "" + value);
}
};
// tslint:disable-next-line forin
for (var key in headers) {
_loop_1(key);
}
return function buildMetadata(abTests, moreHeaders) {
// TODO: bring the A/B testing info into the metadata.
var copied = false;
var metadata = baseMetadata;
if (moreHeaders) {
var _loop_2 = function (key) {
if (key.toLowerCase() !== 'x-goog-api-client' &&
moreHeaders.hasOwnProperty(key)) {
if (!copied) {
copied = true;
metadata = metadata.clone();
}
var value = moreHeaders[key];
if (Array.isArray(value)) {
value.forEach(function (v) { return metadata.add(key, v); });
}
else {
metadata.set(key, "" + value);
}
}
};
for (var key in moreHeaders) {
_loop_2(key);
}
}
return metadata;
};
};
/**
* A wrapper of {@link constructSettings} function under the gRPC context.
*
* Most of parameters are common among constructSettings, please take a look.
* @param {string} serviceName - The fullly-qualified name of the service.
* @param {Object} clientConfig - A dictionary of the client config.
* @param {Object} configOverrides - A dictionary of overriding configs.
* @param {Object} headers - A dictionary of additional HTTP header name to
* its value.
* @return {Object} A mapping of method names to CallSettings.
*/
GrpcClient.prototype.constructSettings = function (serviceName, clientConfig, configOverrides, headers) {
return gax.constructSettings(serviceName, clientConfig, configOverrides, this.grpc.status, { metadataBuilder: this.metadataBuilder(headers) }, this.promise);
};
/**
* Creates a gRPC stub with current gRPC and auth.
* @param {function} CreateStub - The constructor function of the stub.
* @param {Object} options - The optional arguments to customize
* gRPC connection. This options will be passed to the constructor of
* gRPC client too.
* @param {string} options.servicePath - The name of the server of the service.
* @param {number} options.port - The port of the service.
* @param {grpcTypes.ClientCredentials=} options.sslCreds - The credentials to be used
* to set up gRPC connection.
* @return {Promise} A promse which resolves to a gRPC stub instance.
*/
// tslint:disable-next-line variable-name
GrpcClient.prototype.createStub = function (CreateStub, options) {
var serviceAddress = options.servicePath + ':' + options.port;
return this._getCredentials(options).then(function (credentials) {
var grpcOptions = {};
Object.keys(options).forEach(function (key) {
if (key.indexOf('grpc.') === 0) {
grpcOptions[key] = options[key];
}
});
return new CreateStub(serviceAddress, credentials, grpcOptions);
});
};
/**
* Creates a 'bytelength' function for a given proto message class.
*
* See {@link BundleDescriptor} about the meaning of the return value.
*
* @param {function} message - a constructor function that is generated by
* protobuf.js. Assumes 'encoder' field in the message.
* @return {function(Object):number} - a function to compute the byte length
* for an object.
*/
GrpcClient.createByteLengthFunction = function (message) {
return function getByteLength(obj) {
return message.encode(obj).finish().length;
};
};
return GrpcClient;
}());
exports.GrpcClient = GrpcClient;
var GoogleProtoFilesRoot = /** @class */ (function (_super) {
__extends(GoogleProtoFilesRoot, _super);
function GoogleProtoFilesRoot() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return _super.apply(this, args) || this;
}
// Causes the loading of an included proto to check if it is a common
// proto. If it is a common proto, use the google-proto-files proto.
GoogleProtoFilesRoot.prototype.resolvePath = function (originPath, includePath) {
originPath = path.normalize(originPath);
includePath = path.normalize(includePath);
// Fully qualified paths don't need to be resolved.
if (path.isAbsolute(includePath)) {
if (!fs.existsSync(includePath)) {
throw new Error('The include `' + includePath + '` was not found.');
}
return includePath;
}
if (COMMON_PROTO_FILES.indexOf(includePath) > -1) {
return path.join(googleProtoFilesDir, includePath);
}
return GoogleProtoFilesRoot._findIncludePath(originPath, includePath);
};
GoogleProtoFilesRoot._findIncludePath = function (originPath, includePath) {
originPath = path.normalize(originPath);
includePath = path.normalize(includePath);
var current = originPath;
var found = fs.existsSync(path.join(current, includePath));
while (!found && current.length > 0) {
current = current.substring(0, current.lastIndexOf(path.sep));
found = fs.existsSync(path.join(current, includePath));
}
if (!found) {
throw new Error('The include `' + includePath + '` was not found.');
}
return path.join(current, includePath);
};
return GoogleProtoFilesRoot;
}(protobuf.Root));
exports.GoogleProtoFilesRoot = GoogleProtoFilesRoot;
//# sourceMappingURL=grpc.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,46 @@
/**
* Copyright 2016, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import * as operationsClient from './operations_client';
import * as routingHeader from './routing_header';
import { GrpcClient, GrpcClientOptions } from './grpc';
export { routingHeader };
export { constructSettings } from './gax';
export { StreamType, StreamDescriptor } from './streaming';
export { LongrunningDescriptor, operation } from './longrunning';
export { BundleDescriptor, BundleExecutor } from './bundling';
export { PathTemplate } from './path_template';
export { PageDescriptor } from './paged_iteration';
export { createApiCall } from './api_callable';
export { GrpcClient, GrpcClientOptions, GrpcModule, GoogleProtoFilesRoot, Metadata, MetadataValue, Stub, StubOptions } from './grpc';
declare function lro(options: GrpcClientOptions): operationsClient.OperationsClientBuilder;
export { lro };
export declare const createByteLengthFunction: typeof GrpcClient.createByteLengthFunction;
export declare const version: any;

View File

@@ -0,0 +1,73 @@
/**
* Copyright 2016, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
var extend = require("extend");
var operationsClient = require("./operations_client");
var routingHeader = require("./routing_header");
exports.routingHeader = routingHeader;
var grpc_1 = require("./grpc");
var gax_1 = require("./gax");
exports.constructSettings = gax_1.constructSettings;
var streaming_1 = require("./streaming");
exports.StreamType = streaming_1.StreamType;
exports.StreamDescriptor = streaming_1.StreamDescriptor;
var longrunning_1 = require("./longrunning");
exports.LongrunningDescriptor = longrunning_1.LongrunningDescriptor;
exports.operation = longrunning_1.operation;
var bundling_1 = require("./bundling");
exports.BundleDescriptor = bundling_1.BundleDescriptor;
exports.BundleExecutor = bundling_1.BundleExecutor;
var path_template_1 = require("./path_template");
exports.PathTemplate = path_template_1.PathTemplate;
var paged_iteration_1 = require("./paged_iteration");
exports.PageDescriptor = paged_iteration_1.PageDescriptor;
var api_callable_1 = require("./api_callable");
exports.createApiCall = api_callable_1.createApiCall;
var grpc_2 = require("./grpc");
exports.GrpcClient = grpc_2.GrpcClient;
exports.GoogleProtoFilesRoot = grpc_2.GoogleProtoFilesRoot;
function lro(options) {
options = extend({
// tslint:disable-next-line no-any
scopes: lro.ALL_SCOPES,
}, options);
var gaxGrpc = new grpc_1.GrpcClient(options);
return new operationsClient.OperationsClientBuilder(gaxGrpc);
}
exports.lro = lro;
// tslint:disable-next-line no-any
lro.SERVICE_ADDRESS = operationsClient.SERVICE_ADDRESS;
// tslint:disable-next-line no-any
lro.ALL_SCOPES = operationsClient.ALL_SCOPES;
exports.createByteLengthFunction = grpc_1.GrpcClient.createByteLengthFunction;
exports.version = require('../../package.json').version;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH,YAAY,CAAC;;AAEb,+BAAiC;AAEjC,sDAAwD;AACxD,gDAAkD;AAG1C,sCAAa;AAFrB,+BAA2E;AAG3E,6BAAwC;AAAhC,kCAAA,iBAAiB,CAAA;AACzB,yCAAyD;AAAjD,iCAAA,UAAU,CAAA;AAAE,uCAAA,gBAAgB,CAAA;AACpC,6CAA+D;AAAvD,8CAAA,qBAAqB,CAAA;AAAE,kCAAA,SAAS,CAAA;AACxC,uCAA4D;AAApD,sCAAA,gBAAgB,CAAA;AAAE,oCAAA,cAAc,CAAA;AACxC,iDAA6C;AAArC,uCAAA,YAAY,CAAA;AACpB,qDAAiD;AAAzC,2CAAA,cAAc,CAAA;AACtB,+CAA6C;AAArC,uCAAA,aAAa,CAAA;AACrB,+BAAmI;AAA3H,4BAAA,UAAU,CAAA;AAAiC,sCAAA,oBAAoB,CAAA;AAEvE,SAAS,GAAG,CAAC,OAA0B;IACrC,OAAO,GAAG,MAAM,CACZ;QACE,kCAAkC;QAClC,MAAM,EAAG,GAAW,CAAC,UAAU;KAChC,EACD,OAAO,CAAC,CAAC;IACb,IAAM,OAAO,GAAG,IAAI,iBAAU,CAAC,OAAO,CAAC,CAAC;IACxC,OAAO,IAAI,gBAAgB,CAAC,uBAAuB,CAAC,OAAO,CAAC,CAAC;AAC/D,CAAC;AAMO,kBAAG;AALX,kCAAkC;AACjC,GAAW,CAAC,eAAe,GAAG,gBAAgB,CAAC,eAAe,CAAC;AAChE,kCAAkC;AACjC,GAAW,CAAC,UAAU,GAAG,gBAAgB,CAAC,UAAU,CAAC;AAGzC,QAAA,wBAAwB,GAAG,iBAAU,CAAC,wBAAwB,CAAC;AAC/D,QAAA,OAAO,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAC,OAAO,CAAC"}

View File

@@ -0,0 +1,163 @@
/// <reference types="node" />
import { EventEmitter } from 'events';
import { APICall, APICallback, CancellablePromise, NormalApiCaller, PromiseCanceller } from './api_callable';
import { BackoffSettings, CallOptions } from './gax';
import { GoogleError } from './GoogleError';
import { Metadata } from './grpc';
import { OperationsClient } from './operations_client';
/**
* A callback to upack a google.protobuf.Any message.
* @callback anyDecoder
* @param {google.protobuf.Any} message - The message to unpacked.
* @return {Object} - The unpacked message.
*/
export interface AnyDecoder {
(message: {}): Metadata;
}
/**
* @callback GetOperationCallback
* @param {?Error} error
* @param {?Object} result
* @param {?Object} metadata
* @param {?google.longrunning.Operation} rawResponse
*/
export interface GetOperationCallback {
(err?: Error | null, result?: {}, metadata?: {}, rawResponse?: Operation): void;
}
export declare class LongrunningDescriptor {
operationsClient: OperationsClient;
responseDecoder: AnyDecoder;
metadataDecoder: AnyDecoder;
/**
* Describes the structure of a page-streaming call.
*
* @property {OperationsClient} operationsClient
* @property {anyDecoder} responseDecoder
* @property {anyDecoder} metadataDecoder
*
* @param {OperationsClient} operationsClient - The client used to poll or
* cancel an operation.
* @param {anyDecoder=} responseDecoder - The decoder to unpack
* the response message.
* @param {anyDecoder=} metadataDecoder - The decoder to unpack
* the metadata message.
*
* @constructor
*/
constructor(operationsClient: OperationsClient, responseDecoder: AnyDecoder, metadataDecoder: AnyDecoder);
apiCaller(): LongrunningApiCaller;
}
export declare class LongrunningApiCaller extends NormalApiCaller {
longrunningDescriptor: LongrunningDescriptor;
/**
* Creates an API caller that performs polling on a long running operation.
*
* @private
* @constructor
* @param {LongrunningDescriptor} longrunningDescriptor - Holds the
* decoders used for unpacking responses and the operationsClient
* used for polling the operation.
*/
constructor(longrunningDescriptor: LongrunningDescriptor);
call(apiCall: APICall, argument: {}, settings: CallOptions, canceller: PromiseCanceller): void;
_wrapOperation(apiCall: APICall, settings: CallOptions, argument: {}, callback: APICallback): any;
}
export declare class Operation extends EventEmitter {
completeListeners: number;
hasActiveListeners: boolean;
latestResponse: Operation;
longrunningDescriptor: LongrunningDescriptor;
result: {} | null;
metadata: Metadata | null;
backoffSettings: BackoffSettings;
_callOptions?: CallOptions;
currentCallPromise_?: CancellablePromise;
name?: string;
done?: boolean;
error?: GoogleError;
response?: {
value: {};
};
/**
* Wrapper for a google.longrunnung.Operation.
*
* @constructor
*
* @param {google.longrunning.Operation} grpcOp - The operation to be wrapped.
* @param {LongrunningDescriptor} longrunningDescriptor - This defines the
* operations service client and unpacking mechanisms for the operation.
* @param {BackoffSettings} backoffSettings - The backoff settings used in
* in polling the operation.
* @param {CallOptions=} callOptions - CallOptions used in making get operation
* requests.
*/
constructor(grpcOp: Operation, longrunningDescriptor: LongrunningDescriptor, backoffSettings: BackoffSettings, callOptions?: CallOptions);
/**
* Begin listening for events on the operation. This method keeps track of how
* many "complete" listeners are registered and removed, making sure polling
* is handled automatically.
*
* As long as there is one active "complete" listener, the connection is open.
* When there are no more listeners, the polling stops.
*
* @private
*/
_listenForEvents(): void;
/**
* Cancels current polling api call and cancels the operation.
*
* @return {Promise} the promise of the OperationsClient#cancelOperation api
* request.
*/
cancel(): any;
/**
* Get the updated status of the operation. If the Operation has previously
* completed, this will use the status of the cached completed operation.
*
* - callback(err): Operation failed
* - callback(null, result, metadata, rawResponse): Operation complete
* - callback(null, null, metadata, rawResponse): Operation incomplete
*
* @param {getOperationCallback} callback - Callback to handle the polled
* operation result and metadata.
* @return {Promise|undefined} - This returns a promise if a callback is not specified.
* The promise resolves to an array where the first element is the unpacked
* result, the second element is the metadata, and the third element is the
* raw response of the api call. The promise rejects if the operation returns
* an error.
*/
getOperation(): Promise<{}>;
getOperation(callback: GetOperationCallback): void;
_unpackResponse(op: Operation, callback?: GetOperationCallback): void;
/**
* Poll `getOperation` to check the operation's status. This runs a loop to
* ping using the backoff strategy specified at initialization.
*
* Note: This method is automatically called once a "complete" event handler
* is registered on the operation.
*
* @private
*/
startPolling_(): void;
/**
* Wraps the `complete` and `error` events in a Promise.
*
* @return {promise} - Promise that resolves on operation completion and rejects
* on operation error.
*/
promise(): Promise<{}>;
}
/**
* Method used to create Operation objects.
*
* @constructor
*
* @param {google.longrunning.Operation} op - The operation to be wrapped.
* @param {LongrunningDescriptor} longrunningDescriptor - This defines the
* operations service client and unpacking mechanisms for the operation.
* @param {BackoffSettings} backoffSettings - The backoff settings used in
* in polling the operation.
* @param {CallOptions=} callOptions - CallOptions used in making get operation
* requests.
*/
export declare function operation(op: Operation, longrunningDescriptor: LongrunningDescriptor, backoffSettings: BackoffSettings, callOptions?: CallOptions): Operation;

View File

@@ -0,0 +1,347 @@
"use strict";
/*
* Copyright 2016, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
}
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var events_1 = require("events");
var api_callable_1 = require("./api_callable");
var gax_1 = require("./gax");
var GoogleError_1 = require("./GoogleError");
var LongrunningDescriptor = /** @class */ (function () {
/**
* Describes the structure of a page-streaming call.
*
* @property {OperationsClient} operationsClient
* @property {anyDecoder} responseDecoder
* @property {anyDecoder} metadataDecoder
*
* @param {OperationsClient} operationsClient - The client used to poll or
* cancel an operation.
* @param {anyDecoder=} responseDecoder - The decoder to unpack
* the response message.
* @param {anyDecoder=} metadataDecoder - The decoder to unpack
* the metadata message.
*
* @constructor
*/
function LongrunningDescriptor(operationsClient, responseDecoder, metadataDecoder) {
this.operationsClient = operationsClient;
this.responseDecoder = responseDecoder;
this.metadataDecoder = metadataDecoder;
}
LongrunningDescriptor.prototype.apiCaller = function () {
return new LongrunningApiCaller(this);
};
return LongrunningDescriptor;
}());
exports.LongrunningDescriptor = LongrunningDescriptor;
var LongrunningApiCaller = /** @class */ (function (_super) {
__extends(LongrunningApiCaller, _super);
/**
* Creates an API caller that performs polling on a long running operation.
*
* @private
* @constructor
* @param {LongrunningDescriptor} longrunningDescriptor - Holds the
* decoders used for unpacking responses and the operationsClient
* used for polling the operation.
*/
function LongrunningApiCaller(longrunningDescriptor) {
var _this = _super.call(this) || this;
_this.longrunningDescriptor = longrunningDescriptor;
return _this;
}
LongrunningApiCaller.prototype.call = function (apiCall, argument, settings, canceller) {
var _this = this;
canceller.call(function (argument, callback) {
return _this._wrapOperation(apiCall, settings, argument, callback);
}, argument);
};
LongrunningApiCaller.prototype._wrapOperation = function (apiCall, settings, argument, callback) {
// TODO: this code defies all logic, and just can't be accurate.
// tslint:disable-next-line no-any
var backoffSettings = settings.longrunning;
if (!backoffSettings) {
backoffSettings =
gax_1.createBackoffSettings(100, 1.3, 60000, null, null, null, null);
}
var longrunningDescriptor = this.longrunningDescriptor;
return apiCall(argument, function (err, rawResponse) {
if (err) {
callback(err, null, rawResponse);
return;
}
var operation = new Operation(rawResponse, longrunningDescriptor, backoffSettings, settings);
callback(null, operation, rawResponse);
});
};
return LongrunningApiCaller;
}(api_callable_1.NormalApiCaller));
exports.LongrunningApiCaller = LongrunningApiCaller;
var Operation = /** @class */ (function (_super) {
__extends(Operation, _super);
/**
* Wrapper for a google.longrunnung.Operation.
*
* @constructor
*
* @param {google.longrunning.Operation} grpcOp - The operation to be wrapped.
* @param {LongrunningDescriptor} longrunningDescriptor - This defines the
* operations service client and unpacking mechanisms for the operation.
* @param {BackoffSettings} backoffSettings - The backoff settings used in
* in polling the operation.
* @param {CallOptions=} callOptions - CallOptions used in making get operation
* requests.
*/
function Operation(grpcOp, longrunningDescriptor, backoffSettings, callOptions) {
var _this = _super.call(this) || this;
_this.completeListeners = 0;
_this.hasActiveListeners = false;
_this.latestResponse = grpcOp;
_this.longrunningDescriptor = longrunningDescriptor;
_this.result = null;
_this.metadata = null;
_this.backoffSettings = backoffSettings;
_this._unpackResponse(grpcOp);
_this._listenForEvents();
_this._callOptions = callOptions;
return _this;
}
/**
* Begin listening for events on the operation. This method keeps track of how
* many "complete" listeners are registered and removed, making sure polling
* is handled automatically.
*
* As long as there is one active "complete" listener, the connection is open.
* When there are no more listeners, the polling stops.
*
* @private
*/
Operation.prototype._listenForEvents = function () {
var _this = this;
this.on('newListener', function (event) {
if (event === 'complete') {
_this.completeListeners++;
if (!_this.hasActiveListeners) {
_this.hasActiveListeners = true;
_this.startPolling_();
}
}
});
this.on('removeListener', function (event) {
if (event === 'complete' && --_this.completeListeners === 0) {
_this.hasActiveListeners = false;
}
});
};
/**
* Cancels current polling api call and cancels the operation.
*
* @return {Promise} the promise of the OperationsClient#cancelOperation api
* request.
*/
Operation.prototype.cancel = function () {
if (this.currentCallPromise_) {
this.currentCallPromise_.cancel();
}
var operationsClient = this.longrunningDescriptor.operationsClient;
return operationsClient.cancelOperation({ name: this.latestResponse.name });
};
Operation.prototype.getOperation = function (callback) {
var self = this;
var operationsClient = this.longrunningDescriptor.operationsClient;
function promisifyResponse() {
if (!callback) {
// tslint:disable-next-line variable-name
var PromiseCtor = self._callOptions.promise;
return new PromiseCtor(function (resolve, reject) {
if (self.latestResponse.error) {
var error = new GoogleError_1.GoogleError(self.latestResponse.error.message);
error.code = self.latestResponse.error.code;
reject(error);
}
else {
resolve([self.result, self.metadata, self.latestResponse]);
}
});
}
return;
}
if (this.latestResponse.done) {
this._unpackResponse(this.latestResponse, callback);
return promisifyResponse();
}
this.currentCallPromise_ = operationsClient.getOperation({ name: this.latestResponse.name }, this._callOptions);
var noCallbackPromise = this.currentCallPromise_.then(function (responses) {
self.latestResponse = responses[0];
self._unpackResponse(responses[0], callback);
return promisifyResponse();
});
if (!callback) {
return noCallbackPromise;
}
};
Operation.prototype._unpackResponse = function (op, callback) {
var responseDecoder = this.longrunningDescriptor.responseDecoder;
var metadataDecoder = this.longrunningDescriptor.metadataDecoder;
var response;
var metadata;
if (op.done) {
if (op.result === 'error') {
var error = new GoogleError_1.GoogleError(op.error.message);
error.code = op.error.code;
if (callback) {
callback(error);
}
return;
}
if (responseDecoder && op.response) {
response = responseDecoder(op.response.value);
this.result = response;
}
}
if (metadataDecoder && op.metadata) {
metadata = metadataDecoder(op.metadata.value);
this.metadata = metadata;
}
if (callback) {
callback(null, response, metadata, op);
}
};
/**
* Poll `getOperation` to check the operation's status. This runs a loop to
* ping using the backoff strategy specified at initialization.
*
* Note: This method is automatically called once a "complete" event handler
* is registered on the operation.
*
* @private
*/
Operation.prototype.startPolling_ = function () {
var self = this;
var now = new Date();
var delayMult = this.backoffSettings.retryDelayMultiplier;
var maxDelay = this.backoffSettings.maxRetryDelayMillis;
var delay = this.backoffSettings.initialRetryDelayMillis;
var deadline = Infinity;
if (this.backoffSettings.totalTimeoutMillis) {
deadline = now.getTime() + this.backoffSettings.totalTimeoutMillis;
}
var previousMetadataBytes;
if (this.latestResponse.metadata) {
previousMetadataBytes = this.latestResponse.metadata.value;
}
function emit() {
self.emit.apply(self, Array.prototype.slice.call(arguments, 0));
}
function retry() {
if (!self.hasActiveListeners) {
return;
}
if (now.getTime() >= deadline) {
setImmediate(emit, 'error', new Error('Total timeout exceeded before ' +
'any response was received'));
return;
}
self.getOperation(function (err, result, metadata, rawResponse) {
if (err) {
setImmediate(emit, 'error', err);
return;
}
if (!result) {
if (rawResponse.metadata &&
(!previousMetadataBytes ||
!rawResponse.metadata.value.equals(previousMetadataBytes))) {
setImmediate(emit, 'progress', metadata, rawResponse);
previousMetadataBytes = rawResponse.metadata.value;
}
setTimeout(function () {
now = new Date();
delay = Math.min(delay * delayMult, maxDelay);
retry();
}, delay);
return;
}
setImmediate(emit, 'complete', result, metadata, rawResponse);
});
}
retry();
};
/**
* Wraps the `complete` and `error` events in a Promise.
*
* @return {promise} - Promise that resolves on operation completion and rejects
* on operation error.
*/
Operation.prototype.promise = function () {
var self = this;
// tslint:disable-next-line variable-name
var PromiseCtor = this._callOptions.promise;
return new PromiseCtor(function (resolve, reject) {
self.on('error', reject)
.on('complete', function (result, metadata, rawResponse) {
resolve([result, metadata, rawResponse]);
});
});
};
return Operation;
}(events_1.EventEmitter));
exports.Operation = Operation;
/**
* Method used to create Operation objects.
*
* @constructor
*
* @param {google.longrunning.Operation} op - The operation to be wrapped.
* @param {LongrunningDescriptor} longrunningDescriptor - This defines the
* operations service client and unpacking mechanisms for the operation.
* @param {BackoffSettings} backoffSettings - The backoff settings used in
* in polling the operation.
* @param {CallOptions=} callOptions - CallOptions used in making get operation
* requests.
*/
function operation(op, longrunningDescriptor, backoffSettings, callOptions) {
return new Operation(op, longrunningDescriptor, backoffSettings, callOptions);
}
exports.operation = operation;
//# sourceMappingURL=longrunning.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,289 @@
export declare const SERVICE_ADDRESS = "longrunning.googleapis.com";
/**
* The scopes needed to make gRPC calls to all of the methods defined in
* this service.
*/
export declare const ALL_SCOPES: string[];
/**
* Manages long-running operations with an API service.
*
* When an API method normally takes long time to complete, it can be designed
* to return {@link Operation} to the client, and the client can use this
* interface to receive the real response asynchronously by polling the
* operation resource, or pass the operation resource to another API (such as
* Google Cloud Pub/Sub API) to receive the response. Any API service that
* returns long-running operations should implement the `Operations` interface
* so developers can have a consistent client experience.
*
* This will be created through a builder function which can be obtained by the
* module. See the following example of how to initialize the module and how to
* access to the builder.
* @see {@link operationsClient}
*
* @class
*/
export declare class OperationsClient {
auth: any;
constructor(gaxGrpc: any, grpcClients: any, opts: any);
/**
* Get the project ID used by this class.
* @aram {function(Error, string)} callback - the callback to be called with
* the current project Id.
*/
getProjectId(callback: (err: Error | null, projectId?: string) => void): any;
/**
* Gets the latest state of a long-running operation. Clients can use this
* method to poll the operation result at intervals as recommended by the API
* service.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.name
* The name of the operation resource.
* @param {Object=} options
* Optional parameters. You can override the default settings for this call,
* e.g, timeout, retries, paginations, etc. See [gax.CallOptions]{@link
* https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the
* details.
* @param {function(?Error, ?Object)=} callback
* The function which will be called with the result of the API call.
*
* The second parameter to the callback is an object representing
* [google.longrunning.Operation]{@link
* external:"google.longrunning.Operation"}.
* @return {Promise} - The promise which resolves to an array.
* The first element of the array is an object representing
* [google.longrunning.Operation]{@link
* external:"google.longrunning.Operation"}. The promise has a method named
* "cancel" which cancels the ongoing API call.
*
* @example
*
* var client = longrunning.operationsClient();
* var name = '';
* client.getOperation({name: name}).then(function(responses) {
* var response = responses[0];
* // doThingsWith(response)
* }).catch(function(err) {
* console.error(err);
* });
*/
getOperation(request: {}, options: {}, callback?: any): any;
/**
* Lists operations that match the specified filter in the request. If the
* server doesn't support this method, it returns `UNIMPLEMENTED`.
*
* NOTE: the `name` binding below allows API services to override the binding
* to use different resource name schemes.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.name
* The name of the operation collection.
* @param {string} request.filter
* The standard list filter.
* @param {number=} request.pageSize
* The maximum number of resources contained in the underlying API
* response. If page streaming is performed per-resource, this
* parameter does not affect the return value. If page streaming is
* performed per-page, this determines the maximum number of
* resources in a page.
* @param {Object=} options
* Optional parameters. You can override the default settings for this call,
* e.g, timeout, retries, paginations, etc. See [gax.CallOptions]{@link
* https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the
* details.
* @param {function(?Error, ?Array, ?Object, ?Object)=} callback
* The function which will be called with the result of the API call.
*
* The second parameter to the callback is Array of
* [google.longrunning.Operation]{@link
* external:"google.longrunning.Operation"}.
*
* When autoPaginate: false is specified through options, it contains the
* result in a single response. If the response indicates the next page
* exists, the third parameter is set to be used for the next request object.
* The fourth parameter keeps the raw response object of an object
* representing [google.longrunning.ListOperationsResponse]{@link
* external:"google.longrunning.ListOperationsResponse"}.
* @return {Promise} - The promise which resolves to an array.
* The first element of the array is Array of
* [google.longrunning.Operation]{@link
* external:"google.longrunning.Operation"}.
*
* When autoPaginate: false is specified through options, the array has
* three elements. The first element is Array of
* [google.longrunning.Operation]{@link
* external:"google.longrunning.Operation"} in a single response. The second
* element is the next request object if the response indicates the next page
* exists, or null. The third element is an object representing
* [google.longrunning.ListOperationsResponse]{@link
* external:"google.longrunning.ListOperationsResponse"}.
*
* The promise has a method named "cancel" which cancels the ongoing API
* call.
*
* @example
*
* var client = longrunning.operationsClient();
* var name = '';
* var filter = '';
* var request = {
* name: name,
* filter: filter
* };
* // Iterate over all elements.
* client.listOperations(request).then(function(responses) {
* var resources = responses[0];
* for (var i = 0; i < resources.length; ++i) {
* // doThingsWith(resources[i])
* }
* }).catch(function(err) {
* console.error(err);
* });
*
* // Or obtain the paged response.
* var options = {autoPaginate: false};
* function callback(responses) {
* // The actual resources in a response.
* var resources = responses[0];
* // The next request if the response shows there's more responses.
* var nextRequest = responses[1];
* // The actual response object, if necessary.
* // var rawResponse = responses[2];
* for (var i = 0; i < resources.length; ++i) {
* // doThingsWith(resources[i]);
* }
* if (nextRequest) {
* // Fetch the next page.
* return client.listOperations(nextRequest, options).then(callback);
* }
* }
* client.listOperations(request, options)
* .then(callback)
* .catch(function(err) {
* console.error(err);
* });
*/
listOperations(request: any, options: any, callback: any): any;
/**
* Equivalent to {@link listOperations}, but returns a NodeJS Stream object.
*
* This fetches the paged responses for {@link listOperations} continuously
* and invokes the callback registered for 'data' event for each element in
* the responses.
*
* The returned object has 'end' method when no more elements are required.
*
* autoPaginate option will be ignored.
*
* @see {@link https://nodejs.org/api/stream.html}
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.name
* The name of the operation collection.
* @param {string} request.filter
* The standard list filter.
* @param {number=} request.pageSize
* The maximum number of resources contained in the underlying API
* response. If page streaming is performed per-resource, this
* parameter does not affect the return value. If page streaming is
* performed per-page, this determines the maximum number of
* resources in a page.
* @param {Object=} options
* Optional parameters. You can override the default settings for this call,
* e.g, timeout, retries, paginations, etc. See [gax.CallOptions]{@link
* https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the
* details.
* @return {Stream}
* An object stream which emits an object representing
* [google.longrunning.Operation]{@link
* external:"google.longrunning.Operation"} on 'data' event.
*
* @example
*
* var client = longrunning.operationsClient();
* var name = '';
* var filter = '';
* var request = {
* name: name,
* filter: filter
* };
* client.listOperationsStream(request).on('data', function(element) {
* // doThingsWith(element)
* }).on('error', function(err) {
* console.error(err);
* });
*/
listOperationsStream(request: any, options: any): any;
/**
* Starts asynchronous cancellation on a long-running operation. The server
* makes a best effort to cancel the operation, but success is not
* guaranteed. If the server doesn't support this method, it returns
* `google.rpc.Code.UNIMPLEMENTED`. Clients can use
* {@link Operations.GetOperation} or
* other methods to check whether the cancellation succeeded or whether the
* operation completed despite cancellation. On successful cancellation,
* the operation is not deleted; instead, it becomes an operation with
* an {@link Operation.error} value with a {@link google.rpc.Status.code} of
* 1, corresponding to `Code.CANCELLED`.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.name
* The name of the operation resource to be cancelled.
* @param {Object=} options
* Optional parameters. You can override the default settings for this call,
* e.g, timeout, retries, paginations, etc. See [gax.CallOptions]{@link
* https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the
* details.
* @param {function(?Error)=} callback
* The function which will be called with the result of the API call.
* @return {Promise} - The promise which resolves when API call finishes.
* The promise has a method named "cancel" which cancels the ongoing API
* call.
*
* @example
*
* var client = longrunning.operationsClient();
* var name = '';
* client.cancelOperation({name: name}).catch(function(err) {
* console.error(err);
* });
*/
cancelOperation(request: any, options?: any, callback?: any): any;
/**
* Deletes a long-running operation. This method indicates that the client is
* no longer interested in the operation result. It does not cancel the
* operation. If the server doesn't support this method, it returns
* `google.rpc.Code.UNIMPLEMENTED`.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.name
* The name of the operation resource to be deleted.
* @param {Object=} options
* Optional parameters. You can override the default settings for this call,
* e.g, timeout, retries, paginations, etc. See [gax.CallOptions]{@link
* https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the
* details.
* @param {function(?Error)=} callback
* The function which will be called with the result of the API call.
* @return {Promise} - The promise which resolves when API call finishes.
* The promise has a method named "cancel" which cancels the ongoing API
* call.
*
* @example
*
* var client = longrunning.operationsClient();
* var name = '';
* client.deleteOperation({name: name}).catch(function(err) {
* console.error(err);
* });
*/
deleteOperation(request: any, options: any, callback: any): any;
}
export declare class OperationsClientBuilder {
constructor(gaxGrpc: any);
}

View File

@@ -0,0 +1,438 @@
/*
* Copyright 2016 Google Inc. 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.
*
* EDITING INSTRUCTIONS
* This file was generated from the file
* https://github.com/googleapis/googleapis/blob/master/google/longrunning/operations.proto,
* and updates to that file get reflected here through a refresh process.
* For the short term, the refresh process will only be runnable by Google
* engineers.
*
* The only allowed edits are to method and file documentation. A 3-way
* merge preserves those additions if the generated source changes.
*/
/* TODO: introduce line-wrapping so that it never exceeds the limit. */
/* jscs: disable maximumLineLength */
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
var extend = require("extend");
var apiCallable = require("./api_callable");
var gax = require("./gax");
var pathTemplate = require("./path_template");
var pagedIteration = require("./paged_iteration");
var configData = require('./operations_client_config');
extend(gax, apiCallable);
extend(gax, pathTemplate);
extend(gax, pagedIteration);
exports.SERVICE_ADDRESS = 'longrunning.googleapis.com';
var DEFAULT_SERVICE_PORT = 443;
var CODE_GEN_NAME_VERSION = 'gapic/0.7.1';
var PAGE_DESCRIPTORS = {
listOperations: new gax['PageDescriptor']('pageToken', 'nextPageToken', 'operations'),
};
/**
* The scopes needed to make gRPC calls to all of the methods defined in
* this service.
*/
exports.ALL_SCOPES = [];
/**
* Manages long-running operations with an API service.
*
* When an API method normally takes long time to complete, it can be designed
* to return {@link Operation} to the client, and the client can use this
* interface to receive the real response asynchronously by polling the
* operation resource, or pass the operation resource to another API (such as
* Google Cloud Pub/Sub API) to receive the response. Any API service that
* returns long-running operations should implement the `Operations` interface
* so developers can have a consistent client experience.
*
* This will be created through a builder function which can be obtained by the
* module. See the following example of how to initialize the module and how to
* access to the builder.
* @see {@link operationsClient}
*
* @class
*/
var OperationsClient = /** @class */ (function () {
function OperationsClient(gaxGrpc, grpcClients, opts) {
opts = extend({
servicePath: exports.SERVICE_ADDRESS,
port: DEFAULT_SERVICE_PORT,
clientConfig: {},
}, opts);
var googleApiClient = ['gl-node/' + process.versions.node];
if (opts.libName && opts.libVersion) {
googleApiClient.push(opts.libName + '/' + opts.libVersion);
}
googleApiClient.push(CODE_GEN_NAME_VERSION, 'gax/' + gax['version'], 'grpc/' + gaxGrpc.grpcVersion);
var defaults = gaxGrpc.constructSettings('google.longrunning.Operations', configData, opts.clientConfig, { 'x-goog-api-client': googleApiClient.join(' ') });
var self = this;
this.auth = gaxGrpc.auth;
var operationsStub = gaxGrpc.createStub(grpcClients.google.longrunning.Operations, opts);
var operationsStubMethods = [
'getOperation',
'listOperations',
'cancelOperation',
'deleteOperation',
];
operationsStubMethods.forEach(function (methodName) {
self['_' + methodName] = gax['createApiCall'](operationsStub.then(function (operationsStub) {
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return operationsStub[methodName].apply(operationsStub, args);
};
}), defaults[methodName], PAGE_DESCRIPTORS[methodName]);
});
}
/**
* Get the project ID used by this class.
* @aram {function(Error, string)} callback - the callback to be called with
* the current project Id.
*/
OperationsClient.prototype.getProjectId = function (callback) {
return this.auth.getProjectId(callback);
};
// Service calls
/**
* Gets the latest state of a long-running operation. Clients can use this
* method to poll the operation result at intervals as recommended by the API
* service.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.name
* The name of the operation resource.
* @param {Object=} options
* Optional parameters. You can override the default settings for this call,
* e.g, timeout, retries, paginations, etc. See [gax.CallOptions]{@link
* https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the
* details.
* @param {function(?Error, ?Object)=} callback
* The function which will be called with the result of the API call.
*
* The second parameter to the callback is an object representing
* [google.longrunning.Operation]{@link
* external:"google.longrunning.Operation"}.
* @return {Promise} - The promise which resolves to an array.
* The first element of the array is an object representing
* [google.longrunning.Operation]{@link
* external:"google.longrunning.Operation"}. The promise has a method named
* "cancel" which cancels the ongoing API call.
*
* @example
*
* var client = longrunning.operationsClient();
* var name = '';
* client.getOperation({name: name}).then(function(responses) {
* var response = responses[0];
* // doThingsWith(response)
* }).catch(function(err) {
* console.error(err);
* });
*/
OperationsClient.prototype.getOperation = function (request, options, callback) {
if (options instanceof Function && callback === undefined) {
callback = options;
options = {};
}
if (options === undefined) {
options = {};
}
return this['_getOperation'](request, options, callback);
};
/**
* Lists operations that match the specified filter in the request. If the
* server doesn't support this method, it returns `UNIMPLEMENTED`.
*
* NOTE: the `name` binding below allows API services to override the binding
* to use different resource name schemes.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.name
* The name of the operation collection.
* @param {string} request.filter
* The standard list filter.
* @param {number=} request.pageSize
* The maximum number of resources contained in the underlying API
* response. If page streaming is performed per-resource, this
* parameter does not affect the return value. If page streaming is
* performed per-page, this determines the maximum number of
* resources in a page.
* @param {Object=} options
* Optional parameters. You can override the default settings for this call,
* e.g, timeout, retries, paginations, etc. See [gax.CallOptions]{@link
* https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the
* details.
* @param {function(?Error, ?Array, ?Object, ?Object)=} callback
* The function which will be called with the result of the API call.
*
* The second parameter to the callback is Array of
* [google.longrunning.Operation]{@link
* external:"google.longrunning.Operation"}.
*
* When autoPaginate: false is specified through options, it contains the
* result in a single response. If the response indicates the next page
* exists, the third parameter is set to be used for the next request object.
* The fourth parameter keeps the raw response object of an object
* representing [google.longrunning.ListOperationsResponse]{@link
* external:"google.longrunning.ListOperationsResponse"}.
* @return {Promise} - The promise which resolves to an array.
* The first element of the array is Array of
* [google.longrunning.Operation]{@link
* external:"google.longrunning.Operation"}.
*
* When autoPaginate: false is specified through options, the array has
* three elements. The first element is Array of
* [google.longrunning.Operation]{@link
* external:"google.longrunning.Operation"} in a single response. The second
* element is the next request object if the response indicates the next page
* exists, or null. The third element is an object representing
* [google.longrunning.ListOperationsResponse]{@link
* external:"google.longrunning.ListOperationsResponse"}.
*
* The promise has a method named "cancel" which cancels the ongoing API
* call.
*
* @example
*
* var client = longrunning.operationsClient();
* var name = '';
* var filter = '';
* var request = {
* name: name,
* filter: filter
* };
* // Iterate over all elements.
* client.listOperations(request).then(function(responses) {
* var resources = responses[0];
* for (var i = 0; i < resources.length; ++i) {
* // doThingsWith(resources[i])
* }
* }).catch(function(err) {
* console.error(err);
* });
*
* // Or obtain the paged response.
* var options = {autoPaginate: false};
* function callback(responses) {
* // The actual resources in a response.
* var resources = responses[0];
* // The next request if the response shows there's more responses.
* var nextRequest = responses[1];
* // The actual response object, if necessary.
* // var rawResponse = responses[2];
* for (var i = 0; i < resources.length; ++i) {
* // doThingsWith(resources[i]);
* }
* if (nextRequest) {
* // Fetch the next page.
* return client.listOperations(nextRequest, options).then(callback);
* }
* }
* client.listOperations(request, options)
* .then(callback)
* .catch(function(err) {
* console.error(err);
* });
*/
OperationsClient.prototype.listOperations = function (request, options, callback) {
if (options instanceof Function && callback === undefined) {
callback = options;
options = {};
}
if (options === undefined) {
options = {};
}
return this['_listOperations'](request, options, callback);
};
/**
* Equivalent to {@link listOperations}, but returns a NodeJS Stream object.
*
* This fetches the paged responses for {@link listOperations} continuously
* and invokes the callback registered for 'data' event for each element in
* the responses.
*
* The returned object has 'end' method when no more elements are required.
*
* autoPaginate option will be ignored.
*
* @see {@link https://nodejs.org/api/stream.html}
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.name
* The name of the operation collection.
* @param {string} request.filter
* The standard list filter.
* @param {number=} request.pageSize
* The maximum number of resources contained in the underlying API
* response. If page streaming is performed per-resource, this
* parameter does not affect the return value. If page streaming is
* performed per-page, this determines the maximum number of
* resources in a page.
* @param {Object=} options
* Optional parameters. You can override the default settings for this call,
* e.g, timeout, retries, paginations, etc. See [gax.CallOptions]{@link
* https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the
* details.
* @return {Stream}
* An object stream which emits an object representing
* [google.longrunning.Operation]{@link
* external:"google.longrunning.Operation"} on 'data' event.
*
* @example
*
* var client = longrunning.operationsClient();
* var name = '';
* var filter = '';
* var request = {
* name: name,
* filter: filter
* };
* client.listOperationsStream(request).on('data', function(element) {
* // doThingsWith(element)
* }).on('error', function(err) {
* console.error(err);
* });
*/
OperationsClient.prototype.listOperationsStream = function (request, options) {
if (options === undefined) {
options = {};
}
return PAGE_DESCRIPTORS.listOperations.createStream(this['_listOperations'], request, options);
};
/**
* Starts asynchronous cancellation on a long-running operation. The server
* makes a best effort to cancel the operation, but success is not
* guaranteed. If the server doesn't support this method, it returns
* `google.rpc.Code.UNIMPLEMENTED`. Clients can use
* {@link Operations.GetOperation} or
* other methods to check whether the cancellation succeeded or whether the
* operation completed despite cancellation. On successful cancellation,
* the operation is not deleted; instead, it becomes an operation with
* an {@link Operation.error} value with a {@link google.rpc.Status.code} of
* 1, corresponding to `Code.CANCELLED`.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.name
* The name of the operation resource to be cancelled.
* @param {Object=} options
* Optional parameters. You can override the default settings for this call,
* e.g, timeout, retries, paginations, etc. See [gax.CallOptions]{@link
* https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the
* details.
* @param {function(?Error)=} callback
* The function which will be called with the result of the API call.
* @return {Promise} - The promise which resolves when API call finishes.
* The promise has a method named "cancel" which cancels the ongoing API
* call.
*
* @example
*
* var client = longrunning.operationsClient();
* var name = '';
* client.cancelOperation({name: name}).catch(function(err) {
* console.error(err);
* });
*/
OperationsClient.prototype.cancelOperation = function (request, options, callback) {
if (options instanceof Function && callback === undefined) {
callback = options;
options = {};
}
if (options === undefined) {
options = {};
}
return this['_cancelOperation'](request, options, callback);
};
/**
* Deletes a long-running operation. This method indicates that the client is
* no longer interested in the operation result. It does not cancel the
* operation. If the server doesn't support this method, it returns
* `google.rpc.Code.UNIMPLEMENTED`.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.name
* The name of the operation resource to be deleted.
* @param {Object=} options
* Optional parameters. You can override the default settings for this call,
* e.g, timeout, retries, paginations, etc. See [gax.CallOptions]{@link
* https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the
* details.
* @param {function(?Error)=} callback
* The function which will be called with the result of the API call.
* @return {Promise} - The promise which resolves when API call finishes.
* The promise has a method named "cancel" which cancels the ongoing API
* call.
*
* @example
*
* var client = longrunning.operationsClient();
* var name = '';
* client.deleteOperation({name: name}).catch(function(err) {
* console.error(err);
* });
*/
OperationsClient.prototype.deleteOperation = function (request, options, callback) {
if (options instanceof Function && callback === undefined) {
callback = options;
options = {};
}
if (options === undefined) {
options = {};
}
return this['_deleteOperation'](request, options, callback);
};
return OperationsClient;
}());
exports.OperationsClient = OperationsClient;
var OperationsClientBuilder = /** @class */ (function () {
function OperationsClientBuilder(gaxGrpc) {
var operationsClient = gaxGrpc.load([
{
root: require('google-proto-files')('..'),
file: 'google/longrunning/operations.proto',
},
]);
extend(this, operationsClient.google.longrunning);
/**
* Build a new instance of {@link OperationsClient}.
*
* @param {Object=} opts - The optional parameters.
* @param {String=} opts.servicePath
* The domain name of the API remote host.
* @param {number=} opts.port
* The port on which to connect to the remote host.
* @param {grpc.ClientCredentials=} opts.sslCreds
* A ClientCredentials for use with an SSL-enabled channel.
* @param {Object=} opts.clientConfig
* The customized config to build the call settings. See
* {@link gax.constructSettings} for the format.
*/
this['operationsClient'] = function (opts) {
return new OperationsClient(gaxGrpc, operationsClient, opts);
};
extend(this['operationsClient'], OperationsClient);
}
return OperationsClientBuilder;
}());
exports.OperationsClientBuilder = OperationsClientBuilder;
//# sourceMappingURL=operations_client.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"operations_client.js","sourceRoot":"","sources":["../../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kB,CAAC,EAAE,gBAAgB,CAAC,CAAC;IACrD,CAAC;IACH,8BAAC;AAAD,CAAC,AA7BD,IA6BC;AA7BY,0DAAuB"}

View File

@@ -0,0 +1,46 @@
{
"interfaces": {
"google.longrunning.Operations": {
"retry_codes": {
"idempotent": [
"DEADLINE_EXCEEDED",
"UNAVAILABLE"
],
"non_idempotent": []
},
"retry_params": {
"default": {
"initial_retry_delay_millis": 100,
"retry_delay_multiplier": 1.3,
"max_retry_delay_millis": 60000,
"initial_rpc_timeout_millis": 90000,
"rpc_timeout_multiplier": 1.0,
"max_rpc_timeout_millis": 90000,
"total_timeout_millis": 600000
}
},
"methods": {
"GetOperation": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default"
},
"ListOperations": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default"
},
"CancelOperation": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default"
},
"DeleteOperation": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default"
}
}
}
}
}

View File

@@ -0,0 +1,62 @@
/// <reference types="node" />
import { Transform } from 'stream';
import { NormalApiCaller, APICall, APICallback } from './api_callable';
export declare class PagedIteration extends NormalApiCaller {
pageDescriptor: PageDescriptor;
/**
* Creates an API caller that returns a stream to performs page-streaming.
*
* @private
* @constructor
* @param {PageDescriptor} pageDescriptor - indicates the structure
* of page streaming to be performed.
*/
constructor(pageDescriptor: PageDescriptor);
createActualCallback(request: {
[index: string]: {};
}, callback: APICallback): (err: Error | null, response: {
[index: string]: {};
}) => void;
wrap(func: Function): (argument: any, metadata: any, options: any, callback: any) => any;
init(settings: {}, callback: APICallback): any;
call(apiCall: APICall, argument: {
[index: string]: {};
}, settings: any, canceller: any): void;
}
export declare class PageDescriptor {
requestPageTokenField: string;
responsePageTokenField: string;
requestPageSizeField?: string;
resourceField: string;
/**
* Describes the structure of a page-streaming call.
*
* @property {String} requestPageTokenField
* @property {String} responsePageTokenField
* @property {String} resourceField
*
* @param {String} requestPageTokenField - The field name of the page token in
* the request.
* @param {String} responsePageTokenField - The field name of the page token in
* the response.
* @param {String} resourceField - The resource field name.
*
* @constructor
*/
constructor(requestPageTokenField: string, responsePageTokenField: string, resourceField: string);
/**
* Creates a new object Stream which emits the resource on 'data' event.
* @private
* @param {ApiCall} apiCall - the callable object.
* @param {Object} request - the request object.
* @param {CallOptions=} options - the call options to customize the api call.
* @return {Stream} - a new object Stream.
*/
createStream(apiCall: any, request: any, options: any): Transform;
/**
* Returns a new API caller.
* @private
* @return {PageStreamable} - the page streaming caller.
*/
apiCaller(): PagedIteration;
}

View File

@@ -0,0 +1,221 @@
/**
* Copyright 2016, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
'use strict';
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
}
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var extend = require("extend");
var through2 = require("through2");
var ended = require("is-stream-ended");
var api_callable_1 = require("./api_callable");
var PagedIteration = /** @class */ (function (_super) {
__extends(PagedIteration, _super);
/**
* Creates an API caller that returns a stream to performs page-streaming.
*
* @private
* @constructor
* @param {PageDescriptor} pageDescriptor - indicates the structure
* of page streaming to be performed.
*/
function PagedIteration(pageDescriptor) {
var _this = _super.call(this) || this;
_this.pageDescriptor = pageDescriptor;
return _this;
}
PagedIteration.prototype.createActualCallback = function (request, callback) {
var self = this;
return function fetchNextPageToken(err, response) {
if (err) {
callback(err);
return;
}
var resources = response[self.pageDescriptor.resourceField];
var pageToken = response[self.pageDescriptor.responsePageTokenField];
if (pageToken) {
request[self.pageDescriptor.requestPageTokenField] = pageToken;
callback(err, resources, request, response);
}
else {
callback(err, resources, null, response);
}
};
};
PagedIteration.prototype.wrap = function (func) {
var self = this;
return function wrappedCall(argument, metadata, options, callback) {
return func(argument, metadata, options, self.createActualCallback(argument, callback));
};
};
PagedIteration.prototype.init = function (settings, callback) {
return api_callable_1.NormalApiCaller.prototype.init.call(this, settings, callback);
};
PagedIteration.prototype.call = function (apiCall, argument, settings, canceller) {
argument = extend({}, argument);
if (settings.pageToken) {
argument[this.pageDescriptor.requestPageTokenField] = settings.pageToken;
}
if (settings.pageSize) {
argument[this.pageDescriptor.requestPageSizeField] = settings.pageSize;
}
if (!settings.autoPaginate) {
api_callable_1.NormalApiCaller.prototype.call.call(this, apiCall, argument, settings, canceller);
return;
}
var maxResults = settings.maxResults || -1;
var allResources = [];
function pushResources(err, resources, next) {
if (err) {
canceller.callback(err);
return;
}
for (var i = 0; i < resources.length; ++i) {
allResources.push(resources[i]);
if (allResources.length === maxResults) {
next = null;
break;
}
}
if (!next) {
canceller.callback(null, allResources);
return;
}
setImmediate(apiCall, next, pushResources);
}
setImmediate(apiCall, argument, pushResources);
};
return PagedIteration;
}(api_callable_1.NormalApiCaller));
exports.PagedIteration = PagedIteration;
var PageDescriptor = /** @class */ (function () {
/**
* Describes the structure of a page-streaming call.
*
* @property {String} requestPageTokenField
* @property {String} responsePageTokenField
* @property {String} resourceField
*
* @param {String} requestPageTokenField - The field name of the page token in
* the request.
* @param {String} responsePageTokenField - The field name of the page token in
* the response.
* @param {String} resourceField - The resource field name.
*
* @constructor
*/
function PageDescriptor(requestPageTokenField, responsePageTokenField, resourceField) {
this.requestPageTokenField = requestPageTokenField;
this.responsePageTokenField = responsePageTokenField;
this.resourceField = resourceField;
}
/**
* Creates a new object Stream which emits the resource on 'data' event.
* @private
* @param {ApiCall} apiCall - the callable object.
* @param {Object} request - the request object.
* @param {CallOptions=} options - the call options to customize the api call.
* @return {Stream} - a new object Stream.
*/
PageDescriptor.prototype.createStream = function (apiCall, request, options) {
var stream = through2.obj();
options = extend({}, options, { autoPaginate: false });
var maxResults = 'maxResults' in options ? options.maxResults : -1;
var pushCount = 0;
var started = false;
function callback(err, resources, next) {
if (err) {
stream.emit('error', err);
return;
}
for (var i = 0; i < resources.length; ++i) {
if (ended(stream)) {
return;
}
if (resources[i] === null) {
continue;
}
stream.push(resources[i]);
pushCount++;
if (pushCount === maxResults) {
stream.end();
}
}
if (ended(stream)) {
return;
}
if (!next) {
stream.end();
return;
}
// When pageToken is specified in the original options, it will overwrite
// the page token field in the next request. Therefore it must be cleared.
if ('pageToken' in options) {
delete options.pageToken;
}
if (stream.isPaused()) {
request = next;
started = false;
}
else {
setImmediate(apiCall, next, options, callback);
}
}
stream.on('resume', function () {
if (!started) {
started = true;
apiCall(request, options, callback);
}
});
return stream;
};
/**
* Returns a new API caller.
* @private
* @return {PageStreamable} - the page streaming caller.
*/
PageDescriptor.prototype.apiCaller = function () {
return new PagedIteration(this);
};
return PageDescriptor;
}());
exports.PageDescriptor = PageDescriptor;
//# sourceMappingURL=paged_iteration.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"paged_iteration.js","sourceRoot":"","sources":["../../src/paged_iteration.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,YAAY,CAAC;;;;;;;;;;;;;;;AAEb,+BAAiC;AACjC,mCAAqC;AACrC,uCAAyC;AAGzC,+CAAqE;AAErE;IAAoC,kCAAe;IAEjD;;;;;;;OAOG;IACH,wBAAY,cAA8B;QAA1C,YACE,iBAAO,SAER;QADC,KAAI,CAAC,cAAc,GAAG,cAAc,CAAC;;IACvC,CAAC;IAED,6CAAoB,GAApB,UAAqB,OAA8B,EAAE,QAAqB;QACxE,IAAM,IAAI,GAAG,IAAI,CAAC;QAClB,OAAO,SAAS,kBAAkB,CAC9B,GAAe,EAAE,QAA+B;YAClD,IAAI,GAAG,EAAE;gBACP,QAAQ,CAAC,GAAG,CAAC,CAAC;gBACd,OAAO;aACR;YACD,IAAM,SAAS,GAAG,QAAQ,CAAC,IAAI,CAAC,cAAc,CAAC,aAAa,CAAC,CAAC;YAC9D,IAAM,SAAS,GAAG,QAAQ,CAAC,IAAI,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;YACvE,IAAI,SAAS,EAAE;gBACb,OAAO,CAAC,IAAI,CAAC,cAAc,CAAC,qBAAqB,CAAC,GAAG,SAAS,CAAC;gBAC/D,QAAQ,CAAC,GAAG,EAAE,SAAS,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;a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C,EAAE,CAAC,QAAQ,EAAE;YAClB,IAAI,CAAC,OAAO,EAAE;gBACZ,OAAO,GAAG,IAAI,CAAC;gBACf,OAAO,CAAC,OAAO,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;aACrC;QACH,CAAC,CAAC,CAAC;QACH,OAAO,MAAM,CAAC;IAChB,CAAC;IAED;;;;OAIG;IACH,kCAAS,GAAT;QACE,OAAO,IAAI,cAAc,CAAC,IAAI,CAAC,CAAC;IAClC,CAAC;IACH,qBAAC;AAAD,CAAC,AAhGD,IAgGC;AAhGY,wCAAc"}

View File

@@ -0,0 +1,21 @@
import { Segment } from './path_template';
export declare const BINDING = 1;
export declare const END_BINDING = 2;
export declare const TERMINAL = 3;
/**
* Completes the parsing of the segments
*
* Validates them, and transforms them into the object used by the
* PathTemplate class.
*
* @private
*
* @param {Segments[]} segments the parsed segments
* @param {Object} initializes the attributes of a PathTemplate
* @return {Object} Returns segments and size
* @throws {TypeError} if multiple path wildcards exist
*/
export declare function finishParse(segments: Segment[]): {
segments: Segment[];
size: number;
};

View File

@@ -0,0 +1,115 @@
/*
*
* Copyright 2016, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
var util = require("util");
var _ = require("lodash");
/* constants used in the pegjs parser */
exports.BINDING = 1;
exports.END_BINDING = 2;
exports.TERMINAL = 3;
/**
* Checks that segments only has one terminal segment that is a path wildcard.
*
* @private
*
* @param {Segments[]} segments the parsed segments
* @throws {TypeError} if there are too many
*/
function allowOnePathWildcard(segments) {
var hasPathWildcard = false;
for (var i = 0; i < segments.length; i++) {
var s = segments[i];
if (s.kind !== exports.TERMINAL || s.literal !== '**') {
continue;
}
if (hasPathWildcard) {
var tooManyWildcards = 'cannot contain more than one path wildcard';
throw new TypeError(tooManyWildcards);
}
hasPathWildcard = true;
}
}
/**
* Counts the number of terminal segments.
*
* @private
*
* @param {Segments[]} segments the parsed segments
* @return {number} the number of terminal segments in the template
*/
function countTerminals(segments) {
var terms = _.filter(segments, function (x) {
return x.kind === exports.TERMINAL;
});
return terms.length;
}
/**
* Updates missing literals of each of the binding segments.
*
* @private
*
* @param {Segments[]} segments the parsed segments
*/
function updateBindingLiterals(segments) {
var bindingIndex = 0;
segments.forEach(function (s) {
if (s.kind === exports.BINDING && !s.literal) {
s.literal = util.format('$%d', bindingIndex);
bindingIndex += 1;
}
});
}
/**
* Completes the parsing of the segments
*
* Validates them, and transforms them into the object used by the
* PathTemplate class.
*
* @private
*
* @param {Segments[]} segments the parsed segments
* @param {Object} initializes the attributes of a PathTemplate
* @return {Object} Returns segments and size
* @throws {TypeError} if multiple path wildcards exist
*/
function finishParse(segments) {
allowOnePathWildcard(segments);
updateBindingLiterals(segments);
return {
segments: segments,
size: countTerminals(segments),
};
}
exports.finishParse = finishParse;
//# sourceMappingURL=parser_extras.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"parser_extras.js","sourceRoot":"","sources":["../../src/parser_extras.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,YAAY,CAAC;;AAEb,2BAA6B;AAC7B,0BAA4B;AAG5B,wCAAwC;AAC3B,QAAA,OAAO,GAAG,CAAC,CAAC;AACZ,QAAA,WAAW,GAAG,CAAC,CAAC;AAChB,QAAA,QAAQ,GAAG,CAAC,CAAC;AAE1B;;;;;;;GAOG;AACH,SAAS,oBAAoB,CAAC,QAAmB;IAC/C,IAAI,eAAe,GAAG,KAAK,CAAC;IAC5B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACxC,IAAM,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC;QACtB,IAAI,CAAC,CAAC,IAAI,KAAK,gBAAQ,IAAI,CAAC,CAAC,OAAO,KAAK,IAAI,EAAE;YAC7C,SAAS;SACV;QACD,IAAI,eAAe,EAAE;YACnB,IAAM,gBAAgB,GAAG,4CAA4C,CAAC;YACtE,MAAM,IAAI,SAAS,CAAC,gBAAgB,CAAC,CAAC;SACvC;QACD,eAAe,GAAG,IAAI,CAAC;KACxB;AACH,CAAC;AAED;;;;;;;GAOG;AACH,SAAS,cAAc,CAAC,QAAmB;IACzC,IAAM,KAAK,GAAG,CAAC,CAAC,MAAM,CAAC,QAAQ,EAAE,UAAA,CAAC;QAChC,OAAO,CAAC,CAAC,IAAI,KAAK,gBAAQ,CAAC;IAC7B,CAAC,CAAC,CAAC;IACH,OAAO,KAAK,CAAC,MAAM,CAAC;AACtB,CAAC;AAED;;;;;;GAMG;AACH,SAAS,qBAAqB,CAAC,QAAmB;IAChD,IAAI,YAAY,GAAG,CAAC,CAAC;IACrB,QAAQ,CAAC,OAAO,CAAC,UAAA,CAAC;QAChB,IAAI,CAAC,CAAC,IAAI,KAAK,eAAO,IAAI,CAAC,CAAC,CAAC,OAAO,EAAE;YACpC,CAAC,CAAC,OAAO,GAAG,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,YAAY,CAAC,CAAC;YAC7C,YAAY,IAAI,CAAC,CAAC;SACnB;IACH,CAAC,CAAC,CAAC;AACL,CAAC;AAED;;;;;;;;;;;;GAYG;AACH,SAAgB,WAAW,CAAC,QAAmB;IAC7C,oBAAoB,CAAC,QAAQ,CAAC,CAAC;IAC/B,qBAAqB,CAAC,QAAQ,CAAC,CAAC;IAChC,OAAO;QACL,QAAQ,UAAA;QACR,IAAI,EAAE,cAAc,CAAC,QAAQ,CAAC;KAC/B,CAAC;AACJ,CAAC;AAPD,kCAOC"}

View File

@@ -0,0 +1,45 @@
export interface ParseResult {
size: number;
segments: Segment[];
}
export interface Segment {
kind: number;
literal: string;
}
export declare type Bindings = {
[index: string]: string;
};
export declare class PathTemplate {
private readonly parseResult;
readonly size: number;
readonly segments: Segment[];
/**
* @param {String} data the of the template
*
* @constructor
*/
constructor(data: string);
/**
* Matches a fully-qualified path template string.
*
* @param {String} path a fully-qualified path template string
* @return {Object} contains const names matched to binding values
* @throws {TypeError} if path can't be matched to this template
*/
match(path: string): Bindings;
/**
* Renders a path template using the provided bindings.
*
* @param {Object} bindings a mapping of const names to binding strings
* @return {String} a rendered representation of the path template
* @throws {TypeError} if a key is missing, or if a sub-template cannot be
* parsed
*/
render(bindings: Bindings): string;
/**
* Renders the path template.
*
* @return {string} contains const names matched to binding values
*/
inspect(): string;
}

View File

@@ -0,0 +1,185 @@
/*
*
* Copyright 2016, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
/*
* Path template utility.
*/
var _ = require("lodash");
var util = require("util");
var extras = require("./parser_extras");
var parser = require('./path_template_parser');
var PathTemplate = /** @class */ (function () {
/**
* @param {String} data the of the template
*
* @constructor
*/
function PathTemplate(data) {
this.parseResult = extras.finishParse(parser.parse(data));
}
Object.defineProperty(PathTemplate.prototype, "size", {
get: function () {
return this.parseResult.size;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PathTemplate.prototype, "segments", {
get: function () {
return this.parseResult.segments;
},
enumerable: true,
configurable: true
});
/**
* Matches a fully-qualified path template string.
*
* @param {String} path a fully-qualified path template string
* @return {Object} contains const names matched to binding values
* @throws {TypeError} if path can't be matched to this template
*/
PathTemplate.prototype.match = function (path) {
var pathSegments = path.split('/');
var bindings = {};
var segmentCount = this.size;
var current;
var index = 0;
this.segments.forEach(function (segment) {
if (index > pathSegments.length) {
return;
}
if (segment.kind === extras.BINDING) {
current = segment.literal;
}
else if (segment.kind === extras.TERMINAL) {
if (segment.literal === '*') {
bindings[current] = pathSegments[index];
index += 1;
}
else if (segment.literal === '**') {
var size = pathSegments.length - segmentCount + 1;
segmentCount += size - 1;
bindings[current] = pathSegments.slice(index, index + size).join('/');
index += size;
}
else if (segment.literal === pathSegments[index]) {
index += 1;
}
else {
var msg = util.format('mismatched literal (index=%d): \'%s\' != \'%s\'', index, segment.literal, pathSegments[index]);
throw new TypeError(msg);
}
}
});
if (index !== pathSegments.length || index !== segmentCount) {
var msg = util.format('match error: could not instantiate a path template from %s', path);
throw new TypeError(msg);
}
return bindings;
};
/**
* Renders a path template using the provided bindings.
*
* @param {Object} bindings a mapping of const names to binding strings
* @return {String} a rendered representation of the path template
* @throws {TypeError} if a key is missing, or if a sub-template cannot be
* parsed
*/
PathTemplate.prototype.render = function (bindings) {
var out = [];
var inABinding = false;
this.segments.forEach(function (segment) {
if (segment.kind === extras.BINDING) {
if (!_.has(bindings, segment.literal)) {
var msg = util.format('Value for key %s is not provided in %s', segment.literal, bindings);
throw new TypeError(msg);
}
var tmp = new PathTemplate(bindings[segment.literal]);
Array.prototype.push.apply(out, tmp.segments);
inABinding = true;
}
else if (segment.kind === extras.END_BINDING) {
inABinding = false;
}
else if (inABinding) {
return;
}
else {
out.push(segment);
}
});
var result = formatSegments(out);
this.match(result);
return result;
};
/**
* Renders the path template.
*
* @return {string} contains const names matched to binding values
*/
PathTemplate.prototype.inspect = function () {
return formatSegments(this.segments);
};
return PathTemplate;
}());
exports.PathTemplate = PathTemplate;
/**
* Creates the string representattion for the segments.
* @param {Object[]} segments - The array of segments.
* @return {string} - A string representing segments in the path template
* format.
*/
function formatSegments(segments) {
var out = '';
var slash = true;
segments.forEach(function (segment) {
if (segment.kind === extras.TERMINAL) {
if (slash) {
out += '/';
}
out += segment.literal;
return;
}
slash = true;
if (segment.kind === extras.BINDING) {
out += '/{' + segment.literal + '=';
slash = false;
}
else {
out += segment.literal + '}';
}
});
return out.substring(1);
}
//# sourceMappingURL=path_template.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"path_template.js","sourceRoot":"","sources":["../../src/path_template.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,YAAY,CAAC;;AAEb;;GAEG;AAEH,0BAA4B;AAC5B,2BAA6B;AAC7B,wCAA0C;AAC1C,IAAM,MAAM,GAAG,OAAO,CAAC,wBAAwB,CAAC,CAAC;AAgBjD;IAWE;;;;OAIG;IACH,sBAAY,IAAY;QACtB,IAAI,CAAC,WAAW,GAAG,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC;IAC5D,CAAC;IAfD,sBAAI,8BAAI;aAAR;YACE,OAAO,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC;QAC/B,CAAC;;;OAAA;IAED,sBAAI,kCAAQ;aAAZ;YACE,OAAO,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC;QACnC,CAAC;;;OAAA;IAWD;;;;;;OAMG;IACH,4BAAK,GAAL,UAAM,IAAY;QAChB,IAAM,YAAY,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QACrC,IAAM,QAAQ,GAAa,EAAE,CAAC;QAC9B,IAAI,YAAY,GAAG,IAAI,CAAC,IAAI,CAAC;QAC7B,IAAI,OAAe,CAAC;QACpB,IAAI,KAAK,GAAG,CAAC,CAAC;QACd,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,UAAA,OAAO;YAC3B,IAAI,KAAK,GAAG,YAAY,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AC;IACH,mBAAC;AAAD,CAAC,AA9GD,IA8GC;AA9GY,oCAAY;AAgHzB;;;;;GAKG;AACH,SAAS,cAAc,CAAC,QAAmB;IACzC,IAAI,GAAG,GAAG,EAAE,CAAC;IACb,IAAI,KAAK,GAAG,IAAI,CAAC;IACjB,QAAQ,CAAC,OAAO,CAAC,UAAA,OAAO;QACtB,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,CAAC,QAAQ,EAAE;YACpC,IAAI,KAAK,EAAE;gBACT,GAAG,IAAI,GAAG,CAAC;aACZ;YACD,GAAG,IAAI,OAAO,CAAC,OAAO,CAAC;YACvB,OAAO;SACR;QACD,KAAK,GAAG,IAAI,CAAC;QACb,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,CAAC,OAAO,EAAE;YACnC,GAAG,IAAI,IAAI,GAAG,OAAO,CAAC,OAAO,GAAG,GAAG,CAAC;YACpC,KAAK,GAAG,KAAK,CAAC;SACf;aAAM;YACL,GAAG,IAAI,OAAO,CAAC,OAAO,GAAG,GAAG,CAAC;SAC9B;IACH,CAAC,CAAC,CAAC;IACH,OAAO,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;AAC1B,CAAC"}

View File

@@ -0,0 +1,606 @@
"use strict";
/* eslint-disable */
module.exports = (function () {
'use strict';
/*
* Generated by PEG.js 0.9.0.
*
* http://pegjs.org/
*/
function peg$subclass(child, parent) {
function ctor() {
this.constructor = child;
}
ctor.prototype = parent.prototype;
child.prototype = new ctor();
}
function peg$SyntaxError(message, expected, found, location) {
this.message = message;
this.expected = expected;
this.found = found;
this.location = location;
this.name = 'SyntaxError';
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, peg$SyntaxError);
}
}
peg$subclass(peg$SyntaxError, Error);
function peg$parse(input) {
var options = arguments.length > 1 ? arguments[1] : {};
var parser = this;
var peg$FAILED = {};
var peg$startRuleFunctions = { template: peg$parsetemplate };
var peg$startRuleFunction = peg$parsetemplate;
var peg$c0 = '/';
var peg$c1 = { type: 'literal', value: '/', description: '"/"' };
var peg$c2 = function (segments) {
return segments;
};
var peg$c3 = function (s, segments) {
return s.concat(segments);
};
var peg$c4 = function (s) {
return s;
};
var peg$c5 = '{';
var peg$c6 = { type: 'literal', value: '{', description: '"{"' };
var peg$c7 = '=';
var peg$c8 = { type: 'literal', value: '=', description: '"="' };
var peg$c9 = '}';
var peg$c10 = { type: 'literal', value: '}', description: '"}"' };
var peg$c11 = function (l, segments) {
return _.flatten([
{ kind: extras.BINDING, literal: l },
segments,
{ kind: extras.END_BINDING, literal: '' },
]);
};
var peg$c12 = function (l) {
return [
{ kind: extras.BINDING, literal: l },
{ kind: extras.TERMINAL, literal: '*' },
{ kind: extras.END_BINDING, literal: '' },
];
};
var peg$c13 = function (t, segments) {
return t.concat(segments);
};
var peg$c14 = function (t) {
if (t[0].literal === '*' || t[0].literal === '**') {
return [
{
kind: extras.BINDING,
},
t[0],
{ kind: extras.END_BINDING, literal: '' },
];
}
else {
return t;
}
};
var peg$c15 = '**';
var peg$c16 = { type: 'literal', value: '**', description: '"**"' };
var peg$c17 = '*';
var peg$c18 = { type: 'literal', value: '*', description: '"*"' };
var peg$c19 = function (l) {
return [{ kind: extras.TERMINAL, literal: l }];
};
var peg$c20 = /^[^*=}{\/]/;
var peg$c21 = { type: 'class', value: '[^*=}{/]', description: '[^*=}{/]' };
var peg$c22 = function (cs) {
return cs.join('');
};
var peg$currPos = 0;
var peg$savedPos = 0;
var peg$posDetailsCache = [{ line: 1, column: 1, seenCR: false }];
var peg$maxFailPos = 0;
var peg$maxFailExpected = [];
var peg$silentFails = 0;
var peg$result;
if ('startRule' in options) {
if (!(options.startRule in peg$startRuleFunctions)) {
throw new Error('Can\'t start parsing from rule "' + options.startRule + '".');
}
peg$startRuleFunction = peg$startRuleFunctions[options.startRule];
}
function text() {
return input.substring(peg$savedPos, peg$currPos);
}
function location() {
return peg$computeLocation(peg$savedPos, peg$currPos);
}
function expected(description) {
throw peg$buildException(null, [{ type: 'other', description: description }], input.substring(peg$savedPos, peg$currPos), peg$computeLocation(peg$savedPos, peg$currPos));
}
function error(message) {
throw peg$buildException(message, null, input.substring(peg$savedPos, peg$currPos), peg$computeLocation(peg$savedPos, peg$currPos));
}
function peg$computePosDetails(pos) {
var details = peg$posDetailsCache[pos], p, ch;
if (details) {
return details;
}
else {
p = pos - 1;
while (!peg$posDetailsCache[p]) {
p--;
}
details = peg$posDetailsCache[p];
details = {
line: details.line,
column: details.column,
seenCR: details.seenCR,
};
while (p < pos) {
ch = input.charAt(p);
if (ch === '\n') {
if (!details.seenCR) {
details.line++;
}
details.column = 1;
details.seenCR = false;
}
else if (ch === '\r' || ch === '\u2028' || ch === '\u2029') {
details.line++;
details.column = 1;
details.seenCR = true;
}
else {
details.column++;
details.seenCR = false;
}
p++;
}
peg$posDetailsCache[pos] = details;
return details;
}
}
function peg$computeLocation(startPos, endPos) {
var startPosDetails = peg$computePosDetails(startPos), endPosDetails = peg$computePosDetails(endPos);
return {
start: {
offset: startPos,
line: startPosDetails.line,
column: startPosDetails.column,
},
end: {
offset: endPos,
line: endPosDetails.line,
column: endPosDetails.column,
},
};
}
function peg$fail(expected) {
if (peg$currPos < peg$maxFailPos) {
return;
}
if (peg$currPos > peg$maxFailPos) {
peg$maxFailPos = peg$currPos;
peg$maxFailExpected = [];
}
peg$maxFailExpected.push(expected);
}
function peg$buildException(message, expected, found, location) {
function cleanupExpected(expected) {
var i = 1;
expected.sort(function (a, b) {
if (a.description < b.description) {
return -1;
}
else if (a.description > b.description) {
return 1;
}
else {
return 0;
}
});
while (i < expected.length) {
if (expected[i - 1] === expected[i]) {
expected.splice(i, 1);
}
else {
i++;
}
}
}
function buildMessage(expected, found) {
function stringEscape(s) {
function hex(ch) {
return ch.charCodeAt(0).toString(16).toUpperCase();
}
return s.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/\x08/g, '\\b')
.replace(/\t/g, '\\t')
.replace(/\n/g, '\\n')
.replace(/\f/g, '\\f')
.replace(/\r/g, '\\r')
.replace(/[\x00-\x07\x0B\x0E\x0F]/g, function (ch) {
return '\\x0' + hex(ch);
})
.replace(/[\x10-\x1F\x80-\xFF]/g, function (ch) {
return '\\x' + hex(ch);
})
.replace(/[\u0100-\u0FFF]/g, function (ch) {
return '\\u0' + hex(ch);
})
.replace(/[\u1000-\uFFFF]/g, function (ch) {
return '\\u' + hex(ch);
});
}
var expectedDescs = new Array(expected.length);
var expectedDesc, foundDesc, i;
for (i = 0; i < expected.length; i++) {
expectedDescs[i] = expected[i].description;
}
expectedDesc = expected.length > 1 ?
expectedDescs.slice(0, -1).join(', ') + ' or ' +
expectedDescs[expected.length - 1] :
expectedDescs[0];
foundDesc = found ? '"' + stringEscape(found) + '"' : 'end of input';
return 'Expected ' + expectedDesc + ' but ' + foundDesc + ' found.';
}
if (expected !== null) {
cleanupExpected(expected);
}
return new peg$SyntaxError(message !== null ? message : buildMessage(expected, found), expected, found, location);
}
function peg$parsetemplate() {
var s0, s1, s2;
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 47) {
s1 = peg$c0;
peg$currPos++;
}
else {
s1 = peg$FAILED;
if (peg$silentFails === 0) {
peg$fail(peg$c1);
}
}
if (s1 !== peg$FAILED) {
s2 = peg$parsebound_segments();
if (s2 !== peg$FAILED) {
peg$savedPos = s0;
s1 = peg$c2(s2);
s0 = s1;
}
else {
peg$currPos = s0;
s0 = peg$FAILED;
}
}
else {
peg$currPos = s0;
s0 = peg$FAILED;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parsebound_segments();
if (s1 !== peg$FAILED) {
peg$savedPos = s0;
s1 = peg$c2(s1);
}
s0 = s1;
}
return s0;
}
function peg$parsebound_segments() {
var s0, s1, s2, s3;
s0 = peg$currPos;
s1 = peg$parsebound_segment();
if (s1 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 47) {
s2 = peg$c0;
peg$currPos++;
}
else {
s2 = peg$FAILED;
if (peg$silentFails === 0) {
peg$fail(peg$c1);
}
}
if (s2 !== peg$FAILED) {
s3 = peg$parsebound_segments();
if (s3 !== peg$FAILED) {
peg$savedPos = s0;
s1 = peg$c3(s1, s3);
s0 = s1;
}
else {
peg$currPos = s0;
s0 = peg$FAILED;
}
}
else {
peg$currPos = s0;
s0 = peg$FAILED;
}
}
else {
peg$currPos = s0;
s0 = peg$FAILED;
}
if (s0 === peg$FAILED) {
s0 = peg$parsebound_segment();
}
return s0;
}
function peg$parsebound_segment() {
var s0, s1;
s0 = peg$currPos;
s1 = peg$parsebound_terminal();
if (s1 === peg$FAILED) {
s1 = peg$parsevariable();
}
if (s1 !== peg$FAILED) {
peg$savedPos = s0;
s1 = peg$c4(s1);
}
s0 = s1;
return s0;
}
function peg$parsevariable() {
var s0, s1, s2, s3, s4, s5;
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 123) {
s1 = peg$c5;
peg$currPos++;
}
else {
s1 = peg$FAILED;
if (peg$silentFails === 0) {
peg$fail(peg$c6);
}
}
if (s1 !== peg$FAILED) {
s2 = peg$parseliteral();
if (s2 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 61) {
s3 = peg$c7;
peg$currPos++;
}
else {
s3 = peg$FAILED;
if (peg$silentFails === 0) {
peg$fail(peg$c8);
}
}
if (s3 !== peg$FAILED) {
s4 = peg$parseunbound_segments();
if (s4 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 125) {
s5 = peg$c9;
peg$currPos++;
}
else {
s5 = peg$FAILED;
if (peg$silentFails === 0) {
peg$fail(peg$c10);
}
}
if (s5 !== peg$FAILED) {
peg$savedPos = s0;
s1 = peg$c11(s2, s4);
s0 = s1;
}
else {
peg$currPos = s0;
s0 = peg$FAILED;
}
}
else {
peg$currPos = s0;
s0 = peg$FAILED;
}
}
else {
peg$currPos = s0;
s0 = peg$FAILED;
}
}
else {
peg$currPos = s0;
s0 = peg$FAILED;
}
}
else {
peg$currPos = s0;
s0 = peg$FAILED;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 123) {
s1 = peg$c5;
peg$currPos++;
}
else {
s1 = peg$FAILED;
if (peg$silentFails === 0) {
peg$fail(peg$c6);
}
}
if (s1 !== peg$FAILED) {
s2 = peg$parseliteral();
if (s2 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 125) {
s3 = peg$c9;
peg$currPos++;
}
else {
s3 = peg$FAILED;
if (peg$silentFails === 0) {
peg$fail(peg$c10);
}
}
if (s3 !== peg$FAILED) {
peg$savedPos = s0;
s1 = peg$c12(s2);
s0 = s1;
}
else {
peg$currPos = s0;
s0 = peg$FAILED;
}
}
else {
peg$currPos = s0;
s0 = peg$FAILED;
}
}
else {
peg$currPos = s0;
s0 = peg$FAILED;
}
}
return s0;
}
function peg$parseunbound_segments() {
var s0, s1, s2, s3;
s0 = peg$currPos;
s1 = peg$parseunbound_terminal();
if (s1 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 47) {
s2 = peg$c0;
peg$currPos++;
}
else {
s2 = peg$FAILED;
if (peg$silentFails === 0) {
peg$fail(peg$c1);
}
}
if (s2 !== peg$FAILED) {
s3 = peg$parseunbound_segments();
if (s3 !== peg$FAILED) {
peg$savedPos = s0;
s1 = peg$c13(s1, s3);
s0 = s1;
}
else {
peg$currPos = s0;
s0 = peg$FAILED;
}
}
else {
peg$currPos = s0;
s0 = peg$FAILED;
}
}
else {
peg$currPos = s0;
s0 = peg$FAILED;
}
if (s0 === peg$FAILED) {
s0 = peg$parseunbound_terminal();
}
return s0;
}
function peg$parsebound_terminal() {
var s0, s1;
s0 = peg$currPos;
s1 = peg$parseunbound_terminal();
if (s1 !== peg$FAILED) {
peg$savedPos = s0;
s1 = peg$c14(s1);
}
s0 = s1;
return s0;
}
function peg$parseunbound_terminal() {
var s0, s1;
s0 = peg$currPos;
if (input.substr(peg$currPos, 2) === peg$c15) {
s1 = peg$c15;
peg$currPos += 2;
}
else {
s1 = peg$FAILED;
if (peg$silentFails === 0) {
peg$fail(peg$c16);
}
}
if (s1 === peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 42) {
s1 = peg$c17;
peg$currPos++;
}
else {
s1 = peg$FAILED;
if (peg$silentFails === 0) {
peg$fail(peg$c18);
}
}
if (s1 === peg$FAILED) {
s1 = peg$parseliteral();
}
}
if (s1 !== peg$FAILED) {
peg$savedPos = s0;
s1 = peg$c19(s1);
}
s0 = s1;
return s0;
}
function peg$parseliteral() {
var s0, s1, s2;
s0 = peg$currPos;
s1 = [];
if (peg$c20.test(input.charAt(peg$currPos))) {
s2 = input.charAt(peg$currPos);
peg$currPos++;
}
else {
s2 = peg$FAILED;
if (peg$silentFails === 0) {
peg$fail(peg$c21);
}
}
if (s2 !== peg$FAILED) {
while (s2 !== peg$FAILED) {
s1.push(s2);
if (peg$c20.test(input.charAt(peg$currPos))) {
s2 = input.charAt(peg$currPos);
peg$currPos++;
}
else {
s2 = peg$FAILED;
if (peg$silentFails === 0) {
peg$fail(peg$c21);
}
}
}
}
else {
s1 = peg$FAILED;
}
if (s1 !== peg$FAILED) {
peg$savedPos = s0;
s1 = peg$c22(s1);
}
s0 = s1;
return s0;
}
var _ = require('lodash');
var util = require('util');
var extras = require('./parser_extras');
peg$result = peg$startRuleFunction();
if (peg$result !== peg$FAILED && peg$currPos === input.length) {
return peg$result;
}
else {
if (peg$result !== peg$FAILED && peg$currPos < input.length) {
peg$fail({ type: 'end', description: 'end of input' });
}
throw peg$buildException(null, peg$maxFailExpected, peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null, peg$maxFailPos < input.length ?
peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1) :
peg$computeLocation(peg$maxFailPos, peg$maxFailPos));
}
}
return {
SyntaxError: peg$SyntaxError,
parse: peg$parse,
};
})();
//# sourceMappingURL=path_template_parser.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,9 @@
/**
* Constructs the routing header from the given params
*
* @param {Object} params - the request header parameters.
* @return {string} the routing header value.
*/
export declare function fromParams(params: {
[index: string]: {};
}): string;

View File

@@ -0,0 +1,51 @@
/*
* Copyright 2017, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Helpers for constructing routing headers.
*
* These headers are used by Google infrastructure to determine how to route
* requests, especially for services that are regional.
*
* Generally, these headers are specified as gRPC metadata.
*/
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Constructs the routing header from the given params
*
* @param {Object} params - the request header parameters.
* @return {string} the routing header value.
*/
function fromParams(params) {
return Object.keys(params).map(function (key) { return key + "=" + params[key]; }).join('&');
}
exports.fromParams = fromParams;
//# sourceMappingURL=routing_header.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"routing_header.js","sourceRoot":"","sources":["../../src/routing_header.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH;;;;;;;GAOG;AAEH,YAAY,CAAC;;AAEb;;;;;GAKG;AACH,SAAgB,UAAU,CAAC,MAA6B;IACtD,OAAO,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,UAAA,GAAG,IAAI,OAAG,GAAG,SAAI,MAAM,CAAC,GAAG,CAAG,EAAvB,CAAuB,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAC3E,CAAC;AAFD,gCAEC"}

View File

@@ -0,0 +1,72 @@
/// <reference types="node" />
import * as Duplexify from 'duplexify';
import { Stream, Duplex } from 'stream';
import { APICallback, APICall } from './api_callable';
/**
* The type of gRPC streaming.
* @enum {number}
*/
export declare enum StreamType {
/** Client sends a single request, server streams responses. */
SERVER_STREAMING = 1,
/** Client streams requests, server returns a single response. */
CLIENT_STREAMING = 2,
/** Both client and server stream objects. */
BIDI_STREAMING = 3
}
export declare class StreamProxy extends Duplexify {
type: {};
private _callback?;
private _isCancelCalled;
stream?: Duplex & {
cancel: () => void;
};
/**
* StreamProxy is a proxy to gRPC-streaming method.
*
* @private
* @constructor
* @param {StreamType} type - the type of gRPC stream.
* @param {ApiCallback} callback - the callback for further API call.
*/
constructor(type: StreamType, callback: APICallback);
cancel(): void;
/**
* Forward events from an API request stream to the user's stream.
* @param {Stream} stream - The API request stream.
*/
forwardEvents(stream: Stream): void;
/**
* Specifies the target stream.
* @param {ApiCall} apiCall - the API function to be called.
* @param {Object} argument - the argument to be passed to the apiCall.
*/
setStream(apiCall: APICall, argument: {}): void;
}
export declare class GrpcStreamable {
descriptor: StreamDescriptor;
/**
* An API caller for methods of gRPC streaming.
* @private
* @constructor
* @param {StreamDescriptor} descriptor - the descriptor of the method structure.
*/
constructor(descriptor: StreamDescriptor);
init(settings: {}, callback: APICallback): StreamProxy;
wrap(func: Function): Function;
call(apiCall: APICall, argument: {}, settings: {}, stream: StreamProxy): void;
fail(stream: Stream, err: Error): void;
result(stream: Stream): Stream;
}
export declare class StreamDescriptor {
type: StreamType;
/**
* Describes the structure of gRPC streaming call.
* @constructor
* @param {StreamType} streamType - the type of streaming.
*/
constructor(streamType: StreamType);
apiCaller(settings: {
retry: null;
}): GrpcStreamable;
}

View File

@@ -0,0 +1,225 @@
/**
* Copyright 2016, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
'use strict';
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
}
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
/* This file describes the gRPC-streaming. */
var Duplexify = require("duplexify");
var retryRequest = require('retry-request');
/**
* The type of gRPC streaming.
* @enum {number}
*/
var StreamType;
(function (StreamType) {
/** Client sends a single request, server streams responses. */
StreamType[StreamType["SERVER_STREAMING"] = 1] = "SERVER_STREAMING";
/** Client streams requests, server returns a single response. */
StreamType[StreamType["CLIENT_STREAMING"] = 2] = "CLIENT_STREAMING";
/** Both client and server stream objects. */
StreamType[StreamType["BIDI_STREAMING"] = 3] = "BIDI_STREAMING";
})(StreamType = exports.StreamType || (exports.StreamType = {}));
var StreamProxy = /** @class */ (function (_super) {
__extends(StreamProxy, _super);
/**
* StreamProxy is a proxy to gRPC-streaming method.
*
* @private
* @constructor
* @param {StreamType} type - the type of gRPC stream.
* @param {ApiCallback} callback - the callback for further API call.
*/
function StreamProxy(type, callback) {
var _this = _super.call(this, undefined, undefined, {
objectMode: true,
readable: type !== StreamType.CLIENT_STREAMING,
writable: type !== StreamType.SERVER_STREAMING,
}) || this;
_this.type = type;
_this._callback = callback;
_this._isCancelCalled = false;
return _this;
}
StreamProxy.prototype.cancel = function () {
if (this.stream) {
this.stream.cancel();
}
else {
this._isCancelCalled = true;
}
};
/**
* Forward events from an API request stream to the user's stream.
* @param {Stream} stream - The API request stream.
*/
StreamProxy.prototype.forwardEvents = function (stream) {
var _this = this;
var eventsToForward = ['metadata', 'response', 'status'];
eventsToForward.forEach(function (event) {
stream.on(event, _this.emit.bind(_this, event));
});
// We also want to supply the status data as 'response' event to support
// the behavior of google-cloud-node expects.
// see:
// https://github.com/GoogleCloudPlatform/google-cloud-node/pull/1775#issuecomment-259141029
// https://github.com/GoogleCloudPlatform/google-cloud-node/blob/116436fa789d8b0f7fc5100b19b424e3ec63e6bf/packages/common/src/grpc-service.js#L355
stream.on('metadata', function (metadata) {
// Create a response object with succeeds.
// TODO: unify this logic with the decoration of gRPC response when it's
// added. see: https://github.com/googleapis/gax-nodejs/issues/65
stream.emit('response', {
code: 200,
details: '',
message: 'OK',
metadata: metadata,
});
});
};
/**
* Specifies the target stream.
* @param {ApiCall} apiCall - the API function to be called.
* @param {Object} argument - the argument to be passed to the apiCall.
*/
StreamProxy.prototype.setStream = function (apiCall, argument) {
var _this = this;
if (this.type === StreamType.SERVER_STREAMING) {
var retryStream = retryRequest(null, {
objectMode: true,
request: function () {
if (_this._isCancelCalled) {
if (_this.stream) {
_this.stream.cancel();
}
return;
}
var stream = apiCall(argument, _this._callback);
_this.stream = stream;
_this.forwardEvents(stream);
return stream;
},
});
this.setReadable(retryStream);
return;
}
var stream = apiCall(argument, this._callback);
this.stream = stream;
this.forwardEvents(stream);
if (this.type === StreamType.CLIENT_STREAMING) {
this.setWritable(stream);
}
if (this.type === StreamType.BIDI_STREAMING) {
this.setReadable(stream);
this.setWritable(stream);
}
if (this._isCancelCalled && this.stream) {
this.stream.cancel();
}
};
return StreamProxy;
}(Duplexify));
exports.StreamProxy = StreamProxy;
var GrpcStreamable = /** @class */ (function () {
/**
* An API caller for methods of gRPC streaming.
* @private
* @constructor
* @param {StreamDescriptor} descriptor - the descriptor of the method structure.
*/
function GrpcStreamable(descriptor) {
this.descriptor = descriptor;
}
GrpcStreamable.prototype.init = function (settings, callback) {
return new StreamProxy(this.descriptor.type, callback);
};
GrpcStreamable.prototype.wrap = function (func) {
switch (this.descriptor.type) {
case StreamType.SERVER_STREAMING:
return function (argument, metadata, options) {
return func(argument, metadata, options);
};
case StreamType.CLIENT_STREAMING:
return function (argument, metadata, options, callback) {
return func(metadata, options, callback);
};
case StreamType.BIDI_STREAMING:
return function (argument, metadata, options) {
return func(metadata, options);
};
default:
console.error('Unknown stream type', this.descriptor.type);
}
return func;
};
GrpcStreamable.prototype.call = function (apiCall, argument, settings, stream) {
stream.setStream(apiCall, argument);
};
GrpcStreamable.prototype.fail = function (stream, err) {
stream.emit('error', err);
};
GrpcStreamable.prototype.result = function (stream) {
return stream;
};
return GrpcStreamable;
}());
exports.GrpcStreamable = GrpcStreamable;
var StreamDescriptor = /** @class */ (function () {
/**
* Describes the structure of gRPC streaming call.
* @constructor
* @param {StreamType} streamType - the type of streaming.
*/
function StreamDescriptor(streamType) {
this.type = streamType;
}
StreamDescriptor.prototype.apiCaller = function (settings) {
// Right now retrying does not work with gRPC-streaming, because retryable
// assumes an API call returns an event emitter while gRPC-streaming methods
// return Stream.
// TODO: support retrying.
settings.retry = null;
return new GrpcStreamable(this);
};
return StreamDescriptor;
}());
exports.StreamDescriptor = StreamDescriptor;
//# sourceMappingURL=streaming.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"streaming.js","sourceRoot":"","sources":["../../src/streaming.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,YAAY,CAAC;;;;;;;;;;;;;;;AAEb,6CAA6C;AAE7C,qCAAuC;AAIvC,IAAM,YAAY,GAAG,OAAO,CAAC,eAAe,CAAC,CAAC;AAE9C;;;GAGG;AACH,IAAY,UASX;AATD,WAAY,UAAU;IACpB,+DAA+D;IAC/D,mEAAoB,CAAA;IAEpB,iEAAiE;IACjE,mEAAoB,CAAA;IAEpB,6CAA6C;IAC7C,+DAAkB,CAAA;AACpB,CAAC,EATW,UAAU,GAAV,kBAAU,KAAV,kBAAU,QASrB;AAED;IAAiC,+BAAS;IAKxC;;;;;;;OAOG;IACH,qBAAY,IAAgB,EAAE,QAAqB;QAAnD,YACE,kBAAM,SAAS,EAA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