Firebase Update

This commit is contained in:
Lukas Nowy
2018-12-22 23:30:39 +01:00
parent befb44764d
commit acffe619b3
11523 changed files with 1614327 additions and 930246 deletions

View File

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

View File

@ -0,0 +1,36 @@
"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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
class GoogleError extends 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,MAAa,WAAY,SAAQ,KAAK;CAGrC;AAHD,kCAGC"}

View File

@ -0,0 +1,121 @@
/**
* Provides function wrappers that implement page streaming and retrying.
*/
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,321 @@
"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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
class Canceller {
/**
* 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) {
this.callback = callback;
this.completed = false;
}
/**
* Cancels the ongoing promise.
*/
cancel() {
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.
*/
call(aFunc, argument) {
if (this.completed) {
return;
}
// tslint:disable-next-line no-any
const canceller = aFunc(argument, (...args) => {
this.completed = true;
args.unshift(this.callback);
setImmediate.apply(null, args);
});
this.cancelFunc = () => {
canceller.cancel();
};
}
}
exports.Canceller = Canceller;
// tslint:disable-next-line no-any
class PromiseCanceller extends Canceller {
/**
* 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
constructor(PromiseCtor) {
super();
this.promise = new PromiseCtor((resolve, reject) => {
this.callback = (err, response, next, rawResponse) => {
if (err) {
reject(err);
}
else {
resolve([response, next, rawResponse]);
}
};
});
this.promise.cancel = () => {
this.cancel();
};
}
}
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) {
const now = new Date();
const options = otherArgs.options || {};
options.deadline = new Date(now.getTime() + timeout);
const 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) {
const delayMult = retry.backoffSettings.retryDelayMultiplier;
const maxDelay = retry.backoffSettings.maxRetryDelayMillis;
const timeoutMult = retry.backoffSettings.rpcTimeoutMultiplier;
const maxTimeout = retry.backoffSettings.maxRpcTimeoutMillis;
let delay = retry.backoffSettings.initialRetryDelayMillis;
let 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) {
let canceller;
let timeoutId;
let now = new Date();
let deadline;
if (retry.backoffSettings.totalTimeoutMillis) {
deadline = now.getTime() + retry.backoffSettings.totalTimeoutMillis;
}
let retries = 0;
const 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++;
const toCall = addTimeoutArg(aFunc, timeout, otherArgs);
canceller = toCall(argument, (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 {
const toSleep = Math.random() * delay;
timeoutId = setTimeout(() => {
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() {
if (timeoutId) {
clearTimeout(timeoutId);
}
if (canceller) {
canceller.cancel();
}
else {
callback(new Error('cancelled'));
}
},
};
};
}
/**
* Creates an API caller for normal methods.
*
* @private
* @constructor
*/
class NormalApiCaller {
init(settings, callback) {
if (callback) {
return new Canceller(callback);
}
return new PromiseCanceller(settings.promise);
}
wrap(func) {
return func;
}
call(apiCall, argument, settings, canceller) {
canceller.call(apiCall, argument);
}
fail(canceller, err) {
canceller.callback(err);
}
result(canceller) {
if (canceller.promise) {
return canceller.promise;
}
return;
}
}
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) {
const apiCaller = optDescriptor ? optDescriptor.apiCaller(settings) : new NormalApiCaller();
return function apiCallInner(request, callOptions, callback) {
const thisSettings = settings.merge(callOptions);
const status = apiCaller.init(thisSettings, callback);
funcWithAuth
.then(func => {
func = apiCaller.wrap(func);
const 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(apiCall => {
apiCaller.call(apiCall, request, thisSettings, status);
})
.catch(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 @@
"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.
*
*/
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((resolve, reject) => {
getCredentials((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;;AAIH;;;;;;;;;;;;GAYG;AAEH;;;;;;;;GAQG;AACH,SAAgB,iBAAiB,CAC7B,cAAkC,EAAE,IAAS;IAC/C,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACrC,cAAc,CAAC,CAAC,GAAG,EAAE,WAAW,EAAE,EAAE;YAClC,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,501 @@
"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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Provides behavior that supports request bundling.
*/
const at = require("lodash.at");
const 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) {
const ids = [];
let hasIds = false;
for (let i = 0; i < discriminatorFields.length; ++i) {
const 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
let result;
if (obj === null) {
return null;
}
if (obj === undefined) {
return undefined;
}
if (Array.isArray(obj)) {
result = [];
obj.forEach(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(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;
class Task {
/**
* 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, 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.
*/
getElementCount() {
let count = 0;
for (let 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.
*/
getRequestByteSize() {
let size = 0;
for (let 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.
*/
run() {
if (this._data.length === 0) {
return [];
}
const request = this._request;
const elements = [];
const ids = [];
for (let 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;
const self = this;
this.callCanceller =
this._apiCall(request, (err, response) => {
const responses = [];
if (err) {
self._data.forEach(() => {
responses.push(null);
});
}
else {
let subresponseInfo = null;
if (self._subresponseField) {
subresponseInfo = {
field: self._subresponseField,
start: 0,
};
}
self._data.forEach(data => {
if (subresponseInfo) {
subresponseInfo.end =
subresponseInfo.start + data.elements.length;
}
responses.push(deepCopyForResponse(response, subresponseInfo));
if (subresponseInfo) {
subresponseInfo.start = subresponseInfo.end;
}
});
}
for (let 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.
*/
extend(elements, bytes, callback) {
this._data.push({
elements,
bytes,
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.
*/
cancel(id) {
if (this.callCanceller) {
let allCancelled = true;
this._data.forEach(d => {
if (d.callback.id === id) {
d.cancelled = true;
}
if (!d.cancelled) {
allCancelled = false;
}
});
if (allCancelled) {
this.callCanceller.cancel();
}
return allCancelled;
}
for (let 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;
}
}
exports.Task = Task;
class BundleExecutor {
/**
* 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, 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.
*/
schedule(apiCall, request, callback) {
const 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);
}
let task = this._tasks[bundleId];
callback.id = String(this._invocationId++);
this._invocations[callback.id] = bundleId;
const bundledField = request[this._descriptor.bundledField];
const elementCount = bundledField.length;
let requestBytes = 0;
const self = this;
bundledField.forEach(obj => {
requestBytes += this._descriptor.byteLengthFunction(obj);
});
const countLimit = this._options.elementCountLimit || 0;
const byteLimit = this._options.requestByteLimit || 0;
if ((countLimit > 0 && elementCount >= countLimit) ||
(byteLimit > 0 && requestBytes >= byteLimit)) {
let message;
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,
};
}
const existingCount = task.getElementCount();
const 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);
const ret = {
cancel() {
self._cancel(callback.id);
},
};
const countThreshold = this._options.elementCountThreshold || 0;
const 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(() => {
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
*/
_maybeClearTimeout(bundleId) {
if (bundleId in this._timers) {
const 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
*/
_cancel(id) {
if (!(id in this._invocations)) {
return;
}
const bundleId = this._invocations[id];
if (!(bundleId in this._tasks)) {
return;
}
const 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
*/
_runNow(bundleId) {
if (!(bundleId in this._tasks)) {
console.warn('no such bundleid: ' + bundleId);
return;
}
this._maybeClearTimeout(bundleId);
const task = this._tasks[bundleId];
delete this._tasks[bundleId];
task.run().forEach(id => {
delete this._invocations[id];
});
}
}
exports.BundleExecutor = BundleExecutor;
class Bundleable extends api_callable_1.NormalApiCaller {
/**
* Creates an API caller that bundles requests.
*
* @private
* @constructor
* @param {BundleExecutor} bundler - bundles API calls.
*/
constructor(bundler) {
super();
this.bundler = bundler;
}
// tslint:disable-next-line no-any
call(apiCall, argument, settings, status) {
if (settings.isBundling) {
status.call((argument, callback) => {
this.bundler.schedule(apiCall, argument, callback);
}, argument);
}
else {
api_callable_1.NormalApiCaller.prototype.call.call(this, apiCall, argument, settings, status);
}
}
}
exports.Bundleable = Bundleable;
class BundleDescriptor {
/**
* 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, 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.
*/
apiCaller(settings) {
return new Bundleable(new BundleExecutor(settings.bundleOptions, this));
}
}
exports.BundleDescriptor = BundleDescriptor;
//# sourceMappingURL=bundling.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,394 @@
/**
* 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
*/
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;

503
express-server/node_modules/google-gax/build/src/gax.js generated vendored Normal file
View File

@ -0,0 +1,503 @@
"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.
*/
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
*/
class RetryOptions {
constructor(retryCodes, backoffSettings) {
this.retryCodes = retryCodes;
this.backoffSettings = backoffSettings;
}
}
exports.RetryOptions = RetryOptions;
class CallSettings {
/**
* @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) {
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.
*/
merge(options) {
if (!options) {
return new CallSettings(this);
}
let timeout = this.timeout;
let retry = this.retry;
let autoPaginate = this.autoPaginate;
let pageToken = this.pageToken;
let maxResults = this.maxResults;
let otherArgs = this.otherArgs;
let isBundling = this.isBundling;
let longrunning = this.longrunning;
let 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 (const key in this.otherArgs) {
otherArgs[key] = this.otherArgs[key];
}
// tslint:disable-next-line forin
for (const 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,
retry,
bundleOptions: this.bundleOptions,
longrunning,
autoPaginate,
pageToken,
maxResults,
otherArgs,
isBundling,
promise,
});
}
}
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,
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,
retryDelayMultiplier,
maxRetryDelayMillis,
initialRpcTimeoutMillis,
rpcTimeoutMultiplier,
maxRpcTimeoutMillis,
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,
retryDelayMultiplier,
maxRetryDelayMillis,
initialRpcTimeoutMillis,
rpcTimeoutMultiplier,
maxRpcTimeoutMillis,
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) {
const params = [
'element_count_threshold',
'element_count_limit',
'request_byte_threshold',
'request_byte_limit',
'delay_threshold_millis',
];
params.forEach(param => {
if (param in options && typeof options[param] !== 'number') {
throw new Error(`${param} should be a number`);
}
});
const elementCountThreshold = options.element_count_threshold || 0;
const elementCountLimit = options.element_count_limit || 0;
const requestByteThreshold = options.request_byte_threshold || 0;
const requestByteLimit = options.request_byte_limit || 0;
const delayThreshold = options.delay_threshold_millis || 0;
if (elementCountThreshold === 0 && requestByteThreshold === 0 &&
delayThreshold === 0) {
throw new Error('one threshold should be > 0');
}
return {
elementCountThreshold,
elementCountLimit,
requestByteThreshold,
requestByteLimit,
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;
}
let codes = null;
if (retryCodes && 'retry_codes_name' in methodConfig) {
const retryCodesName = methodConfig['retry_codes_name'];
codes = (retryCodes[retryCodesName] || []).map(name => {
return Number(retryNames[name]);
});
}
let backoffSettings = null;
if (retryParams && 'retry_params_name' in methodConfig) {
const 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;
}
let codes = retry.retryCodes;
if (overrides.retryCodes) {
codes = overrides.retryCodes;
}
let 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
const defaults = {};
const serviceConfig = (clientConfig.interfaces || {})[serviceName];
if (!serviceConfig) {
return null;
}
const overrides = (configOverrides.interfaces || {})[serviceName] || {};
const methods = serviceConfig.methods;
const overridingMethods = overrides.methods || {};
// tslint:disable-next-line forin
for (const methodName in methods) {
const methodConfig = methods[methodName];
const jsName = methodName[0].toLowerCase() + methodName.slice(1);
let retry = constructRetry(methodConfig, serviceConfig.retry_codes, serviceConfig.retry_params, retryNames);
let bundlingConfig = methodConfig.bundling;
let timeout = methodConfig.timeout_millis;
if (methodName in overridingMethods) {
const 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,
retry,
bundleOptions: bundlingConfig ? createBundleOptions(bundlingConfig) :
null,
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,133 @@
/// <reference types="node" />
import * as grpcProtoLoaderTypes from '@grpc/proto-loader';
import { GoogleAuth, GoogleAuthOptions } from 'google-auth-library';
import * as grpcTypes from 'grpc';
import { OutgoingHttpHeaders } from 'http';
import * as protobuf from 'protobufjs';
import * as gax from './gax';
export { GrpcObject } from 'grpc';
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 ClientStubOptions {
servicePath: string;
port: number;
sslCreds: grpcTypes.ChannelCredentials;
}
export declare class ClientStub extends grpcTypes.Client {
[name: string]: Function;
}
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: ClientStubOptions): Promise<grpcTypes.ChannelCredentials>;
/**
* 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 service from a filename hooking in googleapis common protos
* when necessary.
* @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: typeof ClientStub, options: ClientStubOptions): Promise<ClientStub>;
/**
* 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,308 @@
"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 __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());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const grpcProtoLoaderTypes = require("@grpc/proto-loader"); // for types only
const fs = require("fs");
const google_auth_library_1 = require("google-auth-library");
const google_proto_files_1 = require("google-proto-files");
const grpcTypes = require("grpc"); // for types only
const path = require("path");
const protobuf = require("protobufjs");
const semver = require("semver");
const walk = require("walkdir");
const gax = require("./gax");
const googleProtoFilesDir = path.normalize(google_proto_files_1.getProtoPath('..'));
// INCLUDE_DIRS is passed to @grpc/proto-loader
const INCLUDE_DIRS = [];
INCLUDE_DIRS.push(googleProtoFilesDir);
// COMMON_PROTO_FILES logic is here for protobufjs loads (see
// GoogleProtoFilesRoot below)
const 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',
].map(dir => path.join(googleProtoFilesDir, 'google', dir));
const COMMON_PROTO_FILES = COMMON_PROTO_DIRS
.map(dir => {
return walk.sync(dir)
.filter(f => path.extname(f) === '.proto')
.map(f => path.normalize(f).substring(googleProtoFilesDir.length + 1));
})
.reduce((a, c) => a.concat(c), []);
class ClientStub extends grpcTypes.Client {
}
exports.ClientStub = ClientStub;
class GrpcClient {
/**
* 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 = {}) {
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 {
// EXPERIMENTAL: If GOOGLE_CLOUD_USE_GRPC_JS is set, use the JS-based
// implementation of the gRPC client instead. Requires http2 (Node 8+).
if (semver.satisfies(process.version, '8.x') &&
process.env.GOOGLE_CLOUD_USE_GRPC_JS) {
this.grpc = require('@grpc/grpc-js');
this.grpcVersion = require('@grpc/grpc-js/package.json').version;
}
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.
*/
_getCredentials(opts) {
return __awaiter(this, void 0, void 0, function* () {
if (opts.sslCreds) {
return opts.sslCreds;
}
const grpc = this.grpc;
const sslCreds = grpc.credentials.createSsl();
const client = yield this.auth.getClient();
const credentials = grpc.credentials.combineChannelCredentials(sslCreds, grpc.credentials.createFromGoogleCredential(client));
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.
*/
loadFromProto(filename, options) {
const packageDef = grpcProtoLoaderTypes.loadSync(filename, options);
return this.grpc.loadPackageDefinition(packageDef);
}
/**
* Load grpc proto service from a filename hooking in googleapis common protos
* when necessary.
* @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, filename) {
const resolvedPath = GrpcClient._resolveFile(protoPath, filename);
const retval = this.grpc.loadObject(protobuf.loadSync(resolvedPath, new GoogleProtoFilesRoot()));
return retval;
}
static _resolveFile(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);
}
metadataBuilder(headers) {
const Metadata = this.grpc.Metadata;
const baseMetadata = new Metadata();
// tslint:disable-next-line forin
for (const key in headers) {
const value = headers[key];
if (Array.isArray(value)) {
value.forEach(v => baseMetadata.add(key, v));
}
else {
baseMetadata.set(key, `${value}`);
}
}
return function buildMetadata(abTests, moreHeaders) {
// TODO: bring the A/B testing info into the metadata.
let copied = false;
let metadata = baseMetadata;
if (moreHeaders) {
for (const key in moreHeaders) {
if (key.toLowerCase() !== 'x-goog-api-client' &&
moreHeaders.hasOwnProperty(key)) {
if (!copied) {
copied = true;
metadata = metadata.clone();
}
const value = moreHeaders[key];
if (Array.isArray(value)) {
value.forEach(v => metadata.add(key, v));
}
else {
metadata.set(key, `${value}`);
}
}
}
}
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.
*/
constructSettings(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
createStub(CreateStub, options) {
const serviceAddress = options.servicePath + ':' + options.port;
return this._getCredentials(options).then(credentials => {
const grpcOptions = {};
Object.keys(options).forEach(key => {
if (key.indexOf('grpc.') === 0) {
grpcOptions[key] = options[key];
}
else if (key.indexOf('grpc_gcp.') === 0) {
// This prefix is used to pass additional arguments that aren't
// options for grpc. Strip the prefix before passing.
const prefixLength = 'grpc_gcp.'.length;
grpcOptions[key.substr(prefixLength)] = 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.
*/
static createByteLengthFunction(message) {
return function getByteLength(obj) {
return message.encode(obj).finish().length;
};
}
}
exports.GrpcClient = GrpcClient;
class GoogleProtoFilesRoot extends protobuf.Root {
constructor(...args) {
super(...args);
}
// 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.
resolvePath(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);
}
static _findIncludePath(originPath, includePath) {
originPath = path.normalize(originPath);
includePath = path.normalize(includePath);
let current = originPath;
let 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);
}
}
exports.GoogleProtoFilesRoot = GoogleProtoFilesRoot;
//# sourceMappingURL=grpc.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,52 @@
/**
* 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 { GrpcClient, GrpcClientOptions } from './grpc';
import * as operationsClient from './operations_client';
import * as routingHeader from './routing_header';
export { GoogleAuth, GoogleAuthOptions } from 'google-auth-library';
export { createApiCall } from './api_callable';
export { BundleDescriptor, BundleExecutor } from './bundling';
export { CallOptions, ClientConfig, constructSettings } from './gax';
export { GoogleError } from './GoogleError';
export { ClientStub, ClientStubOptions, GoogleProtoFilesRoot, GrpcClient, GrpcClientOptions, GrpcModule, GrpcObject, Metadata, MetadataValue } from './grpc';
export { LongrunningDescriptor, operation } from './longrunning';
export { PageDescriptor } from './paged_iteration';
export { PathTemplate } from './path_template';
export { StreamDescriptor, StreamType } from './streaming';
export { routingHeader };
declare function lro(options: GrpcClientOptions): operationsClient.OperationsClientBuilder;
declare namespace lro {
var SERVICE_ADDRESS: string;
var ALL_SCOPES: string[];
}
export { lro };
export declare const createByteLengthFunction: typeof GrpcClient.createByteLengthFunction;
export declare const version: any;

View File

@ -0,0 +1,72 @@
"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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const grpc_1 = require("./grpc");
const operationsClient = require("./operations_client");
const routingHeader = require("./routing_header");
exports.routingHeader = routingHeader;
var google_auth_library_1 = require("google-auth-library");
exports.GoogleAuth = google_auth_library_1.GoogleAuth;
var api_callable_1 = require("./api_callable");
exports.createApiCall = api_callable_1.createApiCall;
var bundling_1 = require("./bundling");
exports.BundleDescriptor = bundling_1.BundleDescriptor;
exports.BundleExecutor = bundling_1.BundleExecutor;
var gax_1 = require("./gax");
exports.constructSettings = gax_1.constructSettings;
var GoogleError_1 = require("./GoogleError");
exports.GoogleError = GoogleError_1.GoogleError;
var grpc_2 = require("./grpc");
exports.ClientStub = grpc_2.ClientStub;
exports.GoogleProtoFilesRoot = grpc_2.GoogleProtoFilesRoot;
exports.GrpcClient = grpc_2.GrpcClient;
var longrunning_1 = require("./longrunning");
exports.LongrunningDescriptor = longrunning_1.LongrunningDescriptor;
exports.operation = longrunning_1.operation;
var paged_iteration_1 = require("./paged_iteration");
exports.PageDescriptor = paged_iteration_1.PageDescriptor;
var path_template_1 = require("./path_template");
exports.PathTemplate = path_template_1.PathTemplate;
var streaming_1 = require("./streaming");
exports.StreamDescriptor = streaming_1.StreamDescriptor;
exports.StreamType = streaming_1.StreamType;
function lro(options) {
options = Object.assign({ scopes: lro.ALL_SCOPES }, options);
const gaxGrpc = new grpc_1.GrpcClient(options);
return new operationsClient.OperationsClientBuilder(gaxGrpc);
}
exports.lro = lro;
lro.SERVICE_ADDRESS = operationsClient.SERVICE_ADDRESS;
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,iCAAqD;AACrD,wDAAwD;AACxD,kDAAkD;AAY1C,sCAAa;AAVrB,2DAAkE;AAA1D,2CAAA,UAAU,CAAA;AAClB,+CAA6C;AAArC,uCAAA,aAAa,CAAA;AACrB,uCAA4D;AAApD,sCAAA,gBAAgB,CAAA;AAAE,oCAAA,cAAc,CAAA;AACxC,6BAAmE;AAAhC,kCAAA,iBAAiB,CAAA;AACpD,6CAA0C;AAAlC,oCAAA,WAAW,CAAA;AACnB,+BAA2J;AAAnJ,4BAAA,UAAU,CAAA;AAAqB,sCAAA,oBAAoB,CAAA;AAAE,4BAAA,UAAU,CAAA;AACvE,6CAA+D;AAAvD,8CAAA,qBAAqB,CAAA;AAAE,kCAAA,SAAS,CAAA;AACxC,qDAAiD;AAAzC,2CAAA,cAAc,CAAA;AACtB,iDAA6C;AAArC,uCAAA,YAAY,CAAA;AACpB,yCAAyD;AAAjD,uCAAA,gBAAgB,CAAA;AAAE,iCAAA,UAAU,CAAA;AAGpC,SAAS,GAAG,CAAC,OAA0B;IACrC,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,EAAC,MAAM,EAAE,GAAG,CAAC,UAAU,EAAC,EAAE,OAAO,CAAC,CAAC;IAC3D,MAAM,OAAO,GAAG,IAAI,iBAAU,CAAC,OAAO,CAAC,CAAC;IACxC,OAAO,IAAI,gBAAgB,CAAC,uBAAuB,CAAC,OAAO,CAAC,CAAC;AAC/D,CAAC;AAKO,kBAAG;AAHX,GAAG,CAAC,eAAe,GAAG,gBAAgB,CAAC,eAAe,CAAC;AACvD,GAAG,CAAC,UAAU,GAAG,gBAAgB,CAAC,UAAU,CAAC;AAGhC,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,325 @@
"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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const events_1 = require("events");
const api_callable_1 = require("./api_callable");
const gax_1 = require("./gax");
const GoogleError_1 = require("./GoogleError");
class LongrunningDescriptor {
/**
* 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, responseDecoder, metadataDecoder) {
this.operationsClient = operationsClient;
this.responseDecoder = responseDecoder;
this.metadataDecoder = metadataDecoder;
}
apiCaller() {
return new LongrunningApiCaller(this);
}
}
exports.LongrunningDescriptor = LongrunningDescriptor;
class LongrunningApiCaller extends api_callable_1.NormalApiCaller {
/**
* 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) {
super();
this.longrunningDescriptor = longrunningDescriptor;
}
call(apiCall, argument, settings, canceller) {
canceller.call((argument, callback) => {
return this._wrapOperation(apiCall, settings, argument, callback);
}, argument);
}
_wrapOperation(apiCall, settings, argument, callback) {
// TODO: this code defies all logic, and just can't be accurate.
// tslint:disable-next-line no-any
let backoffSettings = settings.longrunning;
if (!backoffSettings) {
backoffSettings =
gax_1.createBackoffSettings(100, 1.3, 60000, null, null, null, null);
}
const longrunningDescriptor = this.longrunningDescriptor;
return apiCall(argument, (err, rawResponse) => {
if (err) {
callback(err, null, rawResponse);
return;
}
const operation = new Operation(rawResponse, longrunningDescriptor, backoffSettings, settings);
callback(null, operation, rawResponse);
});
}
}
exports.LongrunningApiCaller = LongrunningApiCaller;
class Operation extends events_1.EventEmitter {
/**
* 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, longrunningDescriptor, backoffSettings, callOptions) {
super();
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;
}
/**
* 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() {
this.on('newListener', event => {
if (event === 'complete') {
this.completeListeners++;
if (!this.hasActiveListeners) {
this.hasActiveListeners = true;
this.startPolling_();
}
}
});
this.on('removeListener', 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.
*/
cancel() {
if (this.currentCallPromise_) {
this.currentCallPromise_.cancel();
}
const operationsClient = this.longrunningDescriptor.operationsClient;
return operationsClient.cancelOperation({ name: this.latestResponse.name });
}
getOperation(callback) {
const self = this;
const operationsClient = this.longrunningDescriptor.operationsClient;
function promisifyResponse() {
if (!callback) {
// tslint:disable-next-line variable-name
const PromiseCtor = self._callOptions.promise;
return new PromiseCtor((resolve, reject) => {
if (self.latestResponse.error) {
const 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);
const noCallbackPromise = this.currentCallPromise_.then(responses => {
self.latestResponse = responses[0];
self._unpackResponse(responses[0], callback);
return promisifyResponse();
});
if (!callback) {
return noCallbackPromise;
}
}
_unpackResponse(op, callback) {
const responseDecoder = this.longrunningDescriptor.responseDecoder;
const metadataDecoder = this.longrunningDescriptor.metadataDecoder;
let response;
let metadata;
if (op.done) {
if (op.result === 'error') {
const 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
*/
startPolling_() {
const self = this;
let now = new Date();
const delayMult = this.backoffSettings.retryDelayMultiplier;
const maxDelay = this.backoffSettings.maxRetryDelayMillis;
let delay = this.backoffSettings.initialRetryDelayMillis;
let deadline = Infinity;
if (this.backoffSettings.totalTimeoutMillis) {
deadline = now.getTime() + this.backoffSettings.totalTimeoutMillis;
}
let 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((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(() => {
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.
*/
promise() {
const self = this;
// tslint:disable-next-line variable-name
const PromiseCtor = this._callOptions.promise;
return new PromiseCtor((resolve, reject) => {
self.on('error', reject)
.on('complete', (result, metadata, rawResponse) => {
resolve([result, metadata, rawResponse]);
});
});
}
}
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,426 @@
"use strict";
/*
* 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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const google_proto_files_1 = require("google-proto-files");
const apiCallable = require("./api_callable");
const gax = require("./gax");
const pagedIteration = require("./paged_iteration");
const pathTemplate = require("./path_template");
const configData = require('./operations_client_config');
Object.assign(gax, apiCallable);
Object.assign(gax, pathTemplate);
Object.assign(gax, pagedIteration);
exports.SERVICE_ADDRESS = 'longrunning.googleapis.com';
const DEFAULT_SERVICE_PORT = 443;
const CODE_GEN_NAME_VERSION = 'gapic/0.7.1';
const 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
*/
class OperationsClient {
constructor(gaxGrpc, grpcClients, opts) {
opts = Object.assign({
servicePath: exports.SERVICE_ADDRESS,
port: DEFAULT_SERVICE_PORT,
clientConfig: {},
}, opts);
const 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);
const defaults = gaxGrpc.constructSettings('google.longrunning.Operations', configData, opts.clientConfig, { 'x-goog-api-client': googleApiClient.join(' ') });
const self = this;
this.auth = gaxGrpc.auth;
const operationsStub = gaxGrpc.createStub(grpcClients.google.longrunning.Operations, opts);
const operationsStubMethods = [
'getOperation',
'listOperations',
'cancelOperation',
'deleteOperation',
];
operationsStubMethods.forEach(methodName => {
self['_' + methodName] = gax['createApiCall'](operationsStub.then(operationsStub => {
return (...args) => {
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.
*/
getProjectId(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);
* });
*/
getOperation(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);
* });
*/
listOperations(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);
* });
*/
listOperationsStream(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);
* });
*/
cancelOperation(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);
* });
*/
deleteOperation(request, options, callback) {
if (options instanceof Function && callback === undefined) {
callback = options;
options = {};
}
if (options === undefined) {
options = {};
}
return this['_deleteOperation'](request, options, callback);
}
}
exports.OperationsClient = OperationsClient;
class OperationsClientBuilder {
constructor(gaxGrpc) {
const protoFilesRoot = google_proto_files_1.getProtoPath('..');
const operationsClient = gaxGrpc.loadProto(protoFilesRoot, 'google/longrunning/operations.proto');
Object.assign(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'] = opts => {
return new OperationsClient(gaxGrpc, operationsClient, opts);
};
Object.assign(this['operationsClient'], OperationsClient);
}
}
exports.OperationsClientBuilder = OperationsClientBuilder;
//# sourceMappingURL=operations_client.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"operations_client.js","sourceRoot":"","sources":["../../src/operations_client.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;;AAEH,2DAAgD;AAEhD,8CAA8C;AAC9C,6BAA6B;AAC7B,oDAAoD;AACpD,gDAAgD;AAEhD,MAAM,UAAU,GAAG,OAAO,CAAC,4BAA4B,CAAC,CAAC;AAEzD,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE,WAAW,CAAC,CAAC;AAChC,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE,YAAY,CAAC,CAAC;AACjC,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE,cAAc,CAAC,CAAC;AAEtB,QAAA,eAAe,GAAG,4BAA4B,CAAC;AAE5D,MAAM,oBAAoB,GAAG,GAAG,CAAC;AAEjC,MAAM,qBAAqB,GAAG,aAAa,CAAC;AAE5C,MAAM,gBAAgB,GAAG;IACvB,cAAc,EACV,IAAI,GAAG,CAAC,gBAAgB,CAAC,CAAC,WAAW,EAAE,eAAe,EAAE,YAAY,CAAC;CAC1E,CAAC;AAEF;;;GAGG;AACU,QAAA,UAAU,GAAa,EAAE,CAAC;AAEvC;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAa,gBAAgB;IAG3B,YAAY,OAAO,EAAE,WAAW,EAAE,IAAI;QACpC,IAAI,GAAG,MAAM,CAAC,MAAM,CAChB;YACE,WAAW,EAAE,uBAAe;YAC5B,IAAI,EAAE,oBAAoB;YAC1B,YAAY,EAAE,EAAE;SACjB,EACD,IAAI,CAAC,CAAC;QAEV,MAAM,eAAe,GAAG,CAAC,UAAU,GAAG,OAAO,CAAC,QAAQ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AAI,CAAC,EAAE;YAChC,OAAO,IAAI,gBAAgB,CAAC,OAAO,EAAE,gBAAgB,EAAE,IAAI,CAAC,CAAC;QAC/D,CAAC,CAAC;QACF,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,EAAE,gBAAgB,CAAC,CAAC;IAC5D,CAAC;CACF;AA1BD,0DA0BC"}

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,92 @@
/**
* 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.
*/
/// <reference types="node" />
import { Transform } from 'stream';
import { APICall, APICallback, NormalApiCaller } 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,203 @@
"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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const ended = require("is-stream-ended");
const stream_1 = require("stream");
const api_callable_1 = require("./api_callable");
class PagedIteration extends api_callable_1.NormalApiCaller {
/**
* 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) {
super();
this.pageDescriptor = pageDescriptor;
}
createActualCallback(request, callback) {
const self = this;
return function fetchNextPageToken(err, response) {
if (err) {
callback(err);
return;
}
const resources = response[self.pageDescriptor.resourceField];
const pageToken = response[self.pageDescriptor.responsePageTokenField];
if (pageToken) {
request[self.pageDescriptor.requestPageTokenField] = pageToken;
callback(err, resources, request, response);
}
else {
callback(err, resources, null, response);
}
};
}
wrap(func) {
const self = this;
return function wrappedCall(argument, metadata, options, callback) {
return func(argument, metadata, options, self.createActualCallback(argument, callback));
};
}
init(settings, callback) {
return api_callable_1.NormalApiCaller.prototype.init.call(this, settings, callback);
}
call(apiCall, argument, settings, canceller) {
argument = Object.assign({}, 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;
}
const maxResults = settings.maxResults || -1;
const allResources = [];
function pushResources(err, resources, next) {
if (err) {
canceller.callback(err);
return;
}
for (let 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);
}
}
exports.PagedIteration = PagedIteration;
class PageDescriptor {
/**
* 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, 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.
*/
createStream(apiCall, request, options) {
const stream = new stream_1.PassThrough({ objectMode: true });
options = Object.assign({}, options, { autoPaginate: false });
const maxResults = 'maxResults' in options ? options.maxResults : -1;
let pushCount = 0;
let started = false;
function callback(err, resources, next) {
if (err) {
stream.emit('error', err);
return;
}
for (let 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', () => {
if (!started) {
started = true;
apiCall(request, options, callback);
}
});
return stream;
}
/**
* Returns a new API caller.
* @private
* @return {PageStreamable} - the page streaming caller.
*/
apiCaller() {
return new PagedIteration(this);
}
}
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;;AAEH,yCAAyC;AACzC,mCAA8C;AAE9C,iDAAqE;AAErE,MAAa,cAAe,SAAQ,8BAAe;IAEjD;;;;;;;OAOG;IACH,YAAY,cAA8B;QACxC,KAAK,EAAE,CAAC;QACR,IAAI,CAAC,cAAc,GAAG,cAAc,CAAC;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AAK,UAAU,EAAE;oBAC5B,MAAM,CAAC,GAAG,EAAE,CAAC;iBACd;aACF;YACD,IAAI,KAAK,CAAC,MAAM,CAAC,EAAE;gBACjB,OAAO;aACR;YACD,IAAI,CAAC,IAAI,EAAE;gBACT,MAAM,CAAC,GAAG,EAAE,CAAC;gBACb,OAAO;aACR;YACD,yEAAyE;YACzE,0EAA0E;YAC1E,IAAI,WAAW,IAAI,OAAO,EAAE;gBAC1B,OAAO,OAAO,CAAC,SAAS,CAAC;aAC1B;YACD,IAAI,MAAM,CAAC,QAAQ,EAAE,EAAE;gBACrB,OAAO,GAAG,IAAI,CAAC;gBACf,OAAO,GAAG,KAAK,CAAC;aACjB;iBAAM;gBACL,YAAY,CAAC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;aAChD;QACH,CAAC;QACD,MAAM,CAAC,EAAE,CAAC,QAAQ,EAAE,GAAG,EAAE;YACvB,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,SAAS;QACP,OAAO,IAAI,cAAc,CAAC,IAAI,CAAC,CAAC;IAClC,CAAC;CACF;AAhGD,wCAgGC"}

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,111 @@
"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.
*
*/
Object.defineProperty(exports, "__esModule", { value: true });
const util = require("util");
/* 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) {
let hasPathWildcard = false;
for (let i = 0; i < segments.length; i++) {
const s = segments[i];
if (s.kind !== exports.TERMINAL || s.literal !== '**') {
continue;
}
if (hasPathWildcard) {
const 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) {
return segments.filter(x => x.kind === exports.TERMINAL).length;
}
/**
* Updates missing literals of each of the binding segments.
*
* @private
*
* @param {Segments[]} segments the parsed segments
*/
function updateBindingLiterals(segments) {
let bindingIndex = 0;
segments.forEach(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,
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;;AAEH,6BAA6B;AAG7B,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,MAAM,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,MAAM,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,OAAO,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,gBAAQ,CAAC,CAAC,MAAM,CAAC;AAC1D,CAAC;AAED;;;;;;GAMG;AACH,SAAS,qBAAqB,CAAC,QAAmB;IAChD,IAAI,YAAY,GAAG,CAAC,CAAC;IACrB,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE;QACnB,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;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,176 @@
"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.
*
*/
Object.defineProperty(exports, "__esModule", { value: true });
/*
* Path template utility.
*/
const has = require("lodash.has");
const util = require("util");
const extras = require("./parser_extras");
const parser = require('./path_template_parser');
class PathTemplate {
get size() {
return this.parseResult.size;
}
get segments() {
return this.parseResult.segments;
}
/**
* @param {String} data the of the template
*
* @constructor
*/
constructor(data) {
this.parseResult = extras.finishParse(parser.parse(data));
}
/**
* 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) {
const pathSegments = path.split('/');
const bindings = {};
let segmentCount = this.size;
let current;
let index = 0;
this.segments.forEach(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 === '**') {
const 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 {
const msg = util.format('mismatched literal (index=%d): \'%s\' != \'%s\'', index, segment.literal, pathSegments[index]);
throw new TypeError(msg);
}
}
});
if (index !== pathSegments.length || index !== segmentCount) {
const 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
*/
render(bindings) {
const out = [];
let inABinding = false;
this.segments.forEach(segment => {
if (segment.kind === extras.BINDING) {
if (!has(bindings, segment.literal)) {
const msg = util.format('Value for key %s is not provided in %s', segment.literal, bindings);
throw new TypeError(msg);
}
const 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);
}
});
const result = formatSegments(out);
this.match(result);
return result;
}
/**
* Renders the path template.
*
* @return {string} contains const names matched to binding values
*/
inspect() {
return formatSegments(this.segments);
}
}
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) {
let out = '';
let slash = true;
segments.forEach(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;;AAEH;;GAEG;AAEH,kCAAmC;AACnC,6BAA6B;AAC7B,0CAA0C;AAC1C,MAAM,MAAM,GAAG,OAAO,CAAC,wBAAwB,CAAC,CAAC;AAgBjD,MAAa,YAAY;IAGvB,IAAI,IAAI;QACN,OAAO,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC;IAC/B,CAAC;IAED,IAAI,QAAQ;QACV,OAAO,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC;IACnC,CAAC;IAED;;;;OAIG;IACH,YAAY,IAAY;QACtB,IAAI,CAAC,WAAW,GAAG,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC;IAC5D,CAAC;IAED;;;;;;OAMG;IACH,KAAK,CAAC,IAAY;QAChB,MAAM,YAAY,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QACrC,MAAM,QAAQ,GAAa,EAAE,CAAC;QAC9B,IAAI,YAAY,GAAG,IAAI,CAAC,IAAI,CAAC;QAC7B,IAAI,OA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AAO,MAAM,CAAC;IAChB,CAAC;IAED;;;;OAIG;IACH,OAAO;QACL,OAAO,cAAc,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IACvC,CAAC;CACF;AA9GD,oCA8GC;AAED;;;;;GAKG;AACH,SAAS,cAAc,CAAC,QAAmB;IACzC,IAAI,GAAG,GAAG,EAAE,CAAC;IACb,IAAI,KAAK,GAAG,IAAI,CAAC;IACjB,QAAQ,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE;QACzB,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,645 @@
module.exports = (() => {
/*
* 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) {
const options = arguments.length > 1 ? arguments[1] : {};
const parser = this;
const peg$FAILED = {};
const peg$startRuleFunctions = {template: peg$parsetemplate};
let peg$startRuleFunction = peg$parsetemplate;
const peg$c0 = '/';
const peg$c1 = {type: 'literal', value: '/', description: '"/"'};
const peg$c2 = (segments) => {
return segments;
};
const peg$c3 = (s, segments) => {
return s.concat(segments);
};
const peg$c4 = s => {
return s;
};
const peg$c5 = '{';
const peg$c6 = {type: 'literal', value: '{', description: '"{"'};
const peg$c7 = '=';
const peg$c8 = {type: 'literal', value: '=', description: '"="'};
const peg$c9 = '}';
const peg$c10 = {type: 'literal', value: '}', description: '"}"'};
const peg$c11 = (l, segments) => {
return ([
{kind: extras.BINDING, literal: l},
segments,
{kind: extras.END_BINDING, literal: ''},
])
.reduce((a, b) => a.concat(b), []);
};
const peg$c12 = l => {
return [
{kind: extras.BINDING, literal: l},
{kind: extras.TERMINAL, literal: '*'},
{kind: extras.END_BINDING, literal: ''},
];
};
const peg$c13 = (t, segments) => {
return t.concat(segments);
};
const peg$c14 = t => {
if (t[0].literal === '*' || t[0].literal === '**') {
return [
{
kind: extras.BINDING,
},
t[0],
{kind: extras.END_BINDING, literal: ''},
];
} else {
return t;
}
};
const peg$c15 = '**';
const peg$c16 = {type: 'literal', value: '**', description: '"**"'};
const peg$c17 = '*';
const peg$c18 = {type: 'literal', value: '*', description: '"*"'};
const peg$c19 = l => {
return [{kind: extras.TERMINAL, literal: l}];
};
const peg$c20 = /^[^*=}{\/]/;
const peg$c21 = {type: 'class', value: '[^*=}{/]', description: '[^*=}{/]'};
const peg$c22 = cs => {
return cs.join('');
};
let peg$currPos = 0;
let peg$savedPos = 0;
const peg$posDetailsCache = [{line: 1, column: 1, seenCR: false}];
let peg$maxFailPos = 0;
let peg$maxFailExpected = [];
const peg$silentFails = 0;
let 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}],
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) {
let 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) {
const 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) {
let i = 1;
expected.sort((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,
ch => {
return '\\x0' + hex(ch);
})
.replace(
/[\x10-\x1F\x80-\xFF]/g,
ch => {
return '\\x' + hex(ch);
})
.replace(
/[\u0100-\u0FFF]/g,
ch => {
return '\\u0' + hex(ch);
})
.replace(/[\u1000-\uFFFF]/g, ch => {
return '\\u' + hex(ch);
});
}
const expectedDescs = new Array(expected.length);
let 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() {
let 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() {
let 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() {
let 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() {
let 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() {
let 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() {
let 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() {
let 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() {
let 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;
}
const 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,
};
})();

View File

@ -0,0 +1,17 @@
/**
* 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.
*/
/**
* 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 @@
"use strict";
/*
* 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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
/**
* 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.
*/
/**
* 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(key => `${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;;;;;GAKG;AACH,SAAgB,UAAU,CAAC,MAA6B;IACtD,OAAO,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,IAAI,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAC3E,CAAC;AAFD,gCAEC"}

View File

@ -0,0 +1,102 @@
/**
* 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.
*/
/// <reference types="node" />
import * as Duplexify from 'duplexify';
import { Duplex, Stream } from 'stream';
import { APICall, APICallback } 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,205 @@
"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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
/* This file describes the gRPC-streaming. */
const Duplexify = require("duplexify");
const 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 = {}));
class StreamProxy extends Duplexify {
/**
* 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, callback) {
super(undefined, undefined, {
objectMode: true,
readable: type !== StreamType.CLIENT_STREAMING,
writable: type !== StreamType.SERVER_STREAMING,
});
this.type = type;
this._callback = callback;
this._isCancelCalled = false;
}
cancel() {
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.
*/
forwardEvents(stream) {
const eventsToForward = ['metadata', 'response', 'status'];
eventsToForward.forEach(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', 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,
});
});
}
/**
* 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, argument) {
if (this.type === StreamType.SERVER_STREAMING) {
const retryStream = retryRequest(null, {
objectMode: true,
request: () => {
if (this._isCancelCalled) {
if (this.stream) {
this.stream.cancel();
}
return;
}
const stream = apiCall(argument, this._callback);
this.stream = stream;
this.forwardEvents(stream);
return stream;
},
});
this.setReadable(retryStream);
return;
}
const 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();
}
}
}
exports.StreamProxy = StreamProxy;
class GrpcStreamable {
/**
* An API caller for methods of gRPC streaming.
* @private
* @constructor
* @param {StreamDescriptor} descriptor - the descriptor of the method structure.
*/
constructor(descriptor) {
this.descriptor = descriptor;
}
init(settings, callback) {
return new StreamProxy(this.descriptor.type, callback);
}
wrap(func) {
switch (this.descriptor.type) {
case StreamType.SERVER_STREAMING:
return (argument, metadata, options) => {
return func(argument, metadata, options);
};
case StreamType.CLIENT_STREAMING:
return (argument, metadata, options, callback) => {
return func(metadata, options, callback);
};
case StreamType.BIDI_STREAMING:
return (argument, metadata, options) => {
return func(metadata, options);
};
default:
console.error('Unknown stream type', this.descriptor.type);
}
return func;
}
call(apiCall, argument, settings, stream) {
stream.setStream(apiCall, argument);
}
fail(stream, err) {
stream.emit('error', err);
}
result(stream) {
return stream;
}
}
exports.GrpcStreamable = GrpcStreamable;
class StreamDescriptor {
/**
* Describes the structure of gRPC streaming call.
* @constructor
* @param {StreamType} streamType - the type of streaming.
*/
constructor(streamType) {
this.type = streamType;
}
apiCaller(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);
}
}
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;;AAEH,6CAA6C;AAE7C,uCAAuC;AAKvC,MAAM,YAAY,GAAG,OAAO,CAAC,eAAe,CAAC,CAAC;AA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